Use Pandoc on macOS to convert multiple markdown files to a single PDF file

Installation

  1. Install Pandoc
Terminal window
brew install pandoc
  1. Install BasicTex for PDF generation

BasicTex (2GB) is smaller than MacText (110MB) and it’s enough for this task.

Terminal window
brew cask install basictex
ln -s /Library/TeX/Distributions/.DefaultTeX/Contents/Programs/x86_64/pdflatex /usr/local/bin

Usage

Generating a PDF file from multiple markdown files is very simple.

Terminal window
pandoc *.md -o docs.pdf

Code blocks

By default, code blocks are not wrapped. If you have a code block with very long lines (longer than PDF document width), they will be cut off.

Pandoc - code blocks - default

To fix this issue, you need fvextra extension. You can download it from GitHub.

Terminal window
wget https://raw.githubusercontent.com/gpoore/fvextra/master/fvextra/fvextra.sty

Store the file in the directory where you want to execute the pandoc command.

Modify the markdown file where you have code blocks and add YAML header options at the top of the file:

---
header-includes:
- \usepackage{fvextra}
- \DefineVerbatimEnvironment{Highlighting}{Verbatim}{breaklines,commandchars=\\\{\}}
---
...

You can generate a PDF file once again with wrapped code blocks.

Terminal window
pandoc *.md -o docs.pdf

Pandoc - code blocks - wrapped