sha*_*nti 5 javascript pdf pdf-generation html2canvas jspdf
我正在使用 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');
});
Run Code Online (Sandbox Code Playgroud)
从 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';
});
Run Code Online (Sandbox Code Playgroud)
这是我如何在使用 jsPDF 的新.html()方法放大页面时设法获得整页 pdf 。首先,在将其转换为 pdf 之前,我将页面缩放级别强制回 100%。到复位是非常重要的规模在html2canvas选项之后,否则它会返回一个空白页。
<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>
Run Code Online (Sandbox Code Playgroud)
更新:更好的方法是根据比例因子调整 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'));
}
});
}
Run Code Online (Sandbox Code Playgroud)
我遇到了同样的问题,要做到这一点,我所做的是我制作了打印 div 的副本,然后单击打印按钮,我将 div 副本附加到我的 dom 上,边距顶部:500px
获得图像后,我隐藏该 div 的副本,并设置margin-top:0px
我希望这对你有用。
| 归档时间: |
|
| 查看次数: |
4197 次 |
| 最近记录: |