script.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. const PizZip = require("pizzip");
  2. const Docxtemplater = require("docxtemplater");
  3. const fs = require("fs");
  4. const path = require("path");
  5. const CsvReadableStream = require("csv-reader");
  6. const { Transform } = require("stream");
  7. const template = fs.readFileSync(
  8. path.resolve(__dirname, "template.docx"),
  9. "binary"
  10. );
  11. const templateEmpty = fs.readFileSync(
  12. path.resolve(__dirname, "template-empty.docx"),
  13. "binary"
  14. );
  15. const inputStream = fs.createReadStream("data.csv", "utf-8");
  16. fs.rmSync("./docx", { recursive: true, force: true });
  17. fs.mkdirSync("./docx", { recursive: true });
  18. fs.rmSync("./result", { recursive: true, force: true });
  19. fs.mkdirSync("./result", { recursive: true });
  20. console.log("START");
  21. // converting docx to pdf stream
  22. const COUNT = 507;
  23. let counter = 0;
  24. // Transform stream that takes csv data and converts it to docx
  25. // and then to pdf
  26. const pdfStream = new Transform({
  27. objectMode: true,
  28. transform: async (row, encoding, callback) => {
  29. const templateZip = new PizZip(template);
  30. const templateEmptyZip = new PizZip(templateEmpty);
  31. const [NAME, PLACE, NOMINATOIN, TEACHER] = row;
  32. const isEmpty = !NOMINATOIN || !TEACHER;
  33. const doc = new Docxtemplater(isEmpty ? templateEmptyZip : templateZip, {
  34. paragraphLoop: true,
  35. linebreaks: true,
  36. errorLogging: true,
  37. });
  38. doc.render(
  39. isEmpty
  40. ? { NAME, PLACE }
  41. : {
  42. NAME,
  43. PLACE,
  44. NOMINATOIN,
  45. TEACHER,
  46. }
  47. );
  48. const buffer = doc.getZip().generate({
  49. type: "nodebuffer",
  50. });
  51. const fileName = `${isEmpty ? `e-${counter}` : counter}-${NAME.split(" ")
  52. .join("-")
  53. .toLowerCase()}`;
  54. // const html = await mammoth.convertToHtml({ buffer });
  55. fs.writeFileSync(
  56. path.resolve(__dirname, "result", `${fileName}.docx`),
  57. buffer
  58. );
  59. counter += 1;
  60. console.log(`PROCESS ${counter}/${COUNT}`);
  61. callback(null, null);
  62. },
  63. });
  64. inputStream
  65. .pipe(new CsvReadableStream({ trim: true, delimiter: ";", skipHeader: true }))
  66. .pipe(pdfStream)
  67. .on("end", () => {
  68. console.log("DONE");
  69. });