简体   繁体   English

如何在使用 JSPDF 新 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

I have been using JSPDF to generate pdf document based on some html.我一直在使用JSPDF基于一些html生成pdf文档。 Earlier using jspdf fromHTML Api, we could give margins like this之前使用 jspdf fromHTML Api,我们可以提供这样的边距

      var margins2 = {
      top: 415,
      bottom: 10,
      left: 55,
      width: 300
  };

  doc.fromHTML(reactListContent, margins2.left, margins2.top, {
    'width': margins2.width,
    'elementHandlers': specialElementHandlers
  }, margins2);

But, in the new .html API , how can i provide margins, width and height.但是,在新的 .html API 中,我如何提供边距、宽度和高度。 The new API is like新的 API 就像

var pdf = new jsPDF('p', 'pt', 'letter');
pdf.html(document.getElementById('html'), {
    callback: function (pdf) {
      console.log("how to get margins");
    }
});

If you look at the source code of jspdf.debug.js , html.js has the options for x and y offsets.如果你查看jspdf.debug.js源代码html.js有 x 和 y 偏移的选项。

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:所以你可以像这样设置 x 和 y 坐标:

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] .不幸的是,我不能通过修改margin: [0, 0, 0, 0]来做同样的事情。 Looks like they are still working on this issue .看起来他们仍在处理这个问题 So the short answer is NOT YET .所以简短的回答是NOT

A work-around is to calculate the scale of html2canvas by margin:解决方法是按边距计算 html2canvas 的比例:

let pdf = new jsPDF('p', 'pt', 'a4');
let margin = 36; // narrow margin - 12.7 mm
let srcwidth = document.getElementById('html').scrollWidth;
let scale = (595.28 - margin * 2) / srcwidth; // a4 pageSize 595.28

pdf.html(document.getElementById('html'), {
    backgroundColor: 'lightyellow',
    html2canvas: {
        scale: scale // default is window.devicePixelRatio,
    },
    x: margin,
    y: margin,
    callback: function () {
        window.open(pdf.output('bloburl'));
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM