Pandoc, PDFs, and PowerShell
I hope that you've been intrigued by the possibilities of Pandoc. It's a powerful tool that can help you convert documents between a wide variety of formats. In today's article, we'll explore how to use Pandoc to convert documents to PDFs. We'll also look at how to use Pandoc in PowerShell scripts to automate the process of converting documents. I've been having a lot of fun figuring out to incorporate Pandoc into my PowerShell work. An important takeaway is not so much how to use Pandoc, but rather how I assimilated a command-line tool into PowerShell
Converting to PDF
One format you may want to use with Pandoc is PDF. Yes, there are ways to create PDF documents from Markdown files in VS Code. But think about the possibilities of converting a folder of Markdown documents to PDF.
Pandoc will convert to a PDF based on the destination file extension.
pandoc -s -o mydoc.pdf mydoc.md
However, you need to have a LaTeX engine installed on your system for creating PDF files. I use MiKTeX. You can download it from MiKTeX.
I used winget to install it.
winget install --id MiKTeX.MiKTeX --source winget
After installing MiKTeX, you should open the MiKTeX Console and update the packages.
Now you can convert your Markdown file to a PDF using many of the same options I've shown you in previous articles.
pandoc -s -o d:\temp\PSGallerReportReadMe.pdf .\README.md --title "PSGallery Report" --toc=True --embed-resources=true --metadata title="PSGallery Report" --highlight-style=kate --to=pdf
> The first time you convert a document, you may be prompted to install additional files.
In this example, I'm explicitly setting the output format.
--to=pdf
If your output file uses a different extension, you might want to include this parameter. Also, don't forget that if you are embedding resources, to run the command in the root folder where the Markdown document resides.
If you are running in an elevated PowerShell session, you will most likely see this warning.
pdflatex: security risk: running with elevated privileges
As long as you have control and trust the content you are converting, you can ignore this warning.
Be aware that not all Pandoc settings will apply to the PDF output. But it doesn't hurt to include them. One PDF-specific setting you might want to set are the document margins. Include this Pandoc setting.
--variable geometry:margin=1in
You can set values like .75in' or
2cm`. Here's one more example.
I'm going to create a single PDF from all of the function help files for my PSWorkItem module.
$docs = (dir c:\scripts\psworkitem\docs\*-*.md).FullName
pandoc -s -o d:\temp\PSWorkItemCommands.pdf $docs --title "PSWorkItem Commands" --toc=True --toc-depth=2 --metadata title="PSWorkItem" --highlight-style=tango --variable monofont=consolas --variable geometry:margin=1in
Within 5 seconds I consolidated 19 Markdown files into a single PDF.