使用Python实现将图片(JPG/PNG)转换为PDF
作者:LSTM97
在数字化时代,图像与文档的转换与管理变得越来越重要。尤其是在需要将多张 JPG 或 PNG 图片合并成一份 PDF 文件时,使用 Python 编程语言提供了一种简单而高效的解决方案。本文将介绍如何利用 Spire.PDF for Python 库实现图像转换和合并操作。
一、工具准备
在开始之前,确保你已经安装了 Python 环境以及 Spire.PDF for Python 库。可以通过以下命令进行安装:
pip install Spire.PDF
此外,确保你的电脑上有需要转换的 JPG 或 PNG 图像,并将其放在一个文件夹中。
二、代码实现
以下是将 JPG 和 PNG 图片转换为 PDF 文件的示例代码:
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\Images\"
files = os.listdir(path)
# 遍历文件夹中的文件
for root, dirs, files in os.walk(path):
for file in files:
# 加载特定的图像
image = PdfImage.FromFile(os.path.join(root, file))
# 获取图像的宽度和高度
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# 添加页面,其大小与图像相同
page = doc.Pages.Add(SizeF(width, height))
# 在页面的 (0, 0) 位置绘制图像
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# 保存文件
doc.SaveToFile("output/CombineImages.pdf")
doc.Dispose()
三、代码解析
导入库 :首先,导入所需的 spire.pdf 和 os 库,后者用于文件和目录操作。
创建 PdfDocument 对象 :使用 PdfDocument() 初始化一个 PDF 文档对象,之后可以对该对象进行进一步操作。
设置页面边距 :调用 SetMargins(0.0) 方法,将页面边距设置为 0,这样图像可以完全填满整个页面。
读取图像 :使用 os.listdir(path) 获取指定目录下的所有文件,并使用 os.walk 遍历该目录中的所有文件。
加载和处理图像 :对于每个文件,使用 PdfImage.FromFile() 函数加载图像,并获取其宽度和高度。
添加页面 :根据图像的尺寸创建一个与其相同大小的页面,使用 doc.Pages.Add() 方法。
绘制图像 :使用 page.Canvas.DrawImage() 将图像绘制到页面的指定位置。
保存 PDF 文件 :最后,调用 doc.SaveToFile() 将合并后的 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.Width
height = 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()Python3将jpg转为pdf文件
#coding=utf-8
#!/usr/bin/env python
"""
convert image to pdf file
"""
#Author: mrbeann
import os
import sys
import glob
import platform
from reportlab.lib.pagesizes import letter, A4, landscape
from reportlab.platypus import SimpleDocTemplate, Image
from reportlab.lib.units import inch
from reportlab.pdfgen import canvas
from reportlab import rl_settings
from PIL import Image
import importlib,sys
#importlib.reload(sys)
#sys.setdefaultencoding("utf-8")
def topdf(path,recursion=None,pictureType=None,sizeMode=None,width=None,height=None,fit=None,save=None):
"""
Parameters
----------
path : string
path of the pictures
recursion : boolean
None or False for no recursion
True for recursion to children folder
wether to recursion or not
pictureType : list
type of pictures,for example :jpg,png...
sizeMode : int
None or 0 for pdf's pagesize is the biggest of all the pictures
1 for pdf's pagesize is the min of all the pictures
2 for pdf's pagesize is the given value of width and height
to choose how to determine the size of pdf
width : int
width of the pdf page
height : int
height of the pdf page
fit : boolean
None or False for fit the picture size to pagesize
True for keep the size of the pictures
wether to keep the picture size or not
save : string
path to save the pdf
"""
if platform.system() == 'Windows':
path = path.replace('\\','/')
if path[-1] != '/':
path = (path + '/')
if recursion == True:
for i in os.listdir(path):
if os.path.isdir(os.path.abspath(os.path.join(path, i))):
topdf(path+i,recursion,pictureType,sizeMode,width,height,fit,save)
filelist = []
if pictureType == None:
filelist = glob.glob(os.path.join(path, '*.jpg'))
else:
for i in pictureType:
filelist.extend(glob.glob(os.path.join(path, '*.'+i)))
maxw = 0
maxh = 0
if sizeMode == None or sizeMode == 0:
for i in filelist:
im = Image.open(i)
if maxw < im.size[0]:
maxw = im.size[0]
if maxh < im.size[1]:
maxh = im.size[1]
elif sizeMode == 1:
maxw = 999999
maxh = 999999
for i in filelist:
im = Image.open(i)
if maxw > im.size[0]:
maxw = im.size[0]
if maxh > im.size[1]:
maxh = im.size[1]
else:
if width == None or height == None:
raise Exception("no width or height provid")
maxw = width
maxh = height
maxsize = (maxw,maxh)
if save == None:
filename_pdf = path + path.split('/')[-2]
else:
filename_pdf = save + path.split('/')[-2]
filename_pdf = filename_pdf + '.pdf'
c = canvas.Canvas(filename_pdf, pagesize=maxsize )
l = len(filelist)
for i in range(l):
(w, h) =maxsize
width, height = letter
if fit == True:
c.drawImage(filelist[i] , 0,0)
else:
c.drawImage(filelist[i] , 0,0,maxw,maxh)
c.showPage()
c.save()
def main():
topdf(u'F:/gitplace/jpg2pdf/test',pictureType=['png','jpg'],save='F:/gitplace/jpg2pdf/test/新建文件夹')
if __name__ == '__main__':
main()五、总结
通过使用 Spire.PDF for Python 库,我们可以轻松地将多张 JPG 或 PNG 图像合并为一份 PDF 文件。这种方法不仅简单高效,而且在处理大量图像时表现出色。无论是工作还是个人项目,这种自动化的图片处理方式都能够节省大量时间。希望这篇文章能帮助你更好地掌握图像转换与合并的技巧!
到此这篇关于使用Python实现将图片(JPG/PNG)转换为PDF的文章就介绍到这了,更多相关Python图片转PDF内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
