Tuesday, August 24, 2021

Generate pdf from markdown files in a folder using markdown-pdf

I am a big fan of markdown language for writing documents. One of the scenarios we encounter using markdown is to generate a pdf file or convert the markdown files to some other format. This post is to introduce an NPM package that converts markdown files to pdf file. It is considerably old but still does the job.


markdown-pdf npm library is open source software with MIT license. They have just enough documentation as well. It can be used as a command and as a library to use from our nodejs applications.

The limitations I found are as follows.

There is no direct API to convert an entire folder of markdown (.md) files. We have to iterate the folder by ourselves and give it all the file paths. Another problem is to insert page breaks between the markdown files. But that also can be overcome by using pre-processing markdown interceptor and some css tricks.

Sample code

Enough talking. The sample code to perform the below use cases with this library is available in GitHub repo.
  • How a folder can be given to markdown-pdf as there is no direct API
  • How to preprocess markdown files
  • How to give a custom CSS file

How it works

Internally it converts the markdown to HTML by using the remarkable npm library. Once the HTML files are available, it uses the phantomjs to load the HTML in the browser then print as pdf from there. It supports custom CSS files as well. 

Now it might be clear how the line breaks are inserted into the PDF files.

Use cases

If our documentation is prepared using markdown, the pdf file can be generated using this library through the CI/CD pipelines. 

Other libraries


No comments: