我正在尝试使用命令行程序转换将PDF转换为图像(JPEG或PNG)。这是我正在转换的pdf文件之一。

我想让程序去掉多余的空白,并返回足够高质量的图像,以便上标可以轻松读取。

这是我目前最好的尝试。正如你所看到的,修剪工作很好,我只是需要锐化的分辨率相当多。这是我正在使用的命令:

convert -trim 24.pdf -resize 500% -quality 100 -sharpen 0x1.0 24-11.jpg

我试着做了以下有意识的决定:

调整它的大小(对分辨率没有影响) 尽可能提高质量 使用-锐化(我已经尝试了一系列值)

任何建议,请在最终的PNG/JPEG图像的分辨率更高,将非常感谢!


当前回答

我真的没有很好的转换成功[更新2020年5月:实际上:它几乎从来没有为我工作],但我有非常好的pdftoppm成功。下面是几个从PDF生成高质量图像的例子:

[Produces ~25 MB-sized files per pg] Output uncompressed .tif file format at 300 DPI into a folder called "images", with files being named pg-1.tif, pg-2.tif, pg-3.tif, etc: mkdir -p images && pdftoppm -tiff -r 300 mypdf.pdf images/pg [Produces ~1MB-sized files per pg] Output in .jpg format at 300 DPI: mkdir -p images && pdftoppm -jpeg -r 300 mypdf.pdf images/pg [Produces ~2MB-sized files per pg] Output in .jpg format at highest quality (least compression) and still at 300 DPI: mkdir -p images && pdftoppm -jpeg -jpegopt quality=100 -r 300 mypdf.pdf images/pg

要了解更多解释、选项和示例,请参阅我的完整答案:

https://askubuntu.com/questions/150100/extracting-embedded-images-from-a-pdf/1187844 1187844。

相关:

[如何将PDF转换为可搜索的PDF w/pdf2searchablepdf] https://askubuntu.com/questions/473843/how-to-turn-a-pdf-into-a-text-searchable-pdf/1187881#1187881 交联: 如何将一个PDF转换成JPG与命令行在Linux? https://unix.stackexchange.com/questions/11835/pdf-to-jpg-without-quality-loss-gscan2pdf/585574#585574

其他回答

我使用开源java pdf引擎icepdf。检查办公室演示。

package image2pdf;

import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class pdf2image {

   public static void main(String[] args) {

      Document document = new Document();
      try {
         document.setFile("C:\\Users\\Dell\\Desktop\\test.pdf");
      } catch (PDFException ex) {
         System.out.println("Error parsing PDF document " + ex);
      } catch (PDFSecurityException ex) {
         System.out.println("Error encryption not supported " + ex);
      } catch (FileNotFoundException ex) {
         System.out.println("Error file not found " + ex);
      } catch (IOException ex) {
         System.out.println("Error IOException " + ex);
      }

      // save page captures to file.
      float scale = 1.0f;
      float rotation = 0f;

      // Paint each pages content to an image and
      // write the image to file
      for (int i = 0; i < document.getNumberOfPages(); i++) {
         try {
         BufferedImage image = (BufferedImage) document.getPageImage(
             i, GraphicsRenderingHints.PRINT, Page.BOUNDARY_CROPBOX, rotation, scale);

         RenderedImage rendImage = image;
         try {
            System.out.println(" capturing page " + i);
            File file = new File("C:\\Users\\Dell\\Desktop\\test_imageCapture1_" + i + ".png");
            ImageIO.write(rendImage, "png", file);
         } catch (IOException e) {
            e.printStackTrace();
         }
         image.flush();
         }catch(Exception e){
             e.printStackTrace();
         }
      }

      // clean up resources
      document.dispose();
   }
}

我也尝试过imagemagick和pdftoppm, pdftoppm和icepdf的分辨率都比imagemagick高。

下面的python脚本可以在任何Mac (Snow Leopard及以上版本)上运行。它可以在命令行上使用连续的PDF文件作为参数,或者您可以在Automator中放入一个运行Shell脚本操作,并创建一个服务(Mojave中的快速动作)。

您可以在脚本中设置输出图像的分辨率。

脚本和Quick Action可以从github下载。

#!/usr/bin/python
# coding: utf-8

import os, sys
import Quartz as Quartz
from LaunchServices import (kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG, kCFAllocatorDefault) 

resolution = 300.0 #dpi
scale = resolution/72.0

