2014-12-06 97 views
15

是否有任何實際的方法使用Python從圖像文件列表創建PDF?從圖像列表中創建PDF

在Perl中,我知道that module。有了它,我可以創建在短短3線PDF:

use PDF::FromImage; 
... 
my $pdf = PDF::FromImage->new; 
$pdf->load_images(@allPagesDir); 
$pdf->write_file($bookName . '.pdf'); 

我需要做的與此非常相似的東西,但在Python。我知道pyPdf模塊,但我想要一些簡單的東西。

@Edit

如果你通過谷歌來了,這裏是代碼:

from fpdf import FPDF 
from PIL import Image 
def makePdf(pdfFileName, listPages, dir = ''): 
    if (dir): 
     dir += "/" 

    cover = Image.open(dir + str(listPages[0]) + ".jpg") 
    width, height = cover.size 

    pdf = FPDF(unit = "pt", format = [width, height]) 

    for page in listPages: 
     pdf.add_page() 
     pdf.image(dir + str(page) + ".jpg", 0, 0) 

    pdf.output(dir + pdfFileName + ".pdf", "F") 
+1

您可以從您的問題中刪除答案部分,並將其正確發佈,作爲單獨的答案嗎? – usr2564301 2017-02-04 17:42:33

回答

18

安裝FPDF for Python

pip install fpdf 

現在你可以使用相同的邏輯:

from fpdf import FPDF 
pdf = FPDF() 
# imagelist is the list with all image filenames 
for image in imagelist: 
    pdf.add_page() 
    pdf.image(image,x,y,w,h) 
pdf.output("yourfile.pdf", "F") 

您可以找到更多信息at the tutorial pageofficial documentation

+0

謝謝,但我無法成功。我正在處理的圖像是JPG; FDPF不支持JPG。爲此,需要PIL。由於PIL不再支持Python 3,我安裝了PILLOW。但是,FDPF顯然不承認:「PIL未安裝」。 出於測試目的,我測試了PNG圖像,但是,結果出現以下錯誤:「不是PNG文件:0.png」 – Macabeus 2014-12-06 17:17:09

+0

@KeplerBR在上面的回答中,我已經使用了'pgmagick',它支持'jpg,png, JPEG 2000'等多種格式,並且在圖像轉換方面也有很好的效果。 – 2014-12-06 18:12:58

+0

多美妙!幾個月後,我決定返回給我這個問題的項目,並使用FPDF再次嘗試,現在使用最新版本,現在完美運行!謝謝!我使用完整的代碼編輯原始帖子,對於通過Google來到這裏的用戶。 – Macabeus 2015-02-21 04:35:09

2

pgmagick是一個用於Python的GraphicsMagick(Magick++)綁定。

這是一個用於ImageMagick(或GraphicsMagick)的Python包裝器。

import os 
from os import listdir 
from os.path import isfile, join 
from pgmagick import Image 

mypath = "\Images" # path to your Image directory 

for each_file in listdir(mypath): 
    if isfile(join(mypath,each_file)): 
     image_path = os.path.join(mypath,each_file) 
     pdf_path = os.path.join(mypath,each_file.rsplit('.', 1)[0]+'.pdf') 
     img = Image(image_path) 
     img.write(pdf_path) 

Sample input Image: 

enter image description here

PDF looks like this: 

enter image description here

pgmagick窗戶iinstallation指令:

1)下載預編譯的二進制來自Unofficial Windows Binaries for Python Extension Packages的軟件包(如pgmagick網頁中所述)並安裝它。

注意: 嘗試下載與您的機器中安裝的python版本相對應的正確版本,以及它的32位安裝還是64位。

您可以檢查是否僅通過在終端上,然後按Enter鍵入蟒蛇有32位或64位的蟒蛇..

D:\>python 
ActivePython 2.7.2.5 (ActiveState Software Inc.) based on 
Python 2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 

所以它擁有python version 2.732 bit (Intel)] on win32它,所以你必須downlad並安裝pgmagick‑0.5.8.win32‑py2.7.exe

這些是pgmagick以下可用的Python擴展包:

  • pgmagick-0.5.8.win-AMD64-py2.6.exe
  • pgmagick-0.5.8.win-AMD64-PY2 .7.exe
  • pgmagick-0.5.8。雙贏AMD64的py3.2.exe
  • pgmagick-0.5.8.win32-py2.6.exe
  • pgmagick-0.5.8.win32-py2.7.exe
  • pgmagick-0.5.8。 win32-py3.2.exe

2)然後你可以按照安裝說明從here

pip install pgmagick 

然後嘗試導入它。

>>> from pgmagick import gminfo 
>>> gminfo.version 
'1.3.x' 
>>> gminfo.library 
'GraphicsMagick' 
>>> 
+0

我看到了你的答案,但是我無法安裝ImageMagick。當我嘗試安裝模塊時,我總是收到錯誤消息「Magick ++ not found」。我嘗試安裝二進制文件。似乎已成功安裝,但似乎不起作用。我真的需要在源代碼上安裝嗎?或者我有什麼問題? – Macabeus 2014-12-06 20:02:59

+0

@KeplerBR您正在使用哪種操作系統?是的,我知道MagiC++是安裝pgmagick所需的依賴項,但它的價值在於它在許多情況下令人驚歎。 – 2014-12-06 21:06:09

