PDFBOX, Reading a pdf line by line and extracting

2019-02-20 20:54发布

I am using pdfbox to extract text from pdf files. I read the pdf document as follows

    PDFParser parser = null;
    String text = "";
    PDFTextStripper stripper = null;
    PDDocument pdoc = null;
    COSDocument cdoc = null;
    File file = new File("path");

    try {
        parser = new PDFParser(new FileInputStream(file));
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        parser.parse();
        cdoc = parser.getDocument();
        stripper = new PDFTextStripper();
        pdoc = new PDDocument(cdoc);
        stripper.setStartPage(1);
        stripper.setEndPage(2);
        text = stripper.getText(pdoc);
        System.out.println(text);
    } catch (IOException e) {
        e.printStackTrace();
    }

But what I want to do is read the document line by line and to extract the text properties such as bold,italic, from each line. How can I achieve this with pdfbox library

标签: pdfbox
1条回答
2楼-- · 2019-02-20 21:42

extract the text properties such as bold,italic, from each line. How can I achieve this with pdfbox library

Properties such as bold and italic are not first-class properties in a PDF.

Bold or italic writing in PDFs is achieved either using

  • different fonts (which is the better way); in this case one can try to determine whether or not the fonts are bold or italic by

    • looking at the font name: it may contain a substring "bold", "italic", "oblique"...

    • looking at some optional properties of the font, e.g. font weight...

    • inspecting embedded font file.

    Neither of these methods is fool-proof; or

  • using the same font as for non-bold, non-italic text but using special techniques to make them appear bold or italic (aka poor man's bold), e.g.

    • not only filling the glyph contours but also drawing a thicker line along it for a bold impression,

    • drawing the glyph twice, the second time slightly displaced, also for a bold impression,

    • using a text or transformation matrix to slant the letters for an italic impression.

By overriding the PDFTextStripper methods with such tests accordingly, you may achieve a fairly good guess rate for styles during PDF text extraction.

查看更多
登录 后发表回答