How domwalters/mkdocs-to-pdf works
Project Type & Purpose
• This is an open-source MkDocs plugin (Python) whose sole purpose is to hook into the MkDocs build lifecycle, convert the rendered HTML documentation into a paginated PDF (with cover, TOC, styles, etc.), and emit that PDF artifact.
• It provides multiple “drivers” (Headless Chrome, RelaxedJS) and uses Jinja2 templates, SCSS styles, and link-transform preprocessors to produce high-quality PDF outputs.
A. MkDocs Core (external)
• The standard MkDocs build engine that loads plugins and themes.
B. mkdocs-to-pdf Plugin
• plugin.py: registers event hooks with MkDocs.
• options.py: reads plugin configuration.
C. Preprocessor Layer
• preprocessor/links: transforms internal/external links for PDF.
D. Generator Layer
• generator.py: orchestrates PDF creation.
• cover.py: generates optional cover page.
• toc.py: builds PDF table of contents.
E. Driver Layer (strategy pattern)
• headless_chrome.py
• relaxedjs.py
• event_hook.py
(Each implements a common interface to render HTML → PDF.)
F. Template & Style Engine
• templates/: Jinja2 templates (cover.html, back_cover, filters).
• styles/: SCSS partials for fonts, heading, paging, TOC.
• themes/: CSS/JS to polyfill Material theme features.
G. Utility Modules
• utils/: helpers for images, iframes, layout, emoji, soup traversal.
H. Output
• PDF file(s) emitted to MkDocs “site” directory.
I. Docker Support (optional build/runtime environments)
• docker/mkdocs-with-pdf: container definitions for Alpine, Debian, tiny.
J. CLI / Entry Point
• mkdocs plugin entry: invoked by “mkdocs build” or “mkdocs serve.”
1. User runs “mkdocs build” with the plugin enabled.
2. MkDocs Core loads mkdocs-to-pdf plugin (plugin.py).
3. During the page events (on_page_markdown → on_page_content),
the plugin’s preprocessor/links transforms links.
4. After MkDocs finishes rendering HTML, on_post_build triggers generator.generate().
5. generator:
a. Calls cover.py to render front cover via Jinja2 templates + SCSS compiled CSS.
b. Uses driver (headless_chrome or relaxedjs) to convert HTML pages + styles → PDF.
c. Uses toc.py to insert a PDF TOC based on headings.
6. Utility modules supply image sizing, layout grid, and media‐embedding heuristics to both templates and the driver engine.
7. Driver calls external binary/process (Chrome headless or Approx. PhantomJS) or Docker container if configured.
8. Final PDF file is placed under /site or a user-defined output directory.
Architectural Patterns & Principles
• Plugin/Event‐hook pattern (registering to MkDocs lifecycle hooks).
• Strategy pattern for interchangeable PDF drivers.
• Template‐driven code generation (Jinja2, SCSS).
• Separation of concerns:
• Preprocessing (link rewriting)
• Presentation (templates + styles)
• Rendering (drivers)
• Highly pluggable and extensible: new drivers or templates can be dropped into the respective directories.