在生产环境中测试,无水印。
随时随地满足您的需求。
获得30天的全功能产品。
几分钟内就能启动并运行。
在您的产品试用期间,全面访问我们的支持工程团队。
在当今的数字世界中,将网页或 HTML 文档转换为 PDF 文件的能力至关重要。 这对于生成报告、创建发票或简单地以更直观的格式共享信息非常有用。 在本博文中,我们将探讨如何使用 Node.js 和 Puppeteer(Google 开发的开源库)将 HTML 页面转换为 PDF。
Puppeteer 是一个功能强大的 Node.js 库,它允许开发人员控制无头浏览器(主要是 Google Chrome 或 Chromium),并执行各种操作,如网络搜刮、截图和生成 PDF。 Puppeteer 提供了与浏览器交互的广泛 API,是将 HTML 转换为 PDF 的绝佳选择。
在开始之前,您需要建立一个新的 NodeJS 项目。 请按照以下步骤开始:
如果尚未安装 NodeJS,请先安装(可以从 NodeJS 网站 下载)。
为您的项目创建一个新文件夹,并在 Visual Studio Code 或任何特定的代码编辑器中打开。
运行npm init
为您的项目创建一个新的package.json
文件。 按照提示填写所需信息。
运行npm install puppeteer
来安装Puppeteer。
现在我们已经完成了项目设置,让我们开始深入研究代码。
要使用 Puppeteer 将 HTML 模板转换为 PDF 文件,请按照以下步骤操作:
在文件夹中创建一个名为 "HTML To PDF.js "的文件。
const puppeteer = require('puppeteer');
const fs = require('fs');
const puppeteer = require('puppeteer');
const fs = require('fs');
代码首先导入了两个基本的库:puppeteer
,一个用于控制无头浏览器(如Chrome和Chromium)的多功能工具,以及fs
,一个用于处理文件系统操作的内置NodeJS模块。 Puppeteer 可让您自动执行各种基于网络的任务,包括渲染 HTML、截图和生成 PDF 文件。
async function exportWebsiteAsPdf(html, outputPath) {
// Create a browser instance
const browser = await puppeteer.launch({
headless: 'new'
});
// Create a new page
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'domcontentloaded' });
// To reflect CSS used for screens instead of print
await page.emulateMediaType('screen');
// Download the PDF
const PDF = await page.pdf({
path: outputPath,
margin: { top: '100px', right: '50px', bottom: '100px', left: '50px' },
printBackground: true,
format: 'A4',
});
// Close the browser instance
await browser.close();
return PDF;
}
async function exportWebsiteAsPdf(html, outputPath) {
// Create a browser instance
const browser = await puppeteer.launch({
headless: 'new'
});
// Create a new page
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'domcontentloaded' });
// To reflect CSS used for screens instead of print
await page.emulateMediaType('screen');
// Download the PDF
const PDF = await page.pdf({
path: outputPath,
margin: { top: '100px', right: '50px', bottom: '100px', left: '50px' },
printBackground: true,
format: 'A4',
});
// Close the browser instance
await browser.close();
return PDF;
}
exportWebsiteAsPdf
函数是我们代码片段的核心。 这个异步函数接受一个html
字符串和一个outputPath
作为输入参数,并返回一个PDF文件。该函数执行以下步骤:
使用 Puppeteer 启动一个新的无头浏览器实例。
创建新的浏览器页面。
将提供的html
字符串设置为页面内容,等待DOM内容加载。 我们加载html
模板作为HTML字符串,将其转换为PDF格式。
模拟 "屏幕 "媒体类型,应用屏幕使用的 CSS,而不是打印特定的样式。
从加载的HTML内容生成PDF文件,指定边距、背景打印和格式(A4)。
关闭浏览器实例。
// Usage example
// Get HTML content from HTML file
const html = fs.readFileSync('test.html', 'utf-8');
exportWebsiteAsPdf(html, 'result.PDF').then(() => {
console.log('PDF created successfully.');
}).catch((error) => {
console.error('Error creating PDF:', error);
});
// Usage example
// Get HTML content from HTML file
const html = fs.readFileSync('test.html', 'utf-8');
exportWebsiteAsPdf(html, 'result.PDF').then(() => {
console.log('PDF created successfully.');
}).catch((error) => {
console.error('Error creating PDF:', error);
});
代码的最后一部分展示了如何使用exportWebsiteAsPdf
函数。 我们将执行以下步骤:
使用fs
模块的readFileSync
方法从HTML文件中读取HTML内容。 我们正在加载模板文件,以便从 HTML 页面生成 PDF。
使用加载的html
字符串和所需的outputPath
调用exportWebsiteAsPdf
函数。
利用.then
块处理成功的PDF创建,并将成功消息记录到控制台。
使用.catch
代码块来管理在HTML到PDF转换过程中发生的任何错误,将错误信息记录到控制台。
本代码片段提供了一个综合示例,说明如何使用 NodeJS 和 Puppeteer 将 HTML 模板转换为 PDF 文件。 通过实施该解决方案,您可以高效地生成高质量的 PDF,满足各种应用程序和用户的需求。
除了转换 HTML 模板,Puppeteer 还允许您将 URL 直接转换为 PDF 文件。
const puppeteer = require('puppeteer');
const puppeteer = require('puppeteer');
代码首先要导入 Puppeteer 库,它是控制 Chrome 和 Chromium 等无头浏览器的强大工具。 Puppeteer 允许您自动执行各种基于 Web 的任务,包括渲染 HTML 代码、捕获屏幕截图,以及在我们的案例中生成 PDF 文件。
async function exportWebsiteAsPdf(websiteUrl, outputPath) {
// Create a browser instance
const browser = await puppeteer.launch({
headless: 'new'
});
// Create a new page
const page = await browser.newPage();
// Open URL in current page
await page.goto(websiteUrl, { waitUntil: 'networkidle0' });
// To reflect CSS used for screens instead of print
await page.emulateMediaType('screen');
// Download the PDF
const PDF = await page.pdf({
path: outputPath,
margin: { top: '100px', right: '50px', bottom: '100px', left: '50px' },
printBackground: true,
format: 'A4',
});
// Close the browser instance
await browser.close();
return PDF;
}
async function exportWebsiteAsPdf(websiteUrl, outputPath) {
// Create a browser instance
const browser = await puppeteer.launch({
headless: 'new'
});
// Create a new page
const page = await browser.newPage();
// Open URL in current page
await page.goto(websiteUrl, { waitUntil: 'networkidle0' });
// To reflect CSS used for screens instead of print
await page.emulateMediaType('screen');
// Download the PDF
const PDF = await page.pdf({
path: outputPath,
margin: { top: '100px', right: '50px', bottom: '100px', left: '50px' },
printBackground: true,
format: 'A4',
});
// Close the browser instance
await browser.close();
return PDF;
}
exportWebsiteAsPdf
函数是我们代码片段的核心。 这个异步函数接受websiteUrl
和outputPath
作为输入参数,并返回一个PDF文件。该函数执行以下步骤:
使用 Puppeteer 启动一个新的无头浏览器实例。
创建新的浏览器页面。
导航到提供的websiteUrl
,并使用waitUntil
选项设置为networkidle0
等待网络空闲。
模拟 "屏幕 "媒体类型,确保应用屏幕使用的 CSS,而不是打印特定的样式。
将加载的网页转换为具有指定页边距、背景打印和格式(A4)的PDF文件。
关闭浏览器实例。
// Usage example
exportWebsiteAsPdf('https://ironpdf.com/', 'result.pdf').then(() => {
console.log('PDF created successfully.');
}).catch((error) => {
console.error('Error creating PDF:', error);
});
// Usage example
exportWebsiteAsPdf('https://ironpdf.com/', 'result.pdf').then(() => {
console.log('PDF created successfully.');
}).catch((error) => {
console.error('Error creating PDF:', error);
});
代码的最后一部分演示了如何使用exportWebsiteAsPdf
函数。 我们执行以下步骤:
使用所需的websiteUrl
和outputPath
调用exportWebsiteAsPdf
函数。
使用then
块来处理成功的PDF创建。 在此代码块中,我们将向控制台记录一条成功信息。
使用catch
块来处理网站到PDF转换过程中发生的任何错误。 如果出现错误,我们会将错误信息记录到控制台。
将此代码片段集成到您的项目中,您就可以使用 NodeJS 和 Puppeteer 毫不费力地将 URL 转换为高质量的 PDF 文件。
探索 IronPDF 是一个流行的 .NET 库,用于生成、编辑和提取 PDF 文件的内容。 它为从 HTML、文本、图像和现有 PDF 文档创建 PDF 提供了简单高效的解决方案。 IronPDF 支持 .NET Core、.NET Framework 和 .NET 5.0+ 项目,是各种应用的多功能选择。
使用 IronPDF 进行 HTML 到 PDF 转换:IronPDF 允许您将 HTML 内容,包括 CSS,转换为 PDF 文件。 该功能可让您从网页或 HTML 模板创建像素完美的 PDF 文档。
URL 渲染:IronPDF 可以通过 URL 直接从服务器获取网页并将其转换为 PDF 文件,这使得存档网页内容或从动态网页生成报告变得简单。
文本、图像和PDF合并:IronPDF允许您将文本、图像和现有的PDF文件合并到单个PDF文档中。 该功能对于创建包含多个内容来源的复杂文档尤为有用。
PDF 操作:IronPDF 提供用于编辑现有 PDF 文件的工具,例如添加或删除页面、修改元数据,甚至从 PDF 文档中提取文本和图像。
总之,生成和处理 PDF 文件是许多应用程序的共同要求,因此拥有合适的工具至关重要。 本文提供的解决方案,如使用 NodeJS 的 Puppeteer 或使用 .NET 的 IronPDF,提供了将 HTML 内容和 URL 转换为专业、高质量 PDF 文档的强大而高效的方法。
其中,IronPDF 凭借其丰富的功能集脱颖而出,成为 .NET 开发人员的首选。 IronPDF 提供免费试用,让您探索其功能。
用户还可以从Iron Suite包中受益,该软件包包含五个专业的.NET库,包括IronXL、IronPDF、IronOCR等。