Ajuda para abrir varios arquivos pdf editaveis e jogar as string num txt
5 respostas
B
belotabeto
Pessoal oque tenho que fazer é o seguinte, tenho uma pasta predefina onde vão ser salvos diariamente varios pdfs editaveis , oque tenho que fazer é pegar o texto dos pdfs e jogar cada um em um notepad diferente, Consegui fazer usando a classe pdfparser porem só consigo se especificar qual é o arquivo e ele salva em um unico pdf, Gostaria que para cada arquivo que tivesse na pasta gera-se um novo documento do tipo txt. segue meu código!
packageteste;importjava.io.BufferedReader;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileWriter;importjava.io.IOException;importjava.io.InputStreamReader;importorg.apache.pdfbox.pdfparser.PDFParser;importorg.apache.pdfbox.pdmodel.PDDocument;importorg.apache.pdfbox.util.PDFTextStripper;publicclassPdfParser{publicstaticvoidmain(String[]args){PdfParserpdf=newPdfParser();pdf.setEnderecoRecurso("C:\\NNpdf\\luuuuu0001(1).pdf");Stringretorno=pdf.getConteudo();FileWriterx;try{x=newFileWriter("C:\\NNpdf\\teste.txt",false);x.write(retorno);x.close();FileInputStreamstream=newFileInputStream("C:\\NNpdf\\teste.txt");StringBuildertxt=newStringBuilder();InputStreamReaderstreamReader=newInputStreamReader(stream);BufferedReaderreader=newBufferedReader(streamReader);Stringline=null;while((line=reader.readLine())!=null){txt.append(line);txt.append("\n");if(line.contains(" ")){txt.append(line.replaceAll(" ",";"));txt.append("\n");}}System.out.println(txt);}catch(IOExceptione){// TODO Auto-generated catch blocke.printStackTrace();}}privateStringenderecoRecurso;publicvoidsetEnderecoRecurso(StringenderecoRecurso){this.enderecoRecurso=enderecoRecurso;// endereço dos arquivos}publicStringgetConteudo(){Filef=newFile(this.enderecoRecurso);FileInputStreamis=null;try{is=newFileInputStream(f);}catch(IOExceptione){System.out.println("ERRO: "+e.getMessage());returnnull;}PDDocumentpdfDocument=null;try{PDFParserparser=newPDFParser(is);parser.parse();pdfDocument=parser.getPDDocument();PDFTextStripperstripper=newPDFTextStripper();returnstripper.getText(pdfDocument);}catch(IOExceptione){return"ERRO: Não é possível abrir a stream"+e.getLocalizedMessage();}catch(Throwablee){// Fazemos um catch, uma vez que precisamos de fechar o recursoreturn"ERRO: Um erro ocorreu enquanto tentava obter o conteúdo do PDF "+e.getLocalizedMessage()+" Causa "+e.getCause();}finally{if(pdfDocument!=null){try{pdfDocument.close();}catch(IOExceptione){return"ERRO: Não foi possível fechar o PDF. "+e.getLocalizedMessage()+" Causa "+e.getCause();}}}}}
Veja os comentários e vê se ajuda. Não testei e nem tentei compilar. Só tentei elaborar a lógica.
O melhor a fazer é dar uma estudada em Orientação ao Objeto. Seu programa está muito estruturado, tem método que lê arquivo e escreve outro arquivo ao mesmo tempo. Tente separar esses métodos.
publicclassPdfParser{publicstaticvoidmain(String[]args){PdfParserpdf=newPdfParser();// diretórioFiledir=newFile("C:\\NNpdf\\");// Lista os arquivos do diretóriofor(Filearq:dir.listFiles()){// Seta o endereço do arquivopdf.setEnderecoRecurso(arq.getCanonicalPath());Stringretorno=pdf.getConteudo();/* * */FileWriterx;try{//Gera um novo arquivo txt, mantendo o nome do pdf para fazer referência do arquivo migradoStringarquivoTxt=arq.getName()+".txt";x=newFileWriter(arquivoTxt,false);x.write(retorno);x.close();FileInputStreamstream=newFileInputStream(arquivoTxt);StringBuildertxt=newStringBuilder();InputStreamReaderstreamReader=newInputStreamReader(stream);BufferedReaderreader=newBufferedReader(streamReader);Stringline=null;while((line=reader.readLine())!=null){txt.append(line);txt.append("\n");if(line.contains(" ")){txt.append(line.replaceAll(" ",";"));txt.append("\n");}}System.out.println(txt);}}catch(IOExceptione){// TODO Auto-generated catch block e.printStackTrace();}}privateStringenderecoRecurso;publicvoidsetEnderecoRecurso(StringenderecoRecurso){this.enderecoRecurso=enderecoRecurso;// endereço dos arquivos }publicStringgetConteudo(){Filef=newFile(this.enderecoRecurso);FileInputStreamis=null;try{is=newFileInputStream(f);}catch(IOExceptione){System.out.println("ERRO: "+e.getMessage());returnnull;}PDDocumentpdfDocument=null;try{PDFParserparser=newPDFParser(is);parser.parse();pdfDocument=parser.getPDDocument();PDFTextStripperstripper=newPDFTextStripper();returnstripper.getText(pdfDocument);}catch(IOExceptione){return"ERRO: Não é possível abrir a stream"+e.getLocalizedMessage();}catch(Throwablee){// Fazemos um catch, uma vez que precisamos de fechar o recurso return"ERRO: Um erro ocorreu enquanto tentava obter o conteúdo do PDF "+e.getLocalizedMessage()+" Causa "+e.getCause();}finally{if(pdfDocument!=null){try{pdfDocument.close();}catch(IOExceptione){return"ERRO: Não foi possível fechar o PDF. "+e.getLocalizedMessage()+" Causa "+e.getCause();}}}}}
B
belotabeto
não funcionou amigo ficou assim o codigo:
packageteste;importjava.io.BufferedReader;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileWriter;importjava.io.IOException;importjava.io.InputStreamReader;importorg.apache.pdfbox.pdfparser.PDFParser;importorg.apache.pdfbox.pdmodel.PDDocument;importorg.apache.pdfbox.util.PDFTextStripper;publicclassPdfParser{publicstaticvoidmain(String[]args){PdfParserpdf=newPdfParser();// diretório Filedir=newFile("C:\\NNpdf\\");// Lista os arquivos do diretório for(Filearq:dir.listFiles()){// Seta o endereço do arquivo try{pdf.setEnderecoRecurso(arq.getCanonicalPath());}catch(IOExceptione1){// TODO Auto-generated catch blocke1.printStackTrace();}Stringretorno=pdf.getConteudo();/* * */FileWriterx;try{//Gera um novo arquivo txt, mantendo o nome do pdf para fazer referência do arquivo migrado StringarquivoTxt=arq.getName()+".txt";x=newFileWriter(arquivoTxt,false);x.write(retorno);x.close();FileInputStreamstream=newFileInputStream(arquivoTxt);StringBuildertxt=newStringBuilder();InputStreamReaderstreamReader=newInputStreamReader(stream);BufferedReaderreader=newBufferedReader(streamReader);Stringline=null;while((line=reader.readLine())!=null){txt.append(line);txt.append("\n");if(line.contains(" ")){txt.append(line.replaceAll(" ",";"));txt.append("\n");}}System.out.println(txt);}catch(IOExceptione){// TODO Auto-generated catch block e.printStackTrace();}}}privateStringenderecoRecurso;publicvoidsetEnderecoRecurso(StringenderecoRecurso){this.enderecoRecurso=enderecoRecurso;// endereço dos arquivos }publicStringgetConteudo(){Filef=newFile(this.enderecoRecurso);FileInputStreamis=null;try{is=newFileInputStream(f);}catch(IOExceptione){System.out.println("ERRO: "+e.getMessage());returnnull;}PDDocumentpdfDocument=null;try{PDFParserparser=newPDFParser(is);parser.parse();pdfDocument=parser.getPDDocument();PDFTextStripperstripper=newPDFTextStripper();returnstripper.getText(pdfDocument);}catch(IOExceptione){return"ERRO: Não é possível abrir a stream"+e.getLocalizedMessage();}catch(Throwablee){// Fazemos um catch, uma vez que precisamos de fechar o recurso return"ERRO: Um erro ocorreu enquanto tentava obter o conteúdo do PDF "+e.getLocalizedMessage()+" Causa "+e.getCause();}finally{if(pdfDocument!=null){try{pdfDocument.close();}catch(IOExceptione){return"ERRO: Não foi possível fechar o PDF. "+e.getLocalizedMessage()+" Causa "+e.getCause();}}}}}
B
belotabeto
Obs: não está jogando a string do pdf no texto nem gerando um arquivo de texto para cada pdf.
B
belotabeto
Ele esta abrindo todos os arquivos porem não esta salvando cada arquivo em um .txt
lucasportela
Correção então:
// Seta o endereço do arquivo pdf.setEnderecoRecurso(arq.getPath());Stringretorno=pdf.getConteudo();