CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-mdutils

A comprehensive Python library for programmatically creating and manipulating Markdown files with support for headers, tables, lists, images, links, and text formatting.

80

1.90x
Overview
Eval results
Files

advanced.mddocs/

Advanced Features

Advanced functionality including content markers for precise positioning, HTML integration, code block insertion, and file utilities for complex document operations. These features enable sophisticated document generation and manipulation workflows.

Capabilities

Content Markers and Positioning

Create placeholders in documents and precisely position content using markers.

class MdUtils:
    def create_marker(self, text_marker: str) -> str:
        """
        Create a content placement marker in the document.

        Parameters:
        - text_marker (str): Unique identifier for the marker

        Returns:
        str: The marker string in format '##--[text_marker]--##'
        """

    def place_text_using_marker(self, text: str, marker: str) -> str:
        """
        Replace a marker with specific content.

        Parameters:
        - text (str): Content to place at marker location
        - marker (str): The marker to replace

        Returns:
        str: Updated document content with replaced marker
        """

Usage Example:

from mdutils import MdUtils

md = MdUtils(file_name='marker_positioning')

# Create document structure with markers
md.new_header(level=1, title='Project Report')
md.new_paragraph('This report contains dynamic content.')

md.new_header(level=2, title='Executive Summary')
summary_marker = md.create_marker('executive_summary')

md.new_header(level=2, title='Financial Data')
financial_marker = md.create_marker('financial_data')

md.new_header(level=2, title='Conclusions')
md.new_paragraph('Based on the analysis above, we conclude...')

# Later, populate the markers with content
summary_content = '''
The project has exceeded expectations in Q3 2023, showing significant growth in user engagement 
and revenue generation. Key metrics demonstrate a 25% increase in performance compared to Q2.
'''
md.place_text_using_marker(summary_content, summary_marker)

# Create complex content for financial section
financial_data = [
    ['Metric', 'Q2 2023', 'Q3 2023', 'Change'],
    ['Revenue', '$125,000', '$156,250', '+25%'],
    ['Users', '8,500', '10,625', '+25%'],
    ['Retention', '72%', '78%', '+6%']
]
financial_table = md.new_table_array(data=financial_data, text_align=['left', 'right', 'right', 'center'])
md.place_text_using_marker(financial_table, financial_marker)

print("Document with populated markers:")
print(md.get_md_text())

HTML Integration

Integrate HTML elements for enhanced formatting and presentation options not available in standard markdown.

class Html:
    @staticmethod
    def paragraph(text: str, align: str = None) -> str:
        """
        Create HTML paragraphs with alignment options.

        Parameters:
        - text (str): Paragraph content
        - align (str, optional): Text alignment ('left', 'center', 'right')

        Returns:
        str: HTML paragraph element
        """

    @classmethod
    def image(cls, path: str, size: str = None, align: str = None) -> str:
        """
        Create HTML images with size and alignment control.

        Parameters:
        - path (str): Image path or URL
        - size (str, optional): Size specification (e.g., '200x150', '300')
        - align (str, optional): Image alignment ('left', 'center', 'right')

        Returns:
        str: HTML image element
        """

class HtmlSize:
    @classmethod
    def size_to_width_and_height(cls, size: str) -> str:
        """
        Parse size string into width and height attributes.

        Parameters:
        - size (str): Size specification ('WIDTHxHEIGHT' or 'WIDTH')

        Returns:
        str: HTML width and height attributes
        """

# Exception for invalid size formats
class SizeBadFormat(Exception):
    def __init__(self, message):
        """Exception raised for invalid size format specifications."""

Usage Example:

from mdutils import MdUtils
from mdutils.tools import Html, HtmlSize, SizeBadFormat

md = MdUtils(file_name='html_integration')

# HTML paragraphs with alignment
md.new_header(level=1, title='HTML Enhanced Content')

centered_paragraph = Html.paragraph('This paragraph is centered using HTML.', align='center')
md.write(centered_paragraph)

right_aligned = Html.paragraph('This text is right-aligned.', align='right')
md.write(right_aligned)

# HTML images with size control
md.new_header(level=2, title='Sized Images')

