无法在iOS上创建400多页的PDF文档

问题描述:

我使用以下伪代码生成PDF文档:

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);

它适用于小型文件( N pages),但如果文件超过400页(它在崩溃前收到
两个内存警告),它会占用太多的
内存并崩溃。我确保没有泄漏使用
仪器。您对在iOS上创建大型PDF文档有何建议?非常感谢。

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.

编辑:pdf创建在后台线程中完成。

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

由于您是通过 CGPDFContextCreateWithURL 创建单个文档,因此必须将整个内容保存在内存中并附加到通常(尽管我可以'对于iOS和 CGPDFContextCreateWithURL 而言确实如此。要求保留文档的前的 副本。即使没有前后问题,也不需要泄漏来创建问题。

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.

如果你不想捕获一堆现有的UIKit-drawn东西 - 在您的样本中似乎您不是 - 使用操作系统的打印方法,而 内置支持打印到PDF UIGraphicsBeginPDFContextToFile 在添加页面时将页面写入磁盘,这样整个过程就不必一次保存在内存中。你应该能够以这种方式生成一个巨大的PDF。

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.