2013-06-03 23 views
12

"P: \ file.pdf" dosya yoluna sahip bir pdf dosyasını okumalı ve bunu outputStream'e yazmam gerek. Bunu yapmanın en kolay yolu nedir?pdf dosyası nasıl okunur ve çıkışa yazılırStriptiz

@Controller 
public class ExportTlocrt { 

@Autowired 
private PhoneBookService phoneBookSer; 

private void setResponseHeaderTlocrtPDF(HttpServletResponse response) { 
    response.setContentType("application/pdf"); 
    response.setHeader("content-disposition", "attachment; filename=Tlocrt.pdf"); 
} 

@RequestMapping(value = "/exportTlocrt.html", method = RequestMethod.POST) 
public void exportTlocrt(Model model, HttpServletResponse response, HttpServletRequest request){ 

    setResponseHeaderTlocrtPDF(response); 
    File f = new File("C:\\Tlocrt.pdf"); 

    try { 
     OutputStream os = response.getOutputStream(); 
     byte[] buf = new byte[8192]; 
     InputStream is = new FileInputStream(f); 
     int c = 0; 
     while ((c = is.read(buf, 0, buf.length)) > 0) { 
      os.write(buf, 0, c); 
      os.flush(); 
     } 
     os.close(); 
     is.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 
} 

........................................... .................................................

+0

Sorunuz, dosyadan özel bir 'OutputStream' ve @Pheonix'e bir kopyalama yordamının sorulmasını istiyor 'cevabı nasıl yapılacağını gösterir --- sorunuzu etiketlemenizin herhangi bir sebebi var [pdf] yalnız [itext] ? – mkl

+0

Projemde başka bir şey için Itext kullandım, bu yüzden bu örnekte kullanılabilir olduğunu düşündüm. Ben hatalıydım. –

+0

Aslında, tıpkı Stephan'ın yanıtının PDFBox kullanarak bir çözüm sunduğu gibi, tüm PDF'yi ayrıştırmak ve daha sonra yeniden serileştirmek için iText'i de kullanabilirsiniz. Ancak bir PDF kütüphanesi (PDFBox veya iText olsun) ile PDF'leri kopyalamak büyük bir kaynak israfıdır ve söz konusu PDF'yi değiştirebilir. – mkl

cevap

24
import java.io.*; 


public class FileRead { 


    public static void main(String[] args) throws IOException { 


     File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf"); 

     OutputStream oos = new FileOutputStream("test.pdf"); 

     byte[] buf = new byte[8192]; 

     InputStream is = new FileInputStream(f); 

     int c = 0; 

     while ((c = is.read(buf, 0, buf.length)) > 0) { 
      oos.write(buf, 0, c); 
      oos.flush(); 
     } 

     oos.close(); 
     System.out.println("stop"); 
     is.close(); 

    } 

} 

Şimdiye kadar en kolay yolu. Bu yardımcı olur umarım.

+0

Thx. Bu tam ihtiyacım olan şey. –

+1

Kodunuzda bir şey eksik mi ya da bir şeyleri özledim mi? Aldığım dosya 0 bayt ve açamıyorum. Sorumu koduyla düzenleyeceğim. –

+0

@ JurajVlahović: Mükemmel çalışıyor. – ankurtr

10

Kullanımı kolay ve iyi bir performansa sahip olan Apache'den PdfBox'u kullanabilirsiniz. İşte

bir PDF dosyasından metin ayıklamak bir örnektir (okuyabilir daha here):

import java.io.*; 
import org.apache.pdfbox.pdmodel.*; 
import org.apache.pdfbox.util.*; 

public class PDFTest { 

public static void main(String[] args){ 
PDDocument pd; 
BufferedWriter wr; 
try { 
     File input = new File("C:\\Invoice.pdf"); // The PDF file from where you would like to extract 
     File output = new File("C:\\SampleText.txt"); // The text file where you are going to store the extracted data 
     pd = PDDocument.load(input); 
     System.out.println(pd.getNumberOfPages()); 
     System.out.println(pd.isEncrypted()); 
     pd.save("CopyOfInvoice.pdf"); // Creates a copy called "CopyOfInvoice.pdf" 
     PDFTextStripper stripper = new PDFTextStripper(); 
     wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output))); 
     stripper.writeText(pd, wr); 
     if (pd != null) { 
      pd.close(); 
     } 
     // I use close() to flush the stream. 
     wr.close(); 
} catch (Exception e){ 
     e.printStackTrace(); 
     } 
    } 
} 

GÜNCELLEME:

Sen PDFTextStripper kullanarak metin alabilirsiniz:

PDFTextStripper reader = new PDFTextStripper(); 
String pageText = reader.getText(pd); // PDDocument object created 
+0

Pdf, bazı küçük metin içeren resimler içeriyor. Bunu txt veya başka bir dosyaya yazmam gerekmiyor, sadece bunu OutputStream'e yazmam gerek. –

+0

Bu sadece kolayca değiştirebileceğiniz bir örnektir. – Stephan

+0

Benim güncellenmiş cevabımı görün – Stephan