# Image with specific dimensions
sized_image = Html.image('./images/diagram.png', size='400x300', align='center')
md.write(sized_image)

# Image with width only (maintains aspect ratio)
width_only_image = Html.image('./images/logo.png', size='200')
md.write(width_only_image)

# Handle size format errors
try:
    invalid_size = Html.image('./images/test.png', size='invalid-format')
except SizeBadFormat as e:
    print(f"Size format error: {e}")

# Using HtmlSize utility
try:
    size_attrs = HtmlSize.size_to_width_and_height('300x200')
    print(f"Size attributes: {size_attrs}")
except SizeBadFormat as e:
    print(f"Invalid size format: {e}")

File Utilities

Advanced file operations for reading, writing, and manipulating markdown files.

class MarkDownFile:
    def __init__(self, name="", dirname: Optional[str] = None):
        """
        Initialize markdown file handler.

        Parameters:
        - name (str): Filename (with or without .md extension)
        - dirname (str, optional): Directory path for the file
        """

    def rewrite_all_file(self, data: str):
        """
        Completely overwrite file content.

        Parameters:
        - data (str): New content for the file
        """

    def append_end(self, data: str):
        """
        Append content to the end of the file.

        Parameters:
        - data (str): Content to append
        """

    def append_after_second_line(self, data: str):
        """
        Insert content after the second line of the file.

        Parameters:
        - data (str): Content to insert
        """

    @staticmethod
    def read_file(file_name: str) -> str:
        """
        Read content from a markdown file.

        Parameters:
        - file_name (str): Path to the file to read

        Returns:
        str: File content
        """

    # Properties
    dirname: str      # Directory path
    file_name: str    # Complete file path
    file: file        # File handle object

Usage Example:

from mdutils import MdUtils
from mdutils.fileutils import MarkDownFile

# Advanced file operations
md = MdUtils(file_name='advanced_file_ops')
md.new_header(level=1, title='Original Content')
md.new_paragraph('This is the initial content.')

# Create the file
md_file = md.create_md_file()

# Use MarkDownFile for advanced operations
file_handler = MarkDownFile('advanced_file_ops.md')

# Append content to end
additional_content = '''

## Appended Section

This content was appended to the end of the file.
'''
file_handler.append_end(additional_content)

# Insert content after second line
header_addition = '''
**Last Updated:** 2023-11-20
**Version:** 1.0
'''
file_handler.append_after_second_line(header_addition)

# Read existing file content
existing_content = MarkDownFile.read_file('advanced_file_ops.md')
print("Current file content:")
print(existing_content)

# Create new file in specific directory
dir_file = MarkDownFile('report.md', dirname='./reports/')
dir_file.rewrite_all_file('# New Report\n\nThis is a report in a subdirectory.')

Code Block Management

Advanced code block insertion with language specification and formatting.

class MdUtils:
    def insert_code(self, code: str, language: str = "") -> str:
        """
        Insert formatted code blocks with syntax highlighting.

        Parameters:
        - code (str): Code content to insert
        - language (str, optional): Programming language for syntax highlighting

        Returns:
        str: Formatted code block
        """

class TextUtils:
    @staticmethod
    def insert_code(code: str, language: str = "") -> str:
        """
        Format code as markdown code block.

        Parameters:
        - code (str): Code content
        - language (str, optional): Language identifier for syntax highlighting

        Returns:
        str: Formatted code block markdown
        """

Usage Example:

from mdutils import MdUtils
from mdutils.tools import TextUtils

md = MdUtils(file_name='code_management')

md.new_header(level=1, title='Code Examples')

# Python code block
python_code = '''
def fibonacci(n):
    """Calculate Fibonacci number using recursion."""
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

# Example usage
for i in range(10):
    print(f"F({i}) = {fibonacci(i)}")
'''
md.insert_code(python_code, language='python')

# JavaScript code block  
js_code = '''
class Calculator {
    constructor() {
        this.history = [];
    }
    
    add(a, b) {
        const result = a + b;
        this.history.push(`${a} + ${b} = ${result}`);
        return result;
    }
    
    getHistory() {
        return this.history;
    }
}

const calc = new Calculator();
console.log(calc.add(5, 3)); // 8
'''
md.insert_code(js_code, language='javascript')

