將圖片轉為 PDF 的主要原因之一是為了方便共享和傳輸。此外,將多張圖片合并成一個 PDF 文件還可以簡化文件管理。之前文章詳細介紹過如何使用第三方庫Spire.PDF for Python將PDF文件轉為圖片,那么本文介紹使用同樣工具在Python中實現圖片轉PDF文件的功能。
通過以下pip命令進行安裝Python庫:
pip install Spire.PDF
Python 實現圖片轉PDF
以下是將一個文件夾中的多張圖片轉換為一個PDF文件的示例。幾乎每行代碼都有詳細注釋,并且Spire.PDF for Python提供的接口也非常簡單易懂,大家可直接查看。
from spire.pdf.common import *
from spire.pdf import *
import os# 創建PdfDocument對象
doc = PdfDocument()# 將頁邊距設置為0
doc.PageSettings.SetMargins(0.0)# 指定存放圖片的文件夾路徑
path = "C:\\Users\\Administrator\\Desktop\\圖片\\"
files = os.listdir(path)# 遍歷文件夾中的文件
for root, dirs, files in os.walk(path):for file in files:# 加載圖片image = PdfImage.FromFile(os.path.join(root, file)) #FromFile(os.path.join(root, file))# 獲取圖片的寬度和高度width = image.PhysicalDimension.Widthheight = image.PhysicalDimension.Height# 在PDF中添加與圖片相同尺寸的頁面page = doc.Pages.Add(SizeF(width, height))# 從頁面的 (0, 0) 處開始繪制圖片page.Canvas.DrawImage(image, 0.0, 0.0, width, height)# 保存生成文件
doc.SaveToFile("圖片轉Pdf.pdf")
doc.Dispose()
?圖片轉PDF效果圖:
參考:
Python PDF庫下載鏈接https://www.e-iceblue.cn/Downloads/Spire-PDF-Python.html
Spire.PDF for Python 安裝教程https://www.e-iceblue.cn/pdf_python_other/how-to-install-spire-pdf-for-python-in-vs-code.html
Python 操作PDF教程https://www.e-iceblue.cn/pdfforpython/spire-pdf-for-python-program-guide-content.html
申請授權移除水印https://www.e-iceblue.cn/misc/temporary-license.html
?