要將圖片添加到PDF文件中,可以使用Python的第三方庫PyPDF2
和PIL
。首先確保已經安裝了這兩個庫,如果沒有安裝,可以使用以下命令安裝:
pip install PyPDF2
pip install pillow
接下來,可以使用以下代碼將圖片添加到PDF文件中:
from PyPDF2 import PdfFileWriter, PdfFileReader
from PIL import Image
import io
def add_image_to_pdf(pdf_path, image_path, output_path):
# 讀取PDF文件
with open(pdf_path, "rb") as pdf_file:
pdf = PdfFileReader(pdf_file)
output = PdfFileWriter()
# 遍歷PDF的每一頁
for page_number in range(pdf.getNumPages()):
page = pdf.getPage(page_number)
output.addPage(page)
# 打開圖片并將其轉換為RGB模式
image = Image.open(image_path).convert("RGB")
# 將圖片轉換為PDF格式
image_pdf = io.BytesIO()
image.save(image_pdf, "PDF", resolution=100.0)
image_pdf.seek(0)
# 將圖片PDF添加到輸出PDF中
image_pdf_reader = PdfFileReader(image_pdf)
image_page = image_pdf_reader.getPage(0)
output.addPage(image_page)
# 保存帶有圖片的PDF文件
with open(output_path, "wb") as output_file:
output.write(output_file)
# 使用示例
add_image_to_pdf("input.pdf", "image.jpg", "output.pdf")
這段代碼定義了一個名為add_image_to_pdf
的函數,它接受三個參數:輸入的PDF文件路徑、要添加的圖片文件路徑以及輸出的PDF文件路徑。函數首先讀取輸入的PDF文件,然后遍歷每一頁,將其添加到輸出的PDF文件中。接著,它打開圖片文件,將其轉換為RGB模式,然后將其轉換為PDF格式。最后,將圖片PDF的第一頁添加到輸出PDF中,并保存結果。