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

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

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

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

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

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

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


当前回答

我使用的是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工作正常。

其他回答

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

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

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

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

我个人喜欢这个。

convert -density 300 -trim test.pdf -quality 100 test.jpg

文件大小是原来的两倍多一点,但在我看来好多了。

-density 300设置PDF渲染的dpi。

-trim删除任何与角落像素相同颜色的边缘像素。

-quality 100将JPEG压缩质量设置为最高质量。

像-锐化这样的东西不能很好地处理文本,因为它们撤消了字体渲染系统为使文本更易读而做的工作。

如果你真的想放大它,在这里使用resize,可能是一个更大的dpi值,比如targetDPI * scalingFactor,这将以你想要的分辨率/大小渲染PDF。

imagemagick.org上的参数描述在这里

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

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

这适用于从多个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%质量)

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