2

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

Starkey
  • 9,673
  • 6
  • 31
  • 51
Rim
  • 185
  • 3
  • 3
  • 11
  • possible duplicate of [How to read PDF files using java](http://stackoverflow.com/questions/4784825/how-to-read-pdf-files-using-java) – Travis Mar 12 '15 at 13:36

2 Answers2

2

Take a look at this:

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

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
1

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);
}
dina
  • 4,039
  • 6
  • 39
  • 67
  • Can I read a pdf file partially? for example, only the first page, or until a certain text occurance, rather than reading the whole pdf file? so I can avoid downloading the whole file. – vasilevich Sep 27 '17 at 09:29