Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing text to a PDF via from an NSString

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.

like image 688
Scott Avatar asked Dec 21 '22 17:12

Scott


1 Answers

// 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);
like image 198
Ole Begemann Avatar answered Jan 18 '23 12:01

Ole Begemann