Home > Software design >  How to read the pdf content from response and write it to another new pdf file
How to read the pdf content from response and write it to another new pdf file

Time:03-16

%PDF-1.4
%����
1 0 obj
<<
/Type /Catalog
/Pages 9 0 R
/Outlines 8 0 R
/Names 6 0 R

i am trying to read above pdf content response from rest end point in java class and trying to write it to another file but the file is getting corrupted and I could not view the pdf generated

File file = new File("Data.pdf");-- trying to write data to this
FileOutputStream out = new FileOutputStream(file)
\\service call to download pdf document
out.write(response.getBody().getBytes());

how to write the pdf content to another file or generate new pdf in a proper way?

CodePudding user response:

Basically you want to read from an InputStream and then write to an OutputStream. This question has been answered several times e.g. here, here and here and there are lots of possible solutions. Since you also tagged ioutils one possible way is to:

File file = new File("Data.pdf");
FileOutputStream out = new FileOutputStream(file)
IOUtils.copy(response.getBody(), out);

This presumes that response.getBody returns an InputStream. If you supply more code we can tell for sure. (This depends on your restclient implementation you are using like JAX-RS, Spring-Rest, Apache httpClient or HttpUrlConnection...

CodePudding user response:

PdfReader class in iText 7 has got an overloaded version that takes InputStream as an argument. Using this method, you can basically read the bytes of your first input pdf using ByteArrayInputStream. iText 7 has got a PDFWriter class that can write to an OutputStream too. Please refer to the following snippet. PdfDocument class then can read the input pdf file and write it to a new file using pdfWriter.

    //Pdf bytes returned by some rest API or method
    byte[] bytes = {};
    ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
    
    //File where you want to write the pdf and update some content
    File file = new File("Data.pdf");
    FileOutputStream out = new FileOutputStream(file);
    
    PdfDocument dd = new PdfDocument(new PdfReader(bin), new PdfWriter(out));
  • Related