Moved pdf creatior initialization to new function

ref #5
This commit is contained in:
Nicolai Ort 2021-02-06 21:30:18 +01:00
parent f755f4f9fb
commit 47a05facb3
2 changed files with 11 additions and 11 deletions

View File

@ -20,7 +20,13 @@ export class PdfCreator {
* Initializes i18n(ext), Handlebars and puppeteer. * Initializes i18n(ext), Handlebars and puppeteer.
*/ */
constructor() { constructor() {
i18next this.init().then(() => {
return this;
})
}
public async init() {
await i18next
.use(Backend) .use(Backend)
.init({ .init({
fallbackLng: 'en', fallbackLng: 'en',
@ -29,14 +35,12 @@ export class PdfCreator {
loadPath: path.join(__dirname, '/locales/{{lng}}.json') loadPath: path.join(__dirname, '/locales/{{lng}}.json')
} }
}); });
Handlebars.registerHelper('__', await Handlebars.registerHelper('__',
function (str) { function (str) {
return i18next.t(str, PdfCreator.interpolations).toString(); return i18next.t(str, PdfCreator.interpolations).toString();
} }
); );
puppeteer.launch({ headless: true }).then(browser => { this.browser = await puppeteer.launch({ headless: true });
this.browser = browser;
});
} }
/** /**
@ -49,7 +53,6 @@ export class PdfCreator {
const template_source = fs.readFileSync(`${this.templateDir}/sponsoring_contract.html`, 'utf8'); const template_source = fs.readFileSync(`${this.templateDir}/sponsoring_contract.html`, 'utf8');
const template = Handlebars.compile(template_source); const template = Handlebars.compile(template_source);
const result = template({ runners }) const result = template({ runners })
console.log(template)
return await this.renderPdf(result, { format: "A5", landscape: true }); return await this.renderPdf(result, { format: "A5", landscape: true });
} }
@ -59,7 +62,7 @@ export class PdfCreator {
* @param options Puppeteer PDF option (eg: {format: "A4"}) * @param options Puppeteer PDF option (eg: {format: "A4"})
*/ */
public async renderPdf(html: string, options): Promise<any> { public async renderPdf(html: string, options): Promise<any> {
const page = await this.browser.newPage(); let page = await this.browser.newPage();
await page.setContent(html); await page.setContent(html);
const pdf = await page.pdf(options); const pdf = await page.pdf(options);
await page.close(); await page.close();

View File

@ -10,10 +10,7 @@ import { PdfCreator } from '../PdfCreator';
*/ */
@JsonController() @JsonController()
export class PdfController { export class PdfController {
private pdf: PdfCreator; private pdf: PdfCreator = new PdfCreator();
constructor() {
this.pdf = new PdfCreator();
}
@Post('/contracts') @Post('/contracts')
@OpenAPI({ description: "Generate Sponsoring contract pdfs from runner objects.<br>You can choose your prefered locale by passing the 'locale' query-param." }) @OpenAPI({ description: "Generate Sponsoring contract pdfs from runner objects.<br>You can choose your prefered locale by passing the 'locale' query-param." })