將多個圖片轉換為PDF文件在Python中可以通過多個庫來實現,其中最常用的庫之一是Pillow
(用于圖像處理)和reportlab
(用于生成PDF)。不過,對于直接圖片轉PDF的操作,更推薦使用Pillow
配合PyMuPDF
(又名fitz
)或者img2pdf
庫,這些庫提供了更簡潔的接口。
以下是一個使用Pillow
和img2pdf
庫的示例,來將多個圖片轉換為PDF文件:
- 首先,確保你已經安裝了所需的庫。你可以使用以下命令來安裝它們:
pip install pillow img2pdf
- 然后,使用以下Python代碼將多個圖片轉換為PDF:
from PIL import Image
import img2pdf
import osdef images_to_pdf(image_paths, output_pdf_path):# 打開所有的圖片并保存到一個列表中with open(output_pdf_path, "wb") as pdf_file:images = [Image.open(img_path).convert("RGB") for img_path in image_paths]# 使用img2pdf將圖片列表轉換為PDF并寫入文件pdf_file.write(img2pdf.convert(images))# 示例:將當前目錄下的所有jpg圖片轉換為PDF
input_directory = '.' # 當前目錄
output_pdf_path = 'output.pdf'# 獲取當前目錄下所有的jpg圖片路徑
image_files = [f for f in os.listdir(input_directory) if f.lower().endswith('.jpg')]
image_paths = [os.path.join(input_directory, img_file) for img_file in image_files]# 調用函數將圖片轉換為PDF
images_to_pdf(image_paths, output_pdf_path)print(f"PDF文件已生成: {output_pdf_path}")
在這個示例中:
images_to_pdf
函數接收一個圖片路徑列表和一個輸出PDF路徑。- 使用
Pillow
庫的Image.open
打開每個圖片,并將其轉換為RGB模式(如果需要處理其他圖片格式,如PNG,可以省略convert("RGB")
部分)。 - 使用
img2pdf.convert
將圖片列表轉換為PDF二進制數據,并寫入指定的PDF文件中。
你可以根據需要修改這個腳本,比如處理其他圖片格式(如PNG),或者從其他目錄讀取圖片。
希望這對你有所幫助!