Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use window.print content to download a web page as pdf

I would like to have a link that when is clicked, automatically starts the download of the printable version of the web page.

I'm using Moodle. The content I want it's exactly the same If I download the page using ctrl + p and saving as pdf or using

<a href=\"whatever.htm\" onClick=\"window.print();return false\">Download web page</a>

I want exactly that content because using this way, the header, sidebar and footer is removed. I don't want css.

I'm not using this because this doesn't work in some browsers.

I'd rather not using pdf libraries like tcpdf because Moodle loads the content in a dynamic way and send this to a libraries like that is a mess.

I tried using sites like pdfcrowd.com but this kind of sites don't work when the site you want to convert to pdf uses a server-side session to identify the user.

like image 861
Toquis Avatar asked Dec 17 '13 22:12

Toquis


People also ask

How can I save an entire Web page as a PDF?

Press Ctrl + P (Windows) or Cmd + P (Mac). On the following dialog, under Printer, choose 'Microsoft Print to PDF. ' Click 'Print' and voila, you have saved your webpage to PDF.

How do I download a newspaper article as a PDF?

First, get the newspaper file, such as Microsoft Word or even an image file, so that you can convert it. Next, open Adobe Acrobat and go to the File menu. Choose Create and then PDF From File. From here, navigate to the location of the newspaper file and click Open.


2 Answers

**There is easy ways to use jsPDF its very simple just you will use JSpdf Library **

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

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);
like image 108
Shakil Hossain Avatar answered Sep 23 '22 11:09

Shakil Hossain


I don't believe that there is a way to do this with window.print(). However, there are HTML to PDF converters available for free, and you could automatically start a download with that. An example of this would be jsPDF, a free library for converting HTML to a PDF with Javascript

like image 24
scrblnrd3 Avatar answered Sep 21 '22 11:09

scrblnrd3