script.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 [dataFilePath, templateFilePath] = process.argv.slice(2);
  8. const template = fs.readFileSync(templateFilePath, "binary");
  9. const inputStream = fs.createReadStream(dataFilePath, "utf-8");
  10. fs.rmSync("./docx", { recursive: true, force: true });
  11. fs.mkdirSync("./docx", { recursive: true });
  12. fs.rmSync("./result", { recursive: true, force: true });
  13. fs.mkdirSync("./result", { recursive: true });
  14. console.log("ЭТАП ГЕНЕРАЦИИ ПО ШАБЛОНУ");
  15. // converting docx to pdf stream
  16. let counter = 0;
  17. // Transform stream that takes csv data and converts it to docx
  18. // and then to pdf
  19. const pdfStream = new Transform({
  20. objectMode: true,
  21. transform: async (row, _encoding, callback) => {
  22. const templateZip = new PizZip(template);
  23. const doc = new Docxtemplater(templateZip, {
  24. paragraphLoop: true,
  25. linebreaks: true,
  26. errorLogging: true,
  27. });
  28. doc.render(row);
  29. const buffer = doc.getZip().generate({
  30. type: "nodebuffer",
  31. });
  32. const fileName = `${row.NOMINATION.replace(
  33. "Изобразительное искусство",
  34. "ИЗО"
  35. ).replace("Декоративно-прикладное искусство", "ДПИ")} ${row.NAME}`;
  36. fs.writeFileSync(
  37. path.resolve(__dirname, "docx", `${fileName}.docx`),
  38. buffer
  39. );
  40. counter += 1;
  41. console.log(`ГЕНЕРИРОВАНО ${counter}`);
  42. callback(null, null);
  43. },
  44. });
  45. inputStream
  46. .pipe(new CsvReadableStream({ trim: true, delimiter: ";", asObject: true }))
  47. .pipe(pdfStream)
  48. .on("finish", () => {
  49. console.log("ГЕНЕРАЦИЯ ЗАВЕРШЕНА");
  50. console.log("--------------------------------------------");
  51. });