to_pdf.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/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 parseResume(resumePath) {
  8. return yaml.parse(fs.readFileSync(resumePath, { encoding: "utf8" }));
  9. }
  10. function createHtml(pugFile, resumeData, outputPath) {
  11. const rendered = pug.renderFile(pugFile, resumeData);
  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 exportResumeToPdf(resumeDataPath, localPugPath, assetsPath, outputPath) {
  33. const resumeData = parseResume(resumeDataPath);
  34. const htmlPath = path.join(outputPath, "resume.html");
  35. const pdfPath = path.join(outputPath, "resume.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(localPugPath, resumeData, htmlPath);
  41. console.log(`Wrote HTML file to ${htmlPath}`);
  42. exportToPdf(htmlPath, pdfPath);
  43. console.log(`Wrote PDF file to ${pdfPath}`);
  44. }
  45. const [resumeDataPath, resumeTemplatePath, assetsPath, outputPath] = process.argv.slice(2);
  46. if (!resumeDataPath || !resumeTemplatePath || !assetsPath || !outputPath) {
  47. console.error(
  48. `The script should be called like :\n${process.argv[1]} resume_path template_path assets_dir output_dir`
  49. );
  50. process.exit(1);
  51. }
  52. exportResumeToPdf(resumeDataPath, resumeTemplatePath, assetsPath, outputPath);