如何使用JSPDF new html API从html生成pdf时给出宽度,高度,x和y坐标 [英] How to give width, height, x and y coordinates in generating pdf from html using JSPDF new html API
问题描述
我一直在使用JSPDF生成基于某些html的pdf文档.先前使用HTML Api中的jspdf,我们可以给这样的边距
I have been using JSPDF to generate pdf document based on some html. Earlier using jspdf fromHTML Api, we could give margins like this
var margins2 = {
top: 415,
bottom: 10,
left: 55,
width: 300
};
doc.fromHTML(reactListContent, margins2.left, margins2.top, {
'width': margins2.width,
'elementHandlers': specialElementHandlers
}, margins2);
但是,在新的.html API中,我如何提供页边距,宽度和高度. 新的API就像
But, in the new .html API , how can i provide margins, width and height. The new API is like
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.html(document.getElementById('html'), {
callback: function (pdf) {
console.log("how to get margins");
}
});
推荐答案
如果您查看 jspdf.debug.js 的源代码, html.js
具有x和y偏移量的选项.
If you look at the source code of jspdf.debug.js, html.js
has the options for x and y offsets.
opt: {
filename: 'file.pdf',
margin: [0, 0, 0, 0],
enableLinks: true,
x: 0,
y: 0,
html2canvas: {},
jsPDF: {}
}
因此您可以像这样设置x和y坐标:
So you can set the x and y coordinates like this:
pdf.html(document.getElementById('html'), {
x: 36,
y: 36,
callback: function () {
// pdf.save('test.pdf');
window.open(pdf.output('bloburl')); // to debug
}
});
不幸的是,我不能通过修改margin: [0, 0, 0, 0]
来做同样的事情.看起来他们仍在解决此问题.因此,简短的答案是还没有.
Unfortunately, I can't do the same by modifying the margin: [0, 0, 0, 0]
. Looks like they are still working on this issue. So the short answer is NOT YET.
一种解决方法是按边距计算html2canvas的比例:
A work-around is to calculate the scale of html2canvas by margin:
let pdf = new jsPDF('p', 'pt', 'a4');
let left = 36; // narrow margin - 12.7 mm
let srcwidth = document.getElementById('html').style.width;
let scale = (595.28 - left * 2) / Math.ceil(srcwidth.replace('px','')); // a4 pageSize 595.28
pdf.html(document.getElementById('html'), {
html2canvas: {
scale: scale // default is window.devicePixelRatio,
},
x: left,
y: 36,
callback: function () {
window.open(pdf.output('bloburl'));
}
});
这篇关于如何使用JSPDF new html API从html生成pdf时给出宽度,高度,x和y坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!