使用jspdf从HTML生成pdf

使用jspdf从HTML生成pdf

本文介绍了Angular2-使用jspdf从HTML生成pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我正在处理的项目,我需要能够生成用户当前所在页面的PDF,为此,我将使用jspdf.因为我有一个HTML,所以我需要使用它生成PDF,所以我需要addHTML()函数.关于这一点,有很多话题,

For a project I'm working on I need to be able to generate a PDF of the page the user is currently on, for which I'll use jspdf. Since I have a HTML I need to generate a PDF with, I'll need the addHTML() function. There are a lot of topic about this, saying

我选择使用html2canvas.这是我目前的代码:

I've chosen to use html2canvas. This is what my code looks like at the moment:

import { Injectable, ElementRef, ViewChild } from '@angular/core';
import * as jsPDF from 'jspdf';
import * as d3 from 'd3';
import * as html2canvas from 'html2canvas';

@Injectable ()
export class pdfGeneratorService {

  @ViewChild('to-pdf') element: ElementRef;

  GeneratePDF () {
    html2canvas(this.element.nativeElement, <Html2Canvas.Html2CanvasOptions>{
      onrendered: function(canvas: HTMLCanvasElement) {
        var pdf = new jsPDF('p','pt','a4');

        pdf.addHTML(canvas, function() {
          pdf.save('web.pdf');
        });
      }
    });
  }
}

调用此函数时,出现控制台错误:

When this function is called, I get a console error:

这到底是为什么?我给出一个canvas作为参数,它仍然说我需要使用html2canvas.

Why exactly is this? I give a canvas as parameter and it still says I need to use html2canvas.

推荐答案

我发现有效的方法是添加:

What I found worked was adding:

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>

到index.html文件(可能在其他位置).

to the index.html file (it could presumably be elsewhere).

然后我用了:

const elementToPrint = document.getElementById('foo'); //The html element to become a pdf
const pdf = new jsPDF('p', 'pt', 'a4');
pdf.addHTML(elementToPrint, () => {
    doc.save('web.pdf');
});

在代码中不再使用html2canvas.
然后,您可以删除以下导入:

Which no longer uses html2canvas in the code.
You can then remove the following import:

import * as html2canvas from 'html2canvas';

这篇关于Angular2-使用jspdf从HTML生成pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 13:15