我知道有一种方法可以将PDF页面保存到NSImage
,然后像这样输出到JPG:
NSData *pdfData = [NSData dataWithContentsOfFile:pathToUrPDF];
NSPDFImageRep *pdfImg = [NSPDFImageRep imageRepWithData:pdfData];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSInteger pageCount = [pdfImg pageCount];
for(int i = 0 ; i < pageCount ; i++) {
[pdfImg setCurrentPage:i];
NSImage *temp = [[NSImage alloc] init];
[temp addRepresentation:pdfImg];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[temp TIFFRepresentation]];
NSData *finalData = [rep representationUsingType:NSJPEGFileType properties:nil];
NSString *pageName = [NSString stringWithFormat:@"Page_%ld.jpg", (long)[pdfImg currentPage]];
[fileManager createFileAtPath:[NSString stringWithFormat:@"%@/%@", @"pathWrUWantToSave", pageName] contents:finalData attributes:nil];
}
但是“TIFFRepresetation
”只能输出最高72 DPI。所以我认为从PDF获取高DPI图像的最佳方法是在Mac OS X上使用CGImage
。如何做到这一点?我的目标应用程序适用于Mac OS X,而非iOS ...
非常感谢
答案 0 :(得分:3)
最后我得到了解决方案:
自OS X 10.8起,NSImage有一个基于块的初始化器,用于将基于矢量的内容绘制到位图中。 我们的想法是提供一个绘图处理程序,只要请求图像的表示就会调用它。 点和像素之间的关系通过将NSSize(以点为单位)传递给初始化器并显式设置表示的像素尺寸来表示:
NSString* localDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString* pdfPath = [localDocuments stringByAppendingPathComponent:@"1.pdf"];
NSData* pdfData = [NSData dataWithContentsOfFile:pdfPath];
NSPDFImageRep* pdfImageRep = [NSPDFImageRep imageRepWithData:pdfData];
CGFloat factor = 300/72;
NSInteger pageCount = [pdfImageRep pageCount];
for(int i = 0 ; i < pageCount ; i++) {
[pdfImageRep setCurrentPage:i];
NSImage* scaledImage = [NSImage imageWithSize:pdfImageRep.size flipped:NO drawingHandler:^BOOL(NSRect dstRect) {
[pdfImageRep drawInRect:dstRect];
return YES;
}];
NSImageRep* scaledImageRep = [[scaledImage representations] firstObject];
/*
* The sizes of the PDF Image Rep and the [NSImage imageWithSize: drawingHandler:]-context
* are define in terms of points.
* By explicitly setting the size of the scaled representation in in Pixels, you
* define the relation between ponts & pixels.
*/
scaledImageRep.pixelsWide = pdfImageRep.size.width * factor;
scaledImageRep.pixelsHigh = pdfImageRep.size.height * factor;
NSBitmapImageRep* pngImageRep = [NSBitmapImageRep imageRepWithData:[scaledImage TIFFRepresentation]];
NSData* finalData = [pngImageRep representationUsingType:NSJPEGFileType properties:nil];
NSString* pageName = [NSString stringWithFormat:@"Page_%ld.jpg", (long)[pdfImageRep currentPage]];
[[NSFileManager defaultManager] createFileAtPath:[NSString stringWithFormat:@"%@%@", pdfPath, pageName] contents:finalData attributes:nil];
}