Python:PDF文件转图像

Python:PDF文件转图像

什么是PyMuPDF?

Python环境下想要将PDF文件转图像,可以使用PyMuPDF库。

PyMuPDF是MuPDF的Python绑定-“轻量级PDF和XPS查看器”。

MuPDF可以访问PDF,XPS,OpenXPS,CBZ(漫画书档案),FB2和EPUB(电子书)格式的文件,也可以是扩展名为.pdf,.xps,.oxps,.cbz,.fb2 或.epub的文件(因此您可以使用Python开发电子书查看器……),因此它不仅仅可以解析PDF文件。

支持的操作系统是哪些?

PyMuPDF可以在Mac,Linux,Windows XP SP2及更高版本上运行,Python 2.7到Python 3.7(请注意,Python仅支持v3.4以下的Windows XP),32位和64位版本上运行并经过测试。

只要MuPDF和Python支持它们,其他平台也应该可以正常工作。

支持的操作系统还是很广泛的。

如何安装PyMuPDF?

PyMuPDF托管在Github和PyPi上,因此我们可以很方便的安装。

pip install pymupdf

具体安装方法参考:

Installation — PyMuPDF 1.19.1 documentationhttps://pymupdf.readthedocs.io/en/latest/installation.html

PyMuPDF的前世今生

该库的标准Python import语句是import fitz。

这有历史原因:

MuPDF的原始渲染库称为Libart。

“在Artifex Software收购MuPDF项目之后,开发重点转移到编写名为* Fitz的新现代图形库。Fitz最初是作为一个研发项目来替代老化的Ghostscript图形库,但后来成为支持MuPDF的渲染引擎。” *(引自Wikipedia)。

转换图片代码

"""
****************************************************************************************************
@版权声明: Copyright (c) 2012-2021 LiuBing. All rights reserved.
@许可版本: Corporation & Enterprise
@创建时间: 2021-11-18
@创建作者: 370711753
@文件名称: pdf2image.py
@文件功能: PDF文件转图像.
@软件版本: V1.0.1
****************************************************************************************************
"""

####################################################################################################
# Linux/OS X 系统下声明这是一个 Python 可执行程序; Windows 系统会忽略这个注释.
# !/usr/bin/env python
# 指定 Python 解释器按照 UTF-8 编码读取源代码, 否则源代码中的中文输出时可能会乱码.
# -*- coding: utf-8 -*-

####################################################################################################
# 【系统模块】
# 加入“绝对引入”新特性:
# 这样就可用import string引入系统标准string.py, 而用from pkg import string来引入当前目录下的string.py.
from __future__ import absolute_import, division, print_function, unicode_literals
# 导入 os 库: 用于读取文件和目录结构.
import os
# 导入 sys 库: 包含与 Python 解释器和它的环境有关的函数.
import sys
# 导入 time 库: 用于获取时间信息.
import time
# 导入 fitz 库: PyMuPDF, 用于处理PDF.
import fitz


####################################################################################################
# 单个PDF文件转图像
def lmc_pdffile2image(pdf_file, image_path, image_format):
    """
        函数功能: 单个PDF文件转图像.
        pdf_file: 单个PDF文件名称.
        image_path: 图像保存路径.
        image_format: 图像格式.
    """
    # 开始时间
    time_start = time.time()
    # 检验PDF文件是否存在
    if not os.path.exists(pdf_file):
        print(f"PDF文件 {pdf_file} 不存在, 请您核查!")
        return
    else:
        print(f"PDF文件名称为: {pdf_file}")
    # 检验图像保存路径是否存在
    if not os.path.exists(image_path):
        print(f"图像保存路径 {image_path} 不存在, 自动创建!")
        os.makedirs(image_path)
    else:
        print(f"图像保存路径: {image_path}")
    # 检验文件名称是否合法
    if (image_format != "jpg") and (image_format != "bmp") and (image_format != "png") \
            and (image_format != "tif") and (image_format != "gif"):
        print(f"图像文件扩展名: {image_format} 不合法, 请您核查!")
    else:
        print(f"图像文件扩展名: {image_format}")
    # 打开PDF文件
    pdf_doc = fitz.open(pdf_file)
    # 遍历所有PDF页面
    for page_index in range(pdf_doc.pageCount):
        page = pdf_doc[page_index]
        rotate = int(0)
        # 默认页面转图片大小为: "letter": (612, 792), dpi=96
        # 页面缩放系数设为1.3, 这将生成分辨率提高2.6的图像.
        # (1.33333333-->816x1056)   (2-->1224x1584)
        zoom_x = 1.33333333
        zoom_y = 1.33333333
        # 页面缩放
        mat = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate)
        # 转化成图像
        pix = page.get_pixmap(matrix=mat, alpha=False)
        # 保存图像
        pix.save(image_path + '/' + '图像_%08d' % page_index + '.' + image_format)
        print(f"第 {page_index} 页转换完毕...")

    # 结束时间
    time_end = time.time()
    print(f"PDF文件转图像完毕, 总计耗时: %.3f秒!" % (time_end - time_start))


