pymupdf
安装
pip install pymupdf
pip install fitz
直接转换成图片输出
# 读取到内存
pdf_document = fitz.open()
image = fitz.open(image_path)
pdf_bytes = image.convert_to_pdf()
image_pdf = fitz.open("pdf", pdf_bytes)
def images_to_pdf(image_list: list[str], output_pdf_path: str):
"""
将图片列表合并为一个 PDF 文件。
Args:
image_list (list): 包含图片路径的列表,按合并顺序排列。
output_pdf_path (str): 输出 PDF 文件的路径。
"""
# 创建一个新的 PDF 文档
pdf_document = fitz.open()
for image_path in image_list:
# 打开图片
image = fitz.open(image_path)
# 将图片转换为 PDF 页面
rect = image[0].rect # 获取图片的矩形尺寸
pdf_bytes = image.convert_to_pdf()
image_pdf = fitz.open("pdf", pdf_bytes)
# 插入页面到 PDF 文档
pdf_document.insert_pdf(image_pdf)
image.close()
# 保存 PDF 文件
pdf_document.save(output_pdf_path)
pdf_document.close()
在内存中通过PIL打开
from PIL import Image, ImageFont, ImageDraw, ImageFile
pdf_document = fitz.open(pdf_path)
matrix = fitz.Matrix(1, 1)
pix = page.get_pixmap(matrix=matrix)
img = Image.open(io.BytesIO(pix.tobytes()))
img.save()