首页 文章

如何使用pdfbox从pdf中提取粗体文本?

提问于
浏览
6

我正在使用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);

1 回答

  • 17

    PDFTextStripper 的结果是纯文本 . 因此,提取后,为时已晚 . 但是你可以覆盖它的某些方法,只允许通过根据你的意愿格式化的文本 .

    如果是 PDFTextStripper ,您必须覆盖

    protected void processTextPosition( TextPosition text )
    

    在您的覆盖中,您可以检查相关文本是否满足您的要求( TextPosition 包含有关相关文本的大量信息,而不仅仅包含文本本身),如果有,请将 TextPosition text 转发给 super 实现 .

    但主要问题是识别哪个文本是 bold .

    粗体的标准可以是字体名称中的粗体字,例如, 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)

    可能还有其他提示要检查 bold -ism,例如线宽很大

    double lineWidth = getGraphicsState().getLineWidth();
    

    当渲染模式也绘制轮廓时:

    int renderingMode = getGraphicsState().getTextState().getRenderingMode();
    

    您可能需要尝试使用手头的文件,这些标准就足够了 .

相关问题