In this article we’ll see how to create a preview of a PDF file selected for upload using the PDF.js library. This is an interoperable solution that works in various scenarios.
Let’s start with this HTML structure:
<form class="upload-form" action="#" method="post">
<div>
<label for="pdf">Upload PDF</label>
<div class="input-wrapper">
<input type="file" name="pdf" id="pdf" accept="application/pdf">
</div>
</div>
</form>
<div id="pdf-preview-wrapper">
<button type="button" id="pdf-preview-close">×</button>
<canvas id="pdf-preview"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<script src="script.js"></script>
With PDF.js we need to convert the File
object into a URL object containing the bytes of the chosen PDF file. We can then insert the preview of the first page of the document into the canvas.
function handleFile(input, wrapper, preview) {
input.addEventListener('change', async (e) => {
wrapper.classList.remove('visible');
document.body.classList.remove('preview-visible');
const file = e.target.files[0];
if (!file) return;
const fileURL = URL.createObjectURL(file);
const pdf = await pdfjsLib.getDocument(fileURL).promise;
const page = await pdf.getPage(1);
const scale = 1.5;
const viewport = page.getViewport({ scale });
preview.width = viewport.width;
preview.height = viewport.height;
const ctx = preview.getContext('2d');
const renderContext = {
canvasContext: ctx,
viewport: viewport,
};
wrapper.classList.add('visible');
document.body.classList.add('preview-visible');
await page.render(renderContext).promise;
});
}
Since we’re working with a canvas
element, we can of course resize the preview to fit the container by using the viewport’s width and height, with the scale
variable controlling the aspect ratio of the final preview.
Demo
Conclusion
PDF.js is an excellent solution for handling the display of PDF documents in the browser. In this case, it proves especially useful for managing an upload form.