繁体   English   中英

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

[英]Convert PDF images to PNG using Python on macOS

我读了很多的尝试来描述如何PDF文件转换成一个PNG图像的文章。 但是我根本无法正常工作。 我试图在脚本顶部import PythonMagick ,但它返回错误ImportError: No module named PythonMagick

是否可以通过Homebrew像安装shell工具一样容易地安装PythonMagick? 背景是我的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

尝试此操作以解决错误ImportError:没有名为PythonMagick的模块

也看看这个链接

尝试更改: 从。 import _PythonMagick以在您的init .py of PythonMagick中导入 _PythonMagick

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

尝试使用mupdf 您应该使用的命令mudraw由版本决定。 大多数时候应该是:

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

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

您可以将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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM