Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 10, 2022 11:05 pm GMT

Trabalhando com JsPdf com React

Neste domingo tive uma experincia que causou uma dor de cabea bem grande em relao ao JsPdf. Para quem no conhece, uma biblioteca que gera em PDF's. Alguns problemas que tive: imagem jpeg no funciona, textos estavam sendo quebrados pela metade e no adicionava um outra pgina automaticamente quando acaba o A4.

Infelizmente o problema da imagem ainda no descobri como resolver e se voc souber fico feliz que comente neste post para ajudar mais pessoas da comunidade. Mas, o problema do texto + adicionar outra pgina automaticamente, aps MUITA pesquisa, consegui uma soluo.

import { jsPDF as JsPDF } from 'jspdf';import html2canvas from 'html2canvas';const generatePdf = (): any => {const htmlSource = document.getElementById('profile');const filename = `Currculo ${fields.name}`;if (!htmlSource) {  return;}html2canvas(htmlSource).then(function (canvas) {  const imgData = canvas.toDataURL('image/png');  const imgWidth = 180;  const pageHeight = 297;  const imgHeight = (canvas.height * imgWidth) / canvas.width;  let heightLeft = imgHeight;  let position = 5;  const pdf = new JsPDF('p', 'mm');  pdf.addImage(imgData, 'PNG', 10, position, imgWidth, imgHeight);  heightLeft -= pageHeight;  while (heightLeft >= 0) {    position = heightLeft - imgHeight;    pdf.addPage();    pdf.addImage(imgData, 'PNG', 10, position, imgWidth, imgHeight);    heightLeft -= pageHeight;  }  pdf.save(filename);});}; 

Use onClick={() => generatePdf()} no componente que deseja baixar o PDF.

Se no seu caso continuar cortando o texto em algum local que no est bom, modifique o const pageHeight = 297;, para o meu caso 297 ficou bom.

Documentao: http://raw.githack.com/MrRio/jsPDF/master/docs/index.html

Espero ter ajudado!

Image description


Original Link: https://dev.to/jumaschion/trabalhando-com-jspdf-1gki

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To