reportlab 是 Python 經典 PDF 生成庫。本文示範將圖片等比縮放填滿 A4 橫向頁面,並擴充為批次處理多張圖片、多頁 PDF 與邊距控制的完整方案。
pip install reportlab Pillow
import sys
import os
from reportlab.lib.pagesizes import A4, landscape
from reportlab.pdfgen import canvas
from PIL import Image
def image_to_pdf(img_path, pdf_path=None):
if pdf_path is None:
pdf_path = os.path.splitext(img_path)[0] + '.pdf'
# 讀取圖片原始尺寸
with Image.open(img_path) as im:
img_w, img_h = im.size
# 目標頁面:A4 橫向
page_w, page_h = landscape(A4)
# 計算等比縮放比例(填滿頁面,保持比例)
scale = min(page_w / img_w, page_h / img_h)
draw_w, draw_h = img_w * scale, img_h * scale
# 置中座標
x = (page_w - draw_w) / 2
y = (page_h - draw_h) / 2
c = canvas.Canvas(pdf_path, pagesize=landscape(A4))
c.drawImage(img_path, x, y, width=draw_w, height=draw_h)
c.save()
print(f"完成:{pdf_path}")
if __name__ == '__main__':
if len(sys.argv) > 1:
for img in sys.argv[1:]:
image_to_pdf(img)
else:
print("用法:python img2pdf.py image1.jpg image2.png ...")
def images_to_pdf(image_paths, output_pdf, pagesize=landscape(A4), margin=20):
"""多張圖片各佔一頁,保持比例置中,支援邊距"""
page_w, page_h = pagesize
max_w, max_h = page_w - 2*margin, page_h - 2*margin
c = canvas.Canvas(output_pdf, pagesize=pagesize)
for img_path in image_paths:
with Image.open(img_path) as im:
img_w, img_h = im.size
scale = min(max_w / img_w, max_h / img_h)
draw_w, draw_h = img_w * scale, img_h * scale
x = margin + (max_w - draw_w) / 2
y = margin + (max_h - draw_h) / 2
c.drawImage(img_path, x, y, width=draw_w, height=draw_h)
c.showPage() # 換頁
c.save()
print(f"合併完成:{output_pdf}")
# 使用範例
import glob
imgs = sorted(glob.glob('photos/*.jpg'))
images_to_pdf(imgs, 'album.pdf')
| 參數 | 說明 |
|---|---|
canvas.Canvas(filename, pagesize) | 建立 PDF 畫布 |
drawImage(path, x, y, width, height) | 繪製圖片,支援 jpg/png/gif 等 |
showPage() | 結束當前頁、開始新頁 |
save() | 最終寫入檔案(必須呼叫) |
landscape(A4) | 預設頁面大小:595.28 x 841.89 pt(橫向互換) |
os.path.abspath 並確保路徑為 ASCII 或正確編碼。drawImage 會快取,大量處理時定期 c.save() 重新建立 canvas 或使用 c._doSave() 釋放。掌握 drawImage 座標計算與批次流程,即可快速構建圖片轉 PDF 自動化工具。