to_pdf.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env node
  2. const fs = require("fs");
  3. const path = require("path");
  4. const yaml = require("yaml");
  5. const puppeteer = require("puppeteer");
  6. const pug = require("pug");
  7. function parseData(dataFilePath) {
  8. return yaml.parse(fs.readFileSync(dataFilePath, { encoding: "utf8" }));
  9. }
  10. function createHtml(pugFile, data, outputPath) {
  11. const rendered = pug.renderFile(pugFile, data);
  12. fs.writeFile(outputPath, rendered, (err) => {
  13. if (err) throw err;
  14. });
  15. }
  16. async function printPDF(url) {
  17. const browser = await puppeteer.launch({ headless: "new" });
  18. const page = await browser.newPage();
  19. await page.goto(url, { waitUntil: "networkidle0" });
  20. const pdf = await page.pdf({ format: "A4" });
  21. await browser.close();
  22. return pdf;
  23. }
  24. function exportToPdf(htmlFile, pdfPath) {
  25. url = `file://${path.resolve(htmlFile)}`;
  26. printPDF(url).then((pdf) => {
  27. fs.writeFile(pdfPath, pdf, (err) => {
  28. if (err) throw err;
  29. });
  30. });
  31. }
  32. function exportRenderToPdf(dataFilePath, templatePath, assetsPath, outputPath, outputBasename) {
  33. const data = parseData(dataFilePath);
  34. const htmlPath = path.join(outputPath, `${outputBasename}.html`);
  35. const pdfPath = path.join(outputPath, `${outputBasename}.pdf`);
  36. const newAssetsPath = path.join(outputPath, "assets");
  37. fs.mkdirSync(outputPath, { recursive: true });
  38. fs.mkdirSync(newAssetsPath, { recursive: true });
  39. fs.cpSync(assetsPath, newAssetsPath, { recursive: true });
  40. createHtml(templatePath, data, htmlPath);
  41. console.log(`Wrote HTML file to ${htmlPath}`);
  42. exportToPdf(htmlPath, pdfPath);
  43. console.log(`Wrote PDF file to ${pdfPath}`);
  44. }
  45. const [inputPath, templateName, variantName, outputPath] = process.argv.slice(2);
  46. if (!inputPath || !templateName || !variantName || !outputPath) {
  47. console.error(
  48. `The script should be called like :\n${process.argv[1]} input_path template_name variant_name output_dir`
  49. );
  50. process.exit(1);
  51. }
  52. const dataFilePath = path.join(inputPath, `${variantName}.yaml`);
  53. const templatePath = path.join(inputPath, `${templateName}.pug`);
  54. const assetsPath = path.join(inputPath, "assets");
  55. exportRenderToPdf(dataFilePath, templatePath, assetsPath, outputPath, "resume");