我使用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';
});
答案 0 :(得分:3)
我遇到了同样的问题, 为了做到这一点,我做的是我制作了一份打印div副本,点击打印按钮时,我将div拷贝添加到我的dom中 margin-top:500px
获得图像后,我隐藏了div的副本,并设置 margin-top:0px
我希望这对你有用。如果你的逻辑适合你,请接受我的答案。
答案 1 :(得分:0)
这是在使用jsPDF的新.html()
方法放大页面时设法获得整页pdf的方法。首先,我force the page zoom level back to 100%将其转换为pdf。在此之后,请重设scale中的html2canvas
option,这一点很重要,否则它将返回空白页。
<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>