The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Build a markdown to PDF converter

Here’s a simple Markdown to PDF converter implemented in Python using the markdown and pdfkit libraries. It reads a .md file and converts it into a .pdf file.


Prerequisites

Install the following packages:

bash
pip install markdown pdfkit

Also install wkhtmltopdf (required by pdfkit):

Make sure wkhtmltopdf is in your system’s PATH.


🧾 Python Script: Markdown to PDF

python
import markdown import pdfkit import sys import os def markdown_to_pdf(input_md_file, output_pdf_file): if not os.path.exists(input_md_file): print(f"Error: File {input_md_file} not found.") return with open(input_md_file, 'r', encoding='utf-8') as f: md_text = f.read() # Convert Markdown to HTML html_text = markdown.markdown(md_text) # Add basic HTML structure for rendering full_html = f""" <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> body {{ font-family: Arial, sans-serif; margin: 40px; }} </style> </head> <body> {html_text} </body> </html> """ # Convert HTML to PDF try: pdfkit.from_string(full_html, output_pdf_file) print(f"PDF saved to {output_pdf_file}") except Exception as e: print("PDF conversion failed:", e) # Example usage if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: python markdown_to_pdf.py input.md output.pdf") else: markdown_to_pdf(sys.argv[1], sys.argv[2])

🏁 How to Use

bash
python markdown_to_pdf.py sample.md output.pdf

This will convert sample.md to output.pdf using HTML styling for better formatting.

Let me know if you want an interactive GUI version or integration into a web app.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About