Oli*_*eau 5 pdf text-extraction itext
我正在使用iText从pdf文件中的特定位置提取一些文本。为了做到这一点,我正在使用LocationTextExtractionStrategy:
public static void main(String[] args) throws Exception {
PdfReader pdfReader = new PdfReader("location_text_extraction_test.pdf");
Rectangle rectangle = new Rectangle(38, 0, 516, 516);
RenderFilter[] filter = {new RegionTextRenderFilter(rectangle)};
TextExtractionStrategy strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), filter);
String text = PdfTextExtractor.getTextFromPage(pdfReader, 1, strategy);
System.out.println(text);
pdfReader.close();
}
Run Code Online (Sandbox Code Playgroud)
问题在于提取的文本顺序错误:
应该提取为:
Run Code Online (Sandbox Code Playgroud)Part Description Quantity Unit Price Total For Line Extended Price Landing Fee 1.00 407.84 $ USD 407.84 407.84 $
提取为:
Run Code Online (Sandbox Code Playgroud)Total For Line Extended Price Part Description Quantity Unit Price 1.00 407.84 $ USD 407.84 407.84 $ Landing Fee
请注意,当我在Acrobat中打开pdf时,请使用Ctrl + A选择所有文本,进行复制,然后将其粘贴到文本编辑器中,一切均以正确的顺序进行。
有办法解决问题吗?非常感谢 ;)
造成这种情况的原因很简单,就是“线扩展总价”的y坐标为507.37,而“零件描述数量单价”的y坐标为506.42。
在LocationTextExtractionStrategy仅考虑y坐标的整数部分允许小的变化,但即使整数部分在这里有所不同。因此,它假定前一个标题位于后一个标题的上方,并相应地输出其结果。
如果发生这种变化,通常首先要尝试的是SimpleTextExtractionStrategy。不幸的是,这在这里无济于事,因为前者实际上是在后者之前绘制的。因此,此策略还会以错误的顺序返回标题。
在这种情况下,您需要一种工作原理不同的策略,例如,从以下版本开始使用的策略:HorizontalTextExtractionStrategy或HorizontalTextExtractionStrategy2(取决于您的iText版本,前一个取决于iText 5.5.8,后者针对当前的开发代码5.5.9-SNAPSHOT)这个答案。使用它,您将获得
Part Description Quantity Unit Price Total For Line Extended Price
Landing Fee 1.00 407.84 $ USD 407.84 407.84 $
Parking 1.00 101.96$ USD 101.96 101.96$
??? 1.00 51.65$ USD 51.65 51.65$
Pax Baggage Handling Fee 5.00 8.49$ USD 42.45 42.45 $
Pax Airport Tax 5.00 26.36 $ USD 131.80 131.80$
GA terminal for crew on Arr ferry fit 1.00 125.00$ USD 125.00 125.00$
VIP lounge for Pax on Dep. 5.00 124.00$ USD 620.00 620.00 $
GA terminal for crew on dep. 1.00 125.00$ USD 125.00 125.00$
VIP lounge for Guest on Dep. 1.00 38.00$ USD 38.00 38.00 $
Crew transfer on arr 1.00 70.00 $ USD 70.00 70.00 $
Crew transfer on dep 1.00 70.00 $ USD 70.00 70.00 $
Lavatory Service 1.00 75.00 $ USD 75.00 75.00 $
Catering-ISS 1.00 1,324.28 $ USD 1,324.28 1,324.28 $
Ground Handling 1.00 190.00$ USD 190.00 190.00$
Pax Handling 1.00 190.00$ USD 190.00 190.00$
Push Back 1.00 83.00 $ USD 83.00 83.00 $
Towing 1.00 110.00$ USD 110.00 110.00$
Run Code Online (Sandbox Code Playgroud)
(使用TextExtraction测试方法的结果testLocation_text_extraction_test)
但是,不幸的是,如果在不同的并排列中有重叠的行,这些策略将失败,例如,在您的单据中,发票收件人地址及其右侧的信息。
您可以尝试调整水平策略(例如,通过分析分隔列的水平间隙),也可以尝试组合方法,对同一文档使用多种策略的输出。