【发布时间】:2017-09-11 11:37:50
【问题描述】:
我正在使用 iTextSharp 从 PDF 文件中读取文本。为此,我正在使用 LocationTextExtractionStrategy 类。我有一个特定的文档,它的水平线横跨页面的整个宽度并位于页脚附近。此行用作正文文本和页脚内容之间的可视分区。
如何让 iTextSharp 读取这一行?
谢谢, 秀
【问题讨论】:
我正在使用 iTextSharp 从 PDF 文件中读取文本。为此,我正在使用 LocationTextExtractionStrategy 类。我有一个特定的文档,它的水平线横跨页面的整个宽度并位于页脚附近。此行用作正文文本和页脚内容之间的可视分区。
如何让 iTextSharp 读取这一行?
谢谢, 秀
【问题讨论】:
底层思路是实现IEventListener,然后监听PathRenderInfo事件。每当解析器遇到绘图指令时,它们基本上都会被调用。
您可以从 PathRenderInfo 轻松提取正在绘制的线条。然后您可以简单地查找 y 值最低的行(因为原点通常位于页面的左下方)。
我有这段代码在 Java 中,但对于 .net 来说应该非常相似。
public class FooterLine implements IEventListener {
private PdfPage pdfPage = null;
private double footerLineY = Double.MAX_VALUE;
public FooterLine(PdfPage pdfPage)
{
this.pdfPage = pdfPage;
process();
}
public double getFooterLineY()
{
return footerLineY;
}
private void process() {
PdfCanvasProcessor processor = new PdfCanvasProcessor(this);
processor.processPageContent(pdfPage);
}
@Override
public void eventOccurred(IEventData iEventData, EventType eventType) {
if(eventType == EventType.RENDER_PATH)
processPath((PathRenderInfo) iEventData);
}
private void processPath(PathRenderInfo pri)
{
for(Subpath subpath : pri.getPath().getSubpaths())
{
Point p0 = subpath.getStartPoint();
Point p1 = subpath.getLastPoint();
// only horizontal lines are allowed
if(p0.getY() != p1.getY())
continue;
footerLineY = java.lang.Math.min(footerLineY, p0.getY());
}
}
@Override
public Set<EventType> getSupportedEvents() {
return null;
}
}
【讨论】: