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

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

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

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

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

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

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


当前回答

下面的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

其他回答

在投票之前请注意,这个解决方案是针对使用图形界面的Gimp的,而不是使用命令行的ImageMagick的,但它作为一个替代方案对我来说效果非常好,这就是为什么我发现有必要在这里分享它。

按照这些简单的步骤从PDF文档中提取任何格式的图像

Download GIMP Image Manipulation Program Open the Program after installation Open the PDF document that you want to extract Images Select only the pages of the PDF document that you would want to extract images from. N/B: If you need only the cover images, select only the first page. Click open after selecting the pages that you want to extract images from Click on File menu when GIMP when the pages open Select Export as in the File menu Select your preferred file type by extension (say png) below the dialog box that pops up. Click on Export to export your image to your desired location. You can then check your file explorer for the exported image.

这是所有。

我希望这对你们有帮助

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

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

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

我使用的是pdf2image。一个简单的python库,工作起来很有魅力。

首先在非linux机器上安装poppler。你可以下载压缩包。在“程序文件”中解压,并将bin添加到“机器路径”中。

之后,你可以像这样在python类中使用pdf2image:

from pdf2image import convert_from_path, convert_from_bytes
images_from_path = convert_from_path(
   inputfile,
   output_folder=outputpath,
   grayscale=True, fmt='jpeg')

我不擅长python,但能够使它的exe。 稍后,您可以使用带有文件输入和输出参数的exe。我已经在c#中使用了它,事情工作得很好。

图像质量好。OCR工作正常。

它也会给你带来好的结果:

exec("convert -geometry 1600x1600 -density 200x200 -quality 100 test.pdf test_image.jpg");

我在命令行上使用pdftoppm来获取初始图像,通常分辨率为300dpi,因此pdftoppm -r 300,然后使用convert来进行修剪和PNG转换。