Como usar corretamente a biblioteca jsPDF

quero converter algumas das minhas divs em PDF e tentei a biblioteca jsPDF, mas sem sucesso. Parece que não consigo entender o que preciso de importar para fazer a biblioteca funcionar. Já vi os exemplos e ainda não consegui perceber. Tentei o seguinte:

<script type="text/javascript" src="js/jspdf.min.js"></script>

Depois do jQuery e:

$("#html2pdf").on('click', function(){
    var doc = new jsPDF();
    doc.fromHTML($('body').get(0), 15, 15, {
        'width': 170
    });
    console.log(doc);
});

para fins de teste, mas recebo:

"Cannot read property '#smdadminbar' of undefined"

Onde #smdadminbar é o primeiro div do corpo.

Author: Amal Murali, 2013-05-31

5 answers

Pode usar o pdf a partir do html da seguinte forma,

Passo 1: adicionar o seguinte programa ao cabeçalho

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>

Ou transferir localmente

Passo 2: Adicionar um programa HTML para executar o código jsPDF

Personalize isto para passar o identificador ou apenas altere o conteúdo do #para ser o identificador que necessita.

 <script>
    function demoFromHTML() {
        var pdf = new jsPDF('p', 'pt', 'letter');
        // source can be HTML-formatted string, or a reference
        // to an actual DOM element from which the text will be scraped.
        source = $('#content')[0];

        // we support special element handlers. Register them with jQuery-style 
        // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
        // There is no support for any other type of selectors 
        // (class, of compound) at this time.
        specialElementHandlers = {
            // element with id of "bypass" - jQuery style selector
            '#bypassme': function (element, renderer) {
                // true = "handled elsewhere, bypass text extraction"
                return true
            }
        };
        margins = {
            top: 80,
            bottom: 60,
            left: 40,
            width: 522
        };
        // all coords and widths are in jsPDF instance's declared units
        // 'inches' in this case
        pdf.fromHTML(
            source, // HTML string or DOM elem ref.
            margins.left, // x coord
            margins.top, { // y coord
                'width': margins.width, // max width of content on PDF
                'elementHandlers': specialElementHandlers
            },

            function (dispose) {
                // dispose: object with X, Y of the last line add to the PDF 
                //          this allow the insertion of new lines after html
                pdf.save('Test.pdf');
            }, margins
        );
    }
</script>

Passo 3: Adicionar o conteúdo do seu corpo

<a href="javascript:demoFromHTML()" class="button">Run Code</a>
<div id="content">
    <h1>  
        We support special element handlers. Register them with jQuery-style.
    </h1>
</div>

Consulte o tutorial original

Ver um violino a funcionar

 98
Author: Well Wisher, 2017-01-12 12:56:42

Só precisa deste link jspdf.minuto.js

Tem tudo nele.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
 17
Author: user890332, 2017-01-13 17:06:23

Finalmente foi isto que o fez por mim (e desencadeia uma disposição):

function onClick() {
  var pdf = new jsPDF('p', 'pt', 'letter');
  pdf.canvas.height = 72 * 11;
  pdf.canvas.width = 72 * 8.5;

  pdf.fromHTML(document.body);

  pdf.save('test.pdf');
};

var element = document.getElementById("clickbind");
element.addEventListener("click", onClick);
<h1>Dsdas</h1>

<a id="clickbind" href="#">Click</a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>

E para os dos KnockoutJS inclinação, um pouco de ligação:

ko.bindingHandlers.generatePDF = {
    init: function(element) {

        function onClick() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            pdf.canvas.height = 72 * 11;
            pdf.canvas.width = 72 * 8.5;

            pdf.fromHTML(document.body);

            pdf.save('test.pdf');                    
        };

        element.addEventListener("click", onClick);
    }
};
 6
Author: pimbrouwers, 2018-02-02 21:24:16
Não devias estar a usar a jspdf?Forum.from_html.biblioteca js? Além da biblioteca principal (jspdf.js), você deve usar outras bibliotecas para" operações especiais " (como jspdf.Forum.addimage.js para usar imagens). Ver https://github.com/MrRio/jsPDF.
 3
Author: Pedro Almeida, 2013-06-27 22:10:11
Primeiro, tens de criar um manipulador.
var specialElementHandlers = {
    '#editor': function(element, renderer){
        return true;
    }
};

Depois escreva este código no evento:

doc.fromHTML($('body').get(0), 15, 15, {
    'width': 170, 
    'elementHandlers': specialElementHandlers
        });

var pdfOutput = doc.output();
            console.log(">>>"+pdfOutput );
Assumindo que já declarou a variável doc. E então você tem salvar este arquivo pdf usando Arquivo-Plugin.
 3
Author: Akshay Tyagi, 2015-02-06 08:21:50