md-to-pdf is a free, open source documentation & knowledge base project written in TypeScript and released under MIT. It has 1,952 GitHub stars, 161 forks and 47 open issues, and was last pushed 10 months ago. On this registry it ranks #58 of 91 tracked projects in Documentation & Knowledge Base, with 5 head-to-head comparisons available.

Markdown to PDF

GitHub Workflow Status NPM version

Screenshot of markdown file and resulting PDF

A simple and hackable CLI tool for converting markdown to pdf. It uses Marked to convert markdown to html and Puppeteer (headless Chromium) to further convert the html to pdf. It also uses highlight.js for code highlighting. The whole source code of this tool is only ~250 lines of JS ~500 lines of Typescript and ~100 lines of CSS, so it is easy to clone and customize.

Highlights:

  • Concurrently convert multiple Markdown files
  • Watch mode
  • Use your own or remote stylesheets/scripts
  • Front-matter for configuration
  • Headers and Footers
  • Page Breaks
  • Syntax highlighting in code blocks
  • Extend the options of the underlying tools
  • Programmatic API
  • Supports stdio
  • Convert HTML (or inline HTML) to PDF

Installation

Option 1: NPM

npm i -g md-to-pdf

Option 2: Git

If you want to have your own copy to hack around with, clone the repository instead:

git clone "https://github.com/simonhaenisch/md-to-pdf"
cd md-to-pdf
npm link # or npm i -g

Then the commands md-to-pdf and md2pdf (as a shorthand) will be globally available in your cli. Use npm start to start the TypeScript compiler (tsc) in watch mode.

Update

If you installed via npm, run npm i -g md-to-pdf@latest in your CLI. If you cloned this repository instead, you can simply do a git pull to get the latest changes from the master branch, then do npm run build to re-build. Unless there have been changes to packages (i. e. package-lock.json), you don't need to re-install the package (because NPM 5+ uses symlinks, at least on Unix systems).

Usage

$ md-to-pdf [options] path/to/file.md

Options:

  -h, --help ............... Output usage information
  -v, --version ............ Output version
  -w, --watch .............. Watch the current file(s) for changes
  --watch-options .......... Options for Chokidar's watch call
  --basedir ................ Base directory to be served by the file server
  --stylesheet ............. Path to a local or remote stylesheet (can be passed multiple times)
  --css .................... String of styles
  --document-title ......... Name of the HTML Document.
  --body-class ............. Classes to be added to the body tag (can be passed multiple times)
  --page-media-type ........ Media type to emulate the page with (default: screen)
  --highlight-style ........ Style to be used by highlight.js (default: github)
  --marked-options ......... Set custom options for marked (as a JSON string)
  --pdf-options ............ Set custom options for the generated PDF (as a JSON string)
  --launch-options ......... Set custom launch options for Puppeteer
  --gray-matter-options .... Set custom options for gray-matter
  --port ................... Set the port to run the http server on
  --md-file-encoding ....... Set the file encoding for the markdown file
  --stylesheet-encoding .... Set the file encoding for the stylesheet
  --as-html ................ Output as HTML instead
  --config-file ............ Path to a JSON or JS configuration file
  --devtools ............... Open the browser with devtools instead of creating PDF

The pdf is generated into the same directory as the source file and uses the same filename (with .pdf extension) by default. Multiple files can be specified by using shell globbing, e. g.:

md-to-pdf ./**/*.md

(If you use bash, you might need to enable the globstar shell option to make recursive globbing work.)

Alternatively, you can pipe the markdown in from stdin and redirect its stdout into a target file:

cat file.md | md-to-pdf > path/to/output.pdf

Tip: You can concatenate multiple files using cat file1.md file2.md.

The current working directory (process.cwd()) serves as the base directory of the file server by default. This can be adjusted with the --basedir flag (or equivalent config option). Note that because of the file server, if you convert a file that's outside the current folder, you'll have to move the base directory up as well (e. g. md-to-pdf ../path/to/file.md --basedir ..).

Watch Mode

Watch mode (--watch) uses Chokidar's watch method on the markdown file. If you're having issues, you can adjust the watch options via the config (watch_options) or --watch-options CLI arg. The awaitWriteFinish option might be particularly useful if you use editor plugins (e. g. TOC generators) that modify and save the file after the initial save. Check out the Chokidar docs for a full list of options.

Note that Preview on macOS does not automatically reload the preview when the file has changed (or at least not reliably). There are PDF viewers available that can check for file changes and offer auto-reload (e. g. Skim's "Sync" feature).

Programmatic API

The programmatic API is very simple: it only exposes one function that accepts either a path to or content of a markdown file, and an optional config object (which can be used to specify the output file destination).

const fs = require('fs');
const { mdToPdf } = require('md-to-pdf');

(async () => {
	const pdf = await mdToPdf({ path: 'readme.md' }).catch(console.error);

	if (pdf) {
		fs.writeFileSync(pdf.filename, pdf.content);
	}
})();

The function throws an error if anything goes wrong, which can be handled by catching the rejected promise. If you set the dest option in the config, the file will be written to the specified location straight away:

await mdToPdf({ content: '# Hello, World' }, { dest: 'path/to/output.pdf' });
Page Break

Place an element with class page-break to force a page break at a certain point of the document (uses the CSS rule page-break-after: always), e. g.:

<div class="page-break"></div>
Header/Footer

Use headerTemplate and footerTemplate of Puppeteer's page.pdf() options. If either of the two is set, then displayHeaderFooter will be enabled by default. It's possible to inject a few dynamic values like page numbers by using certain class names, as stated in the Puppeteer docs. Please note that for some reason the font-size defaults to 1pt, and you need to make sure to have enough page margin, otherwise your header/footer might be overlayed by your content. If you add a `` tag in either of the templates, it will be applied to both header and footer.

Example markdown frontmatter config that prints the date in the header and the page number in the footer:

---
pdf_options:
  format: a4
  margin: 30mm 20mm
  printBackground: true
  headerTemplate: |-
    <style>
      section {
        margin: 0 auto;
        font-family: system-ui;
        font-size: 11px;
      }
    </style>
    <section>
      <span class="title"></span>
      <span class="date"></span>
    </section>
  footerTemplate: |-
    <section>
      <div>
        Page <span class="pageNumber"></span>
        of <span class="totalPages"></span>
      </div>
    </section>
---

Refer to the Puppeteer docs for more info about header and footer templates.

Formulas

This can be achieved with MathJax. A simple example can be found in /src/test/mathjax.

Default and Advanced Options

For default and advanced options see the following links. The default highlight.js styling for code blocks is github. The default PDF options are the A4 format and some margin (see lib/config.ts for the full default config).

Options

Option Examples
--basedir path/to/folder
--stylesheet path/to/style.css, `https://example.org/stylesh

readme truncated — read the full docs on github

Frequently asked questions

Is md-to-pdf free to use?

md-to-pdf is open source under the MIT licence. There is no licence fee and no seat count — you can self-host it or, where the project offers one, pay a vendor for a managed version instead.

What does md-to-pdf do?

Hackable CLI tool for converting Markdown files to PDF using Node.js and headless Chrome.

What is md-to-pdf written in?

md-to-pdf is primarily written in TypeScript. Its source is publicly available at https://github.com/simonhaenisch/md-to-pdf, and it has 1,952 GitHub stars.