How to create PDF using puppeteer on Azure Functions.

How to create PDF using puppeteer on Azure Functions.

One of the most popular tools for creating PDFs is Puppeteer, which is also required by many Node.js modules. It runs as a “headless browser,” powered by the same Chromium engine as Google Chrome. Because it lacks a graphical user interface, its “headless” design enables developers to use APIs to programmatically control browser behavior, enabling customized features.
HOW TO CREATE PDF USING PUPPETEER ON AZURE FUNCTIONS. | by Prashant Suthar

A strong basis for running and tracking tasks that are initiated by timers, events, or HTTP is provided by Azure Functions. Adopting Azure Functions allows developers to concentrate on creating function logic; infrastructure management, authentication, and monitoring are outsourced to the platform, which is frequently enhanced by Application Insights.

This post will provide instructions on how to use Puppeteer to create PDFs from HTML, webpages, or photos. It will also provide information on how to host this solution as an Azure Functions App. This method facilitates quick setup and smooth integration by streamlining deployment and management.

Let’s now build a PDF using Puppeteer and Azure Functions.

HOW TO CREATE PDF USING PUPPETEER ON AZURE FUNCTIONS. | by Prashant Suthar

To begin, I’ve prepared a working demo available on GitHub.com. Since Puppeteer is a Node.js library, the Function App must be based on Node.js. You can follow the official tutorial for creating a new JavaScript function app using VS Code as your guide.


git clone https://github.com/prashant1879/azure-function-app-puppeteer.git

2. Navigate into the project directory:


cd azure-function-app-puppeteer

3. Install dependencies:


npm install

4. Run the Azure Functions app locally:


func start

HOW TO CREATE PDF USING PUPPETEER ON AZURE FUNCTIONS. | by Prashant Suthar

To initiate the process, launch your preferred web browser and direct it to http://localhost:7071/api/screenshot?url=https://example.com. This action triggers the function responsible for capturing screenshots. Be sure to substitute “https://example.com” with the URL of your choice for the screenshot. This customizable functionality allows you to tailor the screenshot to your specific needs.

package.json


{
    "name": "azure-function-app-puppeteer-pdf",
    "version": "1.0.0",
    "description": "Create pdf from HTML/website",
    "author": "Prashant Suthar",
    "main": "./index.js",
    "scripts": {
      "start": "func start",
      "test": "echo \"No tests yet...\""
    },
    "dependencies": {
      "@azure/functions": "^4.0.0",
      "puppeteer": "^22.8.0",
      "puppeteer-core": "^22.8.0"
    },
    "devDependencies": {
      "azure-functions-core-tools": "^4.x"
    }
  }

screenshot/index.js


const puppeteer = require('puppeteer');

module.exports = async function (context, req) {
    try {
        let options = {
            printBackground: true,
            format: 'a4',
            displayHeaderFooter: false,
            preferCSSPageSize: true, buffer: true,
            margin: {
                top: '12mm',
                right: '12mm',
                bottom: '12mm',
                left: '12mm'
            }
        };

        const browser = await puppeteer.launch({ headless: true, args: [
            '--no-sandbox',
            '--disable-setuid-sandbox'
        ] });

        const page = await browser.newPage();        
        await page.goto('https://image.google.com');

        // Generate PDF
        const pdfBuffer = await page.pdf(options); // Generate PDF as buffer

        // Close the browser
        await browser.close();
        context.res = {
            headers: {
                'Content-Type': 'application/pdf'
            },
            body: pdfBuffer,
            isRaw: true
        };

    } catch (error) {
        context.log.error('[ Generate PDF ] ', error);
        context.res = {
            status: 500,
            body: '[ Generate PDF ] ' + error.toString()
        };
    }
};




{
    "bindings": [
      {
        "authLevel": "anonymous",
        "type": "httpTrigger",
        "direction": "in",
        "name": "req",
        "methods": ["get"]
      },
      {
        "type": "http",
        "direction": "out",
        "name": "res",
        "connection": "AzureWebJobsStorage"
      }
    ]
  }

Don’t overlook the importance of creating a .puppeteerrc.js file at the root of your project. This file is crucial for downloading the latest compatible Chromium version required for Puppeteer to function smoothly. Ensuring the presence of this file guarantees access to the updated Chromium version, optimizing Puppeteer’s performance.

.puppeteerrc.js


// .puppeteerrc.js
const path = require('path');

module.exports = {
  cacheDirectory: path.join(__dirname, '.cache', 'puppeteer')
};

host.json


{
    "version": "2.0",
    "logging": {
      "applicationInsights": {
        "samplingSettings": {
          "isEnabled": true,
          "excludedTypes": "Request"
        }
      }
    },
    "extensionBundle": {
      "id": "Microsoft.Azure.Functions.ExtensionBundle",
      "version": "[4.*, 5.0.0)"
    }
  }

.vscode/settings.json


{
    "azureFunctions.deploySubpath": ".",
    "azureFunctions.projectLanguage": "JavaScript",
    "azureFunctions.projectRuntime": "~4",
    "debug.internalConsoleOptions": "neverOpen",
    "azureFunctions.postDeployTask": "npm install (functions) -f",
    "azureFunctions.preDeployTask": "npm prune (functions)",
    "azureFunctions.scmDoBuildDuringDeployment": true
}

.vscode/extensions.json


{
    "recommendations": [
        "ms-azuretools.vscode-azurefunctions"
    ]
}

.funcignore


*.js.map
*.ts
.git*
.vscode
local.settings.json
test
getting_started.md
node_modules/
node_modules/@types/
node_modules/azure-functions-core-tools/
node_modules/typescript/

Navigate to your directory and run the function locally for quick testing.


npm i && func start

Success! The Azure function is functioning flawlessly. We’ve achieved our goal without any hiccups.

Certainly! Let’s enhance the command for deploying an Azure function from the terminal:


func azure functionapp publish <FuctionApp> --build remote

HOW TO CREATE PDF USING PUPPETEER ON AZURE FUNCTIONS. | by Prashant Suthar
HOW TO CREATE PDF USING PUPPETEER ON AZURE FUNCTIONS. | by Prashant Suthar

I hope you like this article. Keep visiting my website for more upcoming articles. If you need any help with HOW TO CREATE PDF USING PUPPETEER ON AZURE FUNCTIONS. you can contact me. You can ask me questions in the comments also. You can connect me on social media as well as links are below in the footer section. Keep connected. Happy Coding.

Prashant Sutharhttps://prashantsuthar.com
My self Prashant Suthar, I had experience worked with NodeJS, Core PHP, WordPress, CodeIgniter, Shopify, Prestashop, Opencart and many frameworks. I had some basic knowledge about server setup and maintenance. I also worked with third parties APIs like Twillio audio,video, SMS API, FB messenger API and many more. I am working as team lead & sr. developer in Ahmedabad, GJ, IN.

Comments

Similar Articles