如何使用 JSPDF 新 html API 从 html 生成 pdf 时给出宽度、高度、x 和 y 坐标

问题描述 投票:0回答:2

我一直在使用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
2个回答
1
投票

如果您查看 jspdf.debug.js 的源代码,

html.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]
来做到这一点。看起来他们仍在解决这个问题。所以简短的回答是还没有

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

0
投票

使用jsPDF生成与HTML页面尺寸匹配的PDF(不考虑多页),包括渲染的图像。脚本依赖于 jsPDF v2.5.1 和 html2canvas 1.4.1(用于渲染画布,即图像等): // 创建未配置的 PDF。 var pdf = new jsPDF();

// Generate PDF content from HTML body. 
pdf.html
(document.querySelector("body"),
  { // Config PDF page to match HTML page dimensions.
    margin: [0, 0, 0, 0], // PDF margins
    x: 0, y: 0, // PDF content origin offset from PDF page origin
    width: pdf.internal.pageSize.getWidth(), // Generated PDF document's width in jsPDF units
    windowWidth: window.innerWidth // Page width in its browser window in CSS pixels
  }
);
© www.soinside.com 2019 - 2024. All rights reserved.