David Carr

Generate PDF and Epub files using Pandoc

Tutorials Bash

I write my books using Markdown. Using a tool called Pandoc you can convert Markdown files into PDFs and Epub files. Let's take a look at the commands.

Install Pandoc with Homebrew

brew install pandoc

Converte a .md file to .pdf aka generate a PDF

pandoc demo.md --pdf-engine=xelatex -o demo.pdf

Note when generating a PDF the option --pdf-engine is required.

The syntax is pandoc followed by the source file add any options with the flag. Set the output location and filename with the -o flag.

if you encounter this error:

pandoc: /Library/TeX/texbin/pdflatex: createProcess: posix_spawnp: illegal operation (Inappropriate ioctl for device)

It means xelatex is not installed on the machine.

To install xelatex:

brew tap homebrew/cask
brew install basictex
eval "$(/usr/libexec/path_helper)"
sudo tlmgr update --self
sudo tlmgr install texliveonfly
sudo tlmgr install xelatex
sudo tlmgr install adjustbox
sudo tlmgr install tcolorbox
sudo tlmgr install collectbox
sudo tlmgr install ucs
sudo tlmgr install environ
sudo tlmgr install trimspaces
sudo tlmgr install titling
sudo tlmgr install enumitem
sudo tlmgr install rsfs

Running the command again:

pandoc demo.md --pdf-engine=xelatex -o demo.pdf

You may see:

[WARNING] Missing character: There is no (U+251C) (U+251C) in font [lmmono10-regular]:!

You can either install a font that supports the symbols, often caused by emojis.

Once the above has been corrected you will be able to generate PDF from Markdown files using:

pandoc demo.md --pdf-engine=xelatex -o demo.pdf

To add a table of contents use the option --toc in the command

Make PDF:

pandoc demo.md --pdf-engine=xelatex --toc -o demo.pdf

Make Epub:

pandoc demo.md --toc -o demo.epub

Front Matter

When working with PDF/Markdown you can specify YAML tags in the markdown to set the book title, author and event the cover image with working with EPUB

This should be at the top of the file, it will not be printed.


---
title: Demo Book
creator:
 - role: author
 text: David Carr
cover-image: cover.jpg
---

Write a book

Here is a basic markdown file; this has chapters designated by # (h1) sub headings can be added by using ## (h2)


---
title: Demo Book
creator:
- role: author
 text: David Carr
cover-image: cover.jpg
---

# Chapter 1

An example chapter.....

# Chapter 2

This is super basic

## Sub chapter that belongs to chapter 2

>Markdown is awesome!

# Chapter 3

Convert this to a PDF or Epub file to produce:

Ebook

Laravel Modules Book by David Carr

Help support the blog so that I can continue creating new content!

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2022 DC Blog. All code MIT license. All rights reserved.