I can set the src
of an image to preview a dropped image file, but how about a pdf?
(If not a preview thumbnail, then how about file type icons at least?)
I can set the src
of an image to preview a dropped image file, but how about a pdf?
(If not a preview thumbnail, then how about file type icons at least?)
Obviously, PDF files are not web compliant, so we have to make use of external libraries which help us deal with these type of files. A very well-known is the Mozilla PDF JS library.
Now do a preview of the first page of the pdf file.
//
// Asynchronous download PDF as an ArrayBuffer
//
PDFJS.disableWorker = true;
var pdf = document.getElementById('pdf');
pdf.onchange = function(ev) {
if (file = document.getElementById('pdf').files[0]) {
fileReader = new FileReader();
fileReader.onload = function(ev) {
// console.log(ev);
PDFJS.getDocument(fileReader.result).then(function getPdfHelloWorld(pdf) {
//
// Fetch the first page
//
// console.log(pdf)
pdf.getPage(1).then(function getPageHelloWorld(page) {
var scale = 0.5;
var viewport = page.getViewport(scale);
//
// Prepare canvas using PDF page dimensions
//
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
//
// Render PDF page into canvas context
//
var task = page.render({
canvasContext: context,
viewport: viewport
})
task.promise.then(function() {
// console.log(canvas.toDataURL('image/jpeg'));
});
});
}, function(error) {
// console.log(error);
});
};
fileReader.readAsArrayBuffer(file);
}
}
<script src="https://rawgithub.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<canvas id="the-canvas" style="border:1px solid black"></canvas>
<input id='pdf' type='file' />
The way to implement this is to get the file type when you are doing the upload of the pdf and save. when you displaying the record you can just do a check to see the file type