### Input File Examples Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/05-cli-reference.md Examples demonstrating how to specify the input Markdown file path. ```bash markdown2docx document.md ``` ```bash markdown2docx /path/to/document.md ``` -------------------------------- ### Test Example Conversion Source: https://github.com/cnkang/markdown2docx/blob/main/README.md Run a conversion of an example Markdown file using the CLI to verify functionality. ```bash uv run python -m src.markdown2docx.cli example.md -o example_output.docx ``` -------------------------------- ### YAML Configuration Example Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/05-cli-reference.md Example of a configuration file in YAML format. Use this to customize pandoc settings, conversion defaults, template properties, and logging levels. ```yaml # config.yaml pandoc: min_version: "2.19" timeout_seconds: 600 conversion: default_toc: true default_toc_depth: 2 validate_output: true template: page_size: "Letter" body_font: "Arial" heading_font: "Georgia" logging: level: "DEBUG" ``` -------------------------------- ### Setup Logging Configuration Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/01-api-reference-converter.md Configures logging based on provided configuration settings. ```python def _setup_logging(self) -> None ``` -------------------------------- ### TOML Configuration Example Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/05-cli-reference.md Example of a configuration file in TOML format. This provides an alternative to YAML for specifying pandoc settings, conversion defaults, template properties, and logging levels. ```toml # config.toml [pandoc] min_version = "2.19" timeout_seconds = 600 [conversion] default_toc = true default_toc_depth = 2 validate_output = true [template] page_size = "Letter" body_font = "Arial" heading_font = "Georgia" [logging] level = "DEBUG" ``` -------------------------------- ### Install Dependencies and Pandoc Source: https://github.com/cnkang/markdown2docx/blob/main/README.md Run this script to install project dependencies and ensure Pandoc is available. For Unix-like systems. Use --group dev for development dependencies. ```bash ./scripts/setup-env.sh ``` ```bash ./scripts/setup-env.sh --group dev ``` -------------------------------- ### Configuration Merging Example Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md Load configuration from multiple sources, such as a file and environment variables. Environment variables take precedence over file-based settings. ```python from markdown2docx.config import load_config from pathlib import Path # Load from file and merge with environment variables # Environment variables take precedence config = load_config(Path("config.yaml")) # Now environment variables have been merged in # MD2DOCX_CONVERSION__DEFAULT_TOC will override config file value ``` -------------------------------- ### MarkdownToDocxConfig Usage Examples Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/03-types.md Demonstrates creating MarkdownToDocxConfig instances using default settings, environment variables, and a dictionary. Also shows how to retrieve Pandoc arguments. ```python from markdown2docx import MarkdownToDocxConfig # Create from defaults config = MarkdownToDocxConfig() # Create from environment variables config = MarkdownToDocxConfig.from_env() # Create from dictionary config_dict = { "pandoc": {"min_version": "2.19"}, "conversion": {"default_toc": True} } config = MarkdownToDocxConfig.from_dict(config_dict) # Get Pandoc arguments args = config.get_pandoc_args(toc=True, toc_depth=2) ``` -------------------------------- ### TOML Configuration File Example Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md Define configuration settings in a TOML file. This format is human-readable and suitable for static configuration files. ```toml # config.toml [pandoc] min_version = "2.19" timeout_seconds = 600 [conversion] default_toc = false default_toc_depth = 3 validate_output = false create_backup = false overwrite_existing = true [template] page_size = "A4" margin_cm = 2.54 body_font = "Calibri" body_size_pt = 11 heading_font = "Calibri" code_font = "Consolas" code_size_pt = 9 [logging] level = "INFO" format = "% (asctime)s - %(name)s - %(levelname)s - %(message)s" file_path = null ``` -------------------------------- ### Logging Configuration Example Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/06-package-reference.md Demonstrates how to set the logging level for the markdown2docx package, either directly or through a configuration object. ```python import logging # Set log level logging.getLogger("markdown2docx").setLevel(logging.DEBUG) # Or configure via MarkdownToDocxConfig config = MarkdownToDocxConfig() config.logging.level = "DEBUG" ``` -------------------------------- ### YAML Configuration File Example Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md Define configuration settings in a YAML file. YAML offers a more human-readable syntax compared to TOML for complex configurations. ```yaml # config.yaml pandoc: min_version: "2.19" timeout_seconds: 600 conversion: default_toc: false default_toc_depth: 3 validate_output: false create_backup: false overwrite_existing: true template: page_size: "A4" margin_cm: 2.54 body_font: "Calibri" body_size_pt: 11 heading_font: "Calibri" code_font: "Consolas" code_size_pt: 9 logging: level: "INFO" format: "% (asctime)s - %(name)s - %(levelname)s - %(message)s" file_path: null ``` -------------------------------- ### Install Dependencies Manually Source: https://github.com/cnkang/markdown2docx/blob/main/README.md Install project dependencies manually using uv. Ensure Pandoc 2.19+ is installed separately. ```bash uv sync ``` ```bash brew install pandoc ``` ```bash sudo apt-get install pandoc ``` -------------------------------- ### Install Package Dependencies Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/00-index.md Install the necessary Python package dependencies for markdown2docx. Ensure Pandoc is also installed separately. ```bash # Install package dependencies pip install markdown2docx # Ensure Pandoc is installed # macOS: brew install pandoc # Ubuntu: sudo apt-get install pandoc # Or: https://pandoc.org/installing.html ``` -------------------------------- ### Configuration Validation Example Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md Shows how markdown2docx validates configuration settings at construction time. Invalid configurations will raise TypeError or TemplateError. ```python from markdown2docx.config import TemplateConfig from markdown2docx.exceptions import TemplateError try: config = TemplateConfig(page_size="B5") # Invalid except TypeError as e: print(f"Invalid configuration: {e}") try: from markdown2docx import DocxTemplateManager manager = DocxTemplateManager(page_size="A3") # Raises TemplateError except TemplateError as e: print(f"Template error: {e}") ``` -------------------------------- ### Python Example: Convert with Template and Validation Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/01-api-reference-converter.md Illustrates converting a Markdown file with a template and enabling output validation. The output path is auto-generated. ```python converter = MarkdownToDocxConverter() # Convert with template and validation output = converter.convert_with_template( "input.md", "template.docx", validate_output=True ) ``` -------------------------------- ### Python Example: Convert Markdown with Template Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/01-api-reference-converter.md Demonstrates how to convert a Markdown file to DOCX using a specified template file. The output path is auto-generated. ```python converter = MarkdownToDocxConverter() # Convert with a specific template output = converter.convert_with_template( "document.md", "corporate_template.docx" ) ``` -------------------------------- ### Pandoc Not Found Error Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/00-index.md This error indicates that Pandoc is not installed or not found in the system's PATH. Ensure Pandoc is installed and accessible, or use pypandoc.download_pandoc() to install it. ```text PandocNotFoundError: Pandoc not found. Please install Pandoc or call pypandoc.download_pandoc(). ``` -------------------------------- ### Inspect Configuration Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/08-usage-examples.md Load and inspect the converter's configuration from a TOML file. This example shows how to access various settings like table of contents, body font, page size, and Pandoc version requirements. ```python from markdown2docx import MarkdownToDocxConfig from markdown2docx.config import load_config from pathlib import Path # Load and inspect configuration config = load_config(Path("config.toml")) print(f"Table of contents: {config.conversion.default_toc}") print(f"TOC depth: {config.conversion.default_toc_depth}") print(f"Body font: {config.template.body_font}") print(f"Page size: {config.template.page_size}") print(f"Pandoc min version: {config.pandoc.min_version}") ``` -------------------------------- ### Get Pandoc Version Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/01-api-reference-converter.md Retrieves the version string of the installed Pandoc. Use this to check Pandoc compatibility. ```python def get_pandoc_version(self) -> str ``` ```python converter = MarkdownToDocxConverter() version = converter.get_pandoc_version() print(f"Pandoc version: {version}") # Pandoc version: 2.19.2 ``` -------------------------------- ### Python Example: Convert with Template and TOC Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/01-api-reference-converter.md Shows how to convert a Markdown file using a template and include a table of contents with a specified depth. An output path is also provided. ```python converter = MarkdownToDocxConverter() # Convert with template and table of contents output = converter.convert_with_template( "document.md", "template.docx", "report.docx", toc=True, toc_depth=3 ) ``` -------------------------------- ### Batch Convert Markdown Files in Python Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/08-usage-examples.md This example shows how to iterate through all markdown files in the current directory and convert them to DOCX format, printing success or failure messages for each. ```python from markdown2docx import MarkdownToDocxConverter from pathlib import Path converter = MarkdownToDocxConverter() md_files = Path(".").glob("*.md") for md_file in md_files: try: output = converter.convert( md_file, md_file.with_suffix(".docx"), toc=True ) print(f"✓ {md_file} → {output}") except Exception as e: print(f"✗ {md_file}: {e}") ``` -------------------------------- ### Initialize MarkdownToDocxConverter Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/01-api-reference-converter.md Instantiate the converter for Markdown to DOCX conversion. You can optionally provide a DOCX file as a style template or a custom configuration object. Ensure Pandoc is installed and accessible in your system's PATH. ```python from markdown2docx import MarkdownToDocxConverter # Basic initialization converter = MarkdownToDocxConverter() ``` ```python # With custom template converter = MarkdownToDocxConverter(reference_doc="my_template.docx") ``` ```python # With custom configuration from markdown2docx import MarkdownToDocxConfig config = MarkdownToDocxConfig() converter = MarkdownToDocxConverter(reference_doc="template.docx", config=config) ``` -------------------------------- ### Check Pandoc Version Source: https://github.com/cnkang/markdown2docx/blob/main/README.md Verify the installed Pandoc version. Version 2.19+ is recommended for optimal modern DOCX support. ```bash pandoc --version ``` -------------------------------- ### Display Version Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/05-cli-reference.md Use the --version flag to display the version of markdown2docx and exit the program. This is a simple command to check the installed version. ```bash markdown2docx --version ``` ```text markdown2docx 0.1.0 ``` -------------------------------- ### Python: Preprocess Markdown Before Conversion Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/08-usage-examples.md This Python example demonstrates how to read markdown content, preprocess it (e.g., ensuring a table of contents marker is present), save the processed content to a temporary file, and then convert it to docx using the MarkdownToDocxConverter. ```python import re from markdown2docx import MarkdownToDocxConverter # Process markdown before conversion def preprocess_markdown(content: str) -> str: """Add table of contents marker if needed.""" if "[TOC]" not in content: content = "[TOC]\n\n" + content return content # Read, process, and convert with open("document.md") as f: content = f.read() processed = preprocess_markdown(content) with open("temp.md", "w") as f: f.write(processed) converter = MarkdownToDocxConverter() output = converter.convert("temp.md", "document.docx") ``` -------------------------------- ### Check Pandoc Version Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/08-usage-examples.md Verify the installed Pandoc version using the `get_pandoc_version` method. This is useful for ensuring compatibility. Handles `PandocError` if Pandoc is not found or has issues. ```python from markdown2docx import MarkdownToDocxConverter, PandocError converter = MarkdownToDocxConverter() try: version = converter.get_pandoc_version() print(f"Pandoc version: {version}") except PandocError as e: print(f"Error: {e}") ``` -------------------------------- ### Corporate Technical Documentation Configuration (TOML) Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md A TOML configuration file example for corporate technical documentation. It specifies Pandoc settings, conversion options, template details, and logging. ```toml # corporate_config.toml [pandoc] min_version = "2.19" timeout_seconds = 600 [conversion] default_toc = true default_toc_depth = 3 validate_output = true overwrite_existing = true [template] page_size = "A4" margin_cm = 2.54 body_font = "Arial" body_size_pt = 11 heading_font = "Georgia" code_font = "Consolas" code_size_pt = 9 [logging] level = "INFO" format = "% (asctime)s - %(name)s - %(levelname)s - %(message)s" file_path = "/var/log/markdown2docx/conversion.log" ``` -------------------------------- ### Handle PandocNotFoundError Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/04-errors.md Example of catching PandocNotFoundError to guide users on installing Pandoc. This is useful for ensuring the Pandoc dependency is met before conversion. ```python from markdown2docx import PandocNotFoundError, MarkdownToDocxConverter try: converter = MarkdownToDocxConverter() except PandocNotFoundError as e: print(f"Install Pandoc: {e.details}") # Guide user to install Pandoc ``` -------------------------------- ### Configuration Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/06-package-reference.md Illustrates how to use default configurations, load configurations from files or environment variables, and create custom configurations for the conversion process. ```APIDOC ## Configuration ### Description This section details how to manage the configuration for markdown to docx conversions, including using default settings, loading from external sources, and defining custom configurations. ### Usage ```python from markdown2docx import MarkdownToDocxConfig, DEFAULT_CONFIG from markdown2docx.config import load_config from pathlib import Path # Initialize converter with default configuration converter = MarkdownToDocxConverter() # Load configuration from a YAML file and environment variables config = load_config(Path("config.yaml")) converter = MarkdownToDocxConverter(config=config) # Create a custom configuration object from a dictionary config = MarkdownToDocxConfig.from_dict({ "conversion": {"default_toc": True}, "template": {"body_font": "Arial"} }) ``` ``` -------------------------------- ### get_pandoc_version Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/01-api-reference-converter.md Retrieves the version string of the installed Pandoc installation. ```APIDOC ## get_pandoc_version ### Description Retrieve the version string of the installed Pandoc installation. ### Method Python method call ### Parameters None ### Returns `str` — Version string of Pandoc (e.g., "2.19.2") ### Raises - `PandocError` — Unable to determine Pandoc version ### Example ```python converter = MarkdownToDocxConverter() version = converter.get_pandoc_version() print(f"Pandoc version: {version}") ``` ``` -------------------------------- ### Validate Pandoc Installation Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/01-api-reference-converter.md Validates that Pandoc is installed and meets minimum version requirements. Called automatically during initialization. ```python def _validate_pandoc(self) -> None ``` -------------------------------- ### Create DOCX Template with Sample Content Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/02-api-reference-templates.md Use `create_template` with `add_sample_content=True` to include sample headings, paragraphs, and code blocks for preview purposes. This is useful for demonstrating template features. ```python manager = DocxTemplateManager(body_font="Arial", heading_font="Georgia") # Create template with sample content for preview template_path = manager.create_template( "preview_template.docx", add_sample_content=True ) ``` -------------------------------- ### Configure Markdown to DOCX Conversion Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/06-package-reference.md Use default configurations, load settings from a YAML file, or create a custom configuration object by providing a dictionary. ```python from markdown2docx import MarkdownToDocxConfig, DEFAULT_CONFIG from markdown2docx.config import load_config from pathlib import Path # Use default configuration converter = MarkdownToDocxConverter() # Load from file and environment config = load_config(Path("config.yaml")) converter = MarkdownToDocxConverter(config=config) # Create custom configuration config = MarkdownToDocxConfig.from_dict({ "conversion": {"default_toc": True}, "template": {"body_font": "Arial"} }) ``` -------------------------------- ### Loading Configuration with Environment Overrides Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md Demonstrates loading configuration from a file and then applying overrides from environment variables. Environment variables with the MD2DOCX_* prefix take precedence. ```python # File-based config config = load_config(Path("config.yaml")) # Loads file # Now apply environment overrides # MD2DOCX_CONVERSION__DEFAULT_TOC=true will override file ``` -------------------------------- ### Error Handling Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/06-package-reference.md Provides examples of how to catch and handle various exceptions that may occur during the markdown to docx conversion process. ```APIDOC ## Error Handling ### Description This section demonstrates how to implement error handling for potential issues during the conversion process using specific exception types provided by the library. ### Usage ```python from markdown2docx import ( MarkdownToDocxError, ConversionError, PandocNotFoundError, TemplateError, ValidationError, ConfigurationError ) try: # Example conversion that might raise an error output = converter.convert("input.md", validate_output=True) except ConversionError as e: print(f"Conversion failed: {e.message}") except ValidationError as e: print(f"Validation errors: {e.validation_errors}") except MarkdownToDocxError as e: print(f"An unexpected error occurred: {e}") ``` ``` -------------------------------- ### Command Line: Create Template Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/00-index.md Generate a default DOCX template file from the command line. ```bash # Create template markdown2docx --create-template my_template.docx ``` -------------------------------- ### Use a Template Document Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/05-cli-reference.md Apply styles from a reference DOCX file using the --template or --reference-doc flags. If the template file does not exist, a warning is logged, and conversion proceeds without it. ```bash markdown2docx input.md --template style.docx markdown2docx input.md --reference-doc style.docx ``` ```bash markdown2docx document.md --template corporate_template.docx markdown2docx document.md --reference-doc my_styles.docx ``` -------------------------------- ### Using Configuration File with CLI Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/05-cli-reference.md Command to execute markdown2docx conversion using a specified configuration file. Ensure the config file path is correct. ```bash markdown2docx document.md --config config.yaml ``` -------------------------------- ### Basic Conversion with Default Settings Source: https://github.com/cnkang/markdown2docx/blob/main/examples/README.md Use this command to convert a Markdown file to DOCX using default settings. ```bash uv run python -m src.markdown2docx.cli examples/example.md ``` -------------------------------- ### Define PandocNotFoundError Exception Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/04-errors.md Custom exception raised when the Pandoc executable is not found. This typically occurs if Pandoc is not installed or not accessible in the system's PATH. ```python class PandocNotFoundError(PandocError): def __init__(self) -> None ``` -------------------------------- ### Get Pandoc Arguments from Config Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/03-types.md Generates Pandoc command line arguments based on the current configuration. Optionally includes table of contents arguments. ```python def get_pandoc_args(self, *, toc: bool = False, toc_depth: int = 3) -> list[str] ``` -------------------------------- ### Command Line: Use Custom Template Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/00-index.md Convert a Markdown file to DOCX using a specified custom template and output file name via the command line. ```bash # With custom template markdown2docx document.md --template my_template.docx -o output.docx ``` -------------------------------- ### Create Default Template (Legacy) Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/02-api-reference-templates.md Use this legacy method to create a modern template with default settings and sample content. It is equivalent to calling create_modern_template with add_sample=True. ```python template_path = DocxTemplateManager.create_default_template("template.docx") ``` -------------------------------- ### Handle Configuration Loading Errors Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/04-errors.md Demonstrates catching ConfigurationError when loading configuration from a file. Includes checking for specific error details like the config_key. ```python from markdown2docx import ConfigurationError, MarkdownToDocxConfig from markdown2docx.config import load_config from pathlib import Path try: config = load_config(Path("invalid.toml")) except ConfigurationError as e: print(f"Config error: {e.message}") if e.config_key: print(f"Key: {e.config_key}") ``` -------------------------------- ### Verify Environment Variable Application Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md Use Python to load the configuration from environment variables and verify that specific settings, like `conversion.default_toc`, have been applied correctly. ```python # Check via Python from markdown2docx import MarkdownToDocxConfig config = MarkdownToDocxConfig.from_env() print(config.conversion.default_toc) # Should be True ``` -------------------------------- ### Load Configuration from TOML File Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/00-index.md Load converter settings from a TOML configuration file using load_config. Instantiate MarkdownToDocxConverter with the loaded configuration. ```python from markdown2docx import MarkdownToDocxConverter from markdown2docx.config import load_config from pathlib import Path config = load_config(Path("config.toml")) converter = MarkdownToDocxConverter(config=config) ``` -------------------------------- ### Academic Paper Configuration (YAML) Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md A YAML configuration file example for an academic paper. It includes settings for Pandoc, conversion, template, and logging, tailored for academic writing. ```yaml # academic_config.yaml pandoc: min_version: "2.19" timeout_seconds: 300 conversion: default_toc: true default_toc_depth: 4 validate_output: true overwrite_existing: false template: page_size: "A4" margin_cm: 2.5 body_font: "Times New Roman" body_size_pt: 12 heading_font: "Times New Roman" code_font: "Courier New" code_size_pt: 10 logging: level: "INFO" ``` -------------------------------- ### Basic Error Handling with Specific Exceptions Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/04-errors.md Use this pattern to catch common errors like Pandoc not being installed or general conversion failures. It provides user-friendly messages for each specific error type. ```python from markdown2docx import ( MarkdownToDocxConverter, MarkdownToDocxError, ConversionError, PandocNotFoundError ) converter = MarkdownToDocxConverter() try: output = converter.convert("input.md", "output.docx") except PandocNotFoundError: print("Pandoc not installed. Visit https://pandoc.org/installing.html") except ConversionError as e: print(f"Conversion failed for {e.input_file}: {e.message}") except MarkdownToDocxError as e: print(f"Unexpected error: {e}") ``` -------------------------------- ### Conditional Batch Processing in Python Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/08-usage-examples.md This example implements conditional batch processing by skipping the conversion of a markdown file if its corresponding DOCX output file already exists. This prevents unnecessary re-conversions. ```python from markdown2docx import MarkdownToDocxConverter from pathlib import Path converter = MarkdownToDocxConverter() for md_file in Path(".").glob("*.md"): # Generate output path output_path = md_file.with_suffix(".docx") # Skip if output already exists if output_path.exists(): print(f"Skipping {md_file} (output exists)") continue try: output = converter.convert(md_file, output_path) print(f"Converted: {output}") except Exception as e: print(f"Error: {e}") ``` -------------------------------- ### Initialize DocxTemplateManager Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/02-api-reference-templates.md Instantiate DocxTemplateManager with default settings or custom parameters for page size, margins, and fonts. You can also provide a custom configuration object. ```python from markdown2docx import DocxTemplateManager # Create with default settings manager = DocxTemplateManager() # Create with custom page size and fonts manager = DocxTemplateManager( page_size="Letter", body_font="Arial", heading_font="Georgia", code_font="Monaco" ) # Create with custom configuration object from markdown2docx import MarkdownToDocxConfig config = MarkdownToDocxConfig() manager = DocxTemplateManager(config=config.template) ``` -------------------------------- ### Loading Configuration from Environment Variables Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md Load configuration settings directly from environment variables using `MarkdownToDocxConfig.from_env()`. This method is convenient for CI/CD pipelines or containerized environments. ```python from markdown2docx import MarkdownToDocxConfig config = MarkdownToDocxConfig.from_env() converter = MarkdownToDocxConverter(config=config) ``` -------------------------------- ### Create Basic DOCX Template Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/02-api-reference-templates.md Use `create_template` to generate a basic DOCX template file. Ensure the output path has a .docx extension. This method is suitable for creating a standard template structure. ```python manager = DocxTemplateManager(body_font="Arial", heading_font="Georgia") # Create basic template template_path = manager.create_template("my_template.docx") ``` -------------------------------- ### Create MarkdownToDocxConfig from Environment Variables Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/03-types.md Instantiates MarkdownToDocxConfig by reading environment variables prefixed with MD2DOCX_. Nested keys are separated by double underscores. ```python @classmethod def from_env(cls) -> MarkdownToDocxConfig ``` -------------------------------- ### Batch Conversion with Custom Template in Python Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/08-usage-examples.md Demonstrates how to perform batch conversion using a custom DOCX template for consistent styling. It creates a modern template and applies it to all markdown files. ```python from markdown2docx import MarkdownToDocxConverter, DocxTemplateManager from pathlib import Path # Create template template = DocxTemplateManager.create_modern_template("template.docx") # Convert all markdown files converter = MarkdownToDocxConverter(reference_doc=template) output_dir = Path("output") output_dir.mkdir(exist_ok=True) for md_file in Path(".").glob("*.md"): output = converter.convert( md_file, output_dir / md_file.with_suffix(".docx").name, toc=True, toc_depth=2 ) print(f"Converted: {output}") ``` -------------------------------- ### Internal: Add Sample Content Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/02-api-reference-templates.md Adds minimal sample content to the document for template preview, including headings, paragraphs, and a code block. ```python def _add_sample_content(self, doc: Any) -> None: # Inserts headings (levels 1-3), body paragraphs, and a code block sample. ``` -------------------------------- ### Configuration from TOML File Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/08-usage-examples.md Load configuration settings from a TOML file. This approach is ideal for separating configuration from code and managing complex settings. ```python from markdown2docx import MarkdownToDocxConverter from markdown2docx.config import load_config from pathlib import Path # Load configuration config = load_config(Path("config.toml")) # Create converter with configuration converter = MarkdownToDocxConverter(config=config) # Convert documents output = converter.convert("document1.md", "output1.docx") output = converter.convert("document2.md", "output2.docx") ``` -------------------------------- ### Setting Pandoc Environment Variables Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/03-types.md Configure Pandoc settings including minimum version and timeout using environment variables. ```bash export MD2DOCX_PANDOC__MIN_VERSION=2.20 export MD2DOCX_PANDOC__TIMEOUT_SECONDS=600 ``` -------------------------------- ### Basic CLI Conversion Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/08-usage-examples.md Perform simple markdown to docx conversions using the command line. Options include specifying an output file, adding a table of contents, using a custom template, enabling validation, or increasing verbosity. ```bash # Simple conversion markdown2docx document.md # With output file markdown2docx document.md -o report.docx # With table of contents markdown2docx document.md --toc --toc-depth 2 # With template markdown2docx document.md --template corporate.docx # With validation markdown2docx document.md --validate # Verbose output markdown2docx document.md --verbose ``` -------------------------------- ### Setting Template Environment Variables Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/03-types.md Configure document template settings such as body font, page size, and margins using environment variables. ```bash export MD2DOCX_TEMPLATE__BODY_FONT=Arial export MD2DOCX_TEMPLATE__PAGE_SIZE=Letter export MD2DOCX_TEMPLATE__MARGIN_CM=2.0 ``` -------------------------------- ### Create MarkdownToDocxConfig from Dictionary Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/03-types.md Instantiates MarkdownToDocxConfig from a dictionary. Ensure the dictionary keys match the configuration structure. Raises ConfigurationError for invalid formats. ```python @classmethod def from_dict(cls, config_dict: Dict[str, Any]) -> MarkdownToDocxConfig ``` -------------------------------- ### Dictionary-Based Configuration Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md Initialize configuration from a Python dictionary. This is useful for dynamically generating configurations or when configuration data is already in dictionary format. ```python from markdown2docx import MarkdownToDocxConfig config_dict = { "pandoc": { "min_version": "2.19", "timeout_seconds": 600 }, "conversion": { "default_toc": True, "validate_output": True }, "template": { "body_font": "Arial", "page_size": "Letter" } } config = MarkdownToDocxConfig.from_dict(config_dict) ``` -------------------------------- ### Specify Output File and Use Custom Template Source: https://github.com/cnkang/markdown2docx/blob/main/README.md Convert a Markdown file to DOCX, specifying the output file name and using a custom DOCX template for styling. ```bash uv run python -m src.markdown2docx.cli input.md -o output.docx ``` ```bash uv run python -m src.markdown2docx.cli input.md --template custom.docx ``` -------------------------------- ### Create a Custom DOCX Template Source: https://github.com/cnkang/markdown2docx/blob/main/examples/README.md Generate a new DOCX template file with specified styling using the --create-template flag. ```bash uv run python -m src.markdown2docx.cli --create-template modern_template.docx ``` -------------------------------- ### Create Custom Templates Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/08-usage-examples.md Generate a new docx template file using the command line. The --verbose flag can be used for more detailed output during template creation. ```bash # Create a modern template markdown2docx --create-template modern.docx # Create with verbose output markdown2docx --create-template template.docx --verbose ``` -------------------------------- ### Specify Configuration File Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/05-cli-reference.md Provide a path to a configuration file (YAML or TOML) using the --config flag. Settings from this file are merged with environment variables, with environment variables taking precedence. ```bash markdown2docx input.md --config config.toml markdown2docx input.md --config config.yaml ``` ```bash markdown2docx document.md --config /etc/markdown2docx.toml markdown2docx document.md --config ./config.yaml ``` -------------------------------- ### Create and Use a DOCX Template Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/00-index.md Generate a modern DOCX template and then use it to convert a Markdown file, applying custom styles and layout. ```python from markdown2docx import DocxTemplateManager # Create a template template = DocxTemplateManager.create_modern_template("template.docx") # Convert with template converter = MarkdownToDocxConverter(reference_doc=template) output = converter.convert("document.md", "output.docx") ``` -------------------------------- ### Converters and Templates Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/06-package-reference.md Demonstrates how to create a MarkdownToDocxConverter instance, perform markdown to docx conversion, and create a modern template using DocxTemplateManager. ```APIDOC ## Converters and Templates ### Description This section shows how to instantiate the `MarkdownToDocxConverter` and `DocxTemplateManager` classes to perform conversions and manage document templates. ### Usage ```python from markdown2docx import \ MarkdownToDocxConverter, DocxTemplateManager # Create converter with a reference document converter = MarkdownToDocxConverter(reference_doc="template.docx") # Convert markdown to docx, enabling table of contents output_path = converter.convert("input.md", "output.docx", toc=True) # Create a modern template file template_path = DocxTemplateManager.create_modern_template("my_template.docx") # Convert markdown to docx using a specific template output_path = converter.convert_with_template("input.md", "template.docx") ``` ``` -------------------------------- ### Run Tests Source: https://github.com/cnkang/markdown2docx/blob/main/README.md Execute the project's test suite using uv and pytest. ```bash uv run pytest ``` -------------------------------- ### Set Compact Template Styles Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md Configure template settings via environment variables for a compact document style, adjusting margins and font sizes for body and code text. ```bash # Compact style export MD2DOCX_TEMPLATE__MARGIN_CM=1.5 export MD2DOCX_TEMPLATE__BODY_SIZE_PT=10 export MD2DOCX_TEMPLATE__CODE_SIZE_PT=8 ``` -------------------------------- ### Internal: Create Template File Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/02-api-reference-templates.md Internal method for handling document creation, configuration, and saving to disk. Supports adding sample content. ```python def _create_template_file( self, output_path: Union[str, Path], *, add_sample_content: bool = False ) -> Path: # Handles document creation, configuration, and saving to disk. ``` -------------------------------- ### Command Line: Table of Contents Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/00-index.md Convert a Markdown file to DOCX with a table of contents using command-line arguments. ```bash # With table of contents markdown2docx document.md --toc --toc-depth 2 ``` -------------------------------- ### Programmatic Configuration with Python Objects Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md Create and use custom configuration objects directly in Python by instantiating configuration classes. This method offers fine-grained control over all settings. ```python from markdown2docx import MarkdownToDocxConfig, MarkdownToDocxConverter from markdown2docx.config import PandocConfig, TemplateConfig, ConversionConfig, LoggingConfig # Create custom configuration config = MarkdownToDocxConfig( pandoc=PandocConfig(min_version="2.20"), template=TemplateConfig(page_size="Letter", body_font="Arial"), conversion=ConversionConfig(default_toc=True), logging=LoggingConfig(level="DEBUG") ) # Use with converter converter = MarkdownToDocxConverter(config=config) ``` -------------------------------- ### Dynamic Configuration Creation Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/08-usage-examples.md Dynamically create converter instances based on document type using a factory function. This allows for flexible configuration tailored to specific needs like reports, academic papers, or compact documents. ```python from markdown2docx import MarkdownToDocxConverter, MarkdownToDocxConfig from markdown2docx.config import ConversionConfig, TemplateConfig from pathlib import Path def create_converter(doc_type: str) -> MarkdownToDocxConverter: """Create converter with configuration based on document type.""" configs = { "report": TemplateConfig( page_size="A4", margin_cm=2.54, body_font="Arial" ), "academic": TemplateConfig( page_size="A4", margin_cm=2.5, body_font="Times New Roman", body_size_pt=12 ), "compact": TemplateConfig( page_size="Letter", margin_cm=1.5, body_size_pt=10 ) } config = MarkdownToDocxConfig( template=configs.get(doc_type, configs["report"]), conversion=ConversionConfig( default_toc=True, default_toc_depth=3 ) ) return MarkdownToDocxConverter(config=config) # Use dynamic converters report_converter = create_converter("report") academic_converter = create_converter("academic") report_output = report_converter.convert("report.md") thesis_output = academic_converter.convert("thesis.md") ``` -------------------------------- ### Running Markdown2Docx with TOML Configuration and Environment Override Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md Command-line usage for converting a Markdown file to DOCX using a TOML configuration file. Includes setting an environment variable to override a configuration setting. ```bash # Set environment override for this run export MD2DOCX_CONVERSION__VALIDATE_OUTPUT=true # Convert using corporate config markdown2docx technical_doc.md \ --config corporate_config.toml \ -o output/document.docx ``` -------------------------------- ### Setting Logging Environment Variables Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/03-types.md Configure logging level and file path using environment variables. ```bash export MD2DOCX_LOGGING__LEVEL=DEBUG export MD2DOCX_LOGGING__FILE_PATH=/var/log/md2docx.log ``` -------------------------------- ### Template Creation Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/05-cli-reference.md Generate a new DOCX template file. Use --create-template followed by the desired filename. The --verbose flag provides more output during creation. ```bash # Create a modern template markdown2docx --create-template modern.docx ``` ```bash # Create template with verbose output markdown2docx --create-template template.docx --verbose ``` -------------------------------- ### Load Configuration from File or Environment Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/03-types.md Loads configuration settings, merging values from a specified file (YAML/TOML) and environment variables (prefixed with MD2DOCX_). Environment variables override file settings. ```python def load_config(config_path: Optional[Path] = None) -> MarkdownToDocxConfig: ``` ```python from markdown2docx.config import load_config from pathlib import Path # Load from file config = load_config(Path("config.toml")) # Load from environment variables only config = load_config() # Load from file and environment (environment takes precedence) config = load_config(Path("config.yaml")) ``` -------------------------------- ### Input File Argument Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/05-cli-reference.md Specifies the path to the Markdown file that will be converted to DOCX. ```bash markdown2docx input_file ``` -------------------------------- ### Programmatic Conversion with Options Source: https://github.com/cnkang/markdown2docx/blob/main/README.md Convert a Markdown file to DOCX programmatically, including options like table of contents generation and depth. ```python from src.markdown2docx import MarkdownToDocxConverter converter = MarkdownToDocxConverter() output_path = converter.convert( "input.md", "output.docx", toc=True, toc_depth=3, ) ``` -------------------------------- ### Create Modern DOCX Template with Default Settings Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/02-api-reference-templates.md Use the class method `create_modern_template` for a convenient way to create a template with default settings. This method does not require explicit instantiation of the manager. ```python # Create template with default settings template = DocxTemplateManager.create_modern_template("template.docx") ``` -------------------------------- ### Specify Output File Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/05-cli-reference.md Use the -o or --output flags to specify the path for the output DOCX file. If not provided, the output file is created in the same directory as the input with the same name but a .docx extension. ```bash markdown2docx input.md -o output.docx markdown2docx input.md --output output.docx ``` ```bash markdown2docx document.md -o report.docx markdown2docx input.md -o /tmp/output/document.docx ``` -------------------------------- ### Advanced Conversion Options Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/05-cli-reference.md Combine multiple options for comprehensive control over the conversion process. Includes output path, template, table of contents, validation, and verbosity. Batch conversion can be run in quiet mode using --quiet. Configuration can be loaded from a YAML file using --config. ```bash # Full example with multiple options markdown2docx document.md \ -o report.docx \ --template corporate.docx \ --toc \ --toc-depth 2 \ --validate \ --verbose ``` ```bash # Batch conversion with quiet mode markdown2docx input.md -o output.docx --quiet ``` ```bash # Conversion with configuration file markdown2docx document.md --config config.yaml --verbose ``` -------------------------------- ### Loading TOML Configuration Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md Load configuration settings from a TOML file using the `load_config` function. Ensure the file path is correctly specified. ```python from markdown2docx.config import load_config from pathlib import Path config = load_config(Path("config.toml")) converter = MarkdownToDocxConverter(config=config) ``` -------------------------------- ### Troubleshooting Template Issues Source: https://github.com/cnkang/markdown2docx/blob/main/README.md If custom templates cause issues, try using the built-in modern template for conversion. ```bash uv run python -m src.markdown2docx.cli --create-template modern.docx ``` ```bash uv run python -m src.markdown2docx.cli input.md --template modern.docx ``` -------------------------------- ### Setting Conversion Environment Variables Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/03-types.md Configure default Table of Contents, TOC depth, and output validation using environment variables. ```bash export MD2DOCX_CONVERSION__DEFAULT_TOC=true export MD2DOCX_CONVERSION__DEFAULT_TOC_DEPTH=2 export MD2DOCX_CONVERSION__VALIDATE_OUTPUT=true ``` -------------------------------- ### create_default_template Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/02-api-reference-templates.md Creates a modern template with default settings and sample content. This method is provided for backward compatibility and is equivalent to calling create_modern_template with add_sample=True. ```APIDOC ## Method: create_default_template (Class Method, Legacy) ### Description Create a modern template with default settings and sample content. ### Method Signature `@classmethod def create_default_template(cls, output_path: str | Path) -> Path` ### Parameters #### Path Parameters - **output_path** (str or Path) - Required - Destination path for the template file. ### Returns `Path` - Path to the created template file ### Example ```python # Legacy usage template_path = DocxTemplateManager.create_default_template("template.docx") ``` ``` -------------------------------- ### Convert Using a Template Programmatically Source: https://github.com/cnkang/markdown2docx/blob/main/README.md Convert a Markdown file to DOCX using a specific template file via the programmatic API. ```python from src.markdown2docx import MarkdownToDocxConverter converter = MarkdownToDocxConverter() output_path = converter.convert_with_template( "input.md", "modern.docx", "output.docx" ) ``` -------------------------------- ### Basic Program Invocation Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/05-cli-reference.md Standard command to invoke the markdown2docx CLI with options and an input file. ```bash markdown2docx [options] [input_file] ``` -------------------------------- ### Loading YAML Configuration Source: https://github.com/cnkang/markdown2docx/blob/main/_autodocs/07-configuration-reference.md Load configuration settings from a YAML file using the `load_config` function. This is an alternative to TOML for file-based configuration. ```python from markdown2docx.config import load_config from pathlib import Path config = load_config(Path("config.yaml")) converter = MarkdownToDocxConverter(config=config) ```