# SQL code block
sql_code = '''
SELECT 
    u.username,
    u.email,
    COUNT(p.id) as post_count,
    MAX(p.created_at) as last_post
FROM users u
LEFT JOIN posts p ON u.id = p.user_id
WHERE u.active = true
GROUP BY u.id, u.username, u.email
HAVING COUNT(p.id) > 0
ORDER BY post_count DESC
LIMIT 10;
'''
md.insert_code(sql_code, language='sql')

# Configuration file (no language specified)
config_content = '''
# Application Configuration
DEBUG=true
DATABASE_URL=postgresql://localhost:5432/myapp
REDIS_URL=redis://localhost:6379
SECRET_KEY=your-secret-key-here
'''
md.insert_code(config_content)

# Using TextUtils directly
bash_script = '''#!/bin/bash
echo "Starting deployment..."
git pull origin main
npm install
npm run build
pm2 restart app
echo "Deployment complete!"
'''
formatted_bash = TextUtils.insert_code(bash_script, 'bash')
md.write(formatted_bash)

Complex Document Assembly

Advanced patterns for building complex documents with dynamic content and sophisticated layouts.

Usage Example:

from mdutils import MdUtils
from mdutils.tools import Html
import json
from datetime import datetime

def create_project_report(project_data):
    """Create a comprehensive project report using advanced MDUtils features."""
    
    md = MdUtils(file_name=f"project_report_{project_data['id']}", 
                title=f"Project Report: {project_data['name']}")
    
    # Document metadata using HTML
    metadata_html = Html.paragraph(
        f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | "
        f"Project ID: {project_data['id']} | "
        f"Status: {project_data['status']}", 
        align='right'
    )
    md.write(metadata_html)
    
    # Executive summary with marker
    md.new_header(level=1, title='Executive Summary')
    summary_marker = md.create_marker('executive_summary')
    
    # Create dynamic content sections
    sections = [
        ('Project Overview', 'overview'),
        ('Technical Architecture', 'architecture'), 
        ('Timeline and Milestones', 'timeline'),
        ('Budget Analysis', 'budget'),
        ('Risk Assessment', 'risks'),
        ('Recommendations', 'recommendations')
    ]
    
    # Create section structure with markers
    section_markers = {}
    for title, key in sections:
        md.new_header(level=2, title=title)
        section_markers[key] = md.create_marker(f'section_{key}')
    
    # Populate executive summary
    summary_content = f"""
{Html.paragraph(project_data['description'], align='justify')}

**Key Metrics:**
- Budget: ${project_data['budget']:,}
- Timeline: {project_data['duration']} months  
- Team Size: {project_data['team_size']} members
- Completion: {project_data['completion']}%
"""
    md.place_text_using_marker(summary_content, summary_marker)
    
    # Populate technical architecture
    if 'architecture' in project_data:
        arch_content = f"""
### Technology Stack

{project_data['architecture']['description']}
"""
        # Add technology table
        tech_data = [['Component', 'Technology', 'Version']]
        for comp, details in project_data['architecture']['components'].items():
            tech_data.append([comp.title(), details['name'], details['version']])
        
        arch_table = md.new_table_array(data=tech_data, text_align=['left', 'left', 'center'])
        arch_content += arch_table
        
        md.place_text_using_marker(arch_content, section_markers['architecture'])
    
    # Add timeline with progress tracking
    if 'milestones' in project_data:
        timeline_content = "### Project Milestones\n\n"
        milestone_items = []
        for milestone in project_data['milestones']:
            status_icon = '✅' if milestone['completed'] else '⏳'
            milestone_items.append(f"{milestone['name']} - {milestone['due_date']} {status_icon}")
        
        timeline_list = md.new_list(milestone_items, marked_with='1')
        timeline_content += timeline_list
        
        md.place_text_using_marker(timeline_content, section_markers['timeline'])
    
    # Generate and return the complete document
    return md

