I've a signed applet that retrieves a PDF document from a web service, then stores it on a temp folder, and opens it on Adobe Reader. I would like to avoid storing the file locally, but I really don't know how to achieve it (I'm a newbie with Java applets).
If it were a web application (i.e. a simple servlet), I could just write the PDF content over the ServletResponse
; then the browser would store it on its temporary folder, and open it with Adobe Reader (or whatever application is associated with the MIME type).
Is there a similar way to do this... on a Java applet?
This is my code so far:
public class MyListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
// Retrieve the document contents
byte[] content = webService.getPdfDocument(...);
// Write to file
File f = new File("my-document-filename.pdf");
FileOutputStream fos = new FileOutputStream(f);
fos.write(content);
fos.close();
// Open the file
Desktop.getDesktop().open(new File("my-document-filename.pdf"));
}
}
Any alternative to Desktop.open(File), allowing me to pass a byte[]
instead of a File
?
Adobe reader can handle URL:s, so it could be a way forward to create a temporary (?) URL for the document.
Otherwise you can create a temporary file use File.createTempFile
, from the API:
Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that:
- The file denoted by the returned abstract pathname did not exist before this method was invoked, and
- Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.
This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit() method.
So in your case, instead of creating a new file yourself you can use this method:
File f = File.createTempFile("tmp", ".pdf");
f.deleteOnExit(); // deletes the file on exit
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With