Dica Rápida: Leitura de PDF com PDFBox

Dica Rápida: Leitura de PDF com PDFBox

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/feltexco/public_html/felix/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/feltexco/public_html/felix/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Dica Rápida: Leitura de PDF com PDFBox


Olá amigos,
A dica de hoje é o PDFBox, mais um projeto Apache. Como o nome já sugere é este framework nos ajuda a manipular arquivos no formado PDF. Para isso mostraremos um código que faz a leitura de um arquivo simples e depois faremos alteração no programa para criar novas funcionalidades.

PDFBox

1. Fazendo a leitura do PDF


Crie um novo projeto e adicione a classe conforme o código abaixo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package br.com.feltex.lerpdf;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
 
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
 
public class LeituraPDFBox {
 
	public static void main(String args[]) {
		System.out.println("Inicio");
		PDFTextStripper pdfStripper = null;
		PDDocument pdDoc = null;
		COSDocument cosDoc = null;
		File file = new File("MeuArquivo.pdf");
		try {
			PDFParser parser = new PDFParser(new FileInputStream(file));
			parser.parse();
			cosDoc = parser.getDocument();
			pdfStripper = new PDFTextStripper();
			pdDoc = new PDDocument(cosDoc);
                        //Começa a leitura do arquivo a partir da página informada
                        // neste exemplo é a página "1"
			pdfStripper.setStartPage(1);
 
			pdfStripper.setEndPage(pdfStripper.getEndPage());
			String parsedText = pdfStripper.getText(pdDoc);
 
			Scanner s = new Scanner(parsedText);
			s.useDelimiter("\n");
 
			String linha = "";
			while (s.hasNext()) {
				linha = s.next();				
				System.out.println(linha);				
			}
			s.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("Fim");
	}
}

2. Criando um arquivo a partir da leitura do PDF


Agora vamos melhorar o nosso código gerando uma arquivo TXT a partir do PDF que foi lido.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package br.com.feltex.lerpdf;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
 
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
 
public class LeituraJava2 {
 
	public static void main(String args[]) {
		System.out.println("Inicio");
		PDFTextStripper pdfStripper = null;
		PDDocument pdDoc = null;
		COSDocument cosDoc = null;
		File file = new File(
				"MeuArquivo.pdf");
		try {
			PDFParser parser = new PDFParser(new FileInputStream(file));
			parser.parse();
			cosDoc = parser.getDocument();
			pdfStripper = new PDFTextStripper();
			pdDoc = new PDDocument(cosDoc);
			pdfStripper.setStartPage(1);
			pdfStripper.setEndPage(pdfStripper.getEndPage());
			String parsedText = pdfStripper.getText(pdDoc);
 
			PrintWriter saida = new PrintWriter(
					new File("D:/Temp/saidapdf.txt"));
 
			Scanner s = new Scanner(parsedText);
			s.useDelimiter("\n");
 
			String linha = "";
			while (s.hasNext()) {
				linha = s.next();
				saida.print(linha);
			}
			saida.close();
			s.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("Fim");
	}
}

3. Conclusão


Conseguimos, através do PDFBox, realizar a leitura de um arquivo PDF e também criamos um novo arquivo “txt” com o conteúdo encontrado no arquivo de origem. Com esse framework é possível também gerar arquivos, manipular imagens entre muitas outras ações com PDFs.
Na seção de Links relacionados acesse a página oficial do projeto e veja os vários exemplos disponíveis.

Abraços e bons estudos. No mais Vida que segue!!

Links relacionados


Site oficial do PDFBox
Criar arquivos PDF em Java iText
Projetos Completos em Java – aprenda na prática

Não esqueça de curtir este post nas redes sociais. Dê a sua contribuição social e ajude o autor:

Deixe um comentário