使用 html2canvas 和 JsPDF 将 HTML 转换为 pdf,并使用下面的代码生成代码,此代码会将 div 的完整 HTML 转换为单个图像,并将在 pdf 中显示为单个页面。
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)
为了分割代码,我使用下面的代码将页面分割成多个页面,但没有正确分割空间,因为我的 pdf 附加了小图像。
var imgWidth = 210;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var …Run Code Online (Sandbox Code Playgroud)