2024-10-03 Web Development
Converting Markdown to PDF with Puppeteer and Markdown-it
By O Wolfson
How to convert a Markdown file to a PDF using Node.js. We'll use the puppeteer-core
library to generate the PDF and markdown-it
to parse the Markdown content. Additionally, we'll add custom styling, including margins and page breaks.
Prerequisites
Before we begin, ensure you have Node.js installed. You'll also need to install the following packages:
puppeteer-core
markdown-it
markdown-it-container
You can install these packages using npm:
Step-by-Step Guide
1. Initializing the Project
First, create a new file called convertMarkdownToPdf.js
and add the following code:
This code imports the necessary modules:
fs
andpath
for file system operations.puppeteer-core
to generate the PDF.markdown-it
andmarkdown-it-container
to parse the Markdown content and handle custom HTML containers.
2. Configuring Markdown-it
Next, we configure markdown-it
to use the markdown-it-container
plugin for custom HTML containers:
This configuration allows us to use ::: pagebreak :::
in our Markdown file to insert a page break in the PDF.
3. Converting Markdown to HTML
We create a function to convert Markdown content to HTML and include custom styling:
This function takes the Markdown content, converts it to HTML, and wraps it with additional styling for padding and margins.
4. Converting HTML to PDF
We then create a function to convert the HTML content to a PDF using Puppeteer:
Ensure the executablePath
points to your Chrome executable. You can find the path using:
- macOS:
which /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome
- Linux:
which google-chrome
- Windows: Use the full path, e.g.,
C:\Program Files\Google\Chrome\Application\chrome.exe
5. Main Function to Convert Markdown to PDF
Finally, we create the main function to read the Markdown file, convert it to HTML, and then to a PDF:
This function reads the content of example.md
, converts it to HTML, and then generates a PDF example.pdf
.
Running the Script
Ensure your example.md
file is in the same directory as the script. The Markdown file can contain the following content for testing:
Run the script using Node.js:
This will generate example.pdf
with the specified formatting and page breaks.
Conclusion
By following this guide, you can convert Markdown files to PDFs with custom styling and page breaks using Node.js, Puppeteer, and Markdown-it. This method provides a flexible way to generate professional-looking PDFs from Markdown content.