jsPDF is converting html to pdf but not formatting correctly. How can I slove this?

95 Views Asked by At

I am working on html to pdf conversion. I have created a sample html to pdf conversion but it is not converting pdf in the correct format. Following is the code and attached SS of the output.

Code:

import React, { useRef } from "react";
import jsPDF from "jspdf";

const htmlContent = `
<p style="margin-top:12pt; margin-bottom:6pt; text-align:center; page-break-after:avoid; font-size:28pt;"><strong><span style="font-family:'Liberation Sans;">Lorem ipsum&nbsp;</span></strong></p>`;

function PdfPreview() {
  const pdfPreviewRef = useRef(null);

  const generatePdf = () => {
    const doc = new jsPDF();
    doc.html(htmlContent, {
      margin: [41, 41, 41, 41],
      x: 33,
      y: 33,
      html2canvas: {
          scale: 0.6,
          width: 1000
      },
      autoPaging: 'text',
      callback: function (pdf) {
        const pdfBlob = pdf.output("blob");
        const objectUrl = URL.createObjectURL(pdfBlob);
        if (pdfPreviewRef.current) {
          pdfPreviewRef.current.data = objectUrl;
        }
      },
    });
  };

  return (
    <div>
      <button onClick={generatePdf}>Generate PDF</button>
      <object
        ref={pdfPreviewRef}
        type="application/pdf"
        width="100%"
        height="500px"
      >
        Preview PDF will appear here after generation.
      </object>
    </div>
  );
}

export default PdfPreview;

Result: enter image description here

0

There are 0 best solutions below