# Example usage
project_info = {
    'id': 'PROJ-2023-001',
    'name': 'E-commerce Platform Modernization',
    'description': 'Migration of legacy e-commerce system to modern cloud-native architecture.',
    'status': 'In Progress',
    'budget': 500000,
    'duration': 8,
    'team_size': 12,
    'completion': 65,
    'architecture': {
        'description': 'Microservices architecture using containerized applications.',
        'components': {
            'frontend': {'name': 'React', 'version': '18.2.0'},
            'backend': {'name': 'Node.js', 'version': '18.17.0'},
            'database': {'name': 'PostgreSQL', 'version': '15.3'},
            'cache': {'name': 'Redis', 'version': '7.0.11'}
        }
    },
    'milestones': [
        {'name': 'Requirements Analysis', 'due_date': '2023-09-15', 'completed': True},
        {'name': 'Architecture Design', 'due_date': '2023-10-01', 'completed': True},
        {'name': 'Core Development', 'due_date': '2023-11-30', 'completed': False},
        {'name': 'Testing & QA', 'due_date': '2023-12-15', 'completed': False},
        {'name': 'Deployment', 'due_date': '2023-12-30', 'completed': False}
    ]
}

# Generate the report
report = create_project_report(project_info)
report.create_md_file()

Document Template System

Create reusable document templates with marker-based content injection.

Usage Example:

from mdutils import MdUtils

class DocumentTemplate:
    """Template system for creating standardized documents."""
    
    def __init__(self, template_name):
        self.template_name = template_name
        self.markers = {}
    
    def create_template(self):
        """Create base template structure."""
        md = MdUtils(file_name=self.template_name)
        
        # Standard header
        md.new_header(level=1, title='Document Title')
        self.markers['title'] = md.create_marker('document_title')
        
        # Metadata section
        md.new_paragraph('**Document Information:**')
        self.markers['metadata'] = md.create_marker('document_metadata')
        
        # Main content sections
        sections = ['introduction', 'methodology', 'results', 'conclusion']
        for section in sections:
            md.new_header(level=2, title=section.title())
            self.markers[section] = md.create_marker(f'section_{section}')
        
        # Appendix
        md.new_header(level=2, title='Appendix')
        self.markers['appendix'] = md.create_marker('appendix_content')
        
        return md
    
    def populate_template(self, md, content_dict):
        """Populate template with actual content."""
        for key, content in content_dict.items():
            if key in self.markers:
                md.place_text_using_marker(content, self.markers[key])
        return md

# Use the template system
template_system = DocumentTemplate('research_report')
template_md = template_system.create_template()

# Define content
report_content = {
    'title': 'Impact of Cloud Computing on Business Operations',
    'metadata': '''
- **Author:** Dr. Jane Smith
- **Date:** November 2023
- **Department:** Information Technology
- **Classification:** Public
''',
    'introduction': '''
This study examines the transformative impact of cloud computing technologies on modern business operations. 
Through comprehensive analysis of industry data and case studies, we explore the benefits, challenges, 
and strategic implications of cloud adoption.
''',
    'methodology': '''
### Research Approach

Our methodology included:
- Literature review of 150+ academic papers
- Survey of 500 enterprise decision makers  
- Case study analysis of 25 organizations
- Statistical analysis using Python and R

### Data Collection

Data was collected over a 6-month period from January to June 2023.
''',
    'results': '''
### Key Findings

1. **Cost Reduction**: Average 30% reduction in IT infrastructure costs
2. **Scalability**: 85% improvement in system scalability metrics
3. **Performance**: 25% increase in application performance
4. **Security**: Mixed results with 60% reporting improved security

### Statistical Analysis

Detailed statistical analysis reveals significant correlations between cloud adoption and operational efficiency.
''',
    'conclusion': '''
Cloud computing demonstrates substantial benefits for business operations, particularly in cost reduction and scalability. 
However, organizations must carefully consider security implications and change management requirements.

### Recommendations

1. Develop comprehensive cloud strategy
2. Invest in staff training and development
3. Implement robust security measures
4. Plan for gradual migration approach
'''
}

# Populate and create the document
final_document = template_system.populate_template(template_md, report_content)
final_document.create_md_file()

Install with Tessl CLI

npx tessl i tessl/pypi-mdutils

docs

advanced.md

core-document.md

headers-toc.md

index.md

links-images.md

lists.md

tables.md

text-formatting.md

tile.json