首页 > 解决方案 > JSPdf 在生产应用程序中生成盒子

问题描述

在 react 中使用 jspdf 时,在 localhost 中它工作正常,当应用程序构建在生产中时会出现问题。我的代码

const createPDF = () => {

      var contentWidth = canvas.width;
      var contentHeight = canvas.height;

      //One page pdf shows the height of canvas generated by html page;
      var pageHeight = (contentWidth / 592.28) * 841.89;
      //html page height without pdf generation
      var leftHeight = contentHeight;
      //Page offset
      var position = 0;
      //a4 paper size [595.28841.89], width and height of image in pdf of canvas generated by html page
      var imgWidth = 595.28;
      var imgHeight = (592.28 / contentWidth) * contentHeight;

      //Return picture dataURL, parameters: picture format and sharpness (0-1)
      var pageData = canvas.toDataURL("image/jpeg", 1.0);

      //Direction is vertical by default, dimension ponits, format A4 [595.28841.89]
      var pdf = new jsPDF("", "pt", "a4");
      pdf.internal.scaleFactor = 50;

      //There are two heights to distinguish, one is the actual height of the html page, and the height of the generated pdf page (841.89)
      //When the content does not exceed the display range of one page of pdf, paging is not required
      if (leftHeight < pageHeight) {
        pdf.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
      } else {
        while (leftHeight > 0) {
          pdf.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
          leftHeight -= pageHeight;
          position -= 841.89;
          //Avoid adding blank pages
          if (leftHeight > 0) {
            pdf.addPage();
          }
        }
      }
      pdf.save(Math.floor(Math.random() * 101));
    });
  };

此图像来自本地主机生成的 pdf

此图像 id 来自生产生成的 pdf

使用 localhost 时,屏幕的任何分辨率都不会扭曲 pdf,但生产应用程序会扭曲 pdf。

标签: reactjsjspdfhtml2canvas

解决方案


推荐阅读