Home  >  Article  >  Web Front-end  >  How to convert HTML to PDF

How to convert HTML to PDF

PHPz
PHPzOriginal
2024-02-24 08:36:29518browse

How to convert HTML to PDF

Converting HTML to PDF is one of the common requirements in web development. Below you will learn how to implement this functionality using specific code examples.

First of all, what needs to be introduced is a commonly used open source library-pdfmake. pdfmake is a JavaScript library for generating PDFs that can specify the structure, style, and content of PDFs by using JSON objects. Before using it, we need to install it through npm:

npm install pdfmake

After the installation is completed, we can use it in the project. Here is a simple example that uses pdfmake to generate a PDF file with HTML content:

const pdfMake = require('pdfmake');

// 创建一个包含HTML内容的PDF文档
function createPdf(htmlContent) {
  const docDefinition = {
    content: [
      {
        // 使用HTML内容
        html: htmlContent
      }
    ]
  };

  const pdfDoc = pdfMake.createPdf(docDefinition);
  return pdfDoc;
}

// 保存PDF文件到本地
function savePdf(pdfDoc, filePath) {
  pdfDoc.getBuffer((buffer) => {
    // 将PDF数据写入文件
    fs.writeFileSync(filePath, buffer);
  });
}

// 示例:将HTML转化为PDF
const htmlContent = `
  <html>
    <head>
      <style>
        body {
          font-family: Arial, sans-serif;
        }
        h1 {
          color: red;
        }
        p {
          font-size: 14px;
        }
      </style>
    </head>
    <body>
      <h1>Hello, World!</h1>
      <p>This is a sample HTML content.</p>
    </body>
  </html>
`;

const pdfDoc = createPdf(htmlContent);
savePdf(pdfDoc, 'output.pdf');

In the above code, we first create a document with HTML content. Then, use the pdfmake.createPdf() method to create a PDF document object. Finally, obtain the PDF data through the pdfDoc.getBuffer() method and save it as a file.

It should be noted that some JavaScript modules (such as fs) are used in the sample code, and these modules may require additional configuration and installation in order to be used in your project.

To summarize, using the pdfmake library can easily convert HTML to PDF. This article provides a simple sample code for reference, and you can make further adjustments and optimizations according to your needs. Hope this helps!

The above is the detailed content of How to convert HTML to PDF. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn