2017-04-07 673 views
3

对于我正在处理的项目,我需要能够生成用户当前正在使用的页面的PDF,为此我将使用jspdf。因为我有一个HTML我需要生成一个PDF,我需要的addHTML()功能。这里有很多话题,说Angular2 - 使用jspdf从HTML生成pdf

You'll either need to use html2canvas or rasterizehtml .

我选择使用html2canvas。这是我的代码看起来像此刻:

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

当这个函数被调用时,我得到一个控制台错误:

EXCEPTION: Error in ./AppComponent class AppComponent - inline template:3:4 caused by: You need either https://github.com/niklasvh/html2canvas or https://github.com/cburgmer/rasterizeHTML.js

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

+0

你试过从html2canvas/dist/html2canvas.js中导入*作为html2canvas吗? –

+0

@SyedAliTaqi我想你的建议,但它抛出错误 – Vignesh

回答

8

我找到什么工作是添加:

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

到index.html文件(这大概可以在其他地方)。

然后我用:

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代码。
然后,您可以删除以下导入:

import * as html2canvas from 'html2canvas'; 
+1

将是很好,如果import语句工作。但是现在应该选择这个作为答案。 – Ceekay

+0

@Greg,无需在index.html中导入脚本。我们能不能在那里,你在代码中使用html2canvas除了导入能够做到负载html2canvas.js – Vignesh

+0

? 我收到错误 您需要https://github.com/niklasvh/html2canvas或https://github.com/cburgmer/rasterizeHTML.js错误:您需要https://github.com/niklasvh/ html2canvas或https://github.com/cburgmer/rasterizeHTML.js在Object.e.API.addHTML –

0

试试这样说:

GeneratePDF() { 
    html2canvas(this.element.nativeElement, <Html2Canvas.Html2CanvasOptions>{ 
     onrendered: function(canvas: HTMLCanvasElement) { 
     var pdf = new jsPDF('p','pt','a4');  
     var img = canvas.toDataURL("image/png"); 
     pdf.addImage(img, 'PNG', 10, 10, 580, 300); 
     pdf.save('web.pdf'); 
     } 
    }); 
    } 
0

任何人都仍在努力的HTML DIV转换为PDF格式可以选择使用html2pdf,与一对夫妇的你可以轻松地做任何事情。

var element = document.getElementById('element-to-print'); 
html2pdf(element);