qus-node-pdf-generator
Version:
client api for generating pdfs in nestjs
241 lines (240 loc) • 11.1 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PdfFormat = exports.PdfService = void 0;
const common_1 = require("@nestjs/common");
const Handlebars = __importStar(require("handlebars"));
const chromium_1 = __importDefault(require("@sparticuz/chromium"));
const puppeteer_1 = __importDefault(require("puppeteer"));
let PdfService = (() => {
let _classDecorators = [(0, common_1.Injectable)()];
let _classDescriptor;
let _classExtraInitializers = [];
let _classThis;
var PdfService = _classThis = class {
/**
* Renders a single template into a PDF.
*
* @param template
* @param data
* @param format
* @param landscape
*/
render(template_1, data_1, format_1) {
return __awaiter(this, arguments, void 0, function* (template, data, format, landscape = false) {
const compiledTemplate = Handlebars.compile(template);
const htmlContent = compiledTemplate(data);
console.log("chrome path " + (yield chromium_1.default.executablePath()));
const browser = yield puppeteer_1.default.launch({
executablePath: yield chromium_1.default.executablePath(),
args: chromium_1.default.args,
headless: chromium_1.default.headless,
});
const page = yield browser.newPage();
yield page.setContent(htmlContent, { waitUntil: 'networkidle0' });
const pdfBuffer = yield page.pdf({ format, landscape });
yield browser.close();
return pdfBuffer;
});
}
/**
* Renders multiple templates into a single PDF.
*
* @param templates
* @param data
* @param format
* @param addPageBreaks
* @param styles
* @param landscape
*/
renderMultiple(templates_1, data_1, format_1) {
return __awaiter(this, arguments, void 0, function* (templates, data, format, addPageBreaks = true, styles, landscape = false) {
const defaultStyles = this.getDefaultCss(addPageBreaks);
const appliedStyles = styles || defaultStyles;
let htmlContent = `<body>${appliedStyles}`;
for (let i = 0; i < templates.length; i++) {
const compiledTemplate = Handlebars.compile(templates[i]);
const renderedContent = compiledTemplate(data[i]);
htmlContent += `<div class="page">${renderedContent}</div>`;
}
htmlContent += `</body>`;
console.log('Chromium Path:', yield chromium_1.default.executablePath());
const browser = yield puppeteer_1.default.launch({ headless: 'shell' });
const page = yield browser.newPage();
yield page.setContent(htmlContent, { waitUntil: 'networkidle0' });
const pdfBuffer = yield page.pdf({ format, landscape, printBackground: true });
yield browser.close();
return pdfBuffer;
});
}
/**
* Generates HTML content from multiple templates.
*
* @param templates
* @param data
* @param addPageBreaks
* @param styles
*/
generateHtml(templates_1, data_1) {
return __awaiter(this, arguments, void 0, function* (templates, data, addPageBreaks = true, styles) {
// Default styles if none are provided
const defaultStyles = `
<style>
body {
margin: 0;
padding: 0;
width: 100%;
overflow-x: hidden; /* Prevent horizontal scrolling */
}
.page {
width: 100%;
max-width: 800px; /* Constrain content width */
margin: 0 auto; /* Center content */
padding: 20px; /* Add padding for better readability */
box-sizing: border-box;
${addPageBreaks ? 'page-break-after: always;' : ''} /* Optional page break */
}
.page:last-child {
page-break-after: auto; /* Avoid unnecessary blank page at the end */
}
</style>
`;
// Use provided styles or fallback to default
const appliedStyles = styles || defaultStyles;
// Combine all templates into a single HTML string
let htmlContent = `<body>${appliedStyles}`;
for (let i = 0; i < templates.length; i++) {
const compiledTemplate = Handlebars.compile(templates[i]);
const renderedContent = compiledTemplate(data[i]);
htmlContent += `<div class="page">${renderedContent}</div>`;
}
htmlContent += `</body>`;
return htmlContent;
});
}
getDefaultCss(addPageBreaks) {
return `
<style>
body {
margin: 0;
padding: 0;
width: 100%;
overflow-x: hidden;
}
.page {
width: 100%;
max-width: 800px;
margin: 0 auto;
padding: 20px;
box-sizing: border-box;
${addPageBreaks ? 'page-break-after: always;' : ''}
}
.page:last-child {
page-break-after: auto;
}
</style>
`;
}
};
__setFunctionName(_classThis, "PdfService");
(() => {
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
PdfService = _classThis = _classDescriptor.value;
if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
__runInitializers(_classThis, _classExtraInitializers);
})();
return PdfService = _classThis;
})();
exports.PdfService = PdfService;
// Enum for PDF formats
var PdfFormat;
(function (PdfFormat) {
PdfFormat["A3"] = "A3";
PdfFormat["A4"] = "A4";
PdfFormat["A5"] = "A5";
PdfFormat["Letter"] = "letter";
PdfFormat["Legal"] = "legal";
})(PdfFormat || (exports.PdfFormat = PdfFormat = {}));