使用Python實(shí)現(xiàn)將圖片(JPG/PNG)轉(zhuǎn)換為PDF
在數(shù)字化時(shí)代,圖像與文檔的轉(zhuǎn)換與管理變得越來越重要。尤其是在需要將多張 JPG 或 PNG 圖片合并成一份 PDF 文件時(shí),使用 Python 編程語言提供了一種簡單而高效的解決方案。本文將介紹如何利用 Spire.PDF for Python 庫實(shí)現(xiàn)圖像轉(zhuǎn)換和合并操作。
一、工具準(zhǔn)備
在開始之前,確保你已經(jīng)安裝了 Python 環(huán)境以及 Spire.PDF for Python 庫。可以通過以下命令進(jìn)行安裝:
pip install Spire.PDF
此外,確保你的電腦上有需要轉(zhuǎn)換的 JPG 或 PNG 圖像,并將其放在一個(gè)文件夾中。
二、代碼實(shí)現(xiàn)
以下是將 JPG 和 PNG 圖片轉(zhuǎn)換為 PDF 文件的示例代碼:
from spire.pdf.common import *
from spire.pdf import *
import os
# 創(chuàng)建 PdfDocument 對象
doc = PdfDocument()
# 設(shè)置頁面邊距為 0
doc.PageSettings.SetMargins(0.0)
# 獲取圖片存儲(chǔ)文件夾路徑
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()
三、代碼解析
導(dǎo)入庫 :首先,導(dǎo)入所需的 spire.pdf 和 os 庫,后者用于文件和目錄操作。
創(chuàng)建 PdfDocument 對象 :使用 PdfDocument() 初始化一個(gè) PDF 文檔對象,之后可以對該對象進(jìn)行進(jìn)一步操作。
設(shè)置頁面邊距 :調(diào)用 SetMargins(0.0) 方法,將頁面邊距設(shè)置為 0,這樣圖像可以完全填滿整個(gè)頁面。
讀取圖像 :使用 os.listdir(path) 獲取指定目錄下的所有文件,并使用 os.walk 遍歷該目錄中的所有文件。
加載和處理圖像 :對于每個(gè)文件,使用 PdfImage.FromFile() 函數(shù)加載圖像,并獲取其寬度和高度。
添加頁面 :根據(jù)圖像的尺寸創(chuàng)建一個(gè)與其相同大小的頁面,使用 doc.Pages.Add() 方法。
繪制圖像 :使用 page.Canvas.DrawImage() 將圖像繪制到頁面的指定位置。
保存 PDF 文件 :最后,調(diào)用 doc.SaveToFile() 將合并后的 PDF 文件保存到指定路徑。
四、方法補(bǔ)充
Python 實(shí)現(xiàn)圖片轉(zhuǎn)PDF
以下是將一個(gè)文件夾中的多張圖片轉(zhuǎn)換為一個(gè)PDF文件的示例。幾乎每行代碼都有詳細(xì)注釋,并且Spire.PDF for Python提供的接口也非常簡單易懂,大家可直接查看。
from spire.pdf.common import *
from spire.pdf import *
import os
# 創(chuàng)建PdfDocument對象
doc = PdfDocument()
# 將頁邊距設(shè)置為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("圖片轉(zhuǎn)Pdf.pdf")
doc.Dispose()Python3將jpg轉(zhuǎn)為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()五、總結(jié)
通過使用 Spire.PDF for Python 庫,我們可以輕松地將多張 JPG 或 PNG 圖像合并為一份 PDF 文件。這種方法不僅簡單高效,而且在處理大量圖像時(shí)表現(xiàn)出色。無論是工作還是個(gè)人項(xiàng)目,這種自動(dòng)化的圖片處理方式都能夠節(jié)省大量時(shí)間。希望這篇文章能幫助你更好地掌握圖像轉(zhuǎn)換與合并的技巧!
到此這篇關(guān)于使用Python實(shí)現(xiàn)將圖片(JPG/PNG)轉(zhuǎn)換為PDF的文章就介紹到這了,更多相關(guān)Python圖片轉(zhuǎn)PDF內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python輕松實(shí)現(xiàn)將圖片轉(zhuǎn)換為PDF并合并
- Python批量實(shí)現(xiàn)PDF轉(zhuǎn)換為圖片(JPG/PNG)
- Python編程之PDF轉(zhuǎn)圖片的三種實(shí)現(xiàn)方法詳解
- Python實(shí)現(xiàn)將PDF文檔轉(zhuǎn)換為圖片的示例代碼
- Python使用pdf2image實(shí)現(xiàn)PDF轉(zhuǎn)圖片的完整指南
- 利用Python實(shí)現(xiàn)文檔格式互轉(zhuǎn)的操作大全(PDF、Word、圖片、Markdown)
- 利用Python將PDF文件轉(zhuǎn)換為PNG圖片的代碼示例
- Python腳本實(shí)現(xiàn)將PDF批量轉(zhuǎn)換為圖片
相關(guān)文章
python神經(jīng)網(wǎng)絡(luò)Keras?GhostNet模型的實(shí)現(xiàn)
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)Keras?GhostNet模型的復(fù)現(xiàn)詳解,2022-05-05
pandas數(shù)據(jù)框,統(tǒng)計(jì)某列數(shù)據(jù)對應(yīng)的個(gè)數(shù)方法
下面小編就為大家分享一篇pandas數(shù)據(jù)框,統(tǒng)計(jì)某列數(shù)據(jù)對應(yīng)的個(gè)數(shù)方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
Python快速實(shí)現(xiàn)從PDF中提取文本與圖像坐標(biāo)的終極指南
在數(shù)據(jù)處理工作中,提取 PDF 文檔中的文本和圖像坐標(biāo)是一個(gè)常見需求,本文將介紹如何使用 Spire.PDF for Python 庫實(shí)現(xiàn)這一功能,通過簡單的代碼示例幫助你快速上手2026-01-01
python 使用OpenCV進(jìn)行簡單的人像分割與合成
這篇文章主要介紹了python 使用OpenCV進(jìn)行簡單的人像分割與合成的方法,幫助大家更好的利用python處理圖像,感興趣的朋友可以了解下2021-02-02

