buechermarktHelpers/index.js

131 lines
3.2 KiB
JavaScript

const possibleChars = "ABCDESFHIJKLMNOPQRSTUVWXYZ1234567890";
const possibleCharsLength = possibleChars.length;
function randomId(length) {
let ans = "";
for (; length > 0; length--) {
let idx = Math.floor(Math.random() * possibleCharsLength);
ans += possibleChars[idx];
}
return ans;
}
//Generating random preset, to identify possible doubles
const preset = randomId(3);
console.log("The random preset for this set is:", preset);
console.log("Make sure this was not used before and if so, retry");
var etk = {};
for (var i = 0; i < 12 * 100; i++) {
let id = preset + randomId(6);
if (etk[id] !== undefined) i--;
else etk[id] = 1;
}
var ets = Object.keys(etk);
const PDFDocument = require("pdfkit");
const doc = new PDFDocument({ size: "A4", autoFirstPage: false });
const fs = require("fs");
//const barcode = require("barcode");
const bwipjs = require("bwip-js");
const ewidth = 277;
const eheight = 119;
const mgap = 8.49;
doc.pipe(fs.createWriteStream(__dirname + "/etiketten.pdf"));
//A4 2480 x 3508
//doc.addPage({margin: 0});
//S = 1134
//A4: [595.28, 841.89],
// 28.29
//o w:14,15
//o h: 62,24
// <------------> (277)
// |
// | (119)
// |
function print(xo, yo, bc) {
//doc.rect(xo, yo, ewidth, eheight);
//doc.stroke();
//Name Field
doc.fontSize(16);
var h = yo + (eheight / 4) * 3;
doc.text("Name", xo + 5, h + 6);
doc.moveTo(xo + 5, h).lineTo(xo + (ewidth / 4) * 2.2, h);
doc.stroke();
//Price Field;
doc.text("Preis", xo + (ewidth / 4) * 2.4 + 5, h + 6);
doc.moveTo(xo + (ewidth / 4) * 2.4 + 5, h).lineTo(xo + ewidth - 10, h);
doc.stroke();
//Sid Field:
var h = yo + eheight / 4 + 10;
doc.text("SchülerId", xo + (ewidth / 4) * 2.4 + 5, h + 6);
doc.moveTo(xo + (ewidth / 4) * 2.4 + 5, h).lineTo(xo + ewidth - 10, h);
doc.stroke();
//Barcode:
var imagewidth = (ewidth / 4) * 2.2;
var imageheight = 20;
return new Promise((resolve, reject) => {
bwipjs.toBuffer(
{
bcid: "code128",
text: bc,
scale: 1,
height: imageheight,
width: imagewidth,
includetext: true,
textxalign: "center",
textsize: 15,
},
(err, png) => {
if (err) return console.log(err);
doc.image(png, xo + 5, yo + 5, { height: 50, width: imagewidth });
resolve();
}
);
});
}
function page(items, callback, index) {
//bekommt ein array mit 12 ids
doc.addPage({ margin: 0 });
var j = 0;
var proms = [];
for (var i = 0; i < 6; i++) {
if (j >= items.length) break;
proms.push(print(14.15, 62.24 + i * eheight, items[j]));
j++;
}
for (var i = 0; i < 6; i++) {
if (j >= items.length) break;
proms.push(print(14.15 + ewidth + mgap, 62.24 + i * eheight, items[j]));
j++;
}
Promise.all(proms).then(() => {
callback(index + 12);
});
}
function printpack(index) {
if (index >= ets.length) {
doc.end();
return;
}
var i = [];
for (var g = 0; g < 12; g++) {
if (index + g >= ets.length) break;
i.push(ets[index + g]);
}
page(i, printpack, index);
}
printpack(0);