Generate pdf with jspdf and Vue.js

First import the PDF library as:

import jsPDF from 'jspdf'

Then simply instantiate the object and give it the contents:

methods: {
  createPDF () {
    let pdfName = 'test'; 
    var doc = new jsPDF();
    doc.text("Hello World", 10, 10);
    doc.save(pdfName + '.pdf');
  }
}

Make sure to read the documentation for more


Download html page content, One can follow as:

  1. Specify the ref to the element, whose content you want to download as pdf

    <div ref="content">
       ....
       ..
    </div>
    
  2. Create a button download like

    <button @click="download">Download PDF</button>
    
  3. Make sure to add & import jsPDF library into vue-component

    import jsPDF from 'jspdf' 
    import html2canvas from "html2canvas"
    
  4. Specify the method into the VUE component like

    methods: {
     download() {
      const doc = new jsPDF();
      const contentHtml = this.$refs.content.innerHTML;
      doc.fromHTML(contentHtml, 15, 15, {
        width: 170
      });
      doc.save("sample.pdf");
     },
    
     downloadWithCSS() {
       const doc = new jsPDF();
       /** WITH CSS */
       var canvasElement = document.createElement('canvas');
        html2canvas(this.$refs.content, { canvas: canvasElement 
          }).then(function (canvas) {
        const img = canvas.toDataURL("image/jpeg", 0.8);
        doc.addImage(img,'JPEG',20,20);
        doc.save("sample.pdf");
       });
     },
    }
    

    See the demo @Download PDF via VUEJS.


Download html page content, One can follow as:

Specify the ref to the element, whose content you want to download as pdf

<div ref="content">
   ....
   ..
</div>

Create a button download like

<button @click="downloadWithCSS">Download PDF</button>

Make sure to add & import jsPDF library into vue-component

import jsPDF from 'jspdf' 
import domtoimage from "dom-to-image";


Specify the method into the VUE component like

methods: {
 downloadWithCSS() {

   /** WITH CSS */
    domtoimage
    .toPng(this.$refs.content)
    .then(function(dataUrl) {
      var img = new Image();
      img.src = dataUrl;
      const doc = new jsPDF({
        orientation: "portrait",
        // unit: "pt",
        format: [900, 1400]
      });
      doc.addImage(img, "JPEG", 20, 20);
      const date = new Date();
      const filename =
        "timechart_" +
        date.getFullYear() +
        ("0" + (date.getMonth() + 1)).slice(-2) +
        ("0" + date.getDate()).slice(-2) +
        ("0" + date.getHours()).slice(-2) +
        ("0" + date.getMinutes()).slice(-2) +
        ("0" + date.getSeconds()).slice(-2) +
        ".pdf";
      doc.save(filename);
    })
    .catch(function(error) {
      console.error("oops, something went wrong!", error);
    });
 },
}