API Reference
This document provides the Python API reference for using mk2html and mk2pdf programmatically.
mk2html Module
convert_markdown_to_html()
Convert markdown text to a fully styled HTML document.
from mk2html import convert_markdown_to_html
html = convert_markdown_to_html(
markdown_text: str,
title: str = "Document",
enable_mermaid: bool = True,
default_theme: str = "light",
offline_libs: Optional[Dict[str, Optional[str]]] = None,
enable_line_numbers: bool = True,
enable_breaks: bool = True
) -> str
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
markdown_text |
str |
required | The markdown content to convert |
title |
str |
"Document" |
Document title |
enable_mermaid |
bool |
True |
Include Mermaid diagram support |
default_theme |
str |
"light" |
Default theme ("light" or "dark") |
offline_libs |
Dict |
None |
Dictionary with embedded library content |
enable_line_numbers |
bool |
True |
Show line numbers in code blocks |
enable_breaks |
bool |
True |
Convert newlines to <br> tags |
Returns
str - Complete HTML document as a string.
Example
from mk2html import convert_markdown_to_html
markdown = """
# Hello World
This is a **test** document.
```python
print("Hello!")
"""
html = convert_markdown_to_html(
markdown,
title="My Document",
default_theme="dark",
enable_line_numbers=True
)
with open("output.html", "w") as f:
f.write(html)
---
### get_offline_libraries()
Download and cache all required libraries for offline mode.
```python
from mk2html import get_offline_libraries
libs = get_offline_libraries(quiet: bool = False) -> Dict[str, Optional[str]]
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
quiet |
bool |
False |
Suppress download messages |
Returns
Dict[str, Optional[str]] - Dictionary with keys:
- "mermaid": Mermaid.js library content or None
- "highlightjs": Highlight.js library content or None
Example
from mk2html import convert_markdown_to_html, get_offline_libraries
# Download libraries once
offline_libs = get_offline_libraries()
# Use for multiple conversions
for md_file in markdown_files:
html = convert_markdown_to_html(
md_file.read_text(),
offline_libs=offline_libs
)
clear_cache()
Clear the library cache.
from mk2html import clear_cache
count = clear_cache() -> int
Returns
int - Number of files removed.
Example
from mk2html import clear_cache
removed = clear_cache()
print(f"Removed {removed} cached files")
main()
Main CLI entry point.
from mk2html import main
exit_code = main(args: Optional[List[str]] = None) -> int
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
args |
List[str] |
None |
Command-line arguments. Uses sys.argv if None |
Returns
int - Exit code (0 for success, non-zero for error).
Example
from mk2html import main
# Programmatic CLI call
exit_code = main(["input.md", "-o", "output.html", "--offline"])
mk2pdf Module
convert_markdown_to_pdf()
Convert markdown text to PDF.
from mk2pdf import convert_markdown_to_pdf
from pathlib import Path
success = convert_markdown_to_pdf(
markdown_text: str,
output_path: Path,
title: str = "Document",
enable_mermaid: bool = True,
theme: str = "light",
page_size: str = "a4",
margin: str = "1in",
landscape: bool = False,
wait_time: int = 2000,
quiet: bool = False,
enable_line_numbers: bool = True,
enable_breaks: bool = True
) -> bool
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
markdown_text |
str |
required | The markdown content to convert |
output_path |
Path |
required | Path to save the PDF |
title |
str |
"Document" |
Document title |
enable_mermaid |
bool |
True |
Include Mermaid diagram support |
theme |
str |
"light" |
Theme: "light" or "dark" |
page_size |
str |
"a4" |
Page size |
margin |
str |
"1in" |
Page margin |
landscape |
bool |
False |
Landscape orientation |
wait_time |
int |
2000 |
JS rendering wait time (ms) |
quiet |
bool |
False |
Suppress output messages |
enable_line_numbers |
bool |
True |
Show line numbers in code |
enable_breaks |
bool |
True |
Convert newlines to <br> |
Returns
bool - True if successful, False otherwise.
Example
from mk2pdf import convert_markdown_to_pdf
from pathlib import Path
markdown = Path("README.md").read_text()
success = convert_markdown_to_pdf(
markdown,
Path("output.pdf"),
title="README",
page_size="letter",
margin="0.75in"
)
if success:
print("PDF created successfully!")
convert_html_to_pdf()
Convert HTML content to PDF using Playwright.
from mk2pdf import convert_html_to_pdf
from pathlib import Path
success = convert_html_to_pdf(
html_content: str,
output_path: Path,
page_size: str = "a4",
margin: str = "1in",
landscape: bool = False,
wait_time: int = 2000,
quiet: bool = False
) -> bool
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
html_content |
str |
required | The HTML content to convert |
output_path |
Path |
required | Path to save the PDF |
page_size |
str |
"a4" |
Page size |
margin |
str |
"1in" |
Page margin |
landscape |
bool |
False |
Landscape orientation |
wait_time |
int |
2000 |
JS rendering wait time (ms) |
quiet |
bool |
False |
Suppress output messages |
Returns
bool - True if successful, False otherwise.
Example
from mk2html import convert_markdown_to_html
from mk2pdf import convert_html_to_pdf
from pathlib import Path
# First convert to HTML with custom settings
html = convert_markdown_to_html(
markdown_text,
enable_mermaid=True,
default_theme="light"
)
# Then convert to PDF
convert_html_to_pdf(
html,
Path("output.pdf"),
page_size="a4",
margin="1in"
)
ensure_chromium_installed()
Ensure Chromium is installed for Playwright.
from mk2pdf import ensure_chromium_installed
success = ensure_chromium_installed(quiet: bool = False) -> bool
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
quiet |
bool |
False |
Suppress installation messages |
Returns
bool - True if Chromium is available, False otherwise.
Example
from mk2pdf import ensure_chromium_installed, convert_markdown_to_pdf
# Ensure Chromium is installed before batch processing
if not ensure_chromium_installed():
print("Failed to install Chromium")
exit(1)
# Now safe to convert multiple files
for md_file in markdown_files:
convert_markdown_to_pdf(md_file.read_text(), md_file.with_suffix(".pdf"))
Constants
mk2html Constants
from mk2html import __version__, __author__, CACHE_DIR
print(__version__) # "1.3.0"
print(__author__) # "Kinshuk"
print(CACHE_DIR) # Path("~/.cache/mk2html")
mk2pdf Constants
from mk2pdf import __version__, __author__, PLAYWRIGHT_AVAILABLE
print(__version__) # "1.1.0"
print(__author__) # "Kinshuk"
print(PLAYWRIGHT_AVAILABLE) # True or False
Complete Example
#!/usr/bin/env python3
"""Generate documentation in HTML and PDF formats."""
from pathlib import Path
from mk2html import convert_markdown_to_html, get_offline_libraries
from mk2pdf import convert_markdown_to_pdf, ensure_chromium_installed
def generate_docs(input_dir: str, output_dir: str):
"""Generate HTML and PDF documentation."""
input_path = Path(input_dir)
output_path = Path(output_dir)
# Create output directories
html_dir = output_path / "html"
pdf_dir = output_path / "pdf"
html_dir.mkdir(parents=True, exist_ok=True)
pdf_dir.mkdir(parents=True, exist_ok=True)
# Pre-download libraries for offline HTML
print("Downloading libraries...")
offline_libs = get_offline_libraries()
# Ensure Chromium for PDF
print("Checking Chromium...")
if not ensure_chromium_installed():
print("Warning: PDF generation may fail")
# Process all markdown files
for md_file in input_path.glob("*.md"):
print(f"Processing {md_file.name}...")
markdown = md_file.read_text()
title = md_file.stem.replace("-", " ").replace("_", " ").title()
# Generate HTML
html = convert_markdown_to_html(
markdown,
title=title,
offline_libs=offline_libs,
enable_mermaid=True,
enable_line_numbers=True
)
html_file = html_dir / f"{md_file.stem}.html"
html_file.write_text(html)
print(f" ✓ {html_file.name}")
# Generate PDF
pdf_file = pdf_dir / f"{md_file.stem}.pdf"
success = convert_markdown_to_pdf(
markdown,
pdf_file,
title=title,
page_size="a4",
quiet=True
)
if success:
print(f" ✓ {pdf_file.name}")
else:
print(f" ✗ {pdf_file.name} (failed)")
print(f"\nDone! Output in {output_path}")
if __name__ == "__main__":
generate_docs("docs", "dist")