4

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.

Carter Allen
  • 1,984
  • 15
  • 22
Scott
  • 41
  • 1
  • 2

1 Answers1

11
// 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);
Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
  • Thanks man... I knew I had to flip the coordinates but was missing the part CGRect bounds = CGContextGetClipBoundingBox(pdfContext); to flip the coordinates properly – Sherwin Zadeh Feb 16 '14 at 22:04
  • A slightly different question, but how would you change the code to draw text from a `UITextView`? Specifically, I'm thinking of multi-line text that wraps. Thanks! – Olie May 03 '14 at 22:53