Skip to content

Instantly share code, notes, and snippets.

@C4Code
Created May 22, 2012 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save C4Code/2770905 to your computer and use it in GitHub Desktop.
Save C4Code/2770905 to your computer and use it in GitHub Desktop.
Create PDF in iOS
//
// C4WorkSpace.m
// createPDF
//
// Created by Travis Kirton on 12-05-17.
// Copyright (c) 2012 POSTFL. All rights reserved.
//
#import "C4WorkSpace.h"
@interface C4WorkSpace ()
-(void)createAndDrawToPDF;
-(CGContextRef) createPDFContext:(CGRect)inMediaBox path:(CFStringRef) path;
@end
@implementation C4WorkSpace
-(void)setup {
C4Shape *s = [C4Shape ellipse:CGRectMake(100, 0, 100, 100)];
s.origin = s.frame.origin;
[self.canvas addShape:s];
CGPoint p[2] = {CGPointMake(100, 100),CGPointMake(400, 400)};
C4Shape *l = [C4Shape line:p];
l.origin = l.frame.origin;
[self.canvas addShape:l];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self createAndDrawToPDF];
}
-(void)createAndDrawToPDF {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"tmp.pdf"];
CGContextRef pdfContext = [self createPDFContext:self.canvas.frame path:(CFStringRef)writableDBPath];
NSLog(@"PDF Context created");
CGContextBeginPage (pdfContext,nil); // 6
//turn PDF upsidedown
CGAffineTransform transform = CGAffineTransformIdentity;
transform = CGAffineTransformMakeTranslation(0, self.canvas.frame.size.height);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
CGContextConcatCTM(pdfContext, transform);
//Draw view into PDF
for(C4Shape *c in self.canvas.subviews) {
if(c.isLine) {
}
CGPoint orig = c.frame.origin;
CGContextTranslateCTM(pdfContext, orig.x, orig.y);
[c.layer renderInContext:pdfContext];
CGContextTranslateCTM(pdfContext, -1*orig.x, -1*orig.y);
}
CGContextEndPage (pdfContext);// 8
CGContextRelease (pdfContext);
}
-(CGContextRef) createPDFContext:(CGRect)inMediaBox path:(CFStringRef) path
{
CGContextRef myOutContext = NULL;
CFURLRef url;
url = CFURLCreateWithFileSystemPath (NULL, // 1
path,
kCFURLPOSIXPathStyle,
false);
if (url != NULL) {
myOutContext = CGPDFContextCreateWithURL (url,// 2
&inMediaBox,
NULL);
CFRelease(url);// 3
}
return myOutContext;// 4
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment