【发布时间】:2014-01-18 06:33:45
【问题描述】:
我正在尝试使用 Square Annotation 从 pdf 中获取文本。我使用下面的代码使用 PDFBOX.
CODE
try {
PDDocument document = null;
try {
document = PDDocument.load(new File("//Users//" + usr + "//Desktop//BoldTest2 2.pdf"));
List allPages = document.getDocumentCatalog().getAllPages();
for (int i = 0; i < allPages.size(); i++) {
PDPage page = (PDPage) allPages.get(i);
Map<String, PDFont> pageFonts = page.getResources().getFonts();
List<PDAnnotation> la = page.getAnnotations();
for (int f = 0; f < la.size(); f++) {
PDAnnotation pdfAnnot = la.get(f);
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition(true);
PDRectangle rect = pdfAnnot.getRectangle();
float x = 0;
float y = 0;
float width = 0;
float height = 0;
int rotation = page.findRotation();
if (rotation == 0) {
x = rect.getLowerLeftX();
y = rect.getUpperRightY() - 2;
width = rect.getWidth();
height = rect.getHeight();
PDRectangle pageSize = page.findMediaBox();
y = pageSize.getHeight() - y;
}
Rectangle2D.Float awtRect = new Rectangle2D.Float(x, y, width, height);
stripper.addRegion(Integer.toString(f), awtRect);
stripper.extractRegions(page);
PrintTextLocation2 prt = new PrintTextLocation2();
if (pdfAnnot.getSubtype().equals("Square")) {
testTxt = testTxt + "\n " + stripper.getTextForRegion(Integer.toString(f));
}
}
}
} catch (Exception ex) {
} finally {
if (document != null) {
document.close();
}
}
} catch (Exception ex) {
}
通过使用此代码,我只能获取 PDF 文本。如何在文本中获取像 BOLD ITALIC 这样的字体信息。非常感谢您的建议或参考。
【问题讨论】:
-
查看this answer 以了解一般过程(源自
PDFTextStripper并覆盖writeString)及其当前问题。提供给该方法的TextPosition实例包含有关字体和绘制文本时其余当前状态的一些信息。是否必须从字体本身或某些图形状态中获取样式信息,取决于样式是如何生成的。
标签: java pdf fonts annotations pdfbox