Html save as pdf button

Code to Print and Save HTML Page as PDF using JavaScript

Being a web developer, many times you need to allow the user to print or save HTML page as PDF.

Suppose you have a web form on your website and the user has to submit the data. After submitting the form, you can allow the user to print or save the HTML page as a PDF with all the user data. A user can use this data for future reference.

Another example. If you have a tutorial on your website, you can allow a user to print the tutorial so that the user can use it offline.

A simple solution to allow the user to print or save the HTML page as PDF will be very helpful. You don’t need any external tool to convert HTML to PDF.

Code to Print and Save HTML Page as PDF

Hope you are familiar with basic HTML tags. Call the Javascript function inside the HTML to print and save the webpage as PDF.

   

Tutorial to print HTML page

Click the button to print this page.

function printFunction()
  • The window.print() is the inbuilt function to print the current window.
  • The printFunction() is user define javascript function which you call from HTML object.

By clicking on the button, the user can save the HTML page as PDF or can download it.

The print() function supports almost all the popular web browsers like Google Chrome, Firefox, Internet Explorer, Opera, and Safari (Mac and other iOS web browsers).

What’s Next?

If you are a web developer or interested in web development, do check how the 20 best web form design practices have helped me grow professionally.

Javascript is one of the highest-paying programming languages and has very advanced programming features.

Читайте также:  Javascript как объявить массив

This is a simple JavaScript function to convert HTML to PDF or to print or save HTML page as PDF. You can run this code in an online HTML editor for testing.

For more of such content, stay tuned.

Источник

doctor Brain

В этой небольшой статье мы разберем вариант создания pdf-файла из данных HTML-страницы с помощью клиентской библиотеки html2pdf.js.

Для выполнения задчи нам понадобятся:

HTML-страница может содержать любой контент, который нужно сохранить в pdf-формате. Обычно это электронные билеты, счета, инвойсы и иные документы, в том числе qr-код.

После размещения необходимых данных на странице нужно подключить библиотеку html2pdf.js .

Саму библиотеку можно скачать и разместить на своем веб-сервере:

Также можно воспользоваться одним из многочисленных CDN-сервисов. Например, cdnjs:

https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.3/html2pdf.bundle.js 

Следующим шагом мы создаем обертку для контента, подлежащего сохранению в формате pdf:

Конечно, еще нужна кнопка, по нажатию на которую будет генерироваться pdf-файл:

Наконец, напишем нужную нам функцию на ванильном JavaScript:

Новые публикации

Photo by CHUTTERSNAP on Unsplash

JavaScript: сохраняем страницу в pdf

HTML: Полезные примеры

CSS: Ускоряем загрузку страницы

JavaScript: 5 странностей

JavaScript: конструктор сортировщиков

Категории

О нас

Frontend & Backend. Статьи, обзоры, заметки, код, уроки.

© 2021 dr.Brain .
мир глазами веб-разработчика

Источник

HTML to PDF Button

PDF ace

Add a «Save as PDF» to your webpages. Completely FREE!

Use our FREE HTML to PDF service to allow your visitors to download/save your web pages as PDF. No coding or signup required. All you need to do is add a simple HTML link to your web pages.

Webpage to PDF Button

Add the below line of HTML code to your website.

Important: The web page needs to be publicly accessible on the Internet. Our HTML to PDF conversion button will not work if your web page is password protected or hosted on a local development web server.

Feel free to contact us if you need any help.

Additional Options

You can add parameters to the URL to customize the generated PDF. For example:

Below is a list of all available parameters you can pass to the our HTML to PDF script:

  • cache: Set this to 1 to enable caching of the generated PDF on our server. Default is 1. Set to 0 to disable caching.
  • cache_for: Set this to the number of seconds you want to cache the PDF for. By default set to 86400 seconds (24 hours). Set to 0 to clear cache and generate a new PDF.
  • print_media: Set this to 1 to use print media CSS. Click here for brief introduction to CSS media types.
  • url: Set this to the URL of the page you want to convert to PDF. For example consider the following scenario, you want to add a HTML to PDF button on www.example.com/page-1.html but what this button to generate PDF for www.example.com/page-2.html. In this case you can set link to https://pdf-ace.com/pdfme?url=/page-2.html. Now whenever someone clicks this button, it will generate PDF for www.example.com/page-2.html.
Читайте также:  My code school java

Newsletter

Источник

Download HTML Page as PDF Using JavaScript

To store dynamic content from the web page or HTML page for future use PDF format is very helpful. This also can.

Download-HTML-Page-as-PDF-Using-JavaScript

To store dynamic content from the web page or HTML page for future use PDF format is very helpful. This also can help download a big amount of data from the web application by exporting an HTML page to a PDF on the user’s click event using JavaScript functionality. Download HTML Page as PDF Using JavaScript, JavaScript has a huge amount of libraries available to generate PDF from HTML. But here we use jsPDF which is the best JavaScript library to convert and download HTML pages as PDF using JavaScript.

Here, In this tutorial, we will show you how to generate PDF from an HTML page using JavaScript and jQuery and also save an HTML page as a PDF using JavaScript with a live demo.

A video demonstration of the complete source code to download HTML page as PDF using JS is here,

Steps to Download HTML Page as PDF Using JavaScript

  • Include jQuery and jsPDF library by using their CDN link.
  • Create an HTML content div.
  • Instantiate jsPDF class.
  • Create a button-click function to generate and download PDF from HTML.
  • Live Demo

Include jQuery and jsPDF Library

Here we include jQuery and jsPDF library for using jsPDF class and jQuery for button click and getting data from the div.

Источник

How to create a PDF from any HTML page or form using only JavaScript

With the jspdf library, we can easily convert any HTML page or form to a PDF:

import < jsPDF >from ‘jspdf’; const pdfContentEl = document.getElementById(‘pdf-content’); const doc = new jsPDF(); await doc.html(pdfContentEl.innerHTML).save(‘test.pdf’);

PDF is a popular file format we use to present and share documents with a fixed layout across different platforms and devices.

Читайте также:  Нейросеть на java простая

To start the conversion, we create a new jsPDF object with the constructor. Then we call the html() method, passing the element with the contents we want to be in the PDF. On the result, we call save() , passing our desired name of the output PDF file.

Let’s say we had HTML like this:

Test

Here’s what we’re saving to PDF

Оцените статью