cs = Quartz.CGColorSpaceCreateWithName(Quartz.kCGColorSpaceSRGB)
whiteColor = Quartz.CGColorCreate(cs, (1, 1, 1, 1))
# Options: kCGImageAlphaNoneSkipLast (no trans), kCGImageAlphaPremultipliedLast 
transparency = Quartz.kCGImageAlphaNoneSkipLast

#Save image to file
def writeImage (image, url, type, options):
    destination = Quartz.CGImageDestinationCreateWithURL(url, type, 1, None)
    Quartz.CGImageDestinationAddImage(destination, image, options)
    Quartz.CGImageDestinationFinalize(destination)
    return

def getFilename(filepath):
    i=0
    newName = filepath
    while os.path.exists(newName):
        i += 1
        newName = filepath + " %02d"%i
    return newName

if __name__ == '__main__':

    for filename in sys.argv[1:]:
        pdf = Quartz.CGPDFDocumentCreateWithProvider(Quartz.CGDataProviderCreateWithFilename(filename))
        numPages = Quartz.CGPDFDocumentGetNumberOfPages(pdf)
        shortName = os.path.splitext(filename)[0]
        prefix = os.path.splitext(os.path.basename(filename))[0]
        folderName = getFilename(shortName)
        try:
            os.mkdir(folderName)
        except:
            print "Can't create directory '%s'"%(folderName)
            sys.exit()

        # For each page, create a file
        for i in range (1, numPages+1):
            page = Quartz.CGPDFDocumentGetPage(pdf, i)
            if page:
        #Get mediabox
                mediaBox = Quartz.CGPDFPageGetBoxRect(page, Quartz.kCGPDFMediaBox)
                x = Quartz.CGRectGetWidth(mediaBox)
                y = Quartz.CGRectGetHeight(mediaBox)
                x *= scale
                y *= scale
                r = Quartz.CGRectMake(0,0,x, y)
        # Create a Bitmap Context, draw a white background and add the PDF
                writeContext = Quartz.CGBitmapContextCreate(None, int(x), int(y), 8, 0, cs, transparency)
                Quartz.CGContextSaveGState (writeContext)
                Quartz.CGContextScaleCTM(writeContext, scale,scale)
                Quartz.CGContextSetFillColorWithColor(writeContext, whiteColor)
                Quartz.CGContextFillRect(writeContext, r)
                Quartz.CGContextDrawPDFPage(writeContext, page)
                Quartz.CGContextRestoreGState(writeContext)
        # Convert to an "Image"
                image = Quartz.CGBitmapContextCreateImage(writeContext) 
        # Create unique filename per page
                outFile = folderName +"/" + prefix + " %03d.png"%i
                url = Quartz.CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, outFile, len(outFile), False)
        # kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG
                type = kUTTypePNG
        # See the full range of image properties on Apple's developer pages.
                options = {
                    Quartz.kCGImagePropertyDPIHeight: resolution,
                    Quartz.kCGImagePropertyDPIWidth: resolution
                    }
                writeImage (image, url, type, options)
                del page

通常我在原生分辨率下用'pdfimages'提取嵌入图像,然后使用ImageMagick的转换为所需的格式:

$ pdfimages -list fileName.pdf
$ pdfimages fileName.pdf fileName   # save in .ppm format
$ convert fileName-000.ppm fileName-000.png

这将生成最佳和最小的结果文件。

注意:对于有损的JPG嵌入图像,你必须使用-j:

$ pdfimages -j fileName.pdf fileName   # save in .jpg format

最近的“poppler-util”(0.50+,2016),你可以使用-所有保存有损为jpg和无损为png,所以一个简单的:

$ pdfimages -all fileName.pdf fileName

从PDF中提取总是最好的质量内容。

在很少提供的Win平台上,您必须下载最近的(0.68,2018)' popler -util'二进制从: http://blog.alivate.com.au/poppler-windows/

我发现,当使用转换使用的底层gs(又名Ghostscript)命令将大型pdf批量处理为png和jpg时,它既更快又更稳定。

你可以在convert -verbose的输出中看到这个命令,还有一些可能的调整(YMMV),这些调整很难/不可能直接通过convert访问。

然而,这将很难做你的修剪和锐化使用gs,所以,正如我所说的,YMMV!

这适用于从多个PDF和图像文件创建单个文件:

php exec('convert -density 300 -trim "/path/to/input_filename_1.png" "/path/to/input_filename_2.pdf" "/path/to/input_filename_3.png" -quality 100 "/path/to/output_filename_0.pdf"');

地点:

-density 300 = dpi

-trim =一些关于透明度的东西-使边缘看起来光滑

质量100 =质量vs压缩(100%质量)

平……对于多页,不要使用“压平”