python實現圖片轉PDF
阿新 • • 發佈:2021-07-01
import os from PIL import Image from reportlab.pdfgen import canvas def image_resize(img, width, height): """ 圖片縮放 :param img: 圖片路徑 :param width: 寬 :param height: 高 :return: 寬高 """ image = Image.open(img) image.resize((width, height), Image.ANTIALIAS).save(img, quality=95, dpi=(72, 72)) return width, height def image_to_pdf(img, pdf_path=None, resize=True): """ 圖片轉PDF :param img: 圖片路徑 :param pdf_path: 生成的PDF路徑 :param resize: 是否縮放圖片至A4大小 :return: None """ pix_x, pix_y = 595, 842 # 解析度為72畫素時的A4紙大小 if not pdf_path: pdf_path = f'{os.path.splitext(img)[0]}.pdf' w, h = Image.open(img).size if resize: w, h = image_resize(img, pix_x, pix_y) width = (pix_x - w) // 2 height = (pix_y - h) // 2 user = canvas.Canvas(pdf_path) if width > 1 and height > 1: # 圖片size是否小於最小值 user.drawImage(img, width, height) # PDF中居中顯示 else: user.drawImage(img, 0, 0) else: user = canvas.Canvas(pdf_path, pagesize=(w, h)) user.drawImage(img, 0, 0) user.showPage() user.save()