使用jspdf和Vue.js生成pdf

时间:2017-12-06 06:56:05

标签: javascript pdf vuejs2 jspdf

我是Vue.js的新手,我正在尝试生成PDF,但我不知道该怎么做。

这就是我所拥有的:

import * as jsPDF  from "jspdf"

export default {

  props: ['id'],


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

}

错误:

  

属性或方法“pdf”未在实例上定义,但在呈现期间引用

3 个答案:

答案 0 :(得分:18)

首先将PDF库导入为:

var context = new BloggingContext();
var navigationProperty = GetNavigationProperty(context, typeof(Post), "BlogId"); // returns "Blog"

然后简单地实例化对象并给它内容:

import jsPDF from 'jspdf'

请务必阅读documentation了解更多

答案 1 :(得分:4)

下载html页面内容,可以这样:

  1. 指定对元素的引用,您希望将其内容下载为pdf

    <div ref="content">
       ....
       ..
    </div>
    
  2. 创建类似按钮下载

    <button @click="download">Download PDF</button>
    
  3. 确保将jsPDF库添加并导入到vue组件中

    import jsPDF from 'jspdf' 
    
  4. 在VUE组件中指定方法,例如

    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/png");
        doc.addImage(img,'JPEG',20,20);
        doc.save("sample.pdf");
       });
     },
    }
    

    请参见@@ Download PDF via VUEJS演示。

但是使用画布生成的pdf有一个问题,那就是它的大小将变得太大。

答案 2 :(得分:4)

下载html页面内容,方法如下:

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

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

创建类似的按钮下载

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

确保将jsPDF库添加并导入到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);
    });
 },
}