使用ITextSharp从PDF中获取除特定颜色以外的文本



我想从PDF文件中获取除红色文本以外的所有文本(坐标中的特定位置)。 这是我用来从PDF上的特定位置获取文本的代码

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];
LocationTextExtractionStrategy regionFilter = new LocationTextExtractionStrategy();
filters[0] = new RegionTextRenderFilter(customerIdRectangle);
FilteredTextRenderListener strategy = new FilteredTextRenderListener(regionFilter, filters);
try
{
output = PdfTextExtractor.GetTextFromPage(reader, i, strategy);
}
catch (Exception) { }
}

return output;
}

考虑到你的代码,你已经完成了一半!

您所要做的就是添加另一个RenderFilterfilters,一个阻止红色文本的。虽然核心 iText 发行版中不包含这样的过滤器类,但很容易实现:

  • 实现AllowImage始终返回true;
  • 实现AllowText以检查文本颜色。
    这里实际上有多个选项,但对于初学者来说,让我们假设使用默认的(填充的字形轮廓)。这意味着您只需使用其GetFillColor方法从TextRenderInfo对象中检索填充颜色并检查其红色。

最新更新