####################################################################################################
# 指定路径下所有PDF文件转图像
def lmc_pdfpath2image(pdf_path, image_format):
    """
        函数功能: 指定路径下所有PDF文件转图像.
        pdf_path: PDF文件路径.
        image_format: 图像格式.
    """
    # 开始时间
    time_start = time.time()
    # 检验PDF文件路径是否存在
    if not os.path.exists(pdf_path):
        print(f"PDF文件路径 {pdf_path} 不存在, 请您核查!")
        return
    else:
        print(f"PDF文件路径为: {pdf_path}")
    # 检验文件名称是否合法
    if (image_format != "jpg") and (image_format != "bmp") and (image_format != "png") \
            and (image_format != "tif") and (image_format != "gif"):
        print(f"图像文件扩展名: {image_format} 不合法, 请您核查!")
    else:
        print(f"图像文件扩展名: {image_format}")
    # 过滤指定路径下 PDF 文件
    pdf_files = list(filter(file_filter, os.listdir(pdf_path)))
    for pdf_file in pdf_files:
        image_path = os.path.splitext(pdf_file)[0]
        # 检验图像保存路径是否存在
        if not os.path.exists(image_path):
            print(f"图像保存路径 {image_path} 不存在, 自动创建!")
            os.makedirs(image_path)
        else:
            print(f"图像保存路径: {image_path}")
        # 打开PDF文件
        pdf_doc = fitz.open(pdf_file)
        # 遍历所有PDF页面
        for page_index in range(pdf_doc.pageCount):
            page = pdf_doc[page_index]
            rotate = int(0)
            # 默认页面转图片大小为: "letter": (612, 792), dpi=96
            # 页面缩放系数设为1.3, 这将生成分辨率提高2.6的图像.
            # (1.33333333-->816x1056)   (2-->1224x1584)
            zoom_x = 1.33333333
            zoom_y = 1.33333333
            # 页面缩放
            mat = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate)
            # 转化成图像
            pix = page.get_pixmap(matrix=mat, alpha=False)
            # 保存图像
            pix.save(image_path + '/' + '图像_%08d' % page_index + '.' + image_format)
            print(f"第 {page_index} 页转换完毕...")

    # 结束时间
    time_end = time.time()
    print(f"PDF文件转图像完毕, 总计耗时: %.3f秒!" % (time_end - time_start))


# 过滤器
def file_filter(f):
    if f[-4:] in ['.pdf', '.pdf', '.pdf']:
        return True
    else:
        return False


if __name__ == "__main__":
    # 单个PDF文件转图像
    # lmc_pdffile2image('1.pdf', './image', 'png')
    # lmc_pdffile2image(sys.argv[1], sys.argv[2], sys.argv[3])

    # 指定路径下所有PDF文件转图像
    # lmc_pdfpath2image('./', 'png')
    lmc_pdfpath2image(sys.argv[1], sys.argv[2])

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,我们可以使用Pillow库来处理图像,PyPDF2库来处理PDF文件。首先,需要使用Pillow库将骑缝章图像加载进来,然后计算放置图像的位置。接着,使用PyPDF2库打开PDF文件,添加图像,并保存新的PDF文件。 具体步骤如下: 1. 安装需要的库 在命令行中输入以下命令来安装Pillow和PyPDF2库。 ``` pip install Pillow pip install PyPDF2 ``` 2. 加载图像 使用Pillow库的`Image.open()`函数加载骑缝章图像。 ```python from PIL import Image image_path = 'path/to/image.jpg' image = Image.open(image_path) ``` 3. 计算放置位置 首先需要获取PDF页面的大小,可以通过PyPDF2库的`PdfFileReader()`和`getPage()`函数来获取。 ```python from PyPDF2 import PdfFileReader pdf_path = 'path/to/file.pdf' pdf_reader = PdfFileReader(open(pdf_path, 'rb')) page = pdf_reader.getPage(0) page_width = page.mediaBox.getWidth() page_height = page.mediaBox.getHeight() ``` 计算骑缝章图像的放置位置。这里假设骑缝章图像的大小是100x100像素,距离页面左边缘10像素,距离页面底边缘10像素。 ```python image_width = 100 image_height = 100 x = 10 y = 10 ``` 4. 添加图像 使用PyPDF2库的`PdfFileWriter()`和`addPage()`函数创建一个新的PDF文件,将原始PDF文件中的页面复制到新文件中,并在页面上添加骑缝章图像。 ```python from PyPDF2 import PdfFileReader, PdfFileWriter from io import BytesIO pdf_path = 'path/to/file.pdf' pdf_reader = PdfFileReader(open(pdf_path, 'rb')) pdf_writer = PdfFileWriter() for page_num in range(pdf_reader.getNumPages()): page = pdf_reader.getPage(page_num) page_width = page.mediaBox.getWidth() page_height = page.mediaBox.getHeight() overlay = Image.new('RGB', (page_width, page_height), (255, 255, 255, 0)) overlay.paste(image, (x, page_height - y - image_height)) overlay_pdf = BytesIO() overlay.save(overlay_pdf, format='png') overlay_pdf.seek(0) overlay_reader = PdfFileReader(overlay_pdf) page.mergePage(overlay_reader.getPage(0)) pdf_writer.addPage(page) with open('output.pdf', 'wb') as output_file: pdf_writer.write(output_file) ``` 最后,运行以上代码后,就会在`output.pdf`文件中看到添加了骑缝章图像PDF文件了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值