我一直在尝试通过单击页面上的按钮来从HTML页面转换并生成PDF,该按钮使用两个流行的插件自动生成并强制下载页面的PDF。* JSPDF* HTML2Canvas到目前为止,一切正常,但生成的PDF始终模糊且质量不高导入js文件(jquery,html2canvas,jspdf)后。这是我的JavaScript代码
function CreatePDFfromHTML() {
var HTML_Width = $(".html-content").width();
var HTML_Height = $(".html-content").height();
var top_left_margin = 15;
var PDF_Width = HTML_Width + (top_left_margin * 2);
var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
var canvas_image_width = HTML_Width;
var canvas_image_height = HTML_Height;
var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;
html2canvas($(".html-content")[0]).then(function (canvas) {
var imgData = canvas.toDataURL("image/jpeg", 1.0);
var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
for (var i = 1; i <= totalPDFPages; i++) {
pdf.addPage(PDF_Width, PDF_Height);
pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
}
pdf.save("invoice_<?php echo $trackingNumber ;?>.pdf");
$(".html-content").hide();
});
}
我如何调整代码以使html2canvas将页面转换为质量更好的图像(消除模糊并使得生成的PDF文件更好)
经过几天的搜索,我终于找到了一种通过将HTML_weight和HTMLheight乘以3来提高质量的方法,这是新代码
function CreatePDFfromHTML() {
var HTML_Width = $(".html-content").width()*3;
var HTML_Height = $(".html-content").height()*3;
var top_left_margin = 15;
var PDF_Width = HTML_Width + (top_left_margin * 2);
var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
var canvas_image_width = HTML_Width;
var canvas_image_height = HTML_Height;
var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;
html2canvas($(".html-content")[0]).then(function (canvas) {
var imgData = canvas.toDataURL("image/jpeg", 1.0);
var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
for (var i = 1; i <= totalPDFPages; i++) {
pdf.addPage(PDF_Width, PDF_Height);
pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
}
pdf.save("invoice_<?php echo $trackingNumber ;?>.pdf");
$(".html-content").hide();
});
}