How to read pdf file and write it to outputStream [closed]
Asked Answered
F

2

16

I need to read a pdf file with filepath "C:\file.pdf" and write it to outputStream. What is the easiest way to do that?

@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();
    }

}
}

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

Fourteen answered 3/6, 2013 at 7:20 Comment(4)
Your question seems to ask for a copying routine from file to a dedicated OutputStream and @Pheonix' answer shows how to do that --- is there any reason you have tagged your question [pdf] let alone [itext]?Rivera
I used Itext in my project for something else so I thought it may be useable in this example. I was wrong.Suds
Indeed, just like @Stephan's answer presented a solution using PDFBox, you could also have used iText to first parse the whole PDF and then serialize it again. But copying a PDF that way with a PDF library (be it PDFBox or iText) is a big waste of resources and may change the PDF in question.Rivera
Use Apache FileUtils: outputStream.write(FileUtils.readFileToByteArray(file));Fransiscafransisco
R
31
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();

    }

}

The easiest way so far. Hope this helps.

Relax answered 3/6, 2013 at 7:32 Comment(5)
Is there maybe something missing in your code or I missed something? File that I get has 0 bytes and I can't open it. I will edit my question with code.Suds
@JurajVlahović : works perfectly.Relax
can you take a quick look at my code, maybe I missed somethingSuds
I have found the problem. Now it works fine, I Will edit my code in question. Thx once againSuds
Maybe could be better to put the code that reads from the variable is inside a try-finally block and put the is.close() statement inside the finally to ensure that the reading resource is never left open? Same with the writing resource associated with the oos variable.Cheerio
A
11

You can use PdfBox from Apache which is simple to use and has good performance.

Here is an example of extracting text from a PDF file (you can read more 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();
        } 
     }
}

UPDATE:

You can get the text using PDFTextStripper:

PDFTextStripper reader = new PDFTextStripper();
String pageText = reader.getText(pd); // PDDocument object created
Aindrea answered 3/6, 2013 at 7:26 Comment(7)
Pdf contains pictures with some little text. I don't need to write it to txt or other file, just need to write it to OutputStream.Suds
this was only a example you can modify it easilyAindrea
Using a PDF processing library to copy a PDF is quite an overkill, isn't it...Rivera
its debatable ... if in the future it will need to do some modifications to the pdf and/or performance is not a huge factor i don't see why not to use a lib especially since its much cleaner since the lib is detached from the main app.Aindrea
thx for help, but I will use example above because it's simpler for what I need to do.Suds
np, of course but in the future if you need more complex actions on pdf you will need to use a lib.Aindrea
I need the exact formatting of both pdf which i want to merger into resulting pdf, but here its just continuous string. nee your suggestions.Indescribable

© 2022 - 2024 — McMap. All rights reserved.