js converts html pages to pdf

In JavaScript, there are two ways to convert an HTML page to a PDF file:

  1. Use a third-party library such as jsPDF or html2canvas.

  2. HTML pages can be converted to PDF files using the browser's built-in functions, such as the window.print() method.

Here is an example using jsPDF:

// 引入 jsPDF 库
import jsPDF from 'jspdf';

// 创建一个新的 jsPDF 实例
const pdf = new jsPDF();

// 设置文档的页面大小为 A4 纸张
pdf.setProperties({
  title: 'HTML to PDF',
  subject: 'Generated PDF file using jsPDF library',
  author: 'Your Name',
  keywords: 'html, pdf, javascript',
  creator: 'Your Name'
});

// 使用 html2canvas 库将 HTML 页面转换为 canvas 元素
html2canvas(document.querySelector('#html-to-pdf')).then(canvas => {
  // 将 canvas 元素转换为图像数据
  const imgData = canvas.toDataURL('image/png');
  // 将图像数据添加到 PDF 文档中
  pdf.addImage(imgData, 'PNG', 0, 0);
  // 下载 PDF 文件
  pdf.save('html-to-pdf.pdf');
});

Example using the window.print() method:

// 在点击按钮时触发打印功能
document.querySelector('#btn-print').addEventListener('click', () => {
  window.print();
});

In the browser, you can use the shortcut key Ctrl + P or click "Print" in the browser menu to open the browser's print dialog box, and then select "Save as PDF" to save the current page as a PDF file.

Guess you like

Origin blog.csdn.net/weixin_35749786/article/details/128871761