From 4617f2c5bdcb29534b46865ebe21d15e2b1cd72f Mon Sep 17 00:00:00 2001 From: Nicolai Ort Date: Tue, 2 Feb 2021 11:02:23 +0100 Subject: [PATCH] Resolved fun issues with promises ref #3 --- src/PdfCreator.ts | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/src/PdfCreator.ts b/src/PdfCreator.ts index 1650c79..3fa95a8 100644 --- a/src/PdfCreator.ts +++ b/src/PdfCreator.ts @@ -1,14 +1,42 @@ import fs from "fs"; +import pdf_converter from "html-pdf"; import path from 'path'; - /** * This class is responsible for all things pdf creation. * This uses the html templates from src/templates. */ -export class PdFCreator { +export class PdfCreator { private templateDir = path.join(__dirname, '/templates'); - public generateSponsoringContract() { + public async generateSponsoringContract(): Promise { const template = fs.readFileSync(`${this.templateDir}/sponsoring_contract.html`, 'utf8'); + let pdf = await pdf_converter.create(template, { format: "A5", orientation: "landscape" }); + return await this.toBuffer(pdf); + } + + /** + * Promise wrapper function that resolves the toBuffer promise for pdf generation. + * @param pdf The pdf object that shall be turned into a buffer. + */ + public async toBuffer(pdf): Promise { + let promise = await new Promise((resolve, reject) => { + pdf.toBuffer(function (err, buffer) { + resolve(buffer); + }); + }); + return await promise; + } + + /** + * Promise wrapper function that resolves the toStream promise for pdf generation. + * @param pdf The pdf object that shall be turned into a stream. + */ + public async toStream(pdf): Promise { + let promise = await new Promise((resolve, reject) => { + pdf.toStream(function (err, stream) { + resolve(stream); + }); + }); + return await promise; } }