+0

我的操作系統是Windows 7 – Macabeus 2014-12-07 00:39:49

1

這個怎麼樣?

from fpdf import FPDF 
from PIL import Image 
import glob 
import os 


# set here 
image_directory = '/path/to/imageDir' 
extensions = ('*.jpg','*.png','*.gif') 
# set 0 if you want to fit pdf to image 
# unit : pt 
margin = 10 

imagelist=[] 
for ext in extensions: 
    imagelist.extend(glob.glob(os.path.join(image_directory,ext))) 

for imagePath in imagelist: 
cover = Image.open(imagePath) 
width, height = cover.size 

pdf = FPDF(unit="pt", format=[width + 2*margin, height + 2*margin]) 
pdf.add_page() 

pdf.image(imagePath, margin, margin) 

destination = os.path.splitext(imagePath)[0] 
pdf.output(destination + ".pdf", "F") 
0

一些變化,從文件所在的位置

我把代碼並提出了一些細微的變化,使其可用,因爲它是DIR使PDF格式。

from fpdf import FPDF 
from PIL import Image 
import os # I added this and the code at the end 

def makePdf(pdfFileName, listPages, dir=''): 
    if (dir): 
     dir += "/" 

    cover = Image.open(dir + str(listPages[0])) 
    width, height = cover.size 

    pdf = FPDF(unit="pt", format=[width, height]) 

    for page in listPages: 
     pdf.add_page() 
     pdf.image(dir + str(page), 0, 0) 

    pdf.output(dir + pdfFileName + ".pdf", "F") 


# this is what I added 
x = [f for f in os.listdir() if f.endswith(".jpg")] 
y = len(x) 

makePdf("file", x) 
8

如果你使用Python 3,你可以使用Python模塊img2pdf

使用pip3 install img2pdf安裝它,然後你可以用用它在腳本 import img2pdf

示例代碼

import os 
import img2pdf 

with open("output.pdf", "wb") as f: 
    f.write(img2pdf.convert([i for i in os.listdir('path/to/imageDir') if i.endswith(".jpg")])) 
0

我有同樣的問題,所以我創建了一個python函數來合併多個圖片在一個pdf中。代碼(可從my github page,使用reportlab,並且是基於以下鏈接答案:

這裏是的例子如何將圖像合併爲pdf:

我們有文件夾「D:\ pictures」,包含類型爲png和jpg的圖片,我們希望創建文件pdf_with_pictures.pdf,並將它們保存在同一個文件夾中。

outputPdfName = "pdf_with_pictures" 
pathToSavePdfTo = "D:\\pictures" 
pathToPictures = "D:\\pictures" 
splitType = "none" 
numberOfEntitiesInOnePdf = 1 
listWithImagesExtensions = ["png", "jpg"] 
picturesAreInRootFolder = True 
nameOfPart = "volume" 

unite_pictures_into_pdf(outputPdfName, pathToSavePdfTo, pathToPictures, splitType, numberOfEntitiesInOnePdf, listWithImagesExtensions, picturesAreInRootFolder, nameOfPart) 
+0

如果您有新問題,請點擊[問問題](https://stackoverflow.com/questions/ask)按鈕。如果有助於提供上下文,請包含此問題的鏈接。 - [來自評論](/ review/low-quality-posts/17547199) – 2017-10-06 10:58:31

+0

這並沒有真正回答這個問題。如果您有不同的問題,可以通過單擊[提問](https://stackoverflow.com/questions/ask)來提問。您可以[添加賞金](https://stackoverflow.com/help/privileges/set-bounties)在您擁有足夠的[聲譽](https://stackoverflow.com/help/)後吸引更多關注此問題什麼聲譽)。 - [來自評論](/ review/low-quality-posts/17547199) – Pop 2017-10-06 11:17:06

1

多個圖像轉換爲PDF到目前爲止,我已經試過最好的方法是使用PIL純粹。這是很簡單但功能強大:

from PIL import Image 

im1 = Image.open("/Users/apple/Desktop/bbd.jpg") 
im2 = Image.open("/Users/apple/Desktop/bbd1.jpg") 
im3 = Image.open("/Users/apple/Desktop/bbd2.jpg") 
im_list = [im2,im3] 

pdf1_filename = "/Users/apple/Desktop/bbd1.pdf" 

im1.save(pdf1_filename, "PDF" ,resolution=100.0, save_all=True, append_images=im_list) 

只需設置save_allTrueappend_images到要添加圖像列表。您可能會遇到AttributeError: 'JpegImageFile' object has no attribute 'encoderinfo'。解決方法如下:Error while saving multiple JPEGs as a multi-page PDF

注意:安裝最新的PIL以確保save_all參數可用於PDF。

1
**** Convert images files to pdf file.**** 
from os import listdir 
from fpdf import FPDF 

path = "/home/bunny/images/" # get the path of images 

imagelist = listdir(path) # get list of all images 

pdf = FPDF('P','mm','A4') # create an A4-size pdf document 

x,y,w,h = 0,0,200,250 

for image in imagelist: 

    pdf.add_page() 
    pdf.image(path+image,x,y,w,h) 

pdf.output("images.pdf","F")