1. 程式人生 > >windows下用Python把pdf檔案轉化為圖片(png格式)

windows下用Python把pdf檔案轉化為圖片(png格式)

最近工作中需要把pdf檔案轉化為圖片,想用python來實現,於是在網上找啊找啊找啊找,找了半天,倒是找到一些程式碼。

1、第一個找到的程式碼,我試了一下好像是反了,只能實現把圖片轉為pdf,而不能把pdf轉為圖片。。。

程式碼如下:

#!/usr/bin/env python

import os
import sys
from reportlab.lib.pagesizes import A4, landscape
from reportlab.pdfgen import canvas
f = sys.argv[1]
filename = ''.join(f.split('/')[-1:])[:-4]
f_jpg = filename+'.jpg'
print f_jpg
def conpdf(f_jpg):
    f_pdf = filename+'.pdf'
    (w, h) = landscape(A4)
    c = canvas.Canvas(f_pdf, pagesize = landscape(A4))
    c.drawImage(f, 0, 0, w, h)
    c.save()
    print "okkkkkkkk."
 
conpdf(f_jpg)

2、第二個是文章寫的比較詳細,可惜的是linux下的程式碼,所以仍然沒用。

3、第三個文章指出有一個庫PythonMagick可以實現這個功能,需要下載一個庫 PythonMagick-0.9.10-cp27-none-win_amd64.whl 這個是64位的。

這裡不得不說自己又犯了一個錯誤,因為自己從python官網上下載了一個python 2.7,以為是64位的版本,實際上是32位的版本,所以導致python的版本(32位)和下載的PythonMagick的版本(64位)不一致,弄到晚上12點多,總算了發現了這個問題。。。

4、然後,接下來繼續用搜索引擎搜,找到很多stackoverflow的問題帖子,發現了2個程式碼,不過要先下載PyPDF2以及ghostscript模組。

先通過pip來安裝 PyPDF2、PythonMagick、ghostscript 模組。

C:\Users\Administrator>pip install PyPDF2
Collecting PyPDF2
  Using cached PyPDF2-1.25.1.tar.gz
Installing collected packages: PyPDF2
  Running setup.py install for PyPDF2
Successfully installed PyPDF2-1.25.1
You are using pip version 7.1.2, however version 8.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.


C:\Users\Administrator>pip install C:\PythonMagick-0.9.10-cp27-none-win_amd64.whl
Processing c:\pythonmagick-0.9.10-cp27-none-win_amd64.whl
Installing collected packages: PythonMagick
Successfully installed PythonMagick-0.9.10
You are using pip version 7.1.2, however version 8.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.


C:\Users\Administrator>pip install ghostscript
Collecting ghostscript
  Downloading ghostscript-0.4.1.tar.bz2
Requirement already satisfied (use --upgrade to upgrade): setuptools in c:\python27\lib\site-packages (from ghostscript)
Installing collected packages: ghostscript
  Running setup.py install for ghostscript
Successfully installed ghostscript-0.4.1
You are using pip version 7.1.2, however version 8.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

下面是程式碼

程式碼1:

import os
import ghostscript
from PyPDF2 import PdfFileReader, PdfFileWriter
from tempfile import NamedTemporaryFile
from PythonMagick import Image


reader = PdfFileReader(open("C:/deep.pdf", "rb"))
for page_num in xrange(reader.getNumPages()):
    writer = PdfFileWriter()
    writer.addPage(reader.getPage(page_num))
    temp = NamedTemporaryFile(prefix=str(page_num), suffix=".pdf", delete=False)

    writer.write(temp)

    print temp.name

    tempname = temp.name
    temp.close()
    

    im = Image(tempname)
    #im.density("3000") # DPI, for better quality
    #im.read(tempname)
    im.write("some_%d.png" % (page_num))
    
    os.remove(tempname)

程式碼2:
import sys
import PyPDF2
import PythonMagick
import ghostscript

pdffilename = "C:\deep.pdf" 
pdf_im = PyPDF2.PdfFileReader(file(pdffilename, "rb"))

print '1'

npage = pdf_im.getNumPages()
print('Converting %d pages.' % npage)
for p in range(npage):
    im = PythonMagick.Image()
    im.density('300')
    im.read(pdffilename + '[' + str(p) +']')
    im.write('file_out-' + str(p)+ '.png')
    #print pdffilename + '[' + str(p) +']','file_out-' + str(p)+ '.png'

然後執行時都報錯了,這個是 程式碼2 的報錯資訊:

Traceback (most recent call last):
  File "C:\c.py", line 15, in <module>
    im.read(pdffilename + '[' + str(p) +']')
RuntimeError: pythonw.exe: PostscriptDelegateFailed `C:\DEEP.pdf': No such file or directory @ error/pdf.c/ReadPDFImage/713

總是在上面的     im.read(pdffilename + '[' + str(p) +']') 這一行報錯。

於是,根據報錯的資訊在網上查,但是沒查到什麼有用的資訊,但是感覺應該和GhostScript有關,於是在網上去查安裝包,找到一個在github上的下載連線,但是點進去的時候顯示無法下載可憐

最後,在csdn的下載中找到了 這個檔案:GhostScript_Windows_9.15_win32_win64,安裝了64位版本,之後,再次執行上面的程式碼,都能用了得意

不過程式碼2需要做如下修改,不然還是會報 No such file or directory @ error/pdf.c/ReadPDFImage/713 錯誤:

#程式碼2
import sys
import PyPDF2
import PythonMagick
import ghostscript

pdffilename = "C:\deep.pdf" 
pdf_im = PyPDF2.PdfFileReader(file(pdffilename, "rb"))

print '1'

npage = pdf_im.getNumPages()
print('Converting %d pages.' % npage)
for p in range(npage):
    im = PythonMagick.Image(pdffilename + '[' + str(p) +']')
    im.density('300')
    #im.read(pdffilename + '[' + str(p) +']')
    im.write('file_out-' + str(p)+ '.png')

    #print pdffilename + '[' + str(p) +']','file_out-' + str(p)+ '.png'

這次有個很深刻的體會,就是解決這個問題過程中,大部分時間都是用在查資料、驗證資格資料是否有用上了,搜尋資料的能力很重要。

而在實際搜尋資料的過程中,國內關於PythonMagick的文章太少了,搜尋出來的大部分有幫助的文章都是國外的,但是這些國外的帖子文章,也沒有解決我的問題或者是給出有用的線索,最後還是通過自己的思考,解決了問題。

必須給自己點個贊大笑