Cyberbunny Cyberbunny - 1 year ago 99
Java Question

Display PDF document stored in a ByteArrayOutputStream (not in a file)

I've created a PDF document (with iText) in a file and can diplay it on the screen with:

Document document = new Document();
PdfWriter.getInstance(document, filename);;
// ... write something to document
Desktop.getDesktop().open(new File(filename)); // works fine :-)

But on the machine of the customer my program will not have access to the filesystem, so I tried this:

Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ... write something to document

Which works, BUT then (of course)

Desktop.getDesktop().open(new File(baos)); //doesn't work :-(

It's not possible to show the PDF with

Is there a way to display the PDF stored in the ByteArrayOutputStream anyway?

Answer Source

PDF Viewers such as Adobe Reader need the PDF on the file system. Even if the PDF is served through a web server, Adobe Reader will download a local version to the client machine.

PDF Viewers such as Adobe Reader do not accept byte streams. You can't open Adobe Reader and "serve" a byte stream to it. You must always pass a path to a file.

You could work around this by serving a PDF through a web server to a browser. As indicated in the comments, you could create your own web server in Java using a ServerSocket, however:

  1. Firewalls will usually complain about this. An application that suddenly starts acting as a web server is considered suspicious.
  2. The EULA of Adobe Reader prohibits the use of Adobe Reader on the same machine that creates and serves a PDF. Hence you'll have to make sure that your users don't use Adobe Reader or they'll be in violation with the EULA of Adobe Reader.

Especially that last limitation makes the comment by Joop Eggen void. See section 3.2 of the EULA for Adobe Reader DC:

3.2 Server Use. This agreement does not permit you to install or Use the Software on a computer file server.

This clause was added after Adobe found out that people were building local server products that allowed people to use the free Adobe Reader to provide functionality that was only available in Adobe Professional (which is not free).

Long story short: you are trying to do something that isn't possible with the most common PDF viewer. You'll have to ship your application with a custom PDF viewer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download