Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am fairly new to iOS development and this one is killing me. I have not found one complete (simple) example of how to write text to a pdf on the iPhone. The Apple documentation on the subject is code snippets and difficult to follow (for me anyway), and having downloaded the Quartz demo I discovered that all it did was display a pdf that already existed.

Simply put I have the world's simplest view-based app at this point. The view has one button in it. When the button is pressed an NSString is built that contains the numbers 1 through 15. I am able to write a text file to the device that contains the contents of the NSString, but would much prefer it be a pdf.

The bottom line is that I want to build a pdf file from the NSString, ultimately to be emailed as an attachment.

If anyone can point me somewhere that has a complete project that writes text to a pdf I would sure appreciate it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
707 views
Welcome To Ask or Share your Answers For Others

1 Answer

// Create URL for PDF file
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename = @"test.pdf";
NSURL *fileURL = [NSURL fileURLWithPathComponents:[NSArray arrayWithObjects:documentsDirectory, filename, nil]];

// Create PDF context
CGContextRef pdfContext = CGPDFContextCreateWithURL((CFURLRef)fileURL, NULL, NULL);
CGPDFContextBeginPage(pdfContext, NULL);
UIGraphicsPushContext(pdfContext);

// Flip coordinate system
CGRect bounds = CGContextGetClipBoundingBox(pdfContext);
CGContextScaleCTM(pdfContext, 1.0, -1.0);
CGContextTranslateCTM(pdfContext, 0.0, -bounds.size.height);

// Drawing commands
[@"Hello World!" drawAtPoint:CGPointMake(100, 100) withFont:[UIFont boldSystemFontOfSize:72.0f]];

// Clean up
UIGraphicsPopContext();
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...