1

我有一个 PDF,我想把它缩小到一页。

这不起作用:

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

1 回答 1

2

您的代码在同一位置打印所有页面,一个在另一个之上。如果页面有明确的白色背景,那么您只会看到最后一页。
解决方法是在页面绘制完成后,以已绘制页面的高度平移坐标系。
更新:这是完整的代码。它假定源文件中的所有页面都具有相同的大小和旋转:

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];
于 2013-06-10T14:39:04.993 回答