Ani*_*udh 10
到目前为止,我可能想出的最佳解决方案。
您必须从npm安装以下软件包
import * as jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
htmltoPDF()
{
// parentdiv is the html element which has to be converted to PDF
html2canvas(document.querySelector("#parentdiv")).then(canvas => {
var pdf = new jsPDF('p', 'pt', [canvas.width, canvas.height]);
var imgData = canvas.toDataURL("image/jpeg", 1.0);
pdf.addImage(imgData,0,0,canvas.width, canvas.height);
pdf.save('converteddoc.pdf');
});
}
Run Code Online (Sandbox Code Playgroud)
更新:
提出了另一种解决方案。我无法将其分解为A4大小的页面,但是却可以制作一个pdf文件。
包装方式:
import domtoimage from 'dom-to-image';
import * as jsPDF from 'jspdf';
downloadPDF()
{
var node = document.getElementById('parentdiv');
var img;
var filename;
var newImage;
domtoimage.toPng(node, { bgcolor: '#fff' })
.then(function(dataUrl) {
img = new Image();
img.src = dataUrl;
newImage = img.src;
img.onload = function(){
var pdfWidth = img.width;
var pdfHeight = img.height;
// FileSaver.saveAs(dataUrl, 'my-pdfimage.png'); // Save as Image
var doc;
if(pdfWidth > pdfHeight)
{
doc = new jsPDF('l', 'px', [pdfWidth , pdfHeight]);
}
else
{
doc = new jsPDF('p', 'px', [pdfWidth , pdfHeight]);
}
var width = doc.internal.pageSize.getWidth();
var height = doc.internal.pageSize.getHeight();
doc.addImage(newImage, 'PNG', 10, 10, width, height);
filename = 'mypdf_' + '.pdf';
doc.save(filename);
};
})
.catch(function(error) {
// Error Handling
});
}
Run Code Online (Sandbox Code Playgroud)
以下代码已用于并适用于我的项目
第 1 步:运行以下命令安装 npm 包
> npm install jspdf
> npm install html2canvas
Run Code Online (Sandbox Code Playgroud)
第二步:在 app.components.ts 中导入已安装的包。我没有在构造函数()中导入这些包
> import * as jspdf from 'jspdf';
> import html2canvas from 'html2canvas';
Run Code Online (Sandbox Code Playgroud)
第 3 步:为必须导出为 PDF 的 HTML div 提供一个 id。添加一个按钮来激活该功能。
<div id="MyDIv" style="margin-left: 45px;" class="main-container">
</div>
<div class="icon_image " title="Share As PDF" (click)="exportAsPDF('MyDIv');"><img src="assets/img/pdf.png"></div>
Run Code Online (Sandbox Code Playgroud)
第四步:编写生成PDF的代码如下
exportAsPDF(div_id)
{
let data = document.getElementById(div_id);
html2canvas(data).then(canvas => {
const contentDataURL = canvas.toDataURL('image/png')
let pdf = new jspdf('l', 'cm', 'a4'); //Generates PDF in landscape mode
// let pdf = new jspdf('p', 'cm', 'a4'); Generates PDF in portrait mode
pdf.addImage(contentDataURL, 'PNG', 0, 0, 29.7, 21.0);
pdf.save('Filename.pdf');
});
}
Run Code Online (Sandbox Code Playgroud)
经过一番努力,我和我的团队针对我们自己的 Angular HTML 到 PDF 问题提出了最好的解决方案,涉及将原始 HTML 发送到我们的 Java API,然后利用 wkhtmltopdf ( https://github.com/wkhtmltopdf/wkhtmltopdf ) 和Java 包装器(https://github.com/jhonnymertz/java-wkhtmltopdf-wrapper)。克服了一些问题(例如确保服务器正确安装了字体;所有内容都正确编码;找出分页符并使其正常工作),我们能够准确地重现我们的页面并使用我们的 Angular HTML 作为通用模板(根据不同场景而变化)。这不是一条容易的路,但一旦你弄清楚了,它就会在企业级生产环境中产生很好的结果。
应该指出的是,我们还尝试了 jspdf(和其他库)并得出了与您类似的结论:它们只是没有做我们需要它们做的事情。希望这有帮助。
| 归档时间: |
|
| 查看次数: |
22896 次 |
| 最近记录: |