Rim
Rim

Reputation: 183

read pdf files using java

I want to parse pdf websites.

Can anyone say how to extract all the words (word by word) from a pdf file using java.

The code below extract content from a pdf file and write it in another pdf file. I want that the program write it in a text file.

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();

    }

}

Thanks in advance

Upvotes: 2

Views: 22673

Answers (2)

dina
dina

Reputation: 4289

using 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);
}

Upvotes: 1

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102448

Take a look at this:

How to Read PDF File in Java (uses Apache PDF Box library)

Upvotes: 2

Related Questions