Skip to content

Instantly share code, notes, and snippets.

@dphiffer
Created July 28, 2021 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dphiffer/5909fc195bae581ad23a8de47aed9f0d to your computer and use it in GitHub Desktop.
Save dphiffer/5909fc195bae581ad23a8de47aed9f0d to your computer and use it in GitHub Desktop.
Basic Text → PDF converter
const puppeteer = require('puppeteer');
const fs = require('fs');
if (process.argv.length < 3) {
console.log('Usage: node txt2pdf.js [file]');
process.exit(1);
}
const input = process.argv[2];
const output = `${input}.pdf`;
const css = `
<style>
pre {
font: 11px/13px menlo;
}
</style>
`;
(async () => {
const browser = await puppeteer.launch({
headless: true
});
const page = await browser.newPage();
const source = fs.readFileSync(input, 'utf8');
await page.setContent(`${css}<pre>${source}</pre>`, {
waitUntil: 'domcontentloaded'
});
await page.pdf({
path: output,
margin: {
top: '0.5in',
right: '0.75in',
bottom: '0.5in',
left: '0.75in'
}
});
await browser.close();
console.log(`Saved ${output}`);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment