27

I want to save web page directly to PDF.

What I have done is-

<form>
    <input type=button name=print value="Print" onClick="window.print()">
</form>

But it gives me option for print or save the page as PDF.

But what I want is when I click on the button, it directly save the page as PDF not showing any option.

Is there any solution in JavaScript?

Thanks in advance for helping.

Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
  • See: http://stackoverflow.com/questions/6896592/is-it-possible-to-save-html-page-as-pdf-using-javascript-or-jquery and http://stackoverflow.com/questions/17293135/download-a-div-in-a-html-page-as-pdf-using-javascript – Akira Yamamoto Nov 06 '15 at 21:25

2 Answers2

7

The short answer is no, you cannot prevent users from seeing the option in their browser using just javascript.

The slightly-longer answer, is that you can do this with a bit more than javascript.

Using a service such as html2canvas, you can send a POST request to a page on your server. Use that page to convert the image to a PDF, and have it output the file as a download.

Assuming you're using PHP:

<?php
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='screen-shot.pdf'");
// The above headers will cause the file to automatically be downloaded.
// Use a library to convert the image to a PDF here.

An example library to convert an image to a PDF is mPDF, or TCPDF. Feel free to Google others, especially if you're not using PHP.

Do note that this solution is inferior to them just making the choice themselves, as the quality definitely won't be as nice.

jperezov
  • 3,041
  • 1
  • 20
  • 36
4

Must notice here that the suggested solution converts HTML into image and then the raster image is converted into PDF.

If you want to save into PDF that is searchable (so can be archived and printed with best quality) and the text is printed clearly then you should consider one of these options:

  1. Ask user to save the page into PDF by providing instruction to do so for Google Chrome or Safari (both browsers are able to "print" page into PDF files). Maybe you may even try to show this instruction and invoke the printing dialog

  2. Use some of client side javascript libraries to generate PDF from the data with the tool like jsPDF (free, open source) or similar

Eugene
  • 2,820
  • 19
  • 24