Implemented async barcode generation using async helpers

ref #13
This commit is contained in:
2021-02-09 16:38:18 +01:00
parent 4187a8e820
commit edc846ab05
4 changed files with 39 additions and 29 deletions

View File

@@ -1,5 +1,4 @@
import axios from 'axios';
import bwipjs from "bwip-js";
import cheerio from "cheerio";
import fs from "fs";
import Handlebars from 'handlebars';
@@ -9,6 +8,7 @@ import mime from "mime-types";
import path from 'path';
import { PDFDocument } from 'pdf-lib';
import puppeteer from "puppeteer";
import { awaitAsyncHandlebarHelpers, helpers } from './asyncHelpers';
import { Runner } from './models/Runner';
import { RunnerGroup } from './models/RunnerGroup';
@@ -78,18 +78,13 @@ export class PdfCreator {
loadPath: path.join(__dirname, '/locales/{{lng}}.json')
}
});
await Handlebars.registerHelper(helpers);
await Handlebars.registerHelper('__',
function (str) {
return i18next.t(str, PdfCreator.interpolations).toString();
}
);
await Handlebars.registerHelper('--bc',
function (str) {
//TODO: Fix the async behaviour
return "data:image"
return PdfCreator.generateBarcode("code39", str.toString());
}
);
this.browser = await puppeteer.launch({ headless: true, args: minimal_args });
}
@@ -115,7 +110,8 @@ export class PdfCreator {
await i18next.changeLanguage(locale);
const template_source = fs.readFileSync(`${this.templateDir}/sponsoring_contract.html`, 'utf8');
const template = Handlebars.compile(template_source);
const result = template({ runners })
let result = template({ runners });
result = await awaitAsyncHandlebarHelpers(result);
const pdf = await this.renderPdf(result, { format: "A5", landscape: true });
return pdf
}
@@ -190,25 +186,6 @@ export class PdfCreator {
return <Buffer>(await mergedPdf.save());
}
/**
* A simple barcode generation function using default params suitable for usage in pdfs.
* Generates the barcodes as base64-encoded png.
* @param type Barcode type according to this list: https://github.com/metafloor/bwip-js/wiki/BWIPP-Barcode-Types
* @param content Barcode content/text - please remember that some formats only support certain input types.
* @returns Barcode image as base64 encoded png string.
*/
public static async generateBarcode(type: string, content: string): Promise<String> {
let barcode: Buffer = await bwipjs.toBuffer({
bcid: type,
text: content,
scale: 3,
height: 10,
includetext: true,
textxalign: 'center',
});
return `data:image/png;base64,${barcode.toString('base64')}`;
}
/**
* Generates a new dummy runner with halfspaces for all strings.
* Can be used to generate empty sponsoring contracts.