UNPKG

@topgroup/diginext

Version:

A BUILD SERVER & CLI to deploy apps to any Kubernetes clusters.

82 lines (81 loc) 2.94 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const makeDaySlug_1 = require("diginext-utils/dist/string/makeDaySlug"); const fs_1 = require("fs"); const path_1 = __importDefault(require("path")); const puppeteer_1 = __importDefault(require("puppeteer")); const app_config_1 = require("../../app.config"); const const_1 = require("../../config/const"); const defaultExportPdfOptions = { viewport: { width: 1400, height: 900 }, printBackground: true, path: "../public/pdf/webpage.pdf", format: "a4", scale: 1, margin: { top: "20px", bottom: "40px", left: "20px", right: "20px", }, displayHeaderFooter: false, omitBackground: false, }; const exportPdf = async (url, options = defaultExportPdfOptions) => { if (!url) throw new Error("URL parameter is missing."); const _options = { ...defaultExportPdfOptions, ...options }; // upload directory const dir = path_1.default.resolve(const_1.CLI_DIR, "public/upload/pdf"); if (!(0, fs_1.existsSync)(dir)) (0, fs_1.mkdirSync)(dir, { recursive: true }); const fileName = `webpage-${(0, makeDaySlug_1.makeDaySlug)({ divider: "" })}.pdf`; const filePath = path_1.default.resolve(dir, fileName); const fileUrl = `${app_config_1.Config.BASE_URL}/upload/pdf/${fileName}`; _options.path = filePath; const browser = await puppeteer_1.default.launch({ headless: true, defaultViewport: _options.viewport, executablePath: process.env.CHROMIUM_PATH, args: [ "--no-sandbox", "--disable-dev-shm-usage", // <-- add this one ], }); const page = await browser.newPage(); try { // disable cache... await page.setCacheEnabled(false); await page.setDefaultNavigationTimeout(60000); await page.goto(url, { waitUntil: "networkidle0", }); const pdfBuffer = await page.pdf({ printBackground: _options.printBackground, path: _options.path, format: _options.format, scale: _options.scale, margin: _options.margin, displayHeaderFooter: _options.displayHeaderFooter, omitBackground: _options.omitBackground, }); await page.close(); await browser.close(); if (!pdfBuffer) return; // res.contentType("application/pdf"); // res.send(pdfBuffer); return { name: fileName, path: filePath, url: fileUrl, buffer: pdfBuffer, mime: "application/pdf" }; } catch (e) { throw new Error(`Unable to export PDF of "${url}": ${e}`); } finally { await page.close(); await browser.close(); } }; exports.default = exportPdf;