Setup puppeteer and use in Native custom APIs
Puppeteer installation
-
Log in as the root user in your server where API Maker instance is hosted.
-
This step will help you install dependencies essential for using puppeteer. This command is used for ubuntu servers. If your servers uses any other os image then you should refer to puppeteer documentation for more details. Install the necessary dependencies for puppeteer using this command:
sudo apt update && sudo apt install -y \ ca-certificates \ fonts-liberation \ libatk1.0-0t64 \ libatk-bridge2.0-0t64 \ libc6 \ libcairo2 \ libcups2 \ libdbus-1-3 \ libexpat1 \ libfontconfig1 \ libgbm1 \ libgcc1 \ libglib2.0-0 \ libgtk-3-0 \ libnspr4 \ libnss3 \ libpango-1.0-0 \ libpangocairo-1.0-0 \ libstdc++6 \ libx11-6 \ libx11-xcb1 \ libxcb1 \ libxcomposite1 \ libxcursor1 \ libxdamage1 \ libxext6 \ libxfixes3 \ libxi6 \ libxrandr2 \ libxrender1 \ libxss1 \ libxtst6 \ libasound2t64 \ lsb-release \ wget \ xdg-utils -
After confirming the Installation Navigate to the project directory using this command:
-
Now run the this command to install puppeteer.
-
At this point puppeteer is installed in your server successfully, In the next section we will see how to use the package in your code.
How to Use puppeteer in your Custom API.
-
The first step is to make the custom API run on native process, by defining this property in API Configuration.
-
Here is the simple custom API Example using puppeteer for PDF generation.
import * as T from 'types'; import { join } from "path"; const puppeteer = require('puppeteer'); async function main(g: T.IAMGlobal) { const filePath = join(__dirname, 'uploads', 'puppeteer.pdf'); const html = ` <!DOCTYPE html> <html> <body> <p>Hello, this paragraph is converted to a PDF using Puppeteer.</p> </body> </html> `; const browser = await puppeteer.launch({ headless: 'new', args: ['--no-sandbox','--disable-setuid-sandbox'] }); const page = await browser.newPage(); // Load HTML await page.setContent(html, { waitUntil: 'load' }); // Create PDF await page.pdf({ path: filePath, format: 'A4', printBackground: true, }); await browser.close(); // `filePath` contains the location of the generated PDF. // You can use this path to upload the file to a storage provider // or serve it for download. return "ok"; }; module.exports = main;
Reference Pages: