puppeteer api
Puppeteer is a Node library developed by Google and provides a high-level API for developers.
Puppeteer是Google开发的Node库,并为开发人员提供了高级API。
With Node.js already up and running, we will install puppeteer via NPM (node package manager).
在Node.js已经启动并运行的情况下,我们将通过NPM (节点程序包管理器) 安装puppeteer 。
Note: You should have Node.js installed in your PC.
注意:您应该在PC中安装Node.js。
To get started, let's install puppeteer:
首先,让我们安装puppeteer:
Open the command prompt and type npm i puppeteer or npm install puppeteer
打开命令提示符,然后键入npm i puppeteer或npm install puppeteer
"npm" will download and install the puppeteer library together with other dependencies and Chromium.
“ npm”将下载并安装puppeteer库以及其他依赖项和Chromium。
Open a text editor and type the following code and save it with the file name as app.js
打开文本编辑器,然后输入以下代码,并将其保存为文件名app.js。
// Include puppeteer module
const puppeteer = require ('puppeteer');
// file system node js module.
const fs = require ('fs');
(async function () {
try {
// launch puppeteer API
const browser = await puppeteer.launch();
const page = await browser.newPage();
// content of PDF file
await page.setContent ('WELCOME TO GOOGLE PUPPETEER API');
await page.emulateMedia ('screen');
await page.pdf ({
// name of your pdf file in directory
path: 'testpdf.pdf',
// specifies the format
format: 'A4',
// print background property
printBackground: true
});
// console message when conversion is complete!
console.log ('done');
await browser.close();
process.exit();
} catch (e) {
console.log ('our error', e);
}
} ) () ;
The file should be saved in your Node.js directory.
该文件应保存在您的Node.js目录中。
From the code above, we first of all include the puppeteer module and the file system module. The puppeteer API is then launched and it creates a new A4 page with file name test.pdf.
从上面的代码,我们首先包括puppeteer模块和file system模块 。 然后启动puppeteer API,它将创建一个文件名为test.pdf的新A4页面 。
Run the code by initiating it in the command prompt like a regular Node.js file.
通过像常规Node.js文件一样在命令提示符下启动代码来运行代码。
Following our code, done will be printed out when the conversion is complete.
按照我们的代码,转换完成后将打印完成。
The Output pdf file is then stored in the default Node.js directory with name test.pdf.
然后,输出pdf文件存储在默认的Node.js目录中,名称为test.pdf 。
Output PDF file...
输出PDF文件...
翻译自: https://www.includehelp.com/node-js/generate-pdf-file-using-node-js-and-puppeteer-api.aspx
puppeteer api