使用ITextSharp从PDF指定坐标区域提取非红色文本的实现问题
解决方案
你当前使用的iText(iTextSharp)默认的文本提取策略不会校验文本颜色,需要自定义文本提取策略,在渲染文本节点时过滤掉红色文本。
步骤1:自定义支持颜色过滤的文本提取策略
using iTextSharp.text.pdf.parser; using iTextSharp.text; public class FilterRedTextExtractionStrategy : LocationTextExtractionStrategy { public override void RenderText(TextRenderInfo renderInfo) { // 获取当前文本的填充色 BaseColor fillColor = renderInfo.GetFillColor(); // 过滤标准RGB红色(R=255、G=0、B=0),如果是CMYK红色可自行调整判断逻辑 if (fillColor != null && fillColor.R == 255 && fillColor.G == 0 && fillColor.B == 0) { // 红色文本直接跳过不提取 return; } // 非红色文本走默认提取逻辑 base.RenderText(renderInfo); } }
步骤2:修改原有提取方法,替换为自定义策略
public string ReadTextFromRectangle(string pdfPath, int numberOfPages, float x, float y, float width, float height) { this.PdfPath = pdfPath; this.NumberOfPages = numberOfPages; this.X = x; this.Y = y; this.Width = width; this.Height = height; var reader = new PdfReader(PdfPath); System.util.RectangleJ customerIdRectangle = new System.util.RectangleJ(X, Y, Width, Height); string output = ""; for (int i = 1; i <= NumberOfPages; i++) { RenderFilter[] filters = new RenderFilter[1]; // 替换为自定义的过滤红色的提取策略 FilterRedTextExtractionStrategy regionFilter = new FilterRedTextExtractionStrategy(); filters[0] = new RegionTextRenderFilter(customerIdRectangle); FilteredTextRenderListener strategy = new FilteredTextRenderListener(regionFilter, filters); try { // 若只需要返回匹配到的第一页内容,把+=改为=即可 output += PdfTextExtractor.GetTextFromPage(reader, i, strategy); } catch (Exception) { } } reader.Close(); return output; }
注:原代码存在多页提取时仅保留最后一页内容的问题,上述代码已经修正为多页内容拼接,可根据实际需求调整。
内容的提问来源于stack exchange,提问作者user15519784
相关产品推荐
相关产品推荐

