如何用Spire.PDF替换PDF文本并保留原格式与颜色?
问题:Python PDF编辑工具无法保留文本原始颜色与格式
我正在开发一款可编辑PDF文档的Python工具,当前遇到的难题是替换文本时无法保留原始文本的颜色。
我尝试使用Spire.PDF库,它能保留文本的字号和字体,但无法保留颜色、粗体、斜体这类格式。
目前的代码如下:
from spire.pdf import * from spire.pdf.common import * # Create an object of PdfDocument pdf = PdfDocument() # Load a PDF document pdf.LoadFromFile("Spire.pdf") # Get user input for the text to replace input_text = input("Enter the text to replace: ") output_text = input("Enter the replacement text: ") # Loop through the pages in the document for i in range(pdf.Pages.Count): # Get a page page = pdf.Pages.get_Item(0) # Create an object of PdfTextReplacer class based on the page replacer = PdfTextReplacer(page) # Find and replace all matched text with a new color replacer.ReplaceAllText(input_text, output_text, Color.get_Black()) # Save the document pdf.SaveToFile("output/ReplaceAllMatches.pdf") pdf.Close() print(f"Text '{input_text}' has been replaced with '{output_text}' in the output PDF.")
我的目标是改进代码,让替换后的文本保留原始颜色、粗体、斜体、特定字体样式(比如Arial Regular、Arial Bold),确保编辑后的PDF和原文档视觉一致。
我考虑过换其他PDF处理库,或者深入研究Spire.PDF的功能,但还没找到可行方案。保留原始格式对维护PDF的完整性和美观性很重要,希望能得到改进代码的指导或建议。
解决方案
方案一:优化Spire.PDF代码,复用原始文本格式
不要直接使用指定固定颜色的ReplaceAllText方法,而是先定位文本的格式属性,再复用这些属性完成替换:
from spire.pdf import * from spire.pdf.common import * pdf = PdfDocument() pdf.LoadFromFile("Spire.pdf") input_text = input("Enter the text to replace: ") output_text = input("Enter the replacement text: ") for page_idx in range(pdf.Pages.Count): page = pdf.Pages.get_Item(page_idx) finder = PdfTextFinder(page) # 查找所有匹配文本 results = finder.FindAllText(input_text) for result in results: # 获取原始文本的格式信息 text_font = result.Font text_color = result.TextColor # 创建与原字体一致的字体对象 new_font = PdfTrueTypeFont(text_font.FontName, text_font.Size, text_font.Style, True) # 获取原文本的位置边界 bounds = result.Bounds # 用白色(或页面背景色)覆盖原文本 page.Canvas.DrawRectangle(PdfBrushes.get_White(), bounds) # 用原始格式绘制新文本 page.Canvas.DrawString(output_text, new_font, PdfBrushes.fromColor(text_color), bounds.X, bounds.Y) pdf.SaveToFile("output/ReplaceAllMatches_WithStyle.pdf") pdf.Close() print(f"Text '{input_text}' has been replaced with '{output_text}' while preserving original styles.")
注意:部分Spire.PDF免费版本可能限制Font、TextColor等属性的访问权限,需确认版本功能是否支持。
方案二:切换至PyMuPDF(fitz)库
PyMuPDF对PDF文本格式的解析更灵活,能轻松获取并复用文本的字体、颜色、样式属性:
import fitz doc = fitz.open("Spire.pdf") input_text = input("Enter the text to replace: ") output_text = input("Enter the replacement text: ") for page in doc: # 查找所有匹配文本的位置 text_instances = page.search_for(input_text) for inst in text_instances: # 遍历页面文本块,找到对应文本的格式信息 blocks = page.get_text("dict")["blocks"] for block in blocks: if "lines" in block: for line in block["lines"]: for span in line["spans"]: if span["text"] == input_text: # 获取原始格式参数 font_name = span["font"] font_size = span["size"] font_color = span["color"] # 覆盖原文本区域 rect = fitz.Rect(inst) page.draw_rect(rect, color=(1,1,1), fill=(1,1,1)) # 用原始格式写入新文本 page.insert_text( (rect.x0, rect.y0), output_text, fontname=font_name, fontsize=font_size, color=fitz.utils.get_color(font_color) ) doc.save("output/ReplaceWithPyMuPDF.pdf") doc.close() print(f"Text replacement completed with original styles preserved.")
内容的提问来源于stack exchange,提问作者georg
相关产品推荐
相关产品推荐

