Convertire PDF in file di testo (PDF2TXT)

Un tool Open Source che consente di lavorare in Java con documenti PDF è Apache PDFBox. Questo strumento consente di creare PDF programmaticamente, di manipolare documenti esistenti e di estrarre il contenuto dai documenti. L'esempio che segue mostra come è possibile estrarre il contenuto da un PDF e salvarlo in un file di testo. Le due classi principali usate sono org.apache.pdfbox.pdmodel.PDDocument (la rappresentazione in-memory del documento PDF) e org.apache.pdfbox.util.PDFTextStripper (estrae il testo dal documento, ignorando la formattazione).


/**
 * Covert a PDF to a TXT file and remove the PDF
 * @param filePath the full path of the PDF file
 */
private void convertPdfToTxt(String filePath){
	//the pdf file
	File input = new File(filePath);
		
	// The text file where you are going to store the extracted data
	filePath = filePath.replace(".pdf", ".txt");
	File output = new File(filePath); 
	PDDocument pd = null;
	BufferedWriter wr = null;
	try {
		pd = PDDocument.load(input);
		PDFTextStripper stripper = new PDFTextStripper();
		wr = new BufferedWriter(new OutputStreamWriter
				(new FileOutputStream(output)));
		stripper.writeText(pd, wr);
	}
	catch(IOException e){
		System.out.println(e.getMessage());
	}
	catch(Exception e){
		System.out.println(e.getMessage());
	}
	finally {
		/*
		* Close streams
		*/
		if (pd != null) {
			try {
				pd.close();
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
		}
		//I use close() to flush the stream.
		try {
			if(wr!=null)
				wr.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
}