Generate pdf from HTML in div using Javascript

匿名 (未验证) 提交于 2019-12-03 01:06:02

问题:

I have the following html code:

               

don't print this to pdf

print this to pdf

All I want to do is to print to pdf whatever is found in the div with an id of "pdf". This must be done using JavaScript. The "pdf" document should then be automatically downloaded with a filename of "foobar.pdf"

I've been using jspdf to do this, but the only function it has is "text" which accepts only string values. I want to submit HTML to jspdf, not text.

回答1:

jsPDF is able to use plugins. In order to enable it to print HTML, you have to include certain plugins and therefore have to do the following:

  1. Go to https://github.com/MrRio/jsPDF and download the latest Version.
  2. Include the following Scripts in your project:
    • jspdf.js
    • jspdf.plugin.from_html.js
    • jspdf.plugin.split_text_to_size.js
    • jspdf.plugin.standard_fonts_metrics.js

If you want to ignore certain elements, you have to mark them with an ID, which you can then ignore in a special element handler of jsPDF. Therefore your HTML should look like this:

         

don't print this to pdf

print this to pdf

Then you use the following JavaScript code to open the created PDF in a PopUp:

var doc = new jsPDF();           var elementHandler = {   '#ignorePDF': function (element, renderer) {     return true;   } }; var source = window.document.getElementsByTagName("body")[0]; doc.fromHTML(     source,     15,     15,     {       'width': 180,'elementHandlers': elementHandler     });  doc.output("dataurlnewwindow"); 

For me this created a nice and tidy PDF that only included the line 'print this to pdf'.

Please note that the special element handlers only deal with IDs in the current version, which is also stated in a GitHub Issue. It states:

Because the matching is done against every element in the node tree, my desire was to make it as fast as possible. In that case, it meant "Only element IDs are matched" The element IDs are still done in jQuery style "#id", but it does not mean that all jQuery selectors are supported.

Therefore replacing '#ignorePDF' with class selectors like '.ignorePDF' did not work for me. Instead you will have to add the same handler for each and every element, which you want to ignore like:

var elementHandler = {   '#ignoreElement': function (element, renderer) {     return true;   },   '#anotherIdToBeIgnored': function (element, renderer) {     return true;   } }; 

From the examples it is also stated that it is possible to select tags like 'a' or 'li'. That might be a little bit to unrestrictive for the most usecases though:

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.

One very important thing to add is that you lose all your style information (CSS). Luckily jsPDF is able to nicely format h1, h2, h3 etc., which was enough for my purposes. Additionalyl it will only print text within text nodes, which means that it will not print the values of textareas and the like. Example:

   
  • Print me!


回答2:

This is the simple solution. This works for me.You can use the javascript print concept and simple save this as pdf.

      
This content needs to be printed.


回答3:

You can use autoPrint() and set output to 'dataurlnewwindow' like this:

function printPDF() {     var printDoc = new jsPDF();     printDoc.fromHTML($('#pdf').get(0), 10, 10, {'width': 180});     printDoc.autoPrint();     printDoc.output("dataurlnewwindow"); // this opens a new popup,  after this the PDF opens the print window view but there are browser inconsistencies with how this is handled } 


回答4:

As mentioned, you should use jsPDF and html2canvas. I've also found a function inside issues of jsPDF which splits automatically your pdf into multiple pages (sources)

function makePDF() {      var quotes = document.getElementById('container-fluid');      html2canvas(quotes, {         onrendered: function(canvas) {          //! MAKE YOUR PDF         var pdf = new jsPDF('p', 'pt', 'letter');          for (var i = 0; i  0) {                 pdf.addPage(612, 791); //8.5" x 11" in pts (in*72)             }             //! now we declare that we're working on that page             pdf.setPage(i+1);             //! now we add content to that page!             pdf.addImage(canvasDataURL, 'PNG', 20, 40, (width*.62), (height*.62));          }         //! after the for loop is finished running, we save the pdf.         pdf.save('test.pdf');     }   }); } 


回答5:

If you want to export a table, you can take a look at this export sample provided by the Shield UI Grid widget.

It is done by extending the configuration like this:

... exportOptions: {     proxy: "/filesaver/save",     pdf: {         fileName: "shieldui-export",         author: "John Smith",         dataSource: {             data: gridData         },         readDataSource: true,         header: {             cells: [                 { field: "id", title: "ID", width: 50 },                 { field: "name", title: "Person Name", width: 100 },                 { field: "company", title: "Company Name", width: 100 },                 { field: "email", title: "Email Address" }             ]         }     } } ... 


回答6:

To capture div as PDF you can use https://grabz.it solution. It's got a JavaScript API which is easy and flexible and will allow you to capture the contents of a single HTML element such as a div or a span

In order to implement it you will need to first get an app key and secret and download the (free) SDK.

And now an example.

Let's say you have the HTML:

Acme Camera

$399
4.5 out of 5

Cras ut velit sed purus porttitor aliquam. Nulla tristique magna ac libero tempor, ac vestibulum felisvulput ate. Nam ut velit eget risus porttitor tristique at ac diam. Sed nisi risus, rutrum a metus suscipit, euismod tristique nulla. Etiam venenatis rutrum risus at blandit. In hac habitasse platea dictumst. Suspendisse potenti. Phasellus eget vehicula felis.

To capture what is under the features id you will need to:

//add the sdk   

Please note the target: #feature. #feature is you CSS selector, like in the previous example. Now, when the page is loaded an image screenshot will now be created in the same location as the script tag, which will contain all of the contents of the features div and nothing else.

The are other configuration and customization you can do to the div-screenshot mechanism, please check them out here



回答7:

if you need to downloadable pdf of a specific page just add button like this

Print

use window.print() to print your all page not just a div



回答8:

I was able to get jsPDF to print dynamically created tables from a div.

$(document).ready(function() {          $("#pdfDiv").click(function() {      var pdf = new jsPDF('p','pt','letter');     var specialElementHandlers = {     '#rentalListCan': function (element, renderer) {         return true;         }     };      pdf.addHTML($('#rentalListCan').first(), function() {         pdf.save("caravan.pdf");     });     }); }); 

Works great with Chrome and Firefox... formatting is all blown up in IE.

I also included these:

                                                              


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!