How to give width, height, x and y coordinates in generating pdf from html using JSPDF new html API

和自甴很熟 提交于 2019-12-02 07:21:25

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: {}
}

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
    }
});

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.

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'));
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!