13

This is my web page designed with HTML and CSS:

How can I download the same web page as PDF? I was trying many solutions but I am getting only content on PDF file but not with CSS style.

Any solutions?

Ivan
  • 34,531
  • 8
  • 55
  • 100
ajay
  • 149
  • 1
  • 1
  • 5
  • 4
    Possible duplicate of [Is it possible to save HTML page as PDF using JavaScript or jquery?](https://stackoverflow.com/questions/6896592/is-it-possible-to-save-html-page-as-pdf-using-javascript-or-jquery) – Vikas Gupta Sep 02 '17 at 08:46

2 Answers2

24

As explained in this post you can use the jsPDF library to do that.

Make sure to include both jQuery and jsPDF in your file.

Also get html2canvasJS to convert the document elements to canvas in order to fix the CSS.

JS:

let doc = new jsPDF('p','pt','a4');

doc.addHTML(document.body,function() {
    doc.save('html.pdf');
});

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>

<div id="content">
  <h1 style="color:red">Hello World</h1>
  <p>this is a PDF</p>
</div>

Demo: JSFiddle

You can also trigger the download with a button (see initial post for details)

Eric
  • 6,563
  • 5
  • 42
  • 66
Ivan
  • 34,531
  • 8
  • 55
  • 100
1
  1. Download the latest version of jsPDF.

  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
jwpfox
  • 5,124
  • 11
  • 45
  • 42
Kirit
  • 405
  • 3
  • 18