Welcome folks today in this blog post we will be using vue.js
to render pdf documents
in browser using pdf.js
and pdfjs-dist
library using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below libraries using the npm
command as shown below
npm i pdfjs-dist
And after that you need to see the below directory structure
of the vue.js
app as shown below
And after that you need to copy paste the following code inside the App.vue
file as shown below
App.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<template> <div id="app"> <PdfViewer/> </div> </template> <script> import PdfViewer from "./components/PdfViewer"; export default { name: "App", components: { PdfViewer } }; </script> <style> #app { font-family: "Avenir", Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; background-color: black; padding: 50px; } </style> |
As you can see we are importing the PdfViewer
component and then we are also writing the custom
css and also we need to make the pdfviewer
component inside the components folder
components/PdfViewer.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<template> <div id="pageContainer"> <div id="viewer" class="pdfViewer"></div> </div> </template> <script> import pdfjsLib from "pdfjs-dist/build/pdf"; import { PDFViewer } from "pdfjs-dist/web/pdf_viewer"; import "pdfjs-dist/web/pdf_viewer.css"; pdfjsLib.GlobalWorkerOptions.workerSrc = "https://cdn.jsdelivr.net/npm/pdfjs-dist@2.0.943/build/pdf.worker.min.js"; export default { name: "PdfViewer", mounted() { this.getPdf(); }, methods: { async getPdf() { let container = document.getElementById("pageContainer"); let pdfViewer = new PDFViewer({ container: container }); let loadingTask = pdfjsLib.getDocument("./pdf-sample.pdf"); let pdf = await loadingTask.promise; pdfViewer.setDocument(pdf); } } }; </script> <style> #pageContainer { margin: auto; width: 80%; } div.page { display: inline-block; } </style> |
As you can see we are loading the pdfjs-dist
library and then we are initializing the pdfviewer
library passing the container
object. And then we are using the pdfjslib
library method to load the pdf document and then we are using the setDocument()
to set the contents of the pdf document.