0
# Advanced Features
1
2
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.
3
4
## Capabilities
5
6
### Content Markers and Positioning
7
8
Create placeholders in documents and precisely position content using markers.
9
10
```python { .api }
11
class MdUtils:
12
def create_marker(self, text_marker: str) -> str:
13
"""
14
Create a content placement marker in the document.
15
16
Parameters:
17
- text_marker (str): Unique identifier for the marker
18
19
Returns:
20
str: The marker string in format '##--[text_marker]--##'
21
"""
22
23
def place_text_using_marker(self, text: str, marker: str) -> str:
24
"""
25
Replace a marker with specific content.
26
27
Parameters:
28
- text (str): Content to place at marker location
29
- marker (str): The marker to replace
30
31
Returns:
32
str: Updated document content with replaced marker
33
"""
34
```
35
36
**Usage Example:**
37
38
```python
39
from mdutils import MdUtils
40
41
md = MdUtils(file_name='marker_positioning')
42
43
# Create document structure with markers
44
md.new_header(level=1, title='Project Report')
45
md.new_paragraph('This report contains dynamic content.')
46
47
md.new_header(level=2, title='Executive Summary')
48
summary_marker = md.create_marker('executive_summary')
49
50
md.new_header(level=2, title='Financial Data')
51
financial_marker = md.create_marker('financial_data')
52
53
md.new_header(level=2, title='Conclusions')
54
md.new_paragraph('Based on the analysis above, we conclude...')
55
56
# Later, populate the markers with content
57
summary_content = '''
58
The project has exceeded expectations in Q3 2023, showing significant growth in user engagement
59
and revenue generation. Key metrics demonstrate a 25% increase in performance compared to Q2.
60
'''
61
md.place_text_using_marker(summary_content, summary_marker)
62
63
# Create complex content for financial section
64
financial_data = [
65
['Metric', 'Q2 2023', 'Q3 2023', 'Change'],
66
['Revenue', '$125,000', '$156,250', '+25%'],
67
['Users', '8,500', '10,625', '+25%'],
68
['Retention', '72%', '78%', '+6%']
69
]
70
financial_table = md.new_table_array(data=financial_data, text_align=['left', 'right', 'right', 'center'])
71
md.place_text_using_marker(financial_table, financial_marker)
72
73
print("Document with populated markers:")
74
print(md.get_md_text())
75
```
76
77
### HTML Integration
78
79
Integrate HTML elements for enhanced formatting and presentation options not available in standard markdown.
80
81
```python { .api }
82
class Html:
83
@staticmethod
84
def paragraph(text: str, align: str = None) -> str:
85
"""
86
Create HTML paragraphs with alignment options.
87
88
Parameters:
89
- text (str): Paragraph content
90
- align (str, optional): Text alignment ('left', 'center', 'right')
91
92
Returns:
93
str: HTML paragraph element
94
"""
95
96
@classmethod
97
def image(cls, path: str, size: str = None, align: str = None) -> str:
98
"""
99
Create HTML images with size and alignment control.
100
101
Parameters:
102
- path (str): Image path or URL
103
- size (str, optional): Size specification (e.g., '200x150', '300')
104
- align (str, optional): Image alignment ('left', 'center', 'right')
105
106
Returns:
107
str: HTML image element
108
"""
109
110
class HtmlSize:
111
@classmethod
112
def size_to_width_and_height(cls, size: str) -> str:
113
"""
114
Parse size string into width and height attributes.
115
116
Parameters:
117
- size (str): Size specification ('WIDTHxHEIGHT' or 'WIDTH')
118
119
Returns:
120
str: HTML width and height attributes
121
"""
122
123
# Exception for invalid size formats
124
class SizeBadFormat(Exception):
125
def __init__(self, message):
126
"""Exception raised for invalid size format specifications."""
127
```
128
129
**Usage Example:**
130
131
```python
132
from mdutils import MdUtils
133
from mdutils.tools import Html, HtmlSize, SizeBadFormat
134
135
md = MdUtils(file_name='html_integration')
136
137
# HTML paragraphs with alignment
138
md.new_header(level=1, title='HTML Enhanced Content')
139
140
centered_paragraph = Html.paragraph('This paragraph is centered using HTML.', align='center')
141
md.write(centered_paragraph)
142
143
right_aligned = Html.paragraph('This text is right-aligned.', align='right')
144
md.write(right_aligned)
145
146
# HTML images with size control
147
md.new_header(level=2, title='Sized Images')
148
149
# Image with specific dimensions
150
sized_image = Html.image('./images/diagram.png', size='400x300', align='center')
151
md.write(sized_image)
152
153
# Image with width only (maintains aspect ratio)
154
width_only_image = Html.image('./images/logo.png', size='200')
155
md.write(width_only_image)
156
157
# Handle size format errors
158
try:
159
invalid_size = Html.image('./images/test.png', size='invalid-format')
160
except SizeBadFormat as e:
161
print(f"Size format error: {e}")
162
163
# Using HtmlSize utility
164
try:
165
size_attrs = HtmlSize.size_to_width_and_height('300x200')
166
print(f"Size attributes: {size_attrs}")
167
except SizeBadFormat as e:
168
print(f"Invalid size format: {e}")
169
```
170
171
### File Utilities
172
173
Advanced file operations for reading, writing, and manipulating markdown files.
174
175
```python { .api }
176
class MarkDownFile:
177
def __init__(self, name="", dirname: Optional[str] = None):
178
"""
179
Initialize markdown file handler.
180
181
Parameters:
182
- name (str): Filename (with or without .md extension)
183
- dirname (str, optional): Directory path for the file
184
"""
185
186
def rewrite_all_file(self, data: str):
187
"""
188
Completely overwrite file content.
189
190
Parameters:
191
- data (str): New content for the file
192
"""
193
194
def append_end(self, data: str):
195
"""
196
Append content to the end of the file.
197
198
Parameters:
199
- data (str): Content to append
200
"""
201
202
def append_after_second_line(self, data: str):
203
"""
204
Insert content after the second line of the file.
205
206
Parameters:
207
- data (str): Content to insert
208
"""
209
210
@staticmethod
211
def read_file(file_name: str) -> str:
212
"""
213
Read content from a markdown file.
214
215
Parameters:
216
- file_name (str): Path to the file to read
217
218
Returns:
219
str: File content
220
"""
221
222
# Properties
223
dirname: str # Directory path
224
file_name: str # Complete file path
225
file: file # File handle object
226
```
227
228
**Usage Example:**
229
230
```python
231
from mdutils import MdUtils
232
from mdutils.fileutils import MarkDownFile
233
234
# Advanced file operations
235
md = MdUtils(file_name='advanced_file_ops')
236
md.new_header(level=1, title='Original Content')
237
md.new_paragraph('This is the initial content.')
238
239
# Create the file
240
md_file = md.create_md_file()
241
242
# Use MarkDownFile for advanced operations
243
file_handler = MarkDownFile('advanced_file_ops.md')
244
245
# Append content to end
246
additional_content = '''
247
248
## Appended Section
249
250
This content was appended to the end of the file.
251
'''
252
file_handler.append_end(additional_content)
253
254
# Insert content after second line
255
header_addition = '''
256
**Last Updated:** 2023-11-20
257
**Version:** 1.0
258
'''
259
file_handler.append_after_second_line(header_addition)
260
261
# Read existing file content
262
existing_content = MarkDownFile.read_file('advanced_file_ops.md')
263
print("Current file content:")
264
print(existing_content)
265
266
# Create new file in specific directory
267
dir_file = MarkDownFile('report.md', dirname='./reports/')
268
dir_file.rewrite_all_file('# New Report\n\nThis is a report in a subdirectory.')
269
```
270
271
### Code Block Management
272
273
Advanced code block insertion with language specification and formatting.
274
275
```python { .api }
276
class MdUtils:
277
def insert_code(self, code: str, language: str = "") -> str:
278
"""
279
Insert formatted code blocks with syntax highlighting.
280
281
Parameters:
282
- code (str): Code content to insert
283
- language (str, optional): Programming language for syntax highlighting
284
285
Returns:
286
str: Formatted code block
287
"""
288
289
class TextUtils:
290
@staticmethod
291
def insert_code(code: str, language: str = "") -> str:
292
"""
293
Format code as markdown code block.
294
295
Parameters:
296
- code (str): Code content
297
- language (str, optional): Language identifier for syntax highlighting
298
299
Returns:
300
str: Formatted code block markdown
301
"""
302
```
303
304
**Usage Example:**
305
306
```python
307
from mdutils import MdUtils
308
from mdutils.tools import TextUtils
309
310
md = MdUtils(file_name='code_management')
311
312
md.new_header(level=1, title='Code Examples')
313
314
# Python code block
315
python_code = '''
316
def fibonacci(n):
317
"""Calculate Fibonacci number using recursion."""
318
if n <= 1:
319
return n
320
return fibonacci(n - 1) + fibonacci(n - 2)
321
322
# Example usage
323
for i in range(10):
324
print(f"F({i}) = {fibonacci(i)}")
325
'''
326
md.insert_code(python_code, language='python')
327
328
# JavaScript code block
329
js_code = '''
330
class Calculator {
331
constructor() {
332
this.history = [];
333
}
334
335
add(a, b) {
336
const result = a + b;
337
this.history.push(`${a} + ${b} = ${result}`);
338
return result;
339
}
340
341
getHistory() {
342
return this.history;
343
}
344
}
345
346
const calc = new Calculator();
347
console.log(calc.add(5, 3)); // 8
348
'''
349
md.insert_code(js_code, language='javascript')
350
351
# SQL code block
352
sql_code = '''
353
SELECT
354
u.username,
355
u.email,
356
COUNT(p.id) as post_count,
357
MAX(p.created_at) as last_post
358
FROM users u
359
LEFT JOIN posts p ON u.id = p.user_id
360
WHERE u.active = true
361
GROUP BY u.id, u.username, u.email
362
HAVING COUNT(p.id) > 0
363
ORDER BY post_count DESC
364
LIMIT 10;
365
'''
366
md.insert_code(sql_code, language='sql')
367
368
# Configuration file (no language specified)
369
config_content = '''
370
# Application Configuration
371
DEBUG=true
372
DATABASE_URL=postgresql://localhost:5432/myapp
373
REDIS_URL=redis://localhost:6379
374
SECRET_KEY=your-secret-key-here
375
'''
376
md.insert_code(config_content)
377
378
# Using TextUtils directly
379
bash_script = '''#!/bin/bash
380
echo "Starting deployment..."
381
git pull origin main
382
npm install
383
npm run build
384
pm2 restart app
385
echo "Deployment complete!"
386
'''
387
formatted_bash = TextUtils.insert_code(bash_script, 'bash')
388
md.write(formatted_bash)
389
```
390
391
### Complex Document Assembly
392
393
Advanced patterns for building complex documents with dynamic content and sophisticated layouts.
394
395
**Usage Example:**
396
397
```python
398
from mdutils import MdUtils
399
from mdutils.tools import Html
400
import json
401
from datetime import datetime
402
403
def create_project_report(project_data):
404
"""Create a comprehensive project report using advanced MDUtils features."""
405
406
md = MdUtils(file_name=f"project_report_{project_data['id']}",
407
title=f"Project Report: {project_data['name']}")
408
409
# Document metadata using HTML
410
metadata_html = Html.paragraph(
411
f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | "
412
f"Project ID: {project_data['id']} | "
413
f"Status: {project_data['status']}",
414
align='right'
415
)
416
md.write(metadata_html)
417
418
# Executive summary with marker
419
md.new_header(level=1, title='Executive Summary')
420
summary_marker = md.create_marker('executive_summary')
421
422
# Create dynamic content sections
423
sections = [
424
('Project Overview', 'overview'),
425
('Technical Architecture', 'architecture'),
426
('Timeline and Milestones', 'timeline'),
427
('Budget Analysis', 'budget'),
428
('Risk Assessment', 'risks'),
429
('Recommendations', 'recommendations')
430
]
431
432
# Create section structure with markers
433
section_markers = {}
434
for title, key in sections:
435
md.new_header(level=2, title=title)
436
section_markers[key] = md.create_marker(f'section_{key}')
437
438
# Populate executive summary
439
summary_content = f"""
440
{Html.paragraph(project_data['description'], align='justify')}
441
442
**Key Metrics:**
443
- Budget: ${project_data['budget']:,}
444
- Timeline: {project_data['duration']} months
445
- Team Size: {project_data['team_size']} members
446
- Completion: {project_data['completion']}%
447
"""
448
md.place_text_using_marker(summary_content, summary_marker)
449
450
# Populate technical architecture
451
if 'architecture' in project_data:
452
arch_content = f"""
453
### Technology Stack
454
455
{project_data['architecture']['description']}
456
"""
457
# Add technology table
458
tech_data = [['Component', 'Technology', 'Version']]
459
for comp, details in project_data['architecture']['components'].items():
460
tech_data.append([comp.title(), details['name'], details['version']])
461
462
arch_table = md.new_table_array(data=tech_data, text_align=['left', 'left', 'center'])
463
arch_content += arch_table
464
465
md.place_text_using_marker(arch_content, section_markers['architecture'])
466
467
# Add timeline with progress tracking
468
if 'milestones' in project_data:
469
timeline_content = "### Project Milestones\n\n"
470
milestone_items = []
471
for milestone in project_data['milestones']:
472
status_icon = '✅' if milestone['completed'] else '⏳'
473
milestone_items.append(f"{milestone['name']} - {milestone['due_date']} {status_icon}")
474
475
timeline_list = md.new_list(milestone_items, marked_with='1')
476
timeline_content += timeline_list
477
478
md.place_text_using_marker(timeline_content, section_markers['timeline'])
479
480
# Generate and return the complete document
481
return md
482
483
# Example usage
484
project_info = {
485
'id': 'PROJ-2023-001',
486
'name': 'E-commerce Platform Modernization',
487
'description': 'Migration of legacy e-commerce system to modern cloud-native architecture.',
488
'status': 'In Progress',
489
'budget': 500000,
490
'duration': 8,
491
'team_size': 12,
492
'completion': 65,
493
'architecture': {
494
'description': 'Microservices architecture using containerized applications.',
495
'components': {
496
'frontend': {'name': 'React', 'version': '18.2.0'},
497
'backend': {'name': 'Node.js', 'version': '18.17.0'},
498
'database': {'name': 'PostgreSQL', 'version': '15.3'},
499
'cache': {'name': 'Redis', 'version': '7.0.11'}
500
}
501
},
502
'milestones': [
503
{'name': 'Requirements Analysis', 'due_date': '2023-09-15', 'completed': True},
504
{'name': 'Architecture Design', 'due_date': '2023-10-01', 'completed': True},
505
{'name': 'Core Development', 'due_date': '2023-11-30', 'completed': False},
506
{'name': 'Testing & QA', 'due_date': '2023-12-15', 'completed': False},
507
{'name': 'Deployment', 'due_date': '2023-12-30', 'completed': False}
508
]
509
}
510
511
# Generate the report
512
report = create_project_report(project_info)
513
report.create_md_file()
514
```
515
516
### Document Template System
517
518
Create reusable document templates with marker-based content injection.
519
520
**Usage Example:**
521
522
```python
523
from mdutils import MdUtils
524
525
class DocumentTemplate:
526
"""Template system for creating standardized documents."""
527
528
def __init__(self, template_name):
529
self.template_name = template_name
530
self.markers = {}
531
532
def create_template(self):
533
"""Create base template structure."""
534
md = MdUtils(file_name=self.template_name)
535
536
# Standard header
537
md.new_header(level=1, title='Document Title')
538
self.markers['title'] = md.create_marker('document_title')
539
540
# Metadata section
541
md.new_paragraph('**Document Information:**')
542
self.markers['metadata'] = md.create_marker('document_metadata')
543
544
# Main content sections
545
sections = ['introduction', 'methodology', 'results', 'conclusion']
546
for section in sections:
547
md.new_header(level=2, title=section.title())
548
self.markers[section] = md.create_marker(f'section_{section}')
549
550
# Appendix
551
md.new_header(level=2, title='Appendix')
552
self.markers['appendix'] = md.create_marker('appendix_content')
553
554
return md
555
556
def populate_template(self, md, content_dict):
557
"""Populate template with actual content."""
558
for key, content in content_dict.items():
559
if key in self.markers:
560
md.place_text_using_marker(content, self.markers[key])
561
return md
562
563
# Use the template system
564
template_system = DocumentTemplate('research_report')
565
template_md = template_system.create_template()
566
567
# Define content
568
report_content = {
569
'title': 'Impact of Cloud Computing on Business Operations',
570
'metadata': '''
571
- **Author:** Dr. Jane Smith
572
- **Date:** November 2023
573
- **Department:** Information Technology
574
- **Classification:** Public
575
''',
576
'introduction': '''
577
This study examines the transformative impact of cloud computing technologies on modern business operations.
578
Through comprehensive analysis of industry data and case studies, we explore the benefits, challenges,
579
and strategic implications of cloud adoption.
580
''',
581
'methodology': '''
582
### Research Approach
583
584
Our methodology included:
585
- Literature review of 150+ academic papers
586
- Survey of 500 enterprise decision makers
587
- Case study analysis of 25 organizations
588
- Statistical analysis using Python and R
589
590
### Data Collection
591
592
Data was collected over a 6-month period from January to June 2023.
593
''',
594
'results': '''
595
### Key Findings
596
597
1. **Cost Reduction**: Average 30% reduction in IT infrastructure costs
598
2. **Scalability**: 85% improvement in system scalability metrics
599
3. **Performance**: 25% increase in application performance
600
4. **Security**: Mixed results with 60% reporting improved security
601
602
### Statistical Analysis
603
604
Detailed statistical analysis reveals significant correlations between cloud adoption and operational efficiency.
605
''',
606
'conclusion': '''
607
Cloud computing demonstrates substantial benefits for business operations, particularly in cost reduction and scalability.
608
However, organizations must carefully consider security implications and change management requirements.
609
610
### Recommendations
611
612
1. Develop comprehensive cloud strategy
613
2. Invest in staff training and development
614
3. Implement robust security measures
615
4. Plan for gradual migration approach
616
'''
617
}
618
619
# Populate and create the document
620
final_document = template_system.populate_template(template_md, report_content)
621
final_document.create_md_file()
622
```