我有一张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);
答案 0 :(得分: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];