1. 程式人生 > >Python 將pdf轉成圖片

Python 將pdf轉成圖片

本篇文章記錄如何使用python將pdf檔案切分成一張一張圖片,包括環境配置、版本相容問題。

環境配置(mac)

安裝ImageMagick

brew install imagemagick

這裡有個坑,brew安裝都是7.x版本,使用wand時會出錯,需要你安裝6.x版本。

解決辦法:

1.安裝6.x版本

brew install imagemagick@6

2.取消連結7.x版本

brew unlink imagemagick

Unlinking /usr/local/Cellar/imagemagick/7.0.7-4… 71 symlinks removed

3.強制連結6.x版本

 brew link imagemagick@6 --force

Linking /usr/local/Cellar/[email protected]/6.9.9-15… 75 symlinks created

4.export環境變數

 echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' >> ~/.bash_profile

ok,以上解決imagemagick版本問題。

安裝gs

必須安裝gs,否則pdf無法轉換。

 brew install
gs

安裝wand

pip3 install wand

我這裡使用的是python3,所以需要用pip3.

程式碼實現

from wand.image import Image

def convert_pdf_to_jpg(filename):
    with Image(filename=filename) as img :
        print('pages = ', len(img.sequence))

        with img.convert('jpeg') as converted:
            converted.save(filename='image/page.jpeg'
)

效果

筆者將一本書四百多頁都轉出來了,大家也可以去試下啦。

這裡寫圖片描述