使用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');
});
}
我使用以下代码来分割页面,将页面分割成多个部分,但是由于我的PDF文件中有小图片附加在PDF上,所以不能正确地分割空格。
var imgWidth = 210;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
enter code here
var doc = new jsPDF('p', 'mm');
var position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
doc.save( 'file.pdf');
有没有一种方法可以根据静态高度将页面分割,从特定位置分割图像?