使用 jspdf 创建带有 Div 边框的 Pdf

Create Pdf with Div border using jspdf

我正在尝试使用 JsPdf 库创建基于 html 元素的 pdf。我想知道是否可以使用 div 边框,或者我是否必须使用 doc.line 属性 并基本上在我的 div 周围绘制每条线。即

var doc = new jsPDF()

doc.line(20, 20, 60, 20)

我更愿意使用 <div style="border: solid; width: 300px ">

有没有人对此有好运?

这是我的Fiddle

将 jsPdf 与 Html2Canvas 结合使用怎么样?将 html 渲染为 canvas,然后将 canvas 作为图像添加到 pdf,如下所示:

var img = canvas.toDataURL("image/png");
doc.addImage(img, 'JPEG', 300, 200);
doc.save('test.pdf');

完整示例请参阅 fiddle:http://jsfiddle.net/nLLuvnwL/

您可以使用 doc.rect to draw the rectangle. You can also change the border width using doc.setLineWidth.

而不是绘制每条线
doc.setLineWidth(2);
doc.rect(10, 20, 150, 75);

doc.save('sample-file.pdf');

请参阅此处示例 http://jsfiddle.net/508p61r6/5/

for (var i=1;i<pdf.internal.pages.length;i++){
pdf.internal.pages[i].push("0.00 595.28 841.89 -595.28 re");
pdf.internal.pages[i].push("S");
}

找到了解决方法,将矩形作为每个 pdf 页面的边框,并通过改变 pageHeight 从第二页和其他页面开始,希望这会解决一些...

html2canvas(myCanvas, { useCORS: false }, { allowTaint: true }).then(function (canvas) {

  var imgWidth = 210;
  var pageHeight = 290;
  var imgHeight = canvas.height * imgWidth / canvas.width;
  var heightLeft = imgHeight;


  var doc = new jsPDF('p', 'mm');
  var position = 0;
  var pageData = canvas.toDataURL('image/jpeg', 1.0);
  var imgData = encodeURIComponent(pageData);
  doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
  doc.setLineWidth(5);
  doc.setDrawColor(255, 255, 255);
  doc.rect(0, 0, 210, 295);
  heightLeft -= pageHeight;

  while (heightLeft >= 0) {
    position = heightLeft - imgHeight;
    doc.addPage();
    doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
    doc.setLineWidth(5);
    doc.setDrawColor(255, 255, 255);
    doc.rect(0, 0, 210, 295);
    heightLeft -= pageHeight;
  }
  doc.save('file.pdf');

});};