-1

I tried making a button convert my HTML page into a PDF and downloads it, but I can't get it to work. For example, if this is the page:

function download() {
      print()
}
<html>
    <body>
    <h2>Page Content</h2>
    <br>
    <p>The page content will go <span style="color:red;">here...</span></p>
    <br><br>
    <button onclick="download()">Download Page</button><br>
     ^ The above button uses the <code>print()</code> function. However, this prompts the user with a print page, instead of asking to download.
    </body>
</html>
The closest I got was adding a button that ran the print() function, however that asks the user to print the page, not download it. Does anyone know how I can convert the HTML page to a pdf for download?
  • Please add more details of your work, there seem to be some js libraries that can do this. Have you tried any of them? – RamY Jun 02 '18 at 12:12

2 Answers2

1

First, you make a php file (or whatever technique you want to use) to turn the html to pdf (for those who don't have this step completed, wkHtmlToPdf is nice for this).

The next step is optional, but recommended:
You create a download.php which reads the file, and echo's it to the screen, with the proper headers. This file can be secured (now, or later) eg maybe you want the user to be logged in for specific files. This can now easily be added.

And now you link in your html template to it: <a href="/download.php?file=123">download</a>. Because the download.php send headers to the browser (saying "hi there, I am a PDF, download me") the browser knows what to do with it.
If you want to skip the download.php, which again I dont recommend, just link directly to the convertToPdf.php and let thet output its result rather than storing it.

Martijn
  • 15,791
  • 4
  • 36
  • 68
0

Option 1: The print() method prints the contents of the current window.

    <button onclick="window.print()">Download page</button>

Option 2: Use some server side technique to convert html to dpf like Martijn answer.

Option 3: Use jsPDF library to handle on client side. Check out https://rawgit.com/MrRio/jsPDF/master/, they have many examples there.

    function download() {
      var doc = new jsPDF();

      // All units are in the set measurement for the document
      // This can be changed to "pt" (points), "mm" (Default), "cm", "in"
      doc.fromHTML($('body').get(0), 15, 15, {
        'width': 170, 
      });
      doc.save();
    }

<button onclick="download()">Download page</button>

Sy Tran
  • 378
  • 1
  • 2
  • 13