smp-serverless-utils
Version:
Utilities for working with GCP Storage, file handling, and PDF/SVG conversions
68 lines (67 loc) • 2.7 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.htmlToPdf = void 0;
const puppeteer_core_1 = __importDefault(require("puppeteer-core"));
const chromium_1 = __importDefault(require("@sparticuz/chromium"));
const path_1 = require("path");
const fs_1 = require("fs");
const os_1 = require("os");
const utils_1 = require("./utils");
const chromeArgs_1 = require("./chromeArgs");
const xss_1 = require("xss");
const tempDir = (0, os_1.tmpdir)();
const BUCKET_NAME = process.env.BUCKET_NAME;
const htmlToPdf = async ({ html, fileName, margin, htmlHeader, htmlFooter, }) => {
const xssFilter = new xss_1.FilterXSS({
css: false,
whiteList: {
img: ["style", "src", "srcset", "width", "height", "alt"],
div: ["style"],
p: ["style"],
},
});
const uniqueFileName = `${(0, utils_1.getUniqueFileName)(fileName)}.pdf`;
const sanitizedHtml = xssFilter.process(JSON.parse(html));
const finalHtml = htmlHeader + sanitizedHtml + htmlFooter;
const localPath = (0, path_1.join)(tempDir, uniqueFileName);
let browser = await puppeteer_core_1.default.launch({
args: [...chromium_1.default.args, ...chromeArgs_1.minimalArgs],
defaultViewport: chromium_1.default.defaultViewport,
executablePath: await chromium_1.default.executablePath(),
headless: chromium_1.default.headless,
// ignoreHTTPSErrors: true,
});
const page = await browser.newPage();
await page.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36");
try {
await page.setContent(finalHtml);
const pdfBuffer = await page.pdf({
printBackground: true,
margin: {
top: margin?.top || "1cm",
right: margin?.right || "1cm",
bottom: margin?.bottom || "1cm",
left: margin?.left || "1cm",
},
});
(0, fs_1.writeFileSync)(localPath, pdfBuffer);
const publicUrl = await (0, utils_1.uploadToGCPBucket)(BUCKET_NAME, localPath, {
functionName: "htmlToPDFConverter",
fileName: uniqueFileName,
});
return {
message: "PDF generated and uploaded successfully.",
url: publicUrl,
};
}
catch (error) {
throw new Error(error.message || "Failed to process HTML content.");
}
finally {
await browser.close();
}
};
exports.htmlToPdf = htmlToPdf;