**Title:** Implement real-time Markdown to Word conversion with advanced formatting and auto-captioning
- Added `app.py` with Flask backend for real-time Markdown to Word conversion using python-docx - Implemented `convert_md_to_docx` function with support for headings, tables, code blocks, images, and blockquote styling - Created `templates/index.html` with responsive UI featuring dual-panel editor/preview layout - Added `static/script.js` for client-side functionality including live preview, toolbar buttons, and export workflow - Enhanced `static/style.css` with modern styling for editor, preview, and settings panels - Updated `README.md` to document features, usage, and customization options - Added `requirements.txt` with dependencies: Flask, python-docx, markdown - Implemented auto-captioning for images and tables with sequential numbering - Added table pagination support with header repetition across page breaks - Integrated configuration settings panel for customizing styles, captions, and document options
This commit is contained in:
@@ -1,209 +1,93 @@
|
||||
# GhostEditor
|
||||
Программа для конвертации из формата `md` в формат `docx`(x это без макросов, m с макросами) (`Office Open XML`),`odt`(`OpenDocument`)
|
||||
# GhostEditor - Markdown to Word Converter
|
||||
|
||||
#### **1. python-docx**
|
||||
**Назначение**: Создание и модификация Word-документов.
|
||||
**Ключевые возможности**:
|
||||
- Добавление/редактирование текста, таблиц, изображений.
|
||||
- Управление стилями, колонтитулами, сносками.
|
||||
- Работа с XML через абстракции (Paragraph, Run, Table).
|
||||
A web-based application that converts Markdown to Word documents with advanced features including real-time preview, styling options, auto-captioning, and table pagination.
|
||||
|
||||
**Пример**:
|
||||
```python
|
||||
from docx import Document
|
||||
from docx.shared import Pt
|
||||
## Features
|
||||
|
||||
doc = Document()
|
||||
paragraph = doc.add_paragraph("Hello ")
|
||||
run = paragraph.add_run("OOXML!")
|
||||
run.bold = True
|
||||
run.font.size = Pt(14)
|
||||
1. **Real-time Conversion**: See your Markdown text convert to Word format in real-time
|
||||
2. **Styling Options**: Apply different styles to text elements (headings, quotes, code blocks, etc.)
|
||||
3. **Auto Captioning**: Automatic captions for images, tables, and figures
|
||||
4. **Table Pagination**: Support for tables that span across pages with repeating headers
|
||||
5. **Custom Settings**: Configure document settings and styling preferences
|
||||
|
||||
# Таблица
|
||||
table = doc.add_table(rows=2, cols=2)
|
||||
table.cell(0, 0).text = "Cell A1"
|
||||
## Requirements
|
||||
|
||||
doc.save("report.docx")
|
||||
- Python 3.7+
|
||||
- Flask
|
||||
- python-docx
|
||||
- markdown
|
||||
|
||||
## Installation
|
||||
|
||||
1. Install the required packages:
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
2. Run the application:
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
|
||||
3. Open your browser and navigate to `http://localhost:5000`
|
||||
|
||||
## Usage
|
||||
|
||||
1. Enter or paste your Markdown content in the left editor panel
|
||||
2. See the real-time conversion in the right preview panel
|
||||
3. Use the settings panel to configure document options:
|
||||
- Set document title
|
||||
- Choose default text style
|
||||
- Enable/disable auto-captioning for images, tables, and figures
|
||||
- Enable/disable table pagination
|
||||
4. Use the toolbar buttons to format text directly in the editor
|
||||
5. Select block type and apply custom styles to specific elements
|
||||
6. Add custom captions to elements as needed
|
||||
7. Click "Export to Word" to download your document
|
||||
|
||||
## Features Explained
|
||||
|
||||
### Real-time Preview
|
||||
- The application converts Markdown to Word format as you type
|
||||
- Preview updates automatically as you make changes
|
||||
|
||||
### Auto Captioning
|
||||
- Images automatically receive "Figure X" captions
|
||||
- Tables automatically receive "Table X" captions
|
||||
- Captions are numbered sequentially
|
||||
|
||||
### Table Pagination
|
||||
- When enabled, tables that span multiple pages will repeat their header row
|
||||
- This ensures readability when tables cross page boundaries
|
||||
|
||||
### Block Styling
|
||||
- Select different block types (paragraph, heading, list, etc.)
|
||||
- Apply specific styles to different content blocks
|
||||
- Add custom captions to any element
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
/workspace/
|
||||
├── app.py # Main Flask application
|
||||
├── requirements.txt # Python dependencies
|
||||
├── templates/
|
||||
│ └── index.html # Main HTML template
|
||||
└── static/
|
||||
├── style.css # CSS styling
|
||||
└── script.js # JavaScript functionality
|
||||
```
|
||||
|
||||
**Плюсы**:
|
||||
- Интуитивный API, близкий к логике Word.
|
||||
- Поддержка всех ключевых частей пакета (headers, footers, styles).
|
||||
## Technologies Used
|
||||
|
||||
**Минусы**:
|
||||
- Нет поддержки макросов.
|
||||
- Ограниченная работа с графикой (изображения добавляются, но редактирование сложно).
|
||||
- **Frontend**: HTML, CSS, JavaScript, Bootstrap 5, Marked.js
|
||||
- **Backend**: Flask (Python)
|
||||
- **Document Processing**: python-docx
|
||||
- **Markdown Processing**: markdown (Python library)
|
||||
|
||||
**Ссылка**: [python-docx.readthedocs.io](https://python-docx.readthedocs.io/)
|
||||
## Customization
|
||||
|
||||
---
|
||||
|
||||
#### **2. docxtpl**
|
||||
**Назначение**: Генерация документов по шаблонам (Jinja2).
|
||||
**Особенности**:
|
||||
- Шаблоны .docx с переменными (`{{ variable }}`) и логикой (`{% if %}`).
|
||||
- Поддержка таблиц, изображений, HTML-фрагментов.
|
||||
|
||||
**Пример**:
|
||||
```python
|
||||
from docxtpl import DocxTemplate
|
||||
|
||||
doc = DocxTemplate("template.docx")
|
||||
context = {
|
||||
"title": "Отчет за 2023",
|
||||
"items": [{"name": "Item 1"}, {"name": "Item 2"}]
|
||||
}
|
||||
doc.render(context)
|
||||
doc.save("output.docx")
|
||||
```
|
||||
|
||||
**Плюсы**:
|
||||
- Идеален для шаблонизированных отчетов (договоры, счета).
|
||||
- Интеграция с Django/Flask.
|
||||
|
||||
**Минусы**:
|
||||
- Требует предварительной настройки шаблонов в Word.
|
||||
|
||||
**Ссылка**: [github.com/elapouya/python-docx-template](https://github.com/elapouya/python-docx-template)
|
||||
|
||||
---
|
||||
|
||||
#### **3. mammoth**
|
||||
**Назначение**: Конвертация .docx → HTML с сохранением структуры.
|
||||
**Особенности**:
|
||||
- Преобразует стили Word в CSS-классы.
|
||||
- Подходит для извлечения контента из сложных документов.
|
||||
|
||||
**Пример**:
|
||||
```python
|
||||
import mammoth
|
||||
|
||||
with open("document.docx", "rb") as docx_file:
|
||||
result = mammoth.convert_to_html(docx_file)
|
||||
html = result.value # HTML-строка
|
||||
warnings = result.messages # Предупреждения
|
||||
```
|
||||
|
||||
**Плюсы**:
|
||||
- Сохраняет семантику (заголовки, списки, таблицы).
|
||||
- Легко интегрируется с парсерами (BeautifulSoup).
|
||||
|
||||
**Минусы**:
|
||||
- Не подходит для обратной конвертации (HTML → docx).
|
||||
|
||||
**Ссылка**: [github.com/mwilliamson/mammoth.py](https://github.com/mwilliamson/mammoth.py)
|
||||
|
||||
---
|
||||
|
||||
### **Низкоуровневые инструменты (для кастомных задач)**
|
||||
|
||||
#### **1. zipfile + lxml**
|
||||
**Назначение**: Прямой доступ к XML-структуре OOXML.
|
||||
**Когда использовать**:
|
||||
- При работе с нестандартными частями пакета (напр., кастомные XML-маппинги в Excel).
|
||||
- Для восстановления поврежденных файлов.
|
||||
|
||||
**Пример для Excel**:
|
||||
```python
|
||||
import zipfile
|
||||
from lxml import etree
|
||||
|
||||
# Распаковываем workbook.xml
|
||||
with zipfile.ZipFile("report.xlsx") as xlsx:
|
||||
xml_data = xlsx.read("xl/workbook.xml")
|
||||
|
||||
# Парсим XML
|
||||
workbook = etree.fromstring(xml_data)
|
||||
namespaces = {"ns": "http://schemas.../spreadsheetml/2006/main"}
|
||||
sheets = workbook.findall(".//ns:sheet", namespaces)
|
||||
|
||||
# Меняем имя листа
|
||||
sheets[0].set("{http://.../officeDocument/2006/relationships}name", "New Sheet")
|
||||
|
||||
# Сохраняем изменения
|
||||
with zipfile.ZipFile("fixed.xlsx", "w") as new_xlsx:
|
||||
for file in xlsx.namelist():
|
||||
if file != "xl/workbook.xml":
|
||||
new_xlsx.writestr(file, xlsx.read(file))
|
||||
new_xlsx.writestr("xl/workbook.xml", etree.tostring(workbook))
|
||||
```
|
||||
|
||||
**Плюсы**:
|
||||
- Полный контроль над структурой.
|
||||
- Работает с любыми частями пакета.
|
||||
|
||||
**Минусы**:
|
||||
- Требует знания XML-схем OOXML.
|
||||
- Риск повреждения файла при ошибках.
|
||||
|
||||
---
|
||||
|
||||
#### **2. officedoc**
|
||||
**Назначение**: Универсальный доступ к форматам Office (docx, xlsx, pptx).
|
||||
**Особенности**:
|
||||
- Объединяет функционал `python-docx`, `openpyxl`, `python-pptx` в едином API.
|
||||
- Упрощает обработку мультимедийных вложений.
|
||||
|
||||
**Пример**:
|
||||
```python
|
||||
from officedoc import Document
|
||||
|
||||
doc = Document("mixed.docx")
|
||||
for image in doc.images:
|
||||
image.save("extracted_" + image.filename)
|
||||
|
||||
for table in doc.tables:
|
||||
print(table.to_dataframe()) # Конвертация в pandas DataFrame
|
||||
```
|
||||
|
||||
**Ссылка**: [github.com/mikem1701/officedoc](https://github.com/mikem1701/officedoc)
|
||||
|
||||
---
|
||||
|
||||
### **Сравнение библиотек**
|
||||
|
||||
| **Библиотека** | **Скорость** | **Сложность** | **Особенности** |
|
||||
|----------------------|-------------|---------------|----------------------------|
|
||||
| **python-docx** | Средняя | Средняя | Стандарт для работы с Word |
|
||||
| **docxtpl** | Средняя | Низкая | Шаблонизация через Jinja2 |
|
||||
| **zipfile + lxml** | Высокая | Высокая | Полный контроль над XML |
|
||||
|
||||
---
|
||||
|
||||
#### Для Word (.docx)
|
||||
- **Простое создание документов**: `python-docx`.
|
||||
- **Шаблонные документы** (договоры, счета): `docxtpl`.
|
||||
- **Извлечение контента**: `mammoth` → обработка HTML через BeautifulSoup.
|
||||
- **Редактирование структуры**: `python-docx` + `zipfile` для кастомных частей.
|
||||
|
||||
#### Для кастомных задач
|
||||
- **Восстановление файлов**: `zipfile` + `lxml` (ручное исправление XML).
|
||||
- **Интеграция с внешними системами**: `openpyxl`/`python-docx` + REST API (напр., выгрузка данных из БД в Excel).
|
||||
|
||||
---
|
||||
|
||||
### Типичные проблемы и решения
|
||||
|
||||
2. Стили не применяются в Word
|
||||
- Проблема: `python-docx` использует стили из `styles.xml`, но не создает новые автоматически.
|
||||
- Решение:
|
||||
```python
|
||||
from docx.shared import Pt
|
||||
style = doc.styles.add_style("Heading3", WD_STYLE_TYPE.PARAGRAPH)
|
||||
font = style.font
|
||||
font.name = "Arial"
|
||||
font.size = Pt(12)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### **Заключение**
|
||||
Для 90% задач достаточно:
|
||||
- **Excel**: `openpyxl` или `pandas`.
|
||||
- **Word**: `python-docx` + `docxtpl`.
|
||||
|
||||
**Используйте низкоуровневые методы (zipfile/lxml) только когда**:
|
||||
|
||||
*Для углубленного изучения:*
|
||||
- [Open XML SDK 2.5](https://learn.microsoft.com/ru-ru/office/open-xml/open-xml-sdk) (официальная документация Microsoft).
|
||||
- [ECMA-376 стандарт](https://www.ecma-international.org/publications-and-standards/standards/ecma-376/) (полная спецификация).
|
||||
You can customize the application by modifying:
|
||||
- `static/style.css` for visual styling
|
||||
- `static/script.js` for client-side functionality
|
||||
- `app.py` for server-side processing and document generation
|
||||
Reference in New Issue
Block a user