簡體   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