md2pdf Documentation

repository·main·Indexed 19 days ago

https://github.com/jmaupetit/md2pdf

A tool and Python library for converting Markdown files into PDF documents with support for custom CSS styling, Jinja templating, and extensible Markdown features. It provides a CLI for batch conversion and a core Python function for integration into projects, utilizing WeasyPrint for PDF generation.

Tokens
2.4K
Snippets
11
Records
14
Agent score
65%

What's inside md2pdf

  1. Use Jinja templates as input

    main

    md2pdf supports Jinja templating. You can provide dynamic content in two ways:

    1. Frontmatter Header: Define variables in a YAML-style frontmatter block at the top of your Markdown file.
    2. Context Argument: Pass a dictionary to the context argument when using the library.

    Example Markdown with Jinja

    ---
    groceries:
      - name: apple
        quantity: 4 
      - name: orange 
        quantity: 10
    ---
    
    # Groceries
    
    | Item | Quantity |
    | ---- | -------- |
    {% for item in groceries -%}
    | {{ item.name }} | {{ item.quantity }} |
    {% endfor %}
    $ md2pdf \
        --css examples/gutenberg-modern.min.css \
        -i examples/my-music.md.j2 \
        -o examples/my-music.pdf
  2. Watch for changes with --watch

    main

    When the --watch (or -w) flag is used, the CLI monitors the input Markdown files and the provided CSS file for changes. If any of these files are modified, the tool automatically re-renders the PDF(s). Press CTRL+C to stop watching.

    md2pdf -i doc.md -c style.css --watch
  3. Run md2pdf with Docker

    main

    You can run md2pdf using a Debian-based Docker image.

    Pull the image

    $ docker pull jmaupetit/md2pdf:latest

    Run a smoke test

    To run a conversion, mount your current directory to /wrk inside the container:

    $ docker run --rm -t \
        -v $PWD:/wrk \
        -u "$(id -u):$(id -g)" \
        -w /wrk \
        jmaupetit/md2pdf:latest -i README.md

    Note: An Alpine-based image tagged alpine is also available for a smaller footprint. Check the DockerHub repository for all available tags.

  4. Install the md2pdf CLI

    main

    To use the md2pdf command line interface, you must install the cli extra. If you only install the base package, the CLI will not be available.

    pip install "md2pdf[cli]"
  5. Configure Markdown extensions via JSON

    main

    You can pass configuration for Markdown extensions using the --config (or -C) flag. This flag expects a valid JSON string representing the configuration for the activated --extras.

    md2pdf -i doc.md -e some_extension --config '{"key": "value"}'
  6. Use md2pdf as a Python library

    main

    If md2pdf is a dependency in your Python project, you can import and use the md2pdf function from md2pdf.core.

    from md2pdf.core import md2pdf
    
    md2pdf(
        pdf="output.pdf",
        md="input.md",
        css="style.css",
        base_url="/path/to/assets",
        extras=["pymdownx.emoji"],
        context={"foo": 1}
    )

    Arguments

    • pdf: Output PDF file path.
    • raw: Input markdown raw string content (can contain Jinja instructions). Use this instead of md if you have a string.
    • md: Input markdown file path (can contain Jinja instructions). Use this instead of raw if you have a file.
    • css: Input styles path (CSS).
    • base_url: Absolute base path for markdown linked content (e.g., images).
    • extras: A list of markdown extensions to activate.
    • context: A dictionary of variables to inject into rendered Jinja templates.
    from md2pdf.core import md2pdf
    
    md2pdf(pdf,
           md=None,
           raw=None,
           css=None,
           base_url=None,
           extras=[],
           context={"foo": 1}
    )
  7. Reference: md2pdf CLI options

    main

    The following options are available for the md2pdf command:

    FlagShortTypeDescription
    --input-iPATHMarkdown source file path (can be used multiple times).
    --output-oPATHPDF output file path (when a single md input is used).
    --css-cPATHInput CSS file.
    --extras-eTEXTExtra markdown extension to activate (can be used multiple times).
    --config-CTEXTMarkdown extensions configuration (as a JSON string).
    --workers-WINTEGERNumber of parallel workers to start. [default: 4]
    --version-VDisplay program version.
    --install-completionInstall completion for the current shell.
    --show-completionShow completion for the current shell.
    --helpShow this message and exit.
  8. Use md2pdf as a CLI

    main

    The md2pdf CLI allows you to convert Markdown files to PDF, applying custom CSS and Markdown extensions.

    Basic Usage

    To generate a PDF from a single Markdown file (e.g., README.md becomes README.pdf):

    $ md2pdf -i README.md

    Advanced CLI Options

    • Custom Styles: Use --css or -c to provide an external stylesheet.
    • Markdown Extensions: Use --extras or -e to activate extensions (e.g., pymdownx.emoji). This can be used multiple times.
    • Configuration: Use --config or -C to pass Markdown extensions configuration as a JSON string.
    • Output: Use --output or -o to specify the destination path when using a single input.
    $ md2pdf \
        --css examples/custom-styles-with-pygments.css \
        --extras 'pymdownx.emoji' \
        -i README.md
  9. Use the md2pdf CLI for conversion

    main

    The md2pdf command converts Markdown files to PDF. You can convert a single file or multiple files in parallel. If multiple files are provided, you cannot specify a single output file via --output (the tool will generate one PDF per Markdown file by default).

    # Convert a single file with a specific output name and CSS
    md2pdf --input document.md --output document.pdf --css style.css
    
    # Convert multiple files in parallel using 8 workers
    md2pdf --input file1.md --input file2.md --workers 8
  10. Convert Markdown to PDF with md2pdf()

    main

    The md2pdf function is the primary entrypoint for converting Markdown content into a styled PDF file. It supports input from either a raw string or a file path, handles Jinja2 templating (including frontmatter extraction), and applies custom CSS via WeasyPrint.

    Key Features:

    • Input Modes: Provide a Path to a .md file via md, or pass the raw content directly via raw.
    • Templating: If the input contains YAML frontmatter, the frontmatter keys are automatically merged into the Jinja2 rendering context.
    • Styling: Pass a Path to a CSS file via css to style the output.
    • Extensions: Use extras to add supplementary Markdown extensions and extras_config to configure them.
    • Assets: Use base_url to specify the absolute path for resolving linked content like images.
    from pathlib import Path
    from md2pdf import md2pdf
    
    # Example: Converting a markdown file with custom CSS
    md2pdf(
        pdf=Path("output.pdf"),
        md=Path("input.md"),
        css=Path("styles.css"),
        extras=["extra_extension_name"],
        extras_config={"extra_extension_name": {"option": True}}
    )