Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create PDF document with 400+ pages on iOS

I am using the following pseudocode to generate a PDF document:

CGContextRef context = CGPDFContextCreateWithURL(url, &rect, NULL);

for (int i = 1; i <= N; i++)
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  CGContextBeginPage(context, &mediaBox);

  // drawing code

  CGContextEndPage(context);
  [pool release];
}

CGContextRelease(context);

It works very well with small documents (N < 100 pages), but it uses too much memory and crashes if the document has more than about 400 pages (it received two memory warnings before crashing.) I have made sure there were no leaks using Instruments. What's your advice on creating large PDF documents on iOS? Thanks a lot.

edit: The pdf creation is done in a background thread.

like image 532
TP. Avatar asked May 04 '11 04:05

TP.


People also ask

Can you create a PDF on an iPhone?

On your iPhone:Download PDF Expert for free. Open the app and tap the blue plus sign. Select Create PDF from File. Pick the file you wish to convert and tap Create.


1 Answers

Since you're creating a single document via CGPDFContextCreateWithURL the entire thing has to be held in memory and appended to, something that commonly (though I can't say for certain with iOS and CGPDFContextCreateWithURL) requires a full before and after copy of the document to be kept. No need for a leak to create a problem, even without the before-and-after issue.

If you aren't trying to capture a bunch of existing UIKit-drawn stuff -- and in your sample it seems that you're not -- use the OS's printing methods instead, which offer built-in support for printing to a PDF. UIGraphicsBeginPDFContextToFile writes the pages out to disk as they're added so the whole thing doesn't have to be held in memory at once. You should be able to generate a huge PDF that way.

like image 141
Matthew Frederick Avatar answered Sep 19 '22 15:09

Matthew Frederick