Skip to content

Instantly share code, notes, and snippets.

@matiasinsaurralde
Created March 30, 2019 10:20
Show Gist options
  • Save matiasinsaurralde/5ecbe19579de4db96c92be285ee83b4c to your computer and use it in GitHub Desktop.
Save matiasinsaurralde/5ecbe19579de4db96c92be285ee83b4c to your computer and use it in GitHub Desktop.
tykdocs2pdf.js
var markdownpdf = require("markdown-pdf")
path = require("path")
fs = require("fs")
glob = require("glob")
mkdirp = require("mkdirp")
metadataParser = require('markdown-yaml-metadata-parser')
pdftk = require('node-pdftk')
async = require('async')
var tykDocsPath = "/Users/matias/dev/tyk-docs/tyk-docs"
contentPath = path.join(tykDocsPath, "content")
targetPath = "/Users/matias/dev/markdown-experiment/output",
assetsPath = path.join(tykDocsPath, "static")
outputPdfPath = "./output.pdf"
if (!fs.existsSync(targetPath)) {
fs.mkdirSync(targetPath)
}
var pdfs = []
// Iterate through all MD files:
glob(path.join(tykDocsPath, "content", "**/*.md"), {}, function (err, files) {
async.eachSeries(files, function (f, cb) {
var baseName = path.basename(f)
var newDir = path.join(targetPath, f.replace(contentPath, "").replace(baseName, ""))
// Prepare the PDF path:
var pdfPath = path.join(newDir, baseName.replace(".md", ".pdf"))
if (!fs.existsSync(newDir)) {
mkdirp.sync(newDir)
}
// Load the Markdown contents and replace the assets path:
var file = fs.readFileSync(f)
mdContents = file.toString().replace(new RegExp("/docs", 'g'), assetsPath)
// Separate metadata and contents (metadata is available as result.metadata):
var result = metadataParser(mdContents)
// Create the PDF:
markdownpdf().from.string(result.content).to(pdfPath, function () {
console.log("Created", pdfPath)
pdfs.push(pdfPath)
cb();
})
}, function() {
// When finished, merge all the PDFs:
console.log("Done.", pdfs.length, "PDFs created")
pdftk
.input(pdfs)
.output(outputPdfPath)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment