admin管理员组

文章数量:1289623

I am making a dashboard website where I have a canvas having a pie chart as in image below.

screenshot of dashboard

I am exporting image of canvas using html-to-image library and as pdf using jspdf library using the following code.

useEffect(() => {
    if (pageSettings.callForDownload) {
      const input = document.getElementById(
        "GraphAreaToDownload"
      ) as HTMLElement;

      const d = new Date();
      const id = `${tabTileProps.selectedTabName}_${d.getDate()}${d.getMonth() + 1
        }${d.getFullYear()}:${d.getHours()}${d.getMinutes()}${d.getSeconds()}`;
      if (pageSettings.downloadType === "pdf") {
           // exporting for pdf
        html2canvas(input).then((canvas) => {
          const imageData = canvas.toDataURL("image/png");

          const pdf = new jsPDF(
            pageSettings.SelectedOrientation,
            "px",
            pageSettings.selectedFormat
          );
          var width = pdf.internal.pageSize.getWidth();
          var height = pdf.internal.pageSize.getHeight();
          const heightAndWidth = getHeightAndWidth(height, width);
          pdf.addImage(
            imageData,
            "JPEG",
            pageSettings.left_margin,
            pageSettings.top_margin,
            heightAndWidth.width,
            heightAndWidth.height
          );
          pdf.save(`${id}`);
          resetPageSettings();
        });
      } else {
           //exporting for image
        toPng(input, { cacheBust: true })
          .then((dataUrl: any) => {
            const link = document.createElement("a");
            link.download = `${id}`;
            link.href = dataUrl;
            link.click();
            resetPageSettings();
          })
          .catch((err: any) => {
            Logger("error", "", err);
          });
      }
    }
  }, [pageSettings.callForDownload]);

Exporting as pdf works fine whereas pie chart is getting cropped in exporting as image. Below are the exported outcomes.

exported as image

exported as pdf

I tried tinkering with padding and margin but the image was still cropped. I expect the export as an image to show full pie chart similar to export as pdf.

I am making a dashboard website where I have a canvas having a pie chart as in image below.

screenshot of dashboard

I am exporting image of canvas using html-to-image library and as pdf using jspdf library using the following code.

useEffect(() => {
    if (pageSettings.callForDownload) {
      const input = document.getElementById(
        "GraphAreaToDownload"
      ) as HTMLElement;

      const d = new Date();
      const id = `${tabTileProps.selectedTabName}_${d.getDate()}${d.getMonth() + 1
        }${d.getFullYear()}:${d.getHours()}${d.getMinutes()}${d.getSeconds()}`;
      if (pageSettings.downloadType === "pdf") {
           // exporting for pdf
        html2canvas(input).then((canvas) => {
          const imageData = canvas.toDataURL("image/png");

          const pdf = new jsPDF(
            pageSettings.SelectedOrientation,
            "px",
            pageSettings.selectedFormat
          );
          var width = pdf.internal.pageSize.getWidth();
          var height = pdf.internal.pageSize.getHeight();
          const heightAndWidth = getHeightAndWidth(height, width);
          pdf.addImage(
            imageData,
            "JPEG",
            pageSettings.left_margin,
            pageSettings.top_margin,
            heightAndWidth.width,
            heightAndWidth.height
          );
          pdf.save(`${id}`);
          resetPageSettings();
        });
      } else {
           //exporting for image
        toPng(input, { cacheBust: true })
          .then((dataUrl: any) => {
            const link = document.createElement("a");
            link.download = `${id}`;
            link.href = dataUrl;
            link.click();
            resetPageSettings();
          })
          .catch((err: any) => {
            Logger("error", "", err);
          });
      }
    }
  }, [pageSettings.callForDownload]);

Exporting as pdf works fine whereas pie chart is getting cropped in exporting as image. Below are the exported outcomes.

exported as image

exported as pdf

I tried tinkering with padding and margin but the image was still cropped. I expect the export as an image to show full pie chart similar to export as pdf.

Share Improve this question asked Feb 19 at 18:18 ShilpaShilpa 11 silver badge
Add a comment  | 

2 Answers 2

Reset to default 1

Try this ✅ Replaces html2canvas with html-to-image for cleaner image generation.

  <!-- ✅ CDN for jsPDF -->
  <script src="https://cdnjs.cloudflare/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

  <!-- ✅ CDN for html-to-image -->
  <script src="https://unpkg/[email protected]/dist/html-to-image.js"></script>

  <style>
    #GraphAreaToDownload {
      width: 100%;
      height: 100%;
     
      padding: 10px;
      text-align: center;
    }

    img {
      width: 100%;
      height: auto;
    }
  </style>
</head>
<body>

<h2>Export Example (PDF & Image)</h2>

<div id="GraphAreaToDownload">
  <p><img src="graph.png" alt="Graph" crossorigin="anonymous" /></p>
</div>

<br>
<button onclick="downloadFile('pdf')">Download as PDF</button>
<button onclick="downloadFile('image')">Download as Image</button>

<script>
  const { jsPDF } = window.jspdf;

  function getFileName() {
    const d = new Date();
    return `Export_${d.getDate()}${d.getMonth() + 1}${d.getFullYear()}_${d.getHours()}${d.getMinutes()}${d.getSeconds()}`;
  }

  function downloadFile(type) {
    const input = document.getElementById("GraphAreaToDownload");
    const fileName = getFileName();

    if (type === "pdf") {
      // ✅ Export to PDF without html2canvas
      window.htmlToImage.toPng(input, { cacheBust: true })
        .then((dataUrl) => {
          const pdf = new jsPDF("p", "mm", "a4");
          const imgProps = pdf.getImageProperties(dataUrl);
          const pdfWidth = pdf.internal.pageSize.getWidth();
          const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;

          pdf.addImage(dataUrl, "PNG", 0, 0, pdfWidth, pdfHeight);
          pdf.save(`${fileName}.pdf`);
        })
        .catch((err) => console.error("PDF Export Error:", err));

    } else {
      // ✅ Export to Image (PNG) using html-to-image
      window.htmlToImage.toPng(input, { cacheBust: true })
        .then((dataUrl) => {
          const link = document.createElement("a");
          link.href = dataUrl;
          link.download = `${fileName}.png`;
          link.click();
        })
        .catch((err) => console.error("Image Export Error:", err));
    }
  }
</script>

Thanks I have also found a solution. First I am making "GraphAreaToDownload" full screen by adding a section "fullscreen-section" which I am using now to export.

this is component code inside return:

{fullScreen ? 
    (
      <div
        id="areaToDownload"
        className={`${fullScreen && "fullscreen-section"}`} 
        >
          <div 
           style={{ 
              backgroundColor: backgroundColor,
              width: "100vw",
              height: "100vh",
              border: "none",
          }}>
            ..........content to export
          </div>
        </div>
    ) : (...other code)
}

this is css code:

.fullscreen-section{
    display: flex;
    flex-direction: column;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 100vw;
    height: 100vh;
    background-color: white;
    z-index: 1;
    border: "none"
}

And it resolved the issue.

本文标签: javascriptImage is getting cropped using htmltoimage libraryStack Overflow