我使用jspdf和html2canvas组合将html页面保存为pdf。当前页面的pdf副本将在您单击按钮时保存。问题是,如果放大页面,然后单击按钮,保存的pdf包含当前页面的不完整部分。由于缩放,大部分部分在页面上不可见,在保存的pdf页面中被切断。解决办法是什么?下面是单击“保存”按钮时调用的js代码-
var pdf = new jsPDF('l', 'pt', 'a4');
var source = $('#someId')[0];
var options = {
background : '#eee'
};
pdf.addHTML(source, options, function(){
pdf.save('abcd.pdf');
});
编辑
借鉴Saurabh的方法,我尝试了类似的方法,但没有为任何额外的div元素编写代码。在保存到pdf之前,我将屏幕大小设置为固定宽度,打印后,我将宽度恢复到默认的正常值。它工作很好,如果它失败了,我们总是可以固定屏幕的高度,这样它在生成的pdf中显示的很好,尽管缩放。以下是我使用的代码:-
var pdf = new jsPDF('l', 'pt', 'a4');
var source = $('#someId')[0];
var options = {
background : '#eee'
};
var width = source.clientWidth;
source.style.width = '1700px';
pdf.addHTML(source, options,
function(){
pdf.save('abcd.pdf');
source.style.width = width+'px';
});
发布于 2017-01-25 12:32:57
我也遇到了同样的问题,为了做到这一点,我做了一个打印div的副本,在单击“打印”按钮时,我用margin-top:500px将div副本附加到了我的dom上。
得到它的图像之后,我隐藏这个div的副本,并设置margin-top:0px。
我希望这对你有用。
发布于 2019-02-24 00:33:39
以下是我如何在使用jsPDF的新.html()
方法放大页面时,获得完整的页面pdf。首先,在将其转换为pdf之前,我会对其进行强制页面缩放水平回到100%。在此之后重新设置规模中的选项是很重要的,否则它将返回一个空白页。
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js"
integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/"
crossorigin="anonymous"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<!-- html2canvas 1.0.0-alpha.11 or higher version is needed -->
<script>
function download() {
// Bring the page zoom level back to 100%
const scale = window.innerWidth / window.outerWidth;
if (scale != 1) {
document.body.style.zoom = scale;
}
let pdf = new jsPDF('p', 'pt', 'a4');
pdf.html(document.getElementById('idName'), {
html2canvas: {
scale: 1 // default is window.devicePixelRatio
},
callback: function () {
// pdf.save('test.pdf');
window.open(pdf.output('bloburl')); // to debug
}
});
}
</script>
更新:一个更好的方法是根据比例因素调整html2canvas.scale。
function download() {
let pWidth = pdf.internal.pageSize.width; // 595.28 is the width of a4
let srcWidth = document.getElementById('idName').scrollWidth;
let margin = 18; // narrow margin - 1.27 cm (36);
let scale = (pWidth - margin * 2) / srcWidth;
let pdf = new jsPDF('p', 'pt', 'a4');
pdf.html(document.getElementById('idName'), {
x: margin,
y: margin,
html2canvas: {
scale: scale,
},
callback: function () {
window.open(pdf.output('bloburl'));
}
});
}
https://stackoverflow.com/questions/41597817
复制相似问题