34

I am new with Vue.js, and I am trying to generate a PDF, but I have no idea how to do it.

This is what I have:

import * as jsPDF  from "jspdf"

export default {

  props: ['id'],


  methods: {
    pdf () {
      const doc = new jsPDF()
    }
  }

}

Error:

Property or method "pdf" is not defined on the instance but referenced during render

4 Answers 4

37

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

Sign up to request clarification or add additional context in comments.

6 Comments

I'm seeing "ReferenceError: jsPDF is not defined" but when i do new jspdf.jsPDF() it works?
Well, considering this was answered 3 years ago, something must have been updated. make sure the methods file has access to the file importer
How to use this if we put external web url?
@user7411584 I think you need to download the file first
Thanks for your response. Can you guide me on this? If i put any web URL to download innerHTML first?
|
31

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.

8 Comments

Do you know how to make the external css applied as well for the contentHtml ?
@Exceptionhandler, I have updated the demo link for external css as well . check codesandbox.io/s/738o84vxnq
@techyaura the "Download with CSS" button throws `5ms html2canvas: DOMException: "The operation is insecure.". interesting though !
Running the browser without CORS solves it for the purpose of this test.
The link you send for the demo is not working codesandbox.io/s/738o84vxnq
|
4

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);
    });
 },
}

1 Comment

While any web URL as an input to convert this page to pdf ? How can i use this for web URL?
0

I had similar issue, especially with generating proper size and resolution.

To keep it brief, below is a link to the post:

Using jsPDF, html2Canvas, and Vue to generate PDF's

I modified for my use:

downloadItem() {
        const invoiceName = this.currentInvoice.invoiceId,
              content = this.$refs.invoiceContent;

        const doc = new jsPDF({
            orientation: "landscape",
            unit: "px",
            format: "a4",
            hotfixes: ["px_scaling"],
        });

        html2canvas(content, {
            width: doc.internal.pageSize.getWidth(),
            height: doc.internal.pageSize.getHeight(),
        }).then((canvas) => {
            const img = canvas.toDataURL("image/png");

            doc.addImage(
                img,
                "PNG",
                140,
                10,
                doc.internal.pageSize.getWidth(),
                doc.internal.pageSize.getHeight()
            );

            doc.save("invoice-" + invoiceName + ".pdf");
        });
    },

Link to the jsPDF Documentation below:

jsPDF Documentation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.