to_pdf.js 1.3 KB

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