Displaying a pdf from memory
If your web application reads zip or sqlite files, which could come with pdf's, they will be in memory instead of files. Since modern browsers all come with a pdf reader, I'll attempt to display them in a web application with the goal of providing the best reader experience using their built-in, most likely faster pdf rendering engine, compared to the javascript alternatives.
Click Compile to run the code.
Browser | Works? | Comment |
---|---|---|
Desktop | ||
Firefox 82.0.2 | Yes | Suggested filename when downloading: document.pdf |
Chrome 86.0.4240.111 | Yes | Suggested filename when downloading: {random guid}.pdf |
Edge 86.0.622.51 | Yes | Suggested filename when downloading: {random guid}.pdf |
Safari 11.1 * | Yes | Nothing happens when clicking the download button, borderRadius is ignored. |
Mobile | ||
iOS Safari 12.1 | Very limited | The iframe expands to the size of the first page of the pdf, and there's no way to interact with the document. |
Firefox for Android 82.1.1 | No | Pdf is offered as a download. |
Chrome for Android 86.0.4240.110 | No | A button with the text 'open' is displayed in the iframe, but clicking it does nothing. |
* Yes, my mac could use an update.
The browser chart suggests that displaying pdf's using the built-in pdf reader could be ideal when you only need to support desktop browsers. If mobile support is important and you don't mind creating the gui yourself, pdf.js might be a good choice, but don't expect great performance, I assume there's a reason Mozilla is not bundling this with Firefox for Android.
The filename is lost in the process, so if it's important for you to suggest a good filename when downloading, this answer might be worth investigating.
Firefox will happily allow the user to click the download button and store pdf's
locally, but Chrome and Edge fails with a network error because
URL.revokeObjectURL()
is called onload. Download button in Safari 11.1's
pdf reader does nothing, and removing the call to revokeObjectUrl has no effect. Let me
know your results if you test in a more recent Safari.
To prevent memory leaks, URL.revokeObjectURL()
should be called when
working with pdf's this way.
W3C: While not restricting number of uses of the blob URL offers more flexibility, it increases the likelihood of leaks; developers should pair it with a corresponding call to URL.revokeObjectURL().
The user can override default settings for their pdf reader, to prevent pdf's from being inlined (embedded in an iframe). This will cause the pdf to be offered as a download instead.