2

I have an InputStream which I would like to convert to a PDF, and save that PDF in a directory. Currently, my code is able to convert the InputStream to a PDF and the PDF does show up in the correct directory. However, when I try to open it, the file is damaged.

Here is the current code:

 InputStream pAdESStream = signingServiceConnector.getDirectClient().getPAdES(this.statusReader.getStatusResponse().getpAdESUrl()); 
            byte[] buffer = new byte[pAdESStream.available()];
            pAdESStream.read(buffer);

            File targetFile = new File(System.getProperty("user.dir") + "targetFile2.pdf");
            OutputStream outStream = new FileOutputStream(targetFile);
            outStream.write(buffer);

Originally, the InputStream was a pAdES-file (https://en.wikipedia.org/wiki/PAdES). However, it should be able to be read as just a regular PDF.

Does anyone know how to convert the InputStream to a PDF, without getting a damaged PDF as a result?

2
  • 3
    First thing to do is stop using available(). To read a stream completely, you should generally loop until read() returns -1. There are various third party libraries to simplify this, but fundamentally it's not terribly hard... typically you read into a buffer, copying into a ByteArrayOutputStream. Alternatively, if you're just copying the stream to a file, just loop reading from your input stream and writing to the file. Commented Jul 11, 2016 at 9:02
  • 1
    Just to stress @Jon's point: there are only very few InputStream implementations which return the full file size by available, in particular the FileInputStream. Most others merely return the bytes already fetched and residing e.g. in some buffer. Commented Jul 12, 2016 at 10:52

1 Answer 1

1

Hello it might be a bit late but you can use PDFBOX api (or itextpdf) https://www.tutorialkart.com/pdfbox/create-write-text-pdf-file-using-pdfbox/ here is a tuto of the process gl

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.