如何使用pdfbox从pdf中提取粗体文本?
我正在使用Apache pdfbox来提取文本。 我可以从pdf中提取文本,但我不知道如何知道这个词是否是粗体??? (代码建议会很好!!!)这是从pdf中提取纯文本的代码,该代码工作正常。
PDDocument document = PDDocument .load("/home/lipu/workspace/MRCPTester/test.pdf"); document.getClass(); if (document.isEncrypted()) { try { document.decrypt(""); } catch (InvalidPasswordException e) { System.err.println("Error: Document is encrypted with a password."); System.exit(1); } } // PDFTextStripperByArea stripper = new PDFTextStripperByArea(); // stripper.setSortByPosition(true); PDFTextStripper stripper = new PDFTextStripper(); stripper.setStartPage(1); stripper.setEndPage(2); stripper.setSortByPosition(true); String st = stripper.getText(document);
PDFTextStripper
的结果是纯文本。 因此,提取后,为时已晚。 但是你可以覆盖它的某些方法,只允许通过根据你的意愿格式化的文本。
如果是PDFTextStripper
,则必须覆盖
protected void processTextPosition( TextPosition text )
在您的覆盖中,您可以检查相关文本是否满足您的要求( TextPosition
包含有关所讨论文本的大量信息,而不仅仅是文本本身),如果有,则将TextPosition text
转发给super
实现。
但主要问题是识别哪个文本是粗体 。
粗体的标准可能是字体名称中的粗体字,例如Courier-BoldOblique – 您使用text.getFont()
访问文本的字体,使用字体的getBaseFont()
方法访问字体的postscript名称
String postscriptName = text.getFont().getBaseFont();
条件也可以来自字体描述符 – 使用getFontDescriptor
方法获取字体的字体描述符,字体描述符具有可选的字体权重值
float fontWeight = text.getFont().getFontDescriptor().getFontWeight();
该值定义为
(可选; PDF 1.5;应用于标记PDF文档中的Type 3字体)完全限定字体名称或字体说明符的权重(厚度)组件。 可能的值应为100,200,300,400,500,600,700,800或900,其中每个数字表示至少与其前身一样暗的重量。 值400表示正常体重; 700应表示粗体。
这些值的具体解释因字体而异。
一种字体的示例300可能看起来与另一种字体中的500最相似。
(表122,第9.8.1节,ISO 32000-1)
可能还有其他提示要检查粗体 ,例如大线宽
double lineWidth = getGraphicsState().getLineWidth();
当渲染模式也绘制轮廓时:
int renderingMode = getGraphicsState().getTextState().getRenderingMode();
您可能需要尝试使用手头的文件,这些标准就足够了。