Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

485
Visualizações
How to generate a PDF File (just as a File) using html2pdf

I am working on a React project.

Here, I am trying to generate a PDF file (invoice) and upload it to Google Drive.

following code shows how I tried to create the file but I could not get the PDF file I needed. I would like to know how to generate the PDF file using html2pdf.js lib.

    function createPDF() {
    console.log('create PDF function works!');
    let element = document.getElementById('report_component');
    let opt = {
        margin: 1,
        filename: 'my-invoice.pdf',
        image: {type: 'jpeg', quality: 0.98},
        html2canvas: {scale: 2},
        jsPDF: {unit: 'in', format: 'a4', orientation: 'portrait'}
    };

    // New Promise-based usage:
    // window.html2pdf().set(opt).from(element).save(); // I do not want to save/download the PDF using the web browser.

    // I want to get the PDF file. I tried like this;
    let value = window.html2pdf().set(opt).from(element).toContainer().toCanvas().toImg().toPdf().output();

    // const blob = new Blob([value], { type: 'application/pdf'});
    let file = new File([value], 'my-invoice.pdf', {
        type: 'application/pdf',
    });

    /* Here I try to implement the code to upload the PDF file to Google Drive.
    * First I need to get the PDF File. */
    console.log(file);

}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If any one searching an answer for this question. here it is;

I wanted to create a report(invoice) using HTML. Below you can find how I designed my invoice.

Note: Please note that I included html2pdf.js as a script in HTML.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Invoice</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
</head>
<body>
<section id="my_invoice">
    <!-- I designed the invoice here -->
</section>
</body>
</html>

Most of the existing code tutorials show us to download the generated PDF. Following JavaScript code will help you to download the PDF. When you run this code, browser will open a window and asks where to download this PDF file. Then, you can save the PDF file easily.

let element = document.getElementById('my_invoice');
let opt = {
  margin:       1,
  filename:     'my-invoice.pdf',
  image:        { type: 'jpeg', quality: 0.98 },
  html2canvas:  { scale: 2 },
  jsPDF:        { unit: 'in', format: 'a4', orientation: 'portrait' }
};

// New Promise-based usage:
html2pdf().set(opt).from(element).save();

But my requirement was slightly different. I just wanted to create the PDF file. Then, do something with that file. In my scenario, I wanted to upload that generated PDF file to Google Drive. Following code segment shows how I use html2pdf.js to generate the PDF file(blob). Please note that I used .outputPdf() method to get the blob. For more information, you can refer to the html2pdf.js Worker API documentation.

  /** Creates the PDF report document.
     * @return Promise: resolves if PDF report generates successfully,
     * otherwise rejects. */
    function createPDF() {
        return new Promise(async (resolve, reject) => {
            console.log('create PDF function executed!');
            let element = document.getElementById('my_invoice');

            let opt = {
                margin: 1,
                filename: 'my-invoice.pdf',
                image: {type: 'jpeg', quality: 0.95},
                html2canvas: {scale: 2, useCORS: true},
                jsPDF: {unit: 'in', format: 'a4', orientation: 'portrait'}
            };

            try {
                const blob = await window.html2pdf().set(opt).from(element).outputPdf('blob', 'my-invoice.pdf');
                resolve(blob);
            } catch (e) {
                reject(e);
            }
        });

    }

Hope you learnt something. Cheers!

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda