如何用Python将图片批量转换为PDF文件?
- 内容介绍
- 文章标签
- 相关推荐
本文共计218个文字,预计阅读时间需要1分钟。
安装第三方库:Linux平台使用sudo apt install python3-reportlab python3-pil
示例代码:pythonimport sysfrom reportlab.pdfgen import canvasfrom PIL import Image
def imgtopdf(input_paths, outputpath): maxw, maxh=Image.open(input_paths).size c=canvas.Canvas(outputpath) c.drawImage(input_paths, 0, 0, width=maxw, height=maxh) c.save()
安装第三方库
linux平台
示例代码
import sysfrom reportlab.pdfgen import canvas
from PIL import Image
def imgtopdf(input_paths, outputpath):
maxw, maxh = Image.open(input_paths).size
pdf_w,pdf_h = (480.28,702.78)
c = canvas.Canvas(outputpath, pagesize=(pdf_w,pdf_h))
if maxw/pdf_w > maxh/pdf_h:
c.drawImage(input_paths,0, (pdf_h-maxh*pdf_w/maxw)/2,pdf_w,maxh*pdf_w/maxw)
else:
c.drawImage(input_paths,(pdf_w-maxw*pdf_h/maxh)/2,0,maxw*pdf_h/maxh,pdf_h)
c.showPage()
c.save()
if __name__ == "__main__":
imgtopdf("test.png", "test.pdf")
1.实现了图片等比例缩小或放大到与pdf页面大小一致
2.pdf页面大小可以自定义 分别为pdf_w,pdf_h
作者:Hello_wshuo
本文共计218个文字,预计阅读时间需要1分钟。
安装第三方库:Linux平台使用sudo apt install python3-reportlab python3-pil
示例代码:pythonimport sysfrom reportlab.pdfgen import canvasfrom PIL import Image
def imgtopdf(input_paths, outputpath): maxw, maxh=Image.open(input_paths).size c=canvas.Canvas(outputpath) c.drawImage(input_paths, 0, 0, width=maxw, height=maxh) c.save()
安装第三方库
linux平台
示例代码
import sysfrom reportlab.pdfgen import canvas
from PIL import Image
def imgtopdf(input_paths, outputpath):
maxw, maxh = Image.open(input_paths).size
pdf_w,pdf_h = (480.28,702.78)
c = canvas.Canvas(outputpath, pagesize=(pdf_w,pdf_h))
if maxw/pdf_w > maxh/pdf_h:
c.drawImage(input_paths,0, (pdf_h-maxh*pdf_w/maxw)/2,pdf_w,maxh*pdf_w/maxw)
else:
c.drawImage(input_paths,(pdf_w-maxw*pdf_h/maxh)/2,0,maxw*pdf_h/maxh,pdf_h)
c.showPage()
c.save()
if __name__ == "__main__":
imgtopdf("test.png", "test.pdf")
1.实现了图片等比例缩小或放大到与pdf页面大小一致
2.pdf页面大小可以自定义 分别为pdf_w,pdf_h
作者:Hello_wshuo

