Switched to puppeteer for pdf generation

ref #5
This commit is contained in:
2021-02-05 13:53:46 +01:00
parent 4585a83838
commit 5afd26ea22
3 changed files with 23 additions and 39 deletions

View File

@@ -1,7 +1,6 @@
import fs from "fs";
import pdf_converter from "html-pdf";
import path from 'path';
import { Stream } from 'stream';
import puppeteer from "puppeteer";
/**
* This class is responsible for all things pdf creation.
@@ -9,48 +8,32 @@ import { Stream } from 'stream';
*/
export class PdfCreator {
private templateDir = path.join(__dirname, '/templates');
private browser;
constructor() {
puppeteer.launch({ headless: true }).then(browser => {
this.browser = browser;
});
}
//TODO: Accept the runner class
public async generateSponsoringContract(): Promise<Pdf> {
public async generateSponsoringContract(): Promise<any> {
let template = fs.readFileSync(`${this.templateDir}/sponsoring_contract.html`, 'utf8');
template = template.replace("{{Runner Name}}", "lelele");
return new Pdf(await pdf_converter.create(template, { format: "A5", orientation: "landscape" }));
}
}
/**
* This class is a wrapper for the pdf objects created by html-pdf.
* It offers typed conversion to Buffer and Stream.
*/
export class Pdf {
content: any;
constructor(pdf: any) {
this.content = pdf;
return await this.renderPdf(template, { format: "A5", landscape: true });
}
/**
* Promise wrapper function that resolves the toBuffer promise for pdf generation.
* This method manages the creation of pdfs via puppeteer.
* @param html The HTML that should get rendered.
* @param options Puppeteer PDF option (eg: {format: "A4"})
*/
public async toBuffer(): Promise<Buffer> {
let promise = await new Promise<Buffer>((resolve, reject) => {
this.content.toBuffer(function (err, buffer: Buffer) {
resolve(buffer);
});
});
return await promise;
public async renderPdf(html: string, options): Promise<any> {
const page = await this.browser.newPage();
await page.setContent(html);
const pdf = await page.pdf(options);
await page.close();
return pdf;
}
/**
* Promise wrapper function that resolves the toStream promise for pdf generation.
*/
public async toStream(): Promise<Stream> {
let promise = await new Promise<Stream>((resolve, reject) => {
this.content.toStream(function (err, stream: Stream) {
resolve(stream);
});
});
return await promise;
}
}