Is there any direct way to generate pdf from markdown file by python

31,212

Solution 1

I have done and would do it in two steps. First, I'd use python-markdown to make HTML out of my Markdown, and then I'd use xhtml2pdf to make a PDF file.

Edit (2014):

If I were doing this now, I might choose WeasyPrint as my HTML-to-PDF tool; it does a beautiful job, and I've used it on a couple projects recently.

Solution 2

Update for 2015:

I would use a combination of pdfkit and Python-Markdown. While this isn't a pure Python solution, but I've found it works best, especially if you're using Python 3.

First, install a prereq (or download here: http://wkhtmltopdf.org/downloads.html):

# Ubuntu
apt-get install wkhtmltopdf

Then, the necessary Python packages:

pip install pdfkit
pip install markdown

Then it is really simple:

from markdown import markdown
import pdfkit

input_filename = 'README.md'
output_filename = 'README.pdf'

with open(input_filename, 'r') as f:
    html_text = markdown(f.read(), output_format='html4')

pdfkit.from_string(html_text, output_filename)
Share:
31,212
guilin 桂林
Author by

guilin 桂林

Python and web

Updated on April 15, 2020

Comments

  • guilin 桂林
    guilin 桂林 about 4 years

    As the title, I want to use markdown as my main write format and I need to generate PDF files from markdown using pure python.

  • Terje Dahl
    Terje Dahl over 9 years
    Your original answer was better for this question, as WeasyPrint, while perhaps superior, is not "pure Python". Or, to be entirely accurate; WeasyPrint may itself be pure python, but it relies other modules which are not.
  • JasonFruit
    JasonFruit over 9 years
    I had not thought that through. Thank you for the clarification.
  • D-rk
    D-rk over 8 years
    but wkhtmltopdf needs a xserver: github.com/JazzCore/python-pdfkit/wiki/…
  • Humoyun Ahmad
    Humoyun Ahmad over 7 years
    it worked, but the font size is very small, how I can configure it ?
  • TamaMcGlinn
    TamaMcGlinn over 3 years
    @HumoyunAhmad insert a CSS link element into the html_text prior to writing to pdf, and put your styling in that separate file. It's not trivial, we should provide an example of having a custom CSS file in this answer. Note you can debug this better by writing the html_text straight to an html file and making sure that is good before proceeding.
  • TamaMcGlinn
    TamaMcGlinn over 3 years
    @HumoyunAhmad I have added a more advanced example to the answer that also solves your issue.
  • Chris Collett
    Chris Collett almost 3 years
    There are several libraries which can convert HTML to PDF. One that I use is PyMuPDF, which can open an HTML document and use the convert_to_pdf method to generate the PDF. Examples on the linked page.