0

I trying to convert html to PDF using jspdf and html2canvas libs. But on the eighth page i got this error:

enter image description here

But, less than 4 pages it almost works.. From the fourth page background color and page logo disappears too:

enter image description here

Obs: i'm using useRef to get the html element to convert in PDF. This one (className 'allPages') have the real pages ('print') that a want to convert. Maybe this is the cause of the error, but this is the only way the i find to convert pages in pdf.

function generatePDF(){ html2canvas(printRefs.current, { logging: true, allowTaint:true, letterRendering: 1, useCORS: true, scale: 4, dpi: 24 } ).then(canvas => {

  const pdf = new jsPDF('p', 'mm', 'a4');
  
  var imgData = canvas.toDataURL("image/jpeg", 1.0);
  var imgWidth = 210; 
  var pageHeight= pdf.internal.pageSize.height;
  
  var imgHeight = canvas.height * imgWidth / canvas.width;
  var heightLeft = imgHeight;
  
  var position = 0;
  
  pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
  heightLeft -= pageHeight;

  let length = text.length;
  
  for(let i = 0; i < length-1; i++) {
    position += heightLeft - imgHeight; // top padding for other pages
    pdf.addPage();
    pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
    
  }
  pdf.save( 'file.pdf');

}); }

function App(){ return ( <input type="text" onChange={(e) => charConversor(e.target.value)}/>

{text.length}

Generate PDF {text.map((characters, index) => ( <div
      key={index}
        className="print" 
        ref={el => printRefs.current[index] = el}
      >
        <header>
          <img className={"logo"} rel="icon" type="image/svg+xml" src={image} />
        </header>
        {index}
        <div className='text'>
              {
                characters.map((char, index) => {
                  return <p className="char" key={index}> {char}</p>
                })
              }
        </div>
      </div>
    ))}
  </div>
</div>

); }

Jansen
  • 13
  • 2
  • i try to use this solution https://stackoverflow.com/a/59320184/21052555, but the pages are invading each other (page 2 appears at page 1, page 3 appears at page 2...) – Jansen Jan 29 '23 at 20:49

0 Answers0