我有一个组件(角度6),它是几个组件的集合。这将产生一个较长的HTML(我正在使用Bootstrap 4)。现在,我想将此HTML转换为PDF。我进行了广泛搜索,发现许多可用于jsPDF的解决方案。要求是产生清晰的布局,就像它出现在HTML中一样(以便用户可以选择,复制等)。但是我找到的解决方案要么尝试手动添加文本行,这在我的方案中是不可能的;还是将HTML转换(光栅化?)成图像格式。另外,我想保留HTML的格式,字体和样式。
答案 0 :(得分:3)
到目前为止,我想出的最佳解决方案。
您必须从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');
});
}
答案 1 :(得分:0)
参考此内容,您可能会得到一些想法 pdf-angular
答案 2 :(得分:0)
经过一番努力,我们团队和我为自己的Angular HTML to PDF问题提出了最佳解决方案,包括将原始HTML发送到我们的Java API,然后将wkhtmltopdf(https://github.com/wkhtmltopdf/wkhtmltopdf)与Java包装器一起使用( https://github.com/jhonnymertz/java-wkhtmltopdf-wrapper)。克服了一些陷阱(例如,确保服务器具有正确安装的字体;所有内容均已正确编码;找出分页符并使其能够正常工作),我们能够准确地再现页面并将Angular HTML用作通用模板(根据不同情况进行更改)。这不是一条容易的路,但是一旦弄清楚,它就会在企业级生产环境中产生巨大的成果。
应该注意,我们还尝试了jspdf(和其他库),并得出了与您相似的结论:他们只是没有按照我们的要求去做。希望这会有所帮助。
答案 3 :(得分:0)
答案 4 :(得分:0)
首先安装以下内容: 1)npm安装jspdf 2)npm安装html2canvas
稍后导入并使用以下代码
public captureScreen() {
const data = document.getElementById('invoice');
html2canvas(data).then(canvas => {
const imgWidth = 208;
const pageHeight = 295;
const imgHeight = canvas.height * imgWidth / canvas.width;
const heightLeft = imgHeight;
const contentDataURL = canvas.toDataURL('image/png');
const pdf = new jspdf('p', 'mm', 'a4');
const position = 0;
pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
pdf.save('invoice.pdf');
});
}
答案 5 :(得分:0)
以下代码已在我的项目中使用并起作用
第1步:运行以下命令以安装npm软件包
> npm install jspdf
> npm install html2canvas
第2步:将已安装的程序包导入app.components.ts中。我没有将那些包导入constructor()
> import * as jspdf from 'jspdf';
> import html2canvas from 'html2canvas';
第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>
第4步:编写用于生成PDF的代码,如下所示
exportAsPDF()
{
let data = document.getElementById('MyDIv');
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');
});
}
答案 6 :(得分:0)
第1步:安装必需的软件包
npm install jspdf jspdf-autotable
第2步:导入已安装的软件包以供使用
import jsPDF from 'jspdf';
import 'jspdf-autotable';
第3步:如果您的数据包含图像,请将图像转换为Base64
tabledata = [{
img: 'https://i.picsum.photos/id/258/536/354.jpg',
name: 'Joseph',
domain: 'Angular 9'
},
{
img: 'https://i.picsum.photos/id/258/536/354.jpg',
name: 'Vani',
domain: 'Angular 8'
}, {
img: 'https://i.picsum.photos/id/258/536/354.jpg',
name: 'Raj',
domain: 'React.js'
},
];
以上是将图像转换为base64的数据。 转换函数如下:
convertImagetoBase64(url, callback) {
const xhr = new XMLHttpRequest();
xhr.onload = () => {
const reader = new FileReader();
reader.onloadend = () => {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
在绑定到HTML中的表之前,让我们将图像URL转换为base64。
this.tabledata.forEach(elem => {
this.convertImagetoBase64(elem.img, (b64Img) => {
elem.img = b64Img;
});
现在将数据绑定到表。如果您不想在前端显示表格,只需将其样式设置为不显示,如下面的代码所示:
<table id="imgTable" style=”display:none”>
<thead>
<tr><th>Name</th>
<th>Domain</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of tabledata">
<td>{{data.name}}</td>
<td>{{data.domain}}</td>
<td><img src="{{data.img}}" width="100" height="100" /></td>
</tr>
</tbody>
</table>
<button (click)="generatePdf()">Generate Pdf</button>
Generate Pdf函数如下所示:
app.component.ts
generatePdf(){
doc.autoTable({
html: '#imgTable',
bodyStyles: { minCellHeight: 20 },
theme: 'grid',
styles: { valign: 'middle', overflow: 'linebreak', halign: 'center', minCellHeight: 21 },
pageBreak: 'avoid',
columnStyles: {
2: { cellWidth: 22, minCellHeight: 22 },
},
headStyles: { fillColor: '#f2f2f2', textColor: '#000', fontStyle: 'bold', lineWidth: 0.5, lineColor: '#ccc' },
didDrawCell: (data) => {
if (data.column.index === 2 && data.cell.section === 'body') {
const td = data.cell.raw;
const img = td.getElementsByTagName('img')[0];
// let dim = data.cell.height - data.cell.padding('vertical');
// let textPos = data.cell.textPos;
doc.addImage(img.src, data.cell.x + 1, data.cell.y + 1, 19, 19);
}
}
});
doc.save('yourpdfname.pdf');
}
示例pdf生成如下:
有关没有表访问的更多Pdf格式 helperscript.com
答案 7 :(得分:0)
试试这个 code 在 Angular 11 中将 HTML 页面转换为 PDF
安装依赖项:
children: [
...List.generate(snapshot.data.docs.length, (index) {
return buildItemCard(
context,
snapshot.data.docs[index],
onTap: doSomething(snapshot.data.docs[index])
);
})
],
void _onTileClicked(DocumentSnapshot doc){
//do something here
}
npm install jspdf
更新 app.component.ts 文件
npm install html2canvas
更新 app.component.html 文件
import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'html-to-pdf-angular-application';
public convetToPDF() {
var data = document.getElementById('contentToConvert');
html2canvas(data).then(canvas => {
// Few necessary setting options
var imgWidth = 208;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
const contentDataURL = canvas.toDataURL('image/png')
let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
var position = 0;
pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
pdf.save('new-file.pdf'); // Generated PDF
});
}
}
享受这Packages
答案 8 :(得分:0)
我在使用 html2canvas
时遇到问题,因此不得不使用 html-to-image。我不知道为什么,但无论我尝试什么,html2canvas 都呈现空白图像。 html-to-image
虽然让我轻松地进行了适当的渲染。
用作:
var node = <HTMLElement>document.getElementById('export');
htmlToImage.toPng(node)
.then(function (dataUrl) {
var img = new Image();
img.src = dataUrl;
var doc = new jsPDF('p', 'mm', 'a4');
const bufferX = 5;
const bufferY = 5;
const imgProps = (<any>doc).getImageProperties(img);
const pdfWidth = doc.internal.pageSize.getWidth() - 2 * bufferX;
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
doc.addImage(img, 'PNG', bufferX, bufferY, pdfWidth, pdfHeight, undefined, 'FAST');
doc.save('Bill_'+new Date().toDateString());
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
});