如何在 Python 中将图像转换为 PDF

一、说明

如何使得图像转化成pdf文件, 想要将一个或多个图像转换为 PDF 文档?看看img2pdfPyPDF2软件包就是您的最佳选择。

二、需要哪些程序包?

首先,您只需要一个 Python 环境,最好是 3.10 或更高版本。本教程中的代码是在使用 Python 3.10.12 的 Google Colab 环境中执行的。

第一步是确保在 Python 环境中安装以下包:

  • img2pdf
  • PyPDF2
  • Pillow

Pip 可用于在 Colab 中安装这些软件包:

ba 复制代码
!pip install img2pdf PyPDF2 Pillow 

第一个包img2pdf将用于将图像转换为PDF文件。然后,PyPDF2 可用于将多个 PDF 合并为一个 PDF 文件。枕头是一个图像处理库;它提供了转换所需的附加功能。

现在可以导入这些包以及 和 。os``google.colab

ba 复制代码
# required libraries
import os
import img2pdf
import PyPDF2
from PIL import Image
from google.colab import files

三、img2pdf官方文档

img2pdf是一个开源的Python包,用于将图像转换为pdf格式。它包括另一个模块枕头,也可用于增强图像(亮度,对比度和其他东西) 使用此命令安装软件包

复制代码
pip install img2pdf

**以下是实现:**图像可以使用img2pdf模块提供的img2pdf.convert()函数转换为pdf字节,然后在wb模式下打开pdf文件并用字节写入。

  • python

# Python3 program to convert image to pdf

|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| # using img2pdf library # importing necessary libraries import img2pdf from PIL ``import Image import os # storing image path img_path ``= "C:``/``Users``/``Admin``/``Desktop``/``GfG_images``/``do_nawab.png" # storing pdf path pdf_path ``= "C:``/``Users``/``Admin``/``Desktop``/``GfG_images``/``file``.pdf" # opening image image ``= Image.``open``(img_path) # converting into chunks using img2pdf pdf_bytes ``= img2pdf.convert(image.filename) # opening or creating pdf file file = open``(pdf_path, "wb") # writing pdf files with chunks file``.write(pdf_bytes) # closing image file image.close() # closing pdf file file``.close() # output print``("Successfully made pdf ``file``") |

输出:

复制代码
Successfully made pdf file

四、准备映像

在编写更多代码之前,了解每个图像的文件位置非常重要。为了尽可能简化此操作,可以在 Colab 环境中创建一个新文件夹:

ba 复制代码
!mkdir images

所有图像都需要使用 提供的上传程序同时上传到此位置。这些文件将根据其名称进行排序,因此它们应命名为类似 .google.colab``page1.png, page2.png, ..., page9.png

ba 复制代码
os.chdir("images")
files.upload()

将图像存储在已知的文件位置后,其名称可以存储在列表中。

ba 复制代码
imgs = os.listdir()
imgs.sort()

如果图像超过 9 个,则此方法可能会出现问题,应按文件所需的顺序创建列表。

五、将图像转换为 PDF

然后可以使用 for 循环遍历每个图像,将其转换为 PDF,并将其写入名为 的新文件夹。pdfs

ba 复制代码
# create a folder called pdfs
os.mkdir("../pdfs")

# loop over each image
for ind, img in enumerate(imgs):
  # open each image
  with Image.open(img) as image: 
    # convert the image to a PDF
    pdf = img2pdf.convert(image.filename)
    # write the PDF to its final destination
    with open(f"../pdfs/pdf{ind+1}.pdf", "wb") as file:
      file.write(pdf)
      print(f"Converted {img} to pdf{ind+1}.pdf")

六、合并文档

将图像转换为 PDF 文件后,可以独立使用并使用 下载它们,也可以将它们合并在一起。要将文件合并在一起,请提取 PDF 文件列表并按页码对其进行排序。files.download('filename.pdf')

ba 复制代码
os.chdir("../pdfs")
pdfs = os.listdir()

同样,如果有超过 9 个图像或 PDF,它们应按各自的顺序存储在列表中。

对象可用于将每个 PDF 连接成单个文件。PdfMerger

ba 复制代码
pdfMerge = PyPDF2.PdfMerger()

# loop through each pdf page
for pdf in pdfs:
  # open each pdf
  with open(pdf, 'rb') as pdfFile:
    # merge each file
    pdfMerge.append(PyPDF2.PdfReader(pdfFile))

# write the merged pdf 
pdfMerge.write('merged.pdf')

# download the final pdf
files.download('merged.pdf')

最终合并的PDF将按其各自名称的顺序包含每个图像。

七、完整程序

完整的代码可以在下面找到。它是高度可定制的,以满足大多数用例。

ba 复制代码
!pip install img2pdf PyPDF2 Pillow
!mkdir images
# required libraries
import os
import img2pdf
import PyPDF2
from PIL import Image
from google.colab import files

os.chdir("images")
files.upload()
imgs = os.listdir()

# create a folder called pdfs
os.mkdir("../pdfs")

# loop over each image
for ind, img in enumerate(imgs):
  # open each image
  with Image.open(img) as image: 
    # convert the image to a PDF
    pdf = img2pdf.convert(image.filename)
    # write the PDF to its final destination
    with open(f"../pdfs/pdf{ind+1}.pdf", "wb") as file:
      file.write(pdf)
      print(f"Converted {img} to pdf{ind+1}.pdf")

os.chdir("../pdfs")
pdfs = os.listdir()
pdfs.sort()

pdfMerge = PyPDF2.PdfMerger()

# loop through each pdf page
for pdf in pdfs:
  # open each pdf
  with open(pdf, 'rb') as pdfFile:
    # merge each file
    pdfMerge.append(PyPDF2.PdfReader(pdfFile))

# write the merged pdf 
pdfMerge.write('merged.pdf')

# download the final pdf
files.download('merged.pdf')

八、引用

  1. https://www.geeksforgeeks.org/python-convert-image-to-pdf-using-img2pdf-module/
  2. Merging PDFs with Python | Python-bloggers
  3. 亨特·菲利普斯

·

相关推荐
叫我:松哥1 分钟前
基于Python flask的医院管理学院,医生能够增加/删除/修改/删除病人的数据信息,有可视化分析
javascript·后端·python·mysql·信息可视化·flask·bootstrap
Reese_Cool3 分钟前
【C语言二级考试】循环结构设计
android·java·c语言·开发语言
海里真的有鱼4 分钟前
Spring Boot 项目中整合 RabbitMQ,使用死信队列(Dead Letter Exchange, DLX)实现延迟队列功能
开发语言·后端·rabbitmq
zxctsclrjjjcph20 分钟前
【C语言】常见的C语言概念
c语言·开发语言
小灰灰爱代码25 分钟前
C++——求3个数中最大的数(分别考虑整数、双精度数、长整数的情况),用函数模板来实现。
开发语言·c++·算法
Eiceblue31 分钟前
Python 复制Excel 中的行、列、单元格
开发语言·python·excel
项目題供诗35 分钟前
尚品汇-秒杀商品存入缓存、Redis发布订阅实现状态位(五十一)
开发语言·php
m0_7145902643 分钟前
汇编(实现C语言程序的调用)
c语言·开发语言·汇编
NLP工程化1 小时前
对 Python 中 GIL 的理解
python·gil
做技术的Pandaer1 小时前
Go 第二期
开发语言·golang