代码之家  ›  专栏  ›  技术社区  ›  Primoz Rome

使用COCOA将PDF页面转换为图像

  •  3
  • Primoz Rome  · 技术社区  · 16 年前

    我对PDF转换成图像有问题。我想为PDF文档中的每一页创建一个图像文件。

    这是我正在使用的代码,运行良好。每一页都被转换成图像,但我的图像分辨率有问题。我不知道如何设置输出图像的分辨率。有人能帮我吗?

    NSData *pdfData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://localhost/test/test.pdf"]];
    
    
    NSPDFImageRep *img = [NSPDFImageRep imageRepWithData:pdfData]; 
     NSFileManager *fileManager = [NSFileManager defaultManager];
     int count = [img pageCount]; 
     for(int i = 0 ; i < count ; i++) { 
      [img setCurrentPage:i]; 
      NSImage *temp = [[NSImage alloc] init]; 
      [temp addRepresentation:img]; 
      NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[temp TIFFRepresentation]]; 
      NSData *finalData = [rep representationUsingType:NSJPEGFileType properties:nil]; 
      NSString *pageName = [NSString stringWithFormat:@"Page_%d.jpg", [img currentPage]]; 
      [fileManager createFileAtPath:[NSString stringWithFormat:@"%@/%@", @"/Users/mac/Desktop/", pageName] contents:finalData attributes:nil];
     }
    

    谢谢!

    2 回复  |  直到 16 年前
        1
  •  2
  •   refulgentis    16 年前
        2
  •  2
  •   Peter Hosey    16 年前

    最简单的方法是使用ImageIO框架。将PDF数据馈送到 image source 得到一个 CGImage ;将该对象馈送给 image destination 生成(并可选地保存在同一步骤中)JPEG数据。在后一步中,可以在图像属性中指定分辨率;请参见 “Individual Image Properties” in the documentation .

    别忘了 finalize your destination . 这很重要。

    推荐文章