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

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

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

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

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

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

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


当前回答

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

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

其他回答

在mac电脑上使用预览其实很容易做到。你所要做的就是在预览中打开文件,并另存(或导出)png或jpeg格式,但要确保你在窗口底部使用至少300 dpi来获得高质量的图像。

我使用开源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高。

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

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

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

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