Vue.js Render PDF Document in PDF.js Using PDFjs-dist Library Full Tutorial For Beginners

Vue.js Render PDF Document in PDF.js Using PDFjs-dist Library Full Tutorial For Beginners
  • Post author:
  • Post category:Vue
  • Post comments:0 Comments

 

Welcome folks today in this tutorial we will be looking at how to render a pdf document in vue.js using pdfjs-dist library. All the source code is shown below. A step by step youtube video is also shown below.

 

 

 

Get Started

 

In order to get started we first of all need to install the pdfjs-dist npm package from the node package manager and inside your newly created vue.js project. Install this dependency

 

npm i pdfjs-dist

 

Now make the app.js and here we will include the custom component Pdfviewer which we will make later on.

 

<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>

 

READ  Vue.js Dynamic JSON Data File Generator With Live Preview From Form Field Values and Download as JSON Blob File in Browser Using Javascript Full Project For Beginners

 

Pdfviewer.js

 

<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>

 

 

 

 

Leave a Reply