使用java读取pdf文件

时间:2010-10-25 14:22:19

标签: java parsing pdf

我想解析pdf网站。

任何人都可以说如何使用java从pdf文件中提取所有单词(逐字逐句)。

下面的代码从pdf文件中提取内容并将其写入另一个pdf文件中。我希望程序将其写在文本文件中。

import java.io.FileOutputStream;

import java.io.IOException;

import com.itextpdf.text.*;

import com.itextpdf.text.pdf.*;

public class pdf {

    private static String INPUTFILE = "http://www.britishcouncil.org/learning-infosheets-medicine.pdf" ;

    private static String OUTPUTFILE = "c:/new3.pdf";

    public static void main(String[] args) throws DocumentException,
            IOException {

        Document document = new Document();

        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(OUTPUTFILE));

        document.open();

        PdfReader reader = new PdfReader(INPUTFILE);

        int n = reader.getNumberOfPages();

        PdfImportedPage page;


        for (int i = 1; i <= n; i++) {

                page = writer.getImportedPage(reader, i);

                Image instance = Image.getInstance(page);

                document.add(instance);

        }

        document.close();

    }

}

提前致谢

2 个答案:

答案 0 :(得分:2)

看看这个:

How to Read PDF File in Java(使用Apache PDF Box库)

答案 1 :(得分:0)

使用org.apache.pdfbox

import org.apache.pdfbox.*;

public static String convertPDFToTxt(String filePath) {
        byte[] thePDFFileBytes = readFileAsBytes(filePath);
        PDDocument pddDoc = PDDocument.load(thePDFFileBytes);
        PDFTextStripper reader = new PDFTextStripper();
        String pageText = reader.getText(pddDoc);
        pddDoc.close();
        return pageText;
}

private static byte[] readFileAsBytes(String filePath) {
        FileInputStream inputStream = new FileInputStream(filePath);
        return IOUtils.toByteArray(inputStream);
}