script.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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.FILE_NAME;
  33. if (!fileName)
  34. throw new Error("В таблице обязательно должно быть поле FILE_NAME");
  35. fs.writeFileSync(
  36. path.resolve(__dirname, "docx", `${fileName}.docx`),
  37. buffer
  38. );
  39. counter += 1;
  40. console.log(`ГЕНЕРИРОВАНО ${counter}`);
  41. callback(null, null);
  42. },
  43. });
  44. inputStream
  45. .pipe(new CsvReadableStream({ trim: true, delimiter: ";", asObject: true }))
  46. .pipe(pdfStream)
  47. .on("finish", () => {
  48. console.log("ГЕНЕРАЦИЯ ЗАВЕРШЕНА");
  49. console.log("--------------------------------------------");
  50. });