Today I learnt how to use PDF.js to add a PDF preview to a HTML form without having to upload the file to a server.
I needed this to build a multi-step form that shows a preview before we have reached the last step in the form submission.
A demo is worth a thousand words:
Check out the code of the codepen to see how it is done.
A advantage of doing the rendering on the client side is that you do not have to upload the PDF first. This can be a huge benefit if your users are on a slow internet connection and have large files.
A drawback of using PDF.js is that if your PDF is expensive to render, it can take a while to get that preview image on a low powered device like a mobile phone.
One thing that took me a while to figure out is that you should not include the
pdf.worker.js via a
<script> tag. Instead you should set
pdfjsLib.GlobalWorkerOptions.workerSrc = "https://unpkg.com/pdfjs-dist/build/pdf.worker.js" in your JS. Figuring this out
took a while because a lot of examples either load it in
<script> tag or do
not make any mention of it. If you load it the wrong way you will see a warning
in your console about PDF.js using a "dummy worker".