Markdown to PDF in MacOSX

I tend to use markdown almost unconsciously when taking notes or expressing thoughts or ideas in a text editor. But on several occasions I’ve had the need to share what I’ve written with a non technical person and handing off markdown to them seems a bit so-so. So after a few of these incidences I settled the matter and decided to investigate if there was an easy way to just generate a pdf file from markdown from the command-line in MacOSX. A quick tour on google and you’ll find this excellent gist that describes more or less how to get it working. The problem was that everything didn’t quite work for me (I later found out that a fix was written in the comment but I didn’t know at the time). These are the two things that I had to do differently:

  1. When it says that you should do brew tap phinze/cask I simply ignored this step and went directly to brew cask install mactex
  2. When it’s time to create a symlink the gist instructs us to do sudo ln -s /usr/texbin/pdflatex /usr/local/bin/ but instead I had to do ln -s /Library/TeX/Root/bin/x86_64-darwin/pdflatex /usr/local/bin/pdflatex

Here are the instructions in its entirety:

$ brew update
$ brew install pandoc
$ brew install ghc cabal-install
$ cabal install pandoc
$ brew cask install mactex
$ ln -s /Library/TeX/Root/bin/x86_64-darwin/pdflatex /usr/local/bin/pdflatex

Now you should be able to run pandoc from the command-line and generate pdfs like this:

$ pandoc -o out.pdf osx-pdf-from-markdown.markdown

Great! But I’m not using pandoc regularly so in order to make it a little easier to remember I wrote a small bash script that I’ve named md2pdf:

if [ -z "${1}" ]; then 
	echo "You need to specify the markdown file"
	exit 0	

# If second argument is undefined then name the output file the same as the input file 
# expect that use a "pdf" file extension
if [ -z "${2}" ]; then 
	# Get the filename (and path) without the extension
	filename_without_ext=`rev <<< "${1}" | cut -d"." -f2- | rev`

pandoc -o "${pdf_filename}" "${1}"

After some chmod +x md2pdf and having copied it to /usr/local/bin this allows me to simply write:

$ md2pdf

and it'll generate a file called some.pdf. It's also possible to specify another directory or filename if you like:

$ md2pdf ~/pdfs/important.pdf

That's it!

3 thoughts on “Markdown to PDF in MacOSX

  1. You don’t need lines 3 and 4; those relate to the Haskell/Cabal method of installing pandoc and are redundant since brew pandoc works fine.

    Thanks for the instructions!

  2. Thanky ou for this article, very useful script! But I think it suffices to install pandoc via brew. Also, an important option to add to the pandoc command in case you write anything possibly containing special characters: `–pdf-engine=xelatex`

Leave a Reply

Your email address will not be published. Required fields are marked *