HTML2Canvas生成的图片被裁剪了。

13

我使用Html2Canvas和jsPdf导出图像。

这是函数:

function exportPdf() {
    content = $("#print");

    var useWidth = content.prop('scrollWidth');
    var useHeight = content.prop('scrollHeight');

    debugger;

    html2canvas((content), { width: useWidth, height: useHeight}).then(function (canvas) {
        debugger;
        var img = canvas.toDataURL("image/png");
        var doc = new jsPDF({
            unit:'px', 
            format:'a4'
        });

        debugger;
        doc.addImage(img, 'JPEG', 0, 0);
        doc.save('test.pdf');
    });
}

我认为它考虑了视口,就像是做了一个屏幕截图,当然,滚动条下方的内容不予考虑。

有什么想法吗?


有什么想法吗?

7个回答

23

呼叫

    window.scrollTo(0,0)

在调用html2canvas之前,似乎有一个bug,但需要将窗口置于顶部,以使html2canvas捕获传递给它的整个DOM


从用户体验的角度来看并不是很好,但这个技巧确实有效,所以感谢分享!:D - Marcu Daniel

10
当窗口滚动时,会出现这种情况。要解决这个问题,你可以传递窗口滚动的负数。
html2canvas(htmlSource, {scrollY: -window.scrollY}).then(function(canvas) {

// Do Something here

});

3

我设置了 windowHeightheight,这对我起了作用:

你可以试试这样做:

html2canvas(htmlSource, {
     height: window.outerHeight + window.innerHeight,
     windowHeight: window.outerHeight + window.innerHeight,
     scrollY: -window.scrollY
}).then(function(canvas) {
    // Do Something here    
});

2

其中一个原因已经在上面提到了,那就是窗口可能被滚动了,所以在使用html2canvas捕获图像之前,总是要添加这一行代码。

    window.scrollTo(0,0)

另一个问题可能是图像的分辨率高于pdf页面,因此您需要获取PDF文档的宽度和高度。
var width = doc.internal.pageSize.getWidth();
var height = doc.internal.pageSize.getHeight();

将其用于您的图像,以使其适合PDF文档。
doc.addImage(imgData, 'JPEG', 0, 0, width, height);

如果您想要一个动态大小的图像不被扭曲并保持图像宽度/高度比例。
 var width = doc.internal.pageSize.getWidth();
 var height = doc.internal.pageSize.getHeight();

 let widthRatio = width / canvas.width;
 let heightRatio = height / canvas.height;

 let ratio = widthRatio > heightRatio ? heightRatio : widthRatio

跟随着
 doc.addImage(imgData, "PNG", 0, 0, canvas.width * ratio, canvas.height * ratio,);

1
你可以尝试响应式方式,例如:
if (screen.width < 1024) {
    document
      .querySelector("meta[name=viewport]")
      .setAttribute("content", "width=1200px");
  }

  let generatedPDFB64;
  //used the Printable HOC for capturing printable component with print-id attribute
  const printElement = document.querySelector(`div[print-id=${selector}]`);
  // convert the html to canvase
  const convertedCanvas = await html2canvas(printElement, {
    allowTaint: true,
    removeContainer: true,
    backgroundColor: null,
    imageTimeout: 15000,
    logging: true,
    scale: 2,
    scrollY: window.scrollTo({
      top: 0,
      behavior: 'smooth'
    }),
    useCORS: true
  });

  const contentDataURL = convertedCanvas.toDataURL("image/png");
  const imgWidth = 205;
  const pageHeight = 300;
  const imgHeight = (convertedCanvas.height * imgWidth) / convertedCanvas.width;
  let heightLeft = imgHeight;
  const shouldCompress = true

  let pdf = new jsPDF("p", "mm", "a4", shouldCompress); // A4 size page of PDF
  let position = 0;

   pdf.addImage(
    contentDataURL,
    "PNG",
    0,
    position,
    imgWidth,
    imgHeight,
    "print",
    "FAST"
  ); 
  heightLeft -= pageHeight;

  while (heightLeft >= 0) {
    position = heightLeft - imgHeight;
    pdf.addPage();
    pdf.addImage(
      convertedCanvas,
      0,
      position,
      imgWidth,
      imgHeight,
      "print",
      "FAST"
    );
    heightLeft -= pageHeight;
  }

  pdf.save("resume.pdf"); // Generated PDF

  if (screen.width < 1024) {
    document
      .querySelector("meta[name=viewport]")
      .setAttribute("content", "width=device-width, initial-scale=1");
  }


0

对于我的情况,我添加了一个类来使其固定:

$("#print").addClass('ready-fix');

CSS:

.ready-fix {
    position: fixed !important;
    top: 0;
    left: 50%;
    z-index: 9999;
    -ms-transform: translate(-50%, 0);
    transform: translate(-50%, 0);
}

然后称为“html2canvas”,图像不再被裁剪:

html2canvas(document.querySelector("#print"), { scale: window.devicePixelRatio, allowTaint: true }).then(canvas => {
//code here
$("#print").removeClass('ready-fix');
})

最终移除了固定的类。


0
唯一对我有效的方法是将以下代码添加到我的CSS中。
这个样式代码用于防止html2canvas将渲染限制在可视区域内。
.html2canvas-container { 
    width: 3000px; 
    height: 3000px; 
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接