【问题标题】:How to give width, height, x and y coordinates in generating pdf from html using JSPDF new html API如何在使用 JSPDF 新 html API 从 html 生成 pdf 时给出宽度、高度、x 和 y 坐标
【发布时间】:2019-10-03 08:28:32
【问题描述】:

我一直在使用 JSPDF 来生成基于一些 html 的 pdf 文档。之前使用 HTML Api 中的 jspdf,我们可以像这样给出边距

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

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

但是,在新的 .html API 中,我如何提供边距、宽度和高度。 新的 API 就像

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

【问题讨论】:

    标签: javascript pdf-generation jspdf jspdf-autotable pdf-to-html


    【解决方案1】:

    如果您查看source code of jspdf.debug.jshtml.js 有 x 和 y 偏移选项。

    opt: {
        filename: 'file.pdf',
        margin: [0, 0, 0, 0],
        enableLinks: true,
        x: 0,
        y: 0,
        html2canvas: {},
        jsPDF: {}
    }
    

    所以你可以像这样设置 x 和 y 坐标:

    pdf.html(document.getElementById('html'), {
        x: 36,
        y: 36,
        callback: function () {
            // pdf.save('test.pdf');
            window.open(pdf.output('bloburl')); // to debug
        }
    });
    

    不幸的是,我不能通过修改margin: [0, 0, 0, 0] 来做同样的事情。看起来他们是still working on this issue。所以简短的回答是还没有

    一种变通方法是通过边距计算 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'));
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2020-12-28
      • 1970-01-01
      • 2015-03-02
      • 2011-02-24
      • 2017-09-02
      • 2014-08-11
      • 1970-01-01
      • 2020-03-02
      • 2019-04-06
      相关资源
      最近更新 更多