首页 > 编程问答 >Python PDF 编辑器

Python PDF 编辑器

时间:2024-07-25 13:16:18浏览次数:11  
标签:python pdf

我将制作一个 PDF 编辑器,它可以更改 PDF 中的单词,而无需更改文本的来源。

这是我的代码,到目前为止,它所做的一切都是正确的,但我可以获得文本颜色和文本大小。

import pymupdf
import os

# Open the PDF document
doc = pymupdf.open('input.pdf')

# Load the custom font file
font_file = os.path.join(os.path.dirname(__file__), 'BMWGroupTNCondensed-Regular.otf')
with open(font_file, 'rb') as f:
    font_buffer = f.read()

# Iterate over each page of the document
for page in doc:
    # Find all instances of "2024" on the current page
    instances = page.search_for("2024")

    # Create a list to store the replacement coordinates
    replacement_coords = []

    # Redact each instance of "2024" on the current page and replace with "2025"
    for inst in instances:
        page.add_redact_annot(inst)
        replacement_coords.append((inst.x0, inst.y0))

    # Apply the redactions to the current page
    page.apply_redactions()

    # Insert the custom font in the PDF document
    page.insert_font(fontname="BMWGroupTNCondensed-Regular", fontbuffer=font_buffer)

    # Insert the new text "2025" at the redacted locations using the custom font
    for x, y in replacement_coords:
        page.insert_text((x, y + 10), "2025", fontname="BMWGroupTNCondensed-Regular", fontsize=12)

# Save the modified document
doc.save('modified_document.pdf')

# Close the document
doc.close()

我尝试了很多不同的 Bibiliotheks,但没有成功


不幸的是,使用 PyMuPDF(以前称为 fitz)直接操纵现有 PDF 文本的颜色和大小会很复杂。 PyMuPDF 主要用于创建、读取和注释 PDF,对修改现有文本样式的支持有限。

以下是原因和可能的解决方法:

  1. PDF 的结构: PDF 文件没有像 Word 文档那样的文本样式概念。文本和样式通常在 PDF 内部定义为绘制指令,这使得在不重建整个页面布局的情况下进行更改成为一项艰巨的任务。

  2. PyMuPDF 的功能: 虽然 PyMuPDF 允许添加具有特定样式的新文本(如的代码所示),但它不提供直接修改现有文本的字体、大小或颜色的方法。

可能的解决方法:

  1. 使用 OCR 和页面重建:

  2. 使用 OCR(光学字符识别)引擎(如 Tesseract)从 PDF 页面中提取文本内容以及其位置和样式信息。

  3. 使用 PyMuPDF 或类似库创建一个新的 PDF 页面。
  4. 使用提取的文本和样式信息(包括所需的更改),在空白页面上“绘制”文本。这使可以完全控制文本样式。

  5. 探索其他库:

  6. ReportLab: 一个功能强大的 PDF 生成库,可以对文本样式进行更精细的控制。但是,可能需要结合使用 PyMuPDF 来提取内容并使用 ReportLab 重新创建页面。

  7. PDFMiner.six: 用于 PDF 解析和分析的另一个库。它可以帮助提取文本样式信息,但可能需要大量的操作才能实现所需的修改。

  8. 使用外部工具:

  9. 考虑使用命令行工具(如 pdftk Ghostscript )进行更底层的 PDF 操作。这些工具可能提供更改文本外观的选项,但可能需要更复杂的脚本编写。

示例(使用 OCR 和 PyMuPDF 重建页面):

import pymupdf
import pytesseract  # 需要安装 Tesseract OCR 引擎和 pytesseract

def modify_pdf_text(input_path, output_path):
    doc = pymupdf.open(input_path)

    for page_num in range(len(doc)):
        page = doc[page_num]

        # 使用 OCR 提取文本和边界框
        image = page.get_pixmap()
        text_data = pytesseract.image_to_data(image, output_type=pytesseract.Output.DICT)

        # 创建一个新的空白页面
        new_page = doc.new_page(pno=-1, width=page.mediabox_width, height=page.mediabox_height)

        for i in range(len(text_data['text'])):
            text = text_data['text'][i]
            x, y, w, h = text_data['left'][i], text_data['top'][i], text_data['width'][i], text_data['height'][i]

            if text.strip(): # 忽略空白文本
                # 根据需要应用文本样式修改
                if text == "2024":
                    new_page.insert_text((x, y), "2025", fontsize=14, color=(1, 0, 0)) # 红色,更大
                else:
                    new_page.insert_text((x, y), text)

    doc.save(output_path)
    doc.close()

modify_pdf_text('input.pdf', 'modified_document.pdf')

重要提示:

  • OCR 并不总是完美的,尤其是对于复杂布局或字体。
  • 页面重建可能很耗时,尤其是对于大型 PDF 文档。

请记住,修改 PDF 文本样式是一项复杂的任务,可能需要进行大量的实验和调整才能获得所需的结果。

标签:python,pdf
From: 78791533

相关文章