在macOS上使用Python将PDF图像转换为PNG

时间:2017-10-22 22:31:09

标签: python macos pdf imagemagick pythonmagick

我已经阅读了很多文章,试图描述如何将PDF转换为PNG图像。但我根本无法让它发挥作用。我尝试在我的脚本之上import PythonMagick,但它返回错误ImportError: No module named PythonMagick

是否可以通过Homebrew安装PythonMagick像shell工具一样简单?!后台是我的Python脚本,比同等的Bash脚本短得多。唯一不起作用的是PDF到PNG的转换和最终图像的缩放。在Bash中,我使用Imagemagick,但我也想在Python中这样做,因为它是一个单行。

任何想法?

修改

代码可以在Github上找到:https://github.com/Blackjacx/Scripts/blob/master/iconizer.py

解决方案

使用MagickWand效果更好,所以我使用它。要安装它,我做了:

$ brew install imagemagick@6
$ export MAGICK_HOME=/usr/local/opt/imagemagick@6

3 个答案:

答案 0 :(得分:1)

尝试使用此错误导入错误:没有名为PythonMagick的模块

另请查看此link

  

尝试更改:来自。导入_PythonMagick 导入_PythonMagick init .py的PythonMagick

答案 1 :(得分:1)

我不建议您使用imagemagick。因为此工具按像素渲染输出,而不是pdf文件内的矢量。因此,如果您的pdf文件的原始分辨率远低于输出png文件的分辨率,则会导致质量损失。

尝试使用mupdf。您应该使用的命令mudraw由版本决定。大部分时间应该是:

mudraw [-h 1080] [-w 1080] [-o <output_path>] <input_path> 

此工具可以操纵向量,因此无论您如何缩放原始文件都不会有任何质量损失。

答案 2 :(得分:0)

您可以将Apple自己的CoreGraphics API与python脚本“开箱即用”一起使用。以下脚本会将作为参数提供的PDF文件转换为PNG。也可以在Automator的“运行Shell脚本”操作中使用它。

#!/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
相关问题