Trouble Generating PDF with hidden content with jsPDF and html2canvas

Asked

Viewed 996 times

0

I am trying to generate a PDF with js using html2canvas and jsPDF. When the content is being viewed, everything works 100%, but I need this content to be hidden. I’ve tried:

- display: none;
- visibility: hidden;
- Position: absolute;

Among other things. It always returns me this error when I try to generate pdf with "hidden" content on the page.

jspdf.debug.js:2571 Uncaught Error: Supplied data is not a JPEG

Below is the code used:

<div id="conteudo-pdf">
    Conteúdo
</div>

<script type="text/javascript">
    var doc = new jsPDF();

    $('#btGerarPDF').click(function () {
        doc.addHTML($("#conteudo-pdf"), function(){
            doc.save('arquivo.pdf');
        });

    });
</script>
  • You need to display the page as it is made a print of the screen and placed in the PDF

  • Mount a "printable" version of the page without the content you want to hide.

  • Change .addHTML for .fromHTML and lower the library most recent: var html = $("#conteudo-pdf").contents();

1 answer

1

A while ago I answered that question Error - jsPDF PDF Generation, today it is with another title, it may not be working because you are using the plugin addHTML which has been discontinued.

To find out more I recommend you read the answer I gave in the aforementioned question.

See working:

$(document).ready(function(){
    $('#btnPDF').click(function() {
      savePDF(document.querySelector('#documento'));
    });
});
  
function savePDF(codigoHTML) {
  var doc = new jsPDF('portrait', 'pt', 'a4');
    data = new Date();
    margins = {
        top: 40,
        bottom: 60,
        left: 40,
        width: 1000
    };
    doc.fromHTML(codigoHTML,
    margins.left, // x coord
    margins.top, { pagesplit: true },
    function(dispose){
        doc.save("Relatorio - "+data.getDate()+"/"+data.getMonth()+"/"+data.getFullYear()+".pdf");
    });
}
#documento {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>

<div id="documento">Esse conteúdo esta ocultado no navegador, mas ao gerar o <strong>PDF</strong> ele irá aparecer!</div>

<button class="btn btn-danger" id="btnPDF">Gerar PDF</button>

Browser other questions tagged

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