Saving a PDF document to disk using Quartz

会有一股神秘感。 提交于 2019-12-03 21:24:30

So I found 3 things wrong with it.

  1. PDF pages start at 1 and not 0.
  2. Need to tell the pdf context when a page begins and ends.
  3. Release the pdf context prior to writing the data to disk. This is key for some reason.

Here is the corrected code that works.

- (void)testQuartz:(NSData *)pdfDocumentData
{       
    //Create the pdf document reference
    CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((CFDataRef)pdfDocumentData);
    CGPDFDocumentRef document = CGPDFDocumentCreateWithProvider(dataProvider);

    //Create the pdf context
    CGPDFPageRef page = CGPDFDocumentGetPage(document, 1); //Pages are numbered starting at 1
    CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
    CFMutableDataRef mutableData = CFDataCreateMutable(NULL, 0);

    //NSLog(@"w:%2.2f, h:%2.2f",pageRect.size.width, pageRect.size.height);
    CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData(mutableData);
    CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &pageRect, NULL);


    if (CGPDFDocumentGetNumberOfPages(document) > 0)
    {       
        //Draw the page onto the new context
        //page = CGPDFDocumentGetPage(document, 1); //Pages are numbered starting at 1

        CGPDFContextBeginPage(pdfContext, NULL);
        CGContextDrawPDFPage(pdfContext, page);
        CGPDFContextEndPage(pdfContext);
    }
    else
    {
        NSLog(@"Failed to create the document");
    }

    CGContextRelease(pdfContext); //Release before writing data to disk.

    //Write to disk
    [(NSData *)mutableData writeToFile:@"/Users/David/Desktop/test.pdf" atomically:YES];

    //Clean up
    CGDataProviderRelease(dataProvider); //Release the data provider
    CGDataConsumerRelease(dataConsumer);
    CGPDFDocumentRelease(document);
    CFRelease(mutableData);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!