to_pdf.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. const cv = yaml.parse(fs.readFileSync("./cv.yaml", { encoding: "utf8" }));
  8. function changeExt(filePath, new_) {
  9. parsed = path.parse(filePath)
  10. return path.join(parsed.dir, `${path.basename(parsed.name)}.${new_}`)
  11. }
  12. function createHtml(pug_file) {
  13. const rendered = pug.renderFile(pug_file, cv)
  14. const html_path = changeExt(pug_file, "html")
  15. fs.writeFile(html_path, rendered, (err) => {
  16. if (err) throw err;
  17. })
  18. console.log(`Wrote HTML file to ${html_path}`)
  19. return html_path
  20. }
  21. async function printPDF(url) {
  22. const browser = await puppeteer.launch({ headless: "new" });
  23. const page = await browser.newPage();
  24. await page.goto(url, { waitUntil: 'networkidle0' });
  25. const pdf = await page.pdf({ format: 'A4' });
  26. await browser.close();
  27. return pdf
  28. }
  29. function exportToPdf(htmlFile) {
  30. url = `file://${path.resolve(htmlFile)}`
  31. pdf_path = changeExt(htmlFile, "pdf")
  32. printPDF(url).then((pdf) => {
  33. fs.writeFile(pdf_path, pdf, (err) => {
  34. if (err) throw err;
  35. })
  36. console.log(`Wrote PDF file to ${pdf_path}`)
  37. })
  38. }
  39. local_pug_path = './resume.pug'
  40. local_pdf_path = changeExt(local_pug_path, "pdf")
  41. local_html_path = createHtml(local_pug_path)
  42. exportToPdf(local_html_path)