html2canvas - 在 html2canvas/jspdf 中添加边距
问题描述
我使用 html2canvas 和 jspdf 将多页网页导出为 pdf。但是,生成的 pdf 中没有边距。如何使用 html2canvas 或 jspdf 添加边距。
html2canvas(document.body, {
scale: 0.8,
logging: true,
allowTaint: false,
backgroundColor: null
}).then(function(canvas) {
// Export the canvas to its data URI representation
var base64image = canvas.toDataURL("image/jpeg");
console.log('Report Image URL: ' + base64image);
var imgWidth = 295;
var pageHeight = 210;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
var doc = new jsPDF("l", "mm", "a4"); // landscape
var position = 0;
var width = doc.internal.pageSize.getWidth();
var height = doc.internal.pageSize.getHeight();
doc.addImage(base64image,'JPEG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(base64image,'JPEG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
doc.save('test.pdf');
});
解决方案
如果它是多个页面,它不起作用。2页之间没有间隙。以下是我修改后的代码:
html2canvas(document.body, {
scale: 0.8,
logging: true,
allowTaint: false,
backgroundColor: null
}).then(function(canvas) {
// Export the canvas to its data URI representation
var base64image = canvas.toDataURL("image/jpeg");
console.log('Report Image URL: ' + base64image);
var imgWidth = 295;
var pageHeight = 210;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
var doc = new jsPDF("l", "mm", "a4"); // landscape
var position = 0;
/* addImage explained below:
param 1 -> image in code format
param 2 -> type of the image. SVG not supported. needs to be either PNG or JPEG.
all params are specified in integer
param 3 -> X axis margin from left
param 4 -> Y axis margin from top
param 5 -> width of the image
param 6 -> height of the image
*/
var width = doc.internal.pageSize.getWidth();
var height = doc.internal.pageSize.getHeight();
doc.addImage(base64image,'JPEG', 10, 10, imgWidth-17, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(base64image,'JPEG', 10, position, imgWidth-17, imgHeight);
heightLeft -= pageHeight;
}
doc.save('test.pdf');
});
推荐阅读
- python - 无法重新运行在机器人框架中动态创建的失败的测试套件/测试用例
- python - google tasks api权限不足
- html - 无法更新工具栏中的值?
- javascript - jquery 正在调试,但在 IIS 上发布后无法正常工作
- python - Pandas Dataframe - 根据条件获取索引值
- php - 在 Laravel 5.6 中将用于格式化 DB 内容的代码放在哪里
- excel - Excel 异常行为:如果应用程序不可见,隐藏功能区也会隐藏标题栏
- java - 无法生成签名的 APK (java.lang.RuntimeException)
- apache-kafka - kafka-console-consumer 使用什么消费组
- javascript - 使用 JavaScript 创建 JSP 元素