Mount PDF via website

Asked

Viewed 91 times

1

I’m developing a project for a website, where it receives information via input and returns a PDF formatted with this information.

I believe that one solution would be to develop a API passing the information via JSON or XML, build the file and return via download, but I’m not sure if it’s the best way or practice. So, how to take this information and assemble a PDF ?

1 answer

1


You can use the jsPDF to generate pdf through HTML. For the one you have to:

  1. Create such a html structure that you want to print in PDF format;
  2. Dynamically populate the structure with input information;
  3. And then generate the pdf.

Example:

  
window.html2canvas = html2canvas;

  document.getElementById("gerar_pdf").addEventListener("click", myFunction);

  function myFunction(event) {
    var userName = document.getElementById('userName').value; // Busca o nome no input
    document.getElementById('es_userName').innerHTML = userName; // Preenche a estrutura

    setTimeout(_=> {
      var node = document.getElementById('estruturaParaPDF'); // Busca o node

      print(node);
      
   /* Primeiro gerar o canvas para evitar o erro  [https://stackoverflow.com/questions/54126963/jspdf-html2canvas-not-loaded-while-using-new-html-method]*/

      function print(html) {
        const filename = 'pdfName.pdf';
        const doc = new jsPDF();

        html2canvas(html, {
          onrendered: function(canvas) {
            var imgData = canvas.toDataURL('image/png');
            var doc = new jsPDF('p', 'mm', [297, 210]);
            doc.addImage(imgData, 'PNG', 10, 10);
            doc.save(filename);
          }
        })

      }
    })
  }
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
  <script src="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>

<form id="form_id">
  Introduz nome do utilizador: <input type="text" id="userName" value="" placeholder="">
</form>

<button id="gerar_pdf">Gerar PDF</button>

<div>
  <div id="estruturaParaPDF">
    <h1 style="color: red"> Gerado de HTML para PDF </h1>
    <h4> Nome do utilizador: <span id="es_userName"></span> </h4>
  </div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.