jQuery 如何正确使用jsPDF库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16858954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:55:22  来源:igfitidea点击:

How to properly use jsPDF library

javascriptjqueryhtmljspdf

提问by Daniela costina Vaduva

I want to convert some of my divs into PDF and I've tried jsPDF library but with no success. It seems I can't understand what I need to import to make the library work. I've been through the examples and I still can't figure it out. I've tried the following:

我想将我的一些 div 转换为 PDF,我尝试过 jsPDF 库但没有成功。似乎我无法理解我需要导入什么才能使库工作。我已经完成了这些例子,但我仍然无法弄清楚。我尝试了以下方法:

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

After jQuery and:

在 jQuery 之后:

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

for testing purposes but I receive:

用于测试目的,但我收到:

"Cannot read property '#smdadminbar' of undefined"

where #smdadminbaris the first div from the body.

#smdadminbar身体的第一个 div在哪里。

回答by Well Wisher

you can use pdf from html as follows,

您可以使用 html 中的 pdf,如下所示,

Step 1: Add the following script to the header

第 1 步:将以下脚本添加到标题中

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

or download locally

或者本地下载

Step 2: Add HTML script to execute jsPDF code

第二步:添加HTML脚本执行jsPDF代码

Customize this to pass the identifier or just change #content to be the identifier you need.

自定义它以传递标识符或只是将 #content 更改为您需要的标识符。

 <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>

Step 3: Add your body content

第 3 步:添加您的正文内容

<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>

Refer to the original tutorial

参考原教程

See a working fiddle

看到一个工作小提琴

回答by user890332

You only need this link jspdf.min.js

你只需要这个链接jspdf.min.js

It has everything in it.

它拥有一切。

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

回答by pimbrouwers

This is finally what did it for me (and triggers a disposition):

这终于为我做了什么(并触发了处置):

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>

And for those of the KnockoutJS inclination, a little binding:

对于那些喜欢 KnockoutJS 的人,有点绑定:

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);
    }
};

回答by Akshay Tyagi

first, you have to create a handler.

首先,您必须创建一个处理程序。

var specialElementHandlers = {
    '#editor': function(element, renderer){
        return true;
    }
};

then write this code in click event:

然后在点击事件中编写此代码:

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

var pdfOutput = doc.output();
            console.log(">>>"+pdfOutput );

assuming you've already declared doc variable. And Then you have save this pdf file using File-Plugin.

假设您已经声明了 doc 变量。然后你已经使用 File-Plugin 保存了这个 pdf 文件。

回答by Pedro Almeida

Shouldn't you also be using the jspdf.plugin.from_html.js library? Besides the main library (jspdf.js), you must use other libraries for "special operations" (like jspdf.plugin.addimage.js for using images). Check https://github.com/MrRio/jsPDF.

您不应该也使用 jspdf.plugin.from_html.js 库吗?除了主库(jspdf.js),您必须使用其他库进行“特殊操作”(如使用图像的jspdf.plugin.addimage.js)。检查https://github.com/MrRio/jsPDF

回答by Vitalii Chmovzh

According to the latest version (1.5.3) there is no fromHTML()method anymore. Instead you should utilize jsPDF HTML plugin, see: https://rawgit.com/MrRio/jsPDF/master/docs/module-html.html#~html

根据最新版本(1.5.3),没有fromHTML()方法了。相反,您应该使用 jsPDF HTML 插件,请参阅:https://rawgit.com/MrRio/jsPDF/master/docs/module-html.html#~html

You also need to add html2canvas library in order for it to work properly: https://github.com/niklasvh/html2canvas

您还需要添加 html2canvas 库以使其正常工作:https: //github.com/niklasvh/html2canvas

JS(from API docs):

JS(来自 API 文档):

var doc = new jsPDF();   

doc.html(document.body, {
   callback: function (doc) {
     doc.save();
   }
});

You can provide HTML string instead of reference to the DOM element as well.

您也可以提供 HTML 字符串而不是对 DOM 元素的引用。

回答by Antwnina

how about in vuejs how is it applicable?

在 vuejs 中如何适用?

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>