Save Web page directly to PDF using JS [closed]

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.

Answers:

Answer

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.

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.