Convert a PDF to one page PDF reason for this is PDF pages doesnot have same page height [closed]

你。 提交于 2019-12-23 02:08:29

问题


I have a PDF and I want to shrink it down to one page.

This does not work:

//pages
size_t pages = CGPDFDocumentGetNumberOfPages(document);
pageRect.size.height = pageRect.size.height*pages;
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData(mutableData);
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &pageRect, NULL);

CGPDFContextBeginPage(pdfContext, NULL);
for (int i =1; i<=pages; i++)
{
   CGPDFPageRef pageRef = CGPDFDocumentGetPage(document, i);
   CGContextDrawPDFPage(pdfContext, pageRef);
}
CGPDFContextEndPage(pdfContext);

回答1:


Your code prints all the pages at the same location, one on top of another. If by any chance the pages have an explicit white background then you will see only the last page.
The solution is to translate the coordinate system after the page is drawn with the height of the page that has been drawn.
UPDATE: This is the complete code. It assumes that all pages in the source file have the same size and rotation:

NSURL *pdfURL = [[NSBundle mainBundle] URLForResource:@"source.pdf" withExtension:nil];
pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);

int pageCount = CGPDFDocumentGetNumberOfPages(pdf);
CGPDFPageRef pageRef = CGPDFDocumentGetPage(pdf, 1);
CGRect pageRect = CGPDFPageGetBoxRect(pageRef, kCGPDFMediaBox);
float pageHeight = pageRect.size.height;
pageRect.size.height = pageRect.size.height * pageCount;

NSMutableData* pdfData = [[NSMutableData alloc] init];
CGDataConsumerRef pdfConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfData);
CGContextRef pdfContext = CGPDFContextCreate(pdfConsumer, &pageRect, NULL);

CGPDFContextBeginPage(pdfContext, NULL);
CGContextTranslateCTM(pdfContext, 0, pageRect.size.height);
for (int i = 1; i <= pageCount; i++) {
    pageRef = CGPDFDocumentGetPage(pdf, i);
    CGContextTranslateCTM(pdfContext, 0, -pageHeight);
    CGContextDrawPDFPage(pdfContext, pageRef);
}
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFile = [documentsDirectory stringByAppendingPathComponent:@"destination.pdf"];

[pdfData writeToFile: pdfFile atomically: NO];
[pdfData release];


来源:https://stackoverflow.com/questions/17025701/convert-a-pdf-to-one-page-pdf-reason-for-this-is-pdf-pages-doesnot-have-same-pag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!