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

こ雲淡風輕ζ 提交于 2019-12-13 02:18:52

问题


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);
document.open();
// ... write something to document
document.close();
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();
PdfWriter.getInstance(document,baos);
document.open();
// ... write something to document
document.close();

Which works, BUT then (of course)

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

It's not possible to show the PDF with Desktop.getDesktop().open.

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


回答1:


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.



来源:https://stackoverflow.com/questions/36363205/display-pdf-document-stored-in-a-bytearrayoutputstream-not-in-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!