如何用iText查找指定颜色PDF文本并替换颜色(保留标签树)
问题:替换PDF中指定颜色的文本颜色(基于iText,保留标签树)
我需要查找PDF中指定颜色的文本并将其替换为新颜色。Acrobat可实现此功能,但低级编辑会破坏标签树,因此希望用iText自动化该任务。
我的应用主要基于标签树开展无障碍相关操作,但颜色信息并不存储在标签树中。遍历大量标签未发现颜色内容,且PAC与iText Rups在标签树中也不显示颜色信息。
我推测需深入PDF“底层”操作,但不确定方法。查阅PDF标准后发现颜色信息存储在标识符rg之后,iText Rups在内容流中显示如下内容:
EMC
/Standard <<;/MCID 0 >> BDC
q
0 0 0 rg --------------------- Sets color to black for this word
BT
56.8 724.1 Td
/F1 12 Tf
<0102030405> Tj
ET
Q
EMC
请问如何在iText中访问该内容流?或是否有无需深入此层级的实现方式?我更倾向于使用PdfStructs或标签树相关对象操作。
补充:已编写的测试代码
参考相关思路后,我编写了如下代码,目前已能识别特定颜色,但仍需解决如何修改现有颜色的问题,看起来可能需要重写页面内容而非修改现有文档:
class Program { static void Main(string[] args) { string inputPdfPath = "input.pdf"; string outputPdfPath = "output.pdf"; // set up PDF PdfReader reader = new(inputPdfPath); PdfWriter writer = new(outputPdfPath); PdfDocument pdfDocument = new PdfDocument(reader, writer); pdfDocument.SetTagged(); // Search each page with the processor MyProcessor editor = new MyProcessor(new Listener()); for (int i = 1; i <= pdfDocument.GetNumberOfPages(); i++) { editor.EditPage(pdfDocument, i); } pdfDocument.Close(); } } public class MyProcessor : PdfCanvasProcessor { public MyProcessor(IEventListener eventListener) : base(eventListener) {} protected override void EventOccurred(IEventData data, EventType type) { // Only inspect text, ignore null objects if (data != null) { if (type is EventType.RENDER_TEXT) { TextRenderInfo txt = (TextRenderInfo)data; Console.WriteLine(txt.GetText()); foreach (var color in txt.GetFillColor().GetColorValue()) { Console.Write(color + " "); } Console.WriteLine(""); } } base.EventOccurred(data, type); } public void EditPage(PdfDocument pdfDocument, int pageNumber) { PdfPage page = pdfDocument.GetPage(pageNumber); PdfResources pdfResources = page.GetResources(); PdfCanvas pdfCanvas = new PdfCanvas(new PdfStream(), pdfResources, pdfDocument); ProcessContent(page.GetContentBytes(), pdfResources); } } public class Listener : IEventListener { public void EventOccurred(IEventData data, EventType type) {} public ICollection<EventType> GetSupportedEvents() { return new Collection<EventType>() { EventType.BEGIN_TEXT, EventType.RENDER_TEXT, EventType.END_TEXT, EventType.RENDER_IMAGE, EventType.RENDER_PATH, EventType.CLIP_PATH_CHANGED }; } }
内容的提问来源于stack exchange,提问作者Mytho
相关产品推荐
相关产品推荐

