Ícone do site SOLOWEB Tecnologia

Gerando PDF com JavaScript

No post de hoje vamos mostrar como criar um PDF de uma página utilizando Javascript.

Vamos iniciar montando nossa estrutura básica do HTML da nossa página.

<html>
<title>Gerando PDF com JavaScript</title>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"
        integrity="sha512-GsLlZN/3F2ErC5ifS5QtgpiJtWd43JWSuIgh7mbzZ8zBps+dvLusV+eNQATqgA/HdeKFVgA5v3S/cIrLF7QnIg=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>

<body>
    <div id="content">
        <div id="Panes">
            <div>
                <h2>What is Lorem Ipsum?</h2>
                <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem
                    Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took
                    a galley of type and scrambled it to make a type specimen book. It has survived not only five
                    centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was
                    popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and
                    more recently with desktop publishing software like Aldus PageMaker including versions of Lorem
                    Ipsum.</p>
                <p>Acesse <a href="https://soloweb.com.br">soloweb.com.br</a></p>
            </div>
            <div>
                <h2>Why do we use it?</h2>
                <p>It is a long established fact that a reader will be distracted by the readable content of a page when
                    looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal
                    distribution of letters, as opposed to using 'Content here, content here', making it look like
                    readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their
                    default model text, and a search for 'lorem ipsum' will uncover many web sites still in their
                    infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose
                    (injected humour and the like).</p>
                <p>Acesse <a href="https://soloweb.com.br">soloweb.com.br</a></p> 
            </div>
        </div>
    </div>        
    <button id="btn">Gerar PDF</button>
</body>

</html>

Atenção para alguns pontos:

O include da biblioteca javascript html2pdf.bundle.min.js a partir de um CDN cdnjs.cloudflare.com

O nosso botão que irá executar o evento de gerar o PDF: <button id=”btn”>Gerar PDF</button>

Veja também

Agora vamos criar um código javascript para adicionar o evento ao nosso botão

<script type="text/javascript">

    const btn = document.querySelector('#btn')

    btn.addEventListener("click", () => {

        // ...

    });

</script>

Dentro do bloco do evento vamos escrever o seguinte código:

// pega a div do conteudo que desejamo gerar o pdf
const content = document.querySelector('#content');

//configuração da bilioteca html2pdf
const options = {
    margin: [10, 10, 10, 10],
    filename: "arquivo.pdf",
    html2canvas: { scale: 2 },
    jsPDF: { unit: "mm", format: "a4", orientation: "portrait" }
}

//gerar e baixar pdf
html2pdf().set(options).from(content).save();

Para saber mais sobre as configurações da biblioteca acesse: https://ekoopmans.github.io/html2pdf.js/

Nosso javascript completo irá ficar assim:

    const btn = document.querySelector('#btn')

    btn.addEventListener("click", () => {

        // pega a div do conteudo que desejamo gerar o pdf
        const content = document.querySelector('#content');

        //configuração da bilioteca html2pdf
        const options = {
            margin: [10, 10, 10, 10],
            filename: "arquivo.pdf",
            html2canvas: { scale: 2 },
            image: { type: 'png', quality: 0.98 },
            jsPDF: { unit: "mm", format: "a4", orientation: "portrait" }
        }

        //gerar e baixar pdf
        html2pdf().set(options).from(content).save();
    });

Pronto, agora é só testar

Pronto nosso arquivo PDF

Sair da versão mobile