mirror of
https://github.com/amitwh/markdown-converter.git
synced 2026-08-03 02:11:07 +05:30
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
478b404135 | ||
|
|
8be2651b0e | ||
|
|
922e74d671 |
@@ -33,7 +33,10 @@
|
|||||||
"Bash(git rm:*)",
|
"Bash(git rm:*)",
|
||||||
"Bash(gh release view:*)",
|
"Bash(gh release view:*)",
|
||||||
"Bash(npm run build:linux:*)",
|
"Bash(npm run build:linux:*)",
|
||||||
"Bash(git reset:*)"
|
"Bash(git reset:*)",
|
||||||
|
"Read(//i/Template_exporter/**)",
|
||||||
|
"Bash(copy \"I:\\Template_exporter\\md_to_docx_converter.py\" \"H:\\Development\\pan-converter\\word-template-exporter\"\" && copy \"I:Template_exporterrequirements.txt\" \"H:Developmentpan-converterword-template-exporter\"\")",
|
||||||
|
"Bash(copy \"I:\\Template_exporter\\word_template.docx\" \"H:\\Development\\pan-converter\\word-template-exporter\"\")"
|
||||||
],
|
],
|
||||||
"deny": []
|
"deny": []
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
**PanConverter** is a cross-platform Markdown editor and converter powered by Pandoc, built with Electron. It provides professional-grade editing capabilities with comprehensive export options.
|
**PanConverter** is a cross-platform Markdown editor and converter powered by Pandoc, built with Electron. It provides professional-grade editing capabilities with comprehensive export options.
|
||||||
|
|
||||||
**Current Version**: v1.7.8
|
**Current Version**: v1.7.9
|
||||||
**Author**: Amit Haridas (amit.wh@gmail.com)
|
**Author**: Amit Haridas (amit.wh@gmail.com)
|
||||||
**License**: MIT
|
**License**: MIT
|
||||||
**Repository**: https://github.com/amitwh/pan-converter
|
**Repository**: https://github.com/amitwh/pan-converter
|
||||||
@@ -113,7 +113,132 @@ gh release create v1.2.1 --title "Title" --notes "Release notes" \
|
|||||||
|
|
||||||
## Feature Implementation Guide
|
## Feature Implementation Guide
|
||||||
|
|
||||||
### v1.7.8 Critical Bug Fixes (Latest)
|
### v1.7.9 Enhanced Word Export with Template Support (Latest)
|
||||||
|
|
||||||
|
#### 📝 Template-Based Word Document Generation
|
||||||
|
**Added Enhanced DOCX Export** (`src/wordTemplateExporter.js`, `src/main.js:540-596`, `src/main.js:242`)
|
||||||
|
- **New Export Option**: "DOCX (Enhanced)" in File → Export menu with keyboard shortcut `Ctrl+Shift+W`
|
||||||
|
- **Template Support**: Use custom Word templates to preserve branding, styles, and formatting
|
||||||
|
- **Template Selection**: File → "Select Word Template..." menu option to choose custom templates
|
||||||
|
- **Persistent Template**: Selected template is saved and reused across sessions
|
||||||
|
- **Word XML Manipulation**: Direct manipulation of Word document XML using PizZip
|
||||||
|
- **Template Page Preservation**: Preserves first 2 pages (cover + TOC) when using templates
|
||||||
|
- **Smart Content Insertion**: Inserts markdown content after 2nd section break
|
||||||
|
|
||||||
|
**Full Markdown Support:**
|
||||||
|
- Headings (H1-H6) with markdown numbering stripped (e.g., "1.1 Title" → "Title")
|
||||||
|
- Text formatting (bold, italic, bold+italic, strikethrough)
|
||||||
|
- Inline code with Consolas font and gray background
|
||||||
|
- Code blocks with monospace font and light gray background
|
||||||
|
- Ordered and unordered lists (uses template numbering, strips markdown numbering)
|
||||||
|
- Blockquotes with indentation
|
||||||
|
- **Tables with orange header styling**:
|
||||||
|
- Orange header row (#F58220) with white bold text
|
||||||
|
- White data rows (no alternating colors)
|
||||||
|
- Orange borders (#F58220) on all cells
|
||||||
|
- Proper column alignment and spacing
|
||||||
|
- Horizontal rules
|
||||||
|
- Links
|
||||||
|
- **ASCII Art and Flowcharts**:
|
||||||
|
- Detects box-drawing characters (┌, ─, │, └, etc.)
|
||||||
|
- Detects flowchart patterns with square brackets
|
||||||
|
- Preserves monospace alignment with Consolas font
|
||||||
|
- Each line rendered separately to prevent wrapping
|
||||||
|
- No-wrap paragraph properties for exact spacing
|
||||||
|
- **Red-colored arrows** (↓, →, ←, ↑) for enhanced visibility
|
||||||
|
- Gray background (#F5F5F5) for distinction from regular text
|
||||||
|
|
||||||
|
**ASCII Art Detection Patterns:**
|
||||||
|
- Unicode box-drawing characters: ┌┐└┘├┤┬┴┼─│═║╔╗╚╝╠╣╦╩╬
|
||||||
|
- Arrow characters: ↓→←↑▼►◄▲
|
||||||
|
- ASCII box patterns: +-----+, |-----|, [Text in brackets]
|
||||||
|
- Flowchart steps: START, [Step Description], END
|
||||||
|
|
||||||
|
**ASCII Art Rendering Features:**
|
||||||
|
```javascript
|
||||||
|
// Each line gets its own paragraph with no-wrap
|
||||||
|
xml += `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:wordWrap w:val="0"/> // Disable wrapping
|
||||||
|
<w:keepLines/> // Keep lines together
|
||||||
|
<w:line="240" w:lineRule="exact"/> // Exact line height
|
||||||
|
</w:pPr>
|
||||||
|
// Arrows colored red (#FF0000)
|
||||||
|
// Text in Consolas 16pt with gray background
|
||||||
|
</w:p>`;
|
||||||
|
```
|
||||||
|
|
||||||
|
**Template Selection Workflow:**
|
||||||
|
1. User clicks File → "Select Word Template..."
|
||||||
|
2. Dialog opens to browse for .docx files
|
||||||
|
3. Selected template path stored in global variable and persisted
|
||||||
|
4. Template automatically loaded on app startup
|
||||||
|
5. Enhanced export uses selected template (or defaults to `word_template.docx`)
|
||||||
|
|
||||||
|
**Technical Implementation:**
|
||||||
|
```javascript
|
||||||
|
// Template selection function
|
||||||
|
async function selectWordTemplate() {
|
||||||
|
const result = await dialog.showOpenDialog(mainWindow, {
|
||||||
|
title: 'Select Word Template',
|
||||||
|
filters: [{ name: 'Word Document', extensions: ['docx'] }],
|
||||||
|
properties: ['openFile']
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!result.canceled && result.filePaths.length > 0) {
|
||||||
|
wordTemplatePath = result.filePaths[0];
|
||||||
|
store.set('wordTemplatePath', wordTemplatePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Word Template Exporter with template support
|
||||||
|
class WordTemplateExporter {
|
||||||
|
constructor(templatePath) {
|
||||||
|
this.templatePath = templatePath || path.join(__dirname, '../word_template.docx');
|
||||||
|
}
|
||||||
|
|
||||||
|
async convert(markdownContent, outputPath) {
|
||||||
|
// Load template as ZIP
|
||||||
|
const templateBuffer = fs.readFileSync(this.templatePath);
|
||||||
|
const zip = new PizZip(templateBuffer);
|
||||||
|
|
||||||
|
// Extract and modify document.xml
|
||||||
|
const documentXml = zip.file('word/document.xml').asText();
|
||||||
|
const newContentXml = this.markdownToWordXml(markdownContent);
|
||||||
|
const modifiedXml = this.insertContentAfterPage2(documentXml, newContentXml);
|
||||||
|
|
||||||
|
// Save modified document
|
||||||
|
zip.file('word/document.xml', modifiedXml);
|
||||||
|
const newDocBuffer = zip.generate({ type: 'nodebuffer' });
|
||||||
|
fs.writeFileSync(outputPath, newDocBuffer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Menu Integration:**
|
||||||
|
- Export: File → Export → "DOCX (Enhanced)" (`Ctrl+Shift+W`)
|
||||||
|
- Template Selection: File → "Select Word Template..."
|
||||||
|
- Template path saved to: `userData/settings.json`
|
||||||
|
|
||||||
|
**Dependencies Added:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"docx": "^9.5.1",
|
||||||
|
"pizzip": "^3.2.0",
|
||||||
|
"docx4js": "^3.3.0"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Improvements in v1.7.9:**
|
||||||
|
1. ✅ Template-based export preserving corporate branding
|
||||||
|
2. ✅ Persistent template selection across sessions
|
||||||
|
3. ✅ Tables with professional orange header styling and white data rows
|
||||||
|
4. ✅ ASCII art and flowcharts with perfect alignment and no wrapping
|
||||||
|
5. ✅ Red-colored arrows in flowcharts for enhanced readability
|
||||||
|
6. ✅ Markdown numbering stripped from headings and lists
|
||||||
|
7. ✅ Template's automatic numbering system used instead
|
||||||
|
|
||||||
|
### v1.7.8 Critical Bug Fixes
|
||||||
|
|
||||||
#### 🐛 File Association Fix for Packaged Apps
|
#### 🐛 File Association Fix for Packaged Apps
|
||||||
**Fixed Command-Line Argument Parsing** (`src/main.js:1598-1627`, `src/main.js:70-90`)
|
**Fixed Command-Line Argument Parsing** (`src/main.js:1598-1627`, `src/main.js:70-90`)
|
||||||
@@ -884,10 +1009,14 @@ if (!gotTheLock) {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Last Updated**: October 26, 2025
|
**Last Updated**: October 27, 2025
|
||||||
**Claude Assistant**: Development completed for v1.7.8 with critical bug fixes:
|
**Claude Assistant**: Development completed for v1.7.9 with Template-Based Word Export:
|
||||||
1. **File Association Fix**: Fixed command-line argument parsing to properly detect packaged vs development mode using `app.isPackaged`, enabling files to open correctly on first double-click in packaged app
|
- **Template Support**: Word XML manipulation using PizZip to preserve template branding and styles
|
||||||
2. **Print Preview Fix**: Completely rewrote print handler to rely on CSS `@media print` rules instead of manual DOM manipulation, ensuring preview content (not toolbar) is printed
|
- **Template Selection**: File menu option to choose custom Word templates, persisted across sessions
|
||||||
3. **Code Cleanup**: Removed auto-opening DevTools for production-ready build
|
- **Table Styling**: Orange headers (#F58220) with white bold text, white data rows, orange borders
|
||||||
|
- **ASCII Art & Flowcharts**: Perfect monospace alignment with no-wrap properties, each line as separate paragraph
|
||||||
|
- **Red Arrows**: Flowchart arrows (↓→←↑) rendered in red color for enhanced visibility
|
||||||
|
- **Markdown Numbering Strip**: Removes markdown numbering from headings and lists to use template numbering
|
||||||
|
- **Template Page Preservation**: Keeps first 2 pages (cover + TOC) intact, inserts content after 2nd section break
|
||||||
|
|
||||||
Previous releases: v1.7.7 (print menu with two options, PDFKit/html2pdf integration), v1.7.6 (table header styling cleanup), v1.7.5 (single-instance lock).
|
Previous releases: v1.7.8 (file association & print preview fixes), v1.7.7 (print menu with two options), v1.7.6 (table header cleanup), v1.7.5 (single-instance lock).
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 62 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 171 KiB |
+5
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "pan-converter",
|
"name": "pan-converter",
|
||||||
"version": "1.7.8",
|
"version": "1.7.9",
|
||||||
"description": "Cross-platform Markdown editor and converter using Pandoc",
|
"description": "Cross-platform Markdown editor and converter using Pandoc",
|
||||||
"main": "src/main.js",
|
"main": "src/main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -31,13 +31,16 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"codemirror": "^6.0.2",
|
"codemirror": "^6.0.2",
|
||||||
|
"docx": "^9.5.1",
|
||||||
|
"docx4js": "^3.3.0",
|
||||||
"dompurify": "^3.2.6",
|
"dompurify": "^3.2.6",
|
||||||
"electron-store": "^10.1.0",
|
"electron-store": "^10.1.0",
|
||||||
"html2pdf.js": "^0.10.1",
|
|
||||||
"highlight.js": "^11.11.1",
|
"highlight.js": "^11.11.1",
|
||||||
|
"html2pdf.js": "^0.10.1",
|
||||||
"marked": "^16.2.1",
|
"marked": "^16.2.1",
|
||||||
"pdf-lib": "^1.17.1",
|
"pdf-lib": "^1.17.1",
|
||||||
"pdfkit": "^0.14.0",
|
"pdfkit": "^0.14.0",
|
||||||
|
"pizzip": "^3.2.0",
|
||||||
"tslib": "^2.8.1",
|
"tslib": "^2.8.1",
|
||||||
"xlsx": "^0.18.5"
|
"xlsx": "^0.18.5"
|
||||||
},
|
},
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
+71
-1
@@ -3,6 +3,7 @@ const path = require('path');
|
|||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const { exec } = require('child_process');
|
const { exec } = require('child_process');
|
||||||
const { PDFDocument, rgb, degrees, StandardFonts } = require('pdf-lib');
|
const { PDFDocument, rgb, degrees, StandardFonts } = require('pdf-lib');
|
||||||
|
const WordTemplateExporter = require('./wordTemplateExporter');
|
||||||
|
|
||||||
// Get the system Pandoc path
|
// Get the system Pandoc path
|
||||||
function getPandocPath() {
|
function getPandocPath() {
|
||||||
@@ -47,6 +48,7 @@ const store = {
|
|||||||
let mainWindow;
|
let mainWindow;
|
||||||
let currentFile = null; // This will now represent the active tab's file
|
let currentFile = null; // This will now represent the active tab's file
|
||||||
let pandocAvailable = null; // Cache pandoc availability check
|
let pandocAvailable = null; // Cache pandoc availability check
|
||||||
|
let wordTemplatePath = null; // Path to selected Word template
|
||||||
let rendererReady = false; // Track if renderer is ready to receive file data
|
let rendererReady = false; // Track if renderer is ready to receive file data
|
||||||
|
|
||||||
// Handle single instance lock for Windows file association
|
// Handle single instance lock for Windows file association
|
||||||
@@ -237,6 +239,7 @@ function createMenu() {
|
|||||||
{ label: 'HTML', click: () => exportFile('html') },
|
{ label: 'HTML', click: () => exportFile('html') },
|
||||||
{ label: 'PDF', click: () => exportFile('pdf') },
|
{ label: 'PDF', click: () => exportFile('pdf') },
|
||||||
{ label: 'DOCX', click: () => exportFile('docx') },
|
{ label: 'DOCX', click: () => exportFile('docx') },
|
||||||
|
{ label: 'DOCX (Enhanced)', click: () => exportWordWithTemplate(), accelerator: 'Ctrl+Shift+W' },
|
||||||
{ label: 'LaTeX', click: () => exportFile('latex') },
|
{ label: 'LaTeX', click: () => exportFile('latex') },
|
||||||
{ label: 'RTF', click: () => exportFile('rtf') },
|
{ label: 'RTF', click: () => exportFile('rtf') },
|
||||||
{ label: 'ODT', click: () => exportFile('odt') },
|
{ label: 'ODT', click: () => exportFile('odt') },
|
||||||
@@ -249,6 +252,11 @@ function createMenu() {
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
{ type: 'separator' },
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Select Word Template...',
|
||||||
|
click: selectWordTemplate
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
{
|
{
|
||||||
label: 'Quit',
|
label: 'Quit',
|
||||||
accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
|
accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
|
||||||
@@ -467,7 +475,7 @@ function createMenu() {
|
|||||||
type: 'info',
|
type: 'info',
|
||||||
title: 'About PanConverter',
|
title: 'About PanConverter',
|
||||||
message: 'PanConverter',
|
message: 'PanConverter',
|
||||||
detail: 'A cross-platform Markdown editor and converter using Pandoc.\n\nVersion: 1.7.8\nAuthor: Amit Haridas\nEmail: amit.wh@gmail.com\nLicense: MIT\n\nFeatures:\n• Modern glassmorphism UI with gradient backgrounds\n• Comprehensive PDF Editor (merge, split, compress, rotate, watermark, encrypt)\n• Universal File Converter (LibreOffice, ImageMagick, FFmpeg, Pandoc)\n• Windows Explorer context menu integration\n• Tabbed interface for multiple files\n• Advanced markdown editing with live preview\n• Real-time preview updates while typing\n• Full toolbar markdown editing functions\n• Enhanced PDF export with built-in Electron fallback\n• File association support for .md files\n• Command-line interface for batch conversion\n• Advanced export options with templates and metadata\n• Batch file conversion with progress tracking\n• Improved preview typography and spacing\n• Adjustable font sizes via menu (Ctrl+Shift+Plus/Minus)\n• Complete theme support including Monokai fixes\n• Find & replace with match highlighting\n• Line numbers and auto-indentation\n• Export to multiple formats via Pandoc\n• PowerPoint & presentation export\n• Export tables to Excel/ODS spreadsheets\n• Document import & conversion\n• Table creation helper\n• 22 beautiful themes (including Dracula, Nord, Tokyo Night, Gruvbox, Ayu, Concrete, and more)\n• Undo/redo functionality\n• Live word count and statistics',
|
detail: 'A cross-platform Markdown editor and converter using Pandoc.\n\nVersion: 1.7.9\nAuthor: Amit Haridas\nEmail: amit.wh@gmail.com\nLicense: MIT\n\nFeatures:\n• Modern glassmorphism UI with gradient backgrounds\n• Comprehensive PDF Editor (merge, split, compress, rotate, watermark, encrypt)\n• Universal File Converter (LibreOffice, ImageMagick, FFmpeg, Pandoc)\n• Windows Explorer context menu integration\n• Tabbed interface for multiple files\n• Advanced markdown editing with live preview\n• Real-time preview updates while typing\n• Full toolbar markdown editing functions\n• Enhanced PDF export with built-in Electron fallback\n• File association support for .md files\n• Command-line interface for batch conversion\n• Advanced export options with templates and metadata\n• Batch file conversion with progress tracking\n• Improved preview typography and spacing\n• Adjustable font sizes via menu (Ctrl+Shift+Plus/Minus)\n• Complete theme support including Monokai fixes\n• Find & replace with match highlighting\n• Line numbers and auto-indentation\n• Export to multiple formats via Pandoc\n• PowerPoint & presentation export\n• Export tables to Excel/ODS spreadsheets\n• Document import & conversion\n• Table creation helper\n• 22 beautiful themes (including Dracula, Nord, Tokyo Night, Gruvbox, Ayu, Concrete, and more)\n• Undo/redo functionality\n• Live word count and statistics',
|
||||||
buttons: ['OK']
|
buttons: ['OK']
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -533,6 +541,65 @@ function showBatchConversionDialog() {
|
|||||||
mainWindow.webContents.send('show-batch-dialog');
|
mainWindow.webContents.send('show-batch-dialog');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Select Word Template
|
||||||
|
async function selectWordTemplate() {
|
||||||
|
const result = await dialog.showOpenDialog(mainWindow, {
|
||||||
|
title: 'Select Word Template',
|
||||||
|
filters: [{ name: 'Word Document', extensions: ['docx'] }],
|
||||||
|
properties: ['openFile']
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!result.canceled && result.filePaths.length > 0) {
|
||||||
|
wordTemplatePath = result.filePaths[0];
|
||||||
|
store.set('wordTemplatePath', wordTemplatePath);
|
||||||
|
|
||||||
|
dialog.showMessageBox(mainWindow, {
|
||||||
|
type: 'info',
|
||||||
|
title: 'Template Selected',
|
||||||
|
message: 'Word template has been updated',
|
||||||
|
detail: `Template: ${path.basename(wordTemplatePath)}`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enhanced Word Export with Template Support
|
||||||
|
async function exportWordWithTemplate() {
|
||||||
|
if (!currentFile) {
|
||||||
|
dialog.showErrorBox('Error', 'Please save the file first');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Get markdown content
|
||||||
|
const content = fs.readFileSync(currentFile, 'utf-8');
|
||||||
|
|
||||||
|
// Show dialog for output file
|
||||||
|
const result = await dialog.showSaveDialog(mainWindow, {
|
||||||
|
title: 'Export to Word (Enhanced)',
|
||||||
|
defaultPath: currentFile.replace(/\.md$/, '.docx'),
|
||||||
|
filters: [{ name: 'Word Document', extensions: ['docx'] }]
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.canceled) return;
|
||||||
|
|
||||||
|
// Create exporter instance with selected template (if any)
|
||||||
|
const exporter = new WordTemplateExporter(wordTemplatePath);
|
||||||
|
|
||||||
|
// Convert markdown to DOCX
|
||||||
|
await exporter.convert(content, result.filePath);
|
||||||
|
|
||||||
|
dialog.showMessageBox(mainWindow, {
|
||||||
|
type: 'info',
|
||||||
|
title: 'Export Successful',
|
||||||
|
message: 'Document exported successfully!',
|
||||||
|
detail: `Saved to: ${result.filePath}`
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
dialog.showErrorBox('Export Error', `Failed to export document: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Universal File Converter integration
|
// Universal File Converter integration
|
||||||
function showUniversalConverterDialog() {
|
function showUniversalConverterDialog() {
|
||||||
mainWindow.webContents.send('show-universal-converter-dialog');
|
mainWindow.webContents.send('show-universal-converter-dialog');
|
||||||
@@ -1590,6 +1657,9 @@ function buildPandocCommand(content, format, outputPath) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
app.whenReady().then(() => {
|
app.whenReady().then(() => {
|
||||||
|
// Load saved Word template path
|
||||||
|
wordTemplatePath = store.get('wordTemplatePath', null);
|
||||||
|
|
||||||
// Check for command line conversion requests
|
// Check for command line conversion requests
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
if (args.length >= 2 && (args[0] === '--convert' || args[0] === '--convert-to')) {
|
if (args.length >= 2 && (args[0] === '--convert' || args[0] === '--convert-to')) {
|
||||||
|
|||||||
+84
-12
@@ -1184,23 +1184,95 @@ function handlePrintPreview(withStyles) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add print style classes to body for styling control
|
// Store original display values for restoration
|
||||||
// The @media print CSS will handle hiding toolbar/tabs automatically
|
const elementsToHide = [];
|
||||||
if (!withStyles) {
|
|
||||||
document.body.classList.add('printing-no-styles');
|
|
||||||
}
|
|
||||||
document.body.classList.add('printing');
|
|
||||||
|
|
||||||
// Give browser time to apply classes before printing
|
// Hide toolbar
|
||||||
|
const toolbar = document.querySelector('.toolbar');
|
||||||
|
if (toolbar) {
|
||||||
|
elementsToHide.push({ elem: toolbar, display: toolbar.style.display });
|
||||||
|
toolbar.style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hide tab bar
|
||||||
|
const tabBar = document.querySelector('.tab-bar');
|
||||||
|
if (tabBar) {
|
||||||
|
elementsToHide.push({ elem: tabBar, display: tabBar.style.display });
|
||||||
|
tabBar.style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hide status bar
|
||||||
|
const statusBar = document.querySelector('.status-bar');
|
||||||
|
if (statusBar) {
|
||||||
|
elementsToHide.push({ elem: statusBar, display: statusBar.style.display });
|
||||||
|
statusBar.style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hide editor pane
|
||||||
|
const editorPane = document.getElementById(`editor-pane-${activeTabId}`);
|
||||||
|
if (editorPane) {
|
||||||
|
elementsToHide.push({ elem: editorPane, display: editorPane.style.display });
|
||||||
|
editorPane.style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hide all dialogs
|
||||||
|
const dialogs = document.querySelectorAll('.dialog, .modal-overlay');
|
||||||
|
dialogs.forEach(dialog => {
|
||||||
|
elementsToHide.push({ elem: dialog, display: dialog.style.display });
|
||||||
|
dialog.style.display = 'none';
|
||||||
|
});
|
||||||
|
|
||||||
|
// Make preview pane full width
|
||||||
|
const previewPane = document.getElementById(`preview-pane-${activeTabId}`);
|
||||||
|
let originalPreviewStyles = {};
|
||||||
|
if (previewPane) {
|
||||||
|
originalPreviewStyles = {
|
||||||
|
position: previewPane.style.position,
|
||||||
|
top: previewPane.style.top,
|
||||||
|
left: previewPane.style.left,
|
||||||
|
width: previewPane.style.width,
|
||||||
|
height: previewPane.style.height,
|
||||||
|
margin: previewPane.style.margin,
|
||||||
|
padding: previewPane.style.padding
|
||||||
|
};
|
||||||
|
previewPane.style.position = 'absolute';
|
||||||
|
previewPane.style.top = '0';
|
||||||
|
previewPane.style.left = '0';
|
||||||
|
previewPane.style.width = '100%';
|
||||||
|
previewPane.style.height = 'auto';
|
||||||
|
previewPane.style.margin = '0';
|
||||||
|
previewPane.style.padding = '20px';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply no-styles if needed
|
||||||
|
if (!withStyles && previewContent) {
|
||||||
|
previewContent.style.color = '#000';
|
||||||
|
previewContent.style.background = '#fff';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for DOM updates then print
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
// Tell main process to print
|
|
||||||
ipcRenderer.send('do-print', { withStyles });
|
ipcRenderer.send('do-print', { withStyles });
|
||||||
|
|
||||||
// Restore classes after print dialog appears
|
// Restore everything after print dialog opens
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
document.body.classList.remove('printing', 'printing-no-styles');
|
// Restore hidden elements
|
||||||
}, 1000);
|
elementsToHide.forEach(({ elem, display }) => {
|
||||||
}, 100);
|
elem.style.display = display;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Restore preview pane styles
|
||||||
|
if (previewPane) {
|
||||||
|
Object.assign(previewPane.style, originalPreviewStyles);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore preview content styles
|
||||||
|
if (!withStyles && previewContent) {
|
||||||
|
previewContent.style.color = '';
|
||||||
|
previewContent.style.background = '';
|
||||||
|
}
|
||||||
|
}, 500);
|
||||||
|
}, 200);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Export Dialog functionality
|
// Export Dialog functionality
|
||||||
|
|||||||
@@ -0,0 +1,618 @@
|
|||||||
|
/**
|
||||||
|
* Word Template Exporter
|
||||||
|
* Loads word_template.docx, preserves first 2 pages (cover + TOC),
|
||||||
|
* and adds markdown content starting from page 3 using template styles
|
||||||
|
*/
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const PizZip = require('pizzip');
|
||||||
|
const Docx = require('docx4js').default;
|
||||||
|
|
||||||
|
class WordTemplateExporter {
|
||||||
|
constructor(templatePath) {
|
||||||
|
this.templatePath = templatePath || path.join(__dirname, '../word_template.docx');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert markdown to Word document using template
|
||||||
|
*/
|
||||||
|
async convert(markdownContent, outputPath) {
|
||||||
|
try {
|
||||||
|
// Load template
|
||||||
|
const templateBuffer = fs.readFileSync(this.templatePath);
|
||||||
|
const zip = new PizZip(templateBuffer);
|
||||||
|
|
||||||
|
// Extract document.xml
|
||||||
|
const documentXml = zip.file('word/document.xml').asText();
|
||||||
|
|
||||||
|
// Parse markdown and generate Word XML
|
||||||
|
const newContentXml = this.markdownToWordXml(markdownContent);
|
||||||
|
|
||||||
|
// Insert new content after page 2 (after the section break)
|
||||||
|
const modifiedXml = this.insertContentAfterPage2(documentXml, newContentXml);
|
||||||
|
|
||||||
|
// Update the zip with modified XML
|
||||||
|
zip.file('word/document.xml', modifiedXml);
|
||||||
|
|
||||||
|
// Generate and save the new document
|
||||||
|
const newDocBuffer = zip.generate({ type: 'nodebuffer' });
|
||||||
|
fs.writeFileSync(outputPath, newDocBuffer);
|
||||||
|
|
||||||
|
return outputPath;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in Word export:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert markdown content after page 2 in the document
|
||||||
|
*/
|
||||||
|
insertContentAfterPage2(documentXml, newContentXml) {
|
||||||
|
// Find the last section break (after page 2)
|
||||||
|
// Look for the section properties tag that marks page breaks
|
||||||
|
const sectionBreakRegex = /<w:sectPr[^>]*>[\s\S]*?<\/w:sectPr>/g;
|
||||||
|
const matches = [...documentXml.matchAll(sectionBreakRegex)];
|
||||||
|
|
||||||
|
if (matches.length >= 2) {
|
||||||
|
// Insert after the 2nd section break
|
||||||
|
const insertPoint = matches[1].index + matches[1][0].length;
|
||||||
|
return documentXml.slice(0, insertPoint) + newContentXml + documentXml.slice(insertPoint);
|
||||||
|
} else {
|
||||||
|
// If no section breaks found, insert before closing body tag
|
||||||
|
return documentXml.replace('</w:body>', newContentXml + '</w:body>');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert markdown to Word XML format
|
||||||
|
*/
|
||||||
|
markdownToWordXml(markdown) {
|
||||||
|
const lines = markdown.split('\n');
|
||||||
|
let xml = '';
|
||||||
|
let inCodeBlock = false;
|
||||||
|
let codeLines = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
const line = lines[i];
|
||||||
|
|
||||||
|
// Handle code blocks
|
||||||
|
if (line.trim().startsWith('```')) {
|
||||||
|
if (inCodeBlock) {
|
||||||
|
// End code block
|
||||||
|
xml += this.createCodeBlockXml(codeLines.join('\n'));
|
||||||
|
codeLines = [];
|
||||||
|
inCodeBlock = false;
|
||||||
|
} else {
|
||||||
|
inCodeBlock = true;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inCodeBlock) {
|
||||||
|
codeLines.push(line);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Empty lines
|
||||||
|
if (!line.trim()) {
|
||||||
|
xml += '<w:p><w:pPr></w:pPr></w:p>';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tables - detect table lines
|
||||||
|
if (line.includes('|') && line.trim().startsWith('|')) {
|
||||||
|
const tableLines = [line];
|
||||||
|
i++;
|
||||||
|
// Collect all consecutive table lines
|
||||||
|
while (i < lines.length && lines[i].includes('|')) {
|
||||||
|
tableLines.push(lines[i]);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
i--; // Back up one line
|
||||||
|
xml += this.createTableXml(tableLines);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ASCII flowcharts/diagrams - detect box drawing characters
|
||||||
|
if (this.isAsciiArt(line)) {
|
||||||
|
const asciiLines = [line];
|
||||||
|
i++;
|
||||||
|
// Collect all consecutive ASCII art lines
|
||||||
|
while (i < lines.length && (this.isAsciiArt(lines[i]) || !lines[i].trim())) {
|
||||||
|
asciiLines.push(lines[i]);
|
||||||
|
i++;
|
||||||
|
if (i < lines.length && lines[i].trim() && !this.isAsciiArt(lines[i])) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i--; // Back up one line
|
||||||
|
xml += this.createAsciiArtXml(asciiLines.join('\n'));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Headings - strip markdown numbering
|
||||||
|
if (line.trim().startsWith('#')) {
|
||||||
|
const level = (line.match(/^#+/) || [''])[0].length;
|
||||||
|
let text = line.replace(/^#+\s*/, '').trim();
|
||||||
|
// Remove markdown numbering like "1.1 Title" -> "Title"
|
||||||
|
text = text.replace(/^\d+(\.\d+)*\.?\s+/, '');
|
||||||
|
xml += this.createHeadingXml(text, level);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Blockquotes
|
||||||
|
if (line.trim().startsWith('>')) {
|
||||||
|
const text = line.replace(/^>\s*/, '').trim();
|
||||||
|
xml += this.createQuoteXml(text);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ordered lists - strip markdown numbering, use template numbering
|
||||||
|
if (/^\s*\d+\.\s+/.test(line)) {
|
||||||
|
const text = line.replace(/^\s*\d+\.\s+/, '');
|
||||||
|
xml += this.createListItemXml(text, true);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unordered lists
|
||||||
|
if (/^\s*[-*+]\s+/.test(line)) {
|
||||||
|
const text = line.replace(/^\s*[-*+]\s+/, '');
|
||||||
|
xml += this.createListItemXml(text, false);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Horizontal rule
|
||||||
|
if (/^[-*_]{3,}$/.test(line.trim())) {
|
||||||
|
xml += this.createHorizontalRuleXml();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normal paragraph
|
||||||
|
xml += this.createParagraphXml(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
return xml;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create heading XML using template styles
|
||||||
|
*/
|
||||||
|
createHeadingXml(text, level) {
|
||||||
|
const styleName = `Heading${level}`;
|
||||||
|
const runs = this.parseInlineFormatting(text);
|
||||||
|
|
||||||
|
return `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:pStyle w:val="${styleName}"/>
|
||||||
|
</w:pPr>
|
||||||
|
${runs}
|
||||||
|
</w:p>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create paragraph XML with Normal style
|
||||||
|
*/
|
||||||
|
createParagraphXml(text) {
|
||||||
|
const runs = this.parseInlineFormatting(text);
|
||||||
|
|
||||||
|
return `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:pStyle w:val="Normal"/>
|
||||||
|
</w:pPr>
|
||||||
|
${runs}
|
||||||
|
</w:p>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create quote XML
|
||||||
|
*/
|
||||||
|
createQuoteXml(text) {
|
||||||
|
const runs = this.parseInlineFormatting(text);
|
||||||
|
|
||||||
|
return `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:pStyle w:val="Quote"/>
|
||||||
|
</w:pPr>
|
||||||
|
${runs}
|
||||||
|
</w:p>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create list item XML using template numbering
|
||||||
|
*/
|
||||||
|
createListItemXml(text, numbered) {
|
||||||
|
const runs = this.parseInlineFormatting(text);
|
||||||
|
const numId = numbered ? '1' : '2'; // Template numbering IDs
|
||||||
|
|
||||||
|
return `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:pStyle w:val="${numbered ? 'ListNumber' : 'ListBullet'}"/>
|
||||||
|
<w:numPr>
|
||||||
|
<w:ilvl w:val="0"/>
|
||||||
|
<w:numId w:val="${numId}"/>
|
||||||
|
</w:numPr>
|
||||||
|
</w:pPr>
|
||||||
|
${runs}
|
||||||
|
</w:p>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create code block XML
|
||||||
|
*/
|
||||||
|
createCodeBlockXml(code) {
|
||||||
|
const escapedCode = this.escapeXml(code);
|
||||||
|
|
||||||
|
return `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:pStyle w:val="Code"/>
|
||||||
|
</w:pPr>
|
||||||
|
<w:r>
|
||||||
|
<w:rPr>
|
||||||
|
<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas"/>
|
||||||
|
<w:sz w:val="18"/>
|
||||||
|
</w:rPr>
|
||||||
|
<w:t xml:space="preserve">${escapedCode}</w:t>
|
||||||
|
</w:r>
|
||||||
|
</w:p>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create horizontal rule XML
|
||||||
|
*/
|
||||||
|
createHorizontalRuleXml() {
|
||||||
|
return `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:pBdr>
|
||||||
|
<w:bottom w:val="single" w:sz="6" w:space="1" w:color="auto"/>
|
||||||
|
</w:pBdr>
|
||||||
|
</w:pPr>
|
||||||
|
</w:p>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create table XML from markdown table lines with template styling
|
||||||
|
*/
|
||||||
|
createTableXml(tableLines) {
|
||||||
|
// Parse table
|
||||||
|
const rows = [];
|
||||||
|
for (const line of tableLines) {
|
||||||
|
// Skip separator lines (e.g., |---|---|)
|
||||||
|
if (/^\s*\|[\s\-:]+\|\s*$/.test(line)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Split by | and trim
|
||||||
|
const cells = line.split('|').filter(cell => cell.trim()).map(cell => cell.trim());
|
||||||
|
if (cells.length > 0) {
|
||||||
|
rows.push(cells);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rows.length === 0) return '';
|
||||||
|
|
||||||
|
// Calculate number of columns
|
||||||
|
const numCols = Math.max(...rows.map(row => row.length));
|
||||||
|
|
||||||
|
// Build table XML
|
||||||
|
let tableXml = '<w:tbl>';
|
||||||
|
|
||||||
|
// Table properties - use template table style
|
||||||
|
tableXml += `<w:tblPr>
|
||||||
|
<w:tblStyle w:val="TableGrid"/>
|
||||||
|
<w:tblW w:w="5000" w:type="pct"/>
|
||||||
|
<w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="0" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/>
|
||||||
|
<w:tblBorders>
|
||||||
|
<w:top w:val="single" w:sz="8" w:space="0" w:color="F58220"/>
|
||||||
|
<w:left w:val="single" w:sz="8" w:space="0" w:color="F58220"/>
|
||||||
|
<w:bottom w:val="single" w:sz="8" w:space="0" w:color="F58220"/>
|
||||||
|
<w:right w:val="single" w:sz="8" w:space="0" w:color="F58220"/>
|
||||||
|
<w:insideH w:val="single" w:sz="8" w:space="0" w:color="F58220"/>
|
||||||
|
<w:insideV w:val="single" w:sz="8" w:space="0" w:color="F58220"/>
|
||||||
|
</w:tblBorders>
|
||||||
|
</w:tblPr>`;
|
||||||
|
|
||||||
|
// Table grid
|
||||||
|
tableXml += '<w:tblGrid>';
|
||||||
|
for (let i = 0; i < numCols; i++) {
|
||||||
|
tableXml += '<w:gridCol/>';
|
||||||
|
}
|
||||||
|
tableXml += '</w:tblGrid>';
|
||||||
|
|
||||||
|
// Table rows
|
||||||
|
rows.forEach((rowCells, rowIndex) => {
|
||||||
|
const isHeader = rowIndex === 0;
|
||||||
|
const isEvenRow = rowIndex % 2 === 0;
|
||||||
|
|
||||||
|
tableXml += '<w:tr>';
|
||||||
|
|
||||||
|
// Pad row to have same number of columns
|
||||||
|
while (rowCells.length < numCols) {
|
||||||
|
rowCells.push('');
|
||||||
|
}
|
||||||
|
|
||||||
|
rowCells.forEach((cellText, colIndex) => {
|
||||||
|
tableXml += '<w:tc>';
|
||||||
|
tableXml += '<w:tcPr>';
|
||||||
|
|
||||||
|
// Cell shading - orange for header, white for data rows
|
||||||
|
if (isHeader) {
|
||||||
|
tableXml += '<w:shd w:val="clear" w:color="FFFFFF" w:fill="F58220"/>';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cell borders
|
||||||
|
tableXml += '<w:tcBorders>' +
|
||||||
|
'<w:top w:val="single" w:sz="8" w:space="0" w:color="F58220"/>' +
|
||||||
|
'<w:left w:val="single" w:sz="8" w:space="0" w:color="F58220"/>' +
|
||||||
|
'<w:bottom w:val="single" w:sz="8" w:space="0" w:color="F58220"/>' +
|
||||||
|
'<w:right w:val="single" w:sz="8" w:space="0" w:color="F58220"/>' +
|
||||||
|
'</w:tcBorders>';
|
||||||
|
tableXml += '</w:tcPr>';
|
||||||
|
|
||||||
|
// Cell content
|
||||||
|
tableXml += '<w:p>';
|
||||||
|
tableXml += '<w:pPr>';
|
||||||
|
tableXml += '<w:spacing w:before="100" w:after="100"/>';
|
||||||
|
tableXml += '</w:pPr>';
|
||||||
|
|
||||||
|
const runs = this.parseInlineFormatting(cellText);
|
||||||
|
|
||||||
|
if (isHeader) {
|
||||||
|
// Header: bold white text
|
||||||
|
tableXml += runs.replace(/<w:rPr>/g, '<w:rPr><w:b/><w:color w:val="FFFFFF"/>');
|
||||||
|
} else {
|
||||||
|
// Data rows: normal black text
|
||||||
|
tableXml += runs;
|
||||||
|
}
|
||||||
|
|
||||||
|
tableXml += '</w:p>';
|
||||||
|
tableXml += '</w:tc>';
|
||||||
|
});
|
||||||
|
|
||||||
|
tableXml += '</w:tr>';
|
||||||
|
});
|
||||||
|
|
||||||
|
tableXml += '</w:tbl>';
|
||||||
|
|
||||||
|
return tableXml;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detect if line contains ASCII art/flowchart characters
|
||||||
|
*/
|
||||||
|
isAsciiArt(line) {
|
||||||
|
// Don't treat markdown tables as ASCII art
|
||||||
|
if (line.trim().startsWith('|') && line.trim().endsWith('|')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Common ASCII art characters
|
||||||
|
const asciiArtChars = [
|
||||||
|
'─', '│', '┌', '┐', '└', '┘', '├', '┤', '┬', '┴', '┼', // Box drawing
|
||||||
|
'═', '║', '╔', '╗', '╚', '╝', '╠', '╣', '╦', '╩', '╬', // Double box
|
||||||
|
'▲', '▼', '◄', '►', '♦', '●', '○', '■', '□', // Shapes
|
||||||
|
'↓', '→', '←', '↑', // Arrows
|
||||||
|
];
|
||||||
|
|
||||||
|
// Check for box drawing characters
|
||||||
|
if (asciiArtChars.some(char => line.includes(char))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for ASCII box patterns with regular characters
|
||||||
|
const asciiPatterns = [
|
||||||
|
/^\s*\+[-=_]+\+/, // +-----+
|
||||||
|
/^\s*\|[-=_]{3,}\|/, // |-----|
|
||||||
|
/^\s*[-=_]{5,}$/, // -----
|
||||||
|
/^\s*\([A-Z][a-z]+\)\s*\|\|/, // (Deformable) ||
|
||||||
|
/^\s*\|\s+[A-Z\s]+[-:]\s+[A-Z]/, // | TILE ADHESIVE - TYPE
|
||||||
|
/^\s*\|\s*\[[^\]]+\]/, // | [BIS Mark / CE Mark]
|
||||||
|
/^\s*\|\s{2,}\w+.*\|\|/, // || text ||
|
||||||
|
/^\s*\[[^\]]+\]/, // [Step in brackets]
|
||||||
|
];
|
||||||
|
|
||||||
|
return asciiPatterns.some(pattern => pattern.test(line));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create ASCII art XML with monospace font
|
||||||
|
*/
|
||||||
|
createAsciiArtXml(asciiContent) {
|
||||||
|
// Split ASCII art into individual lines and create a paragraph for each
|
||||||
|
const lines = asciiContent.split('\n');
|
||||||
|
let xml = '';
|
||||||
|
|
||||||
|
lines.forEach((line, index) => {
|
||||||
|
xml += `<w:p>
|
||||||
|
<w:pPr>
|
||||||
|
<w:spacing w:before="${index === 0 ? '120' : '0'}" w:after="${index === lines.length - 1 ? '120' : '0'}" w:line="240" w:lineRule="exact"/>
|
||||||
|
<w:ind w:left="0" w:right="0"/>
|
||||||
|
<w:jc w:val="left"/>
|
||||||
|
<w:keepLines/>
|
||||||
|
<w:wordWrap w:val="0"/>
|
||||||
|
</w:pPr>`;
|
||||||
|
|
||||||
|
// Check if line contains arrow characters and color them red
|
||||||
|
const arrowChars = ['↓', '→', '←', '↑', '▼', '►', '◄', '▲'];
|
||||||
|
const hasArrow = arrowChars.some(arrow => line.includes(arrow));
|
||||||
|
|
||||||
|
if (hasArrow) {
|
||||||
|
// Split line into parts and color arrows red
|
||||||
|
let remainingLine = line;
|
||||||
|
let processedText = '';
|
||||||
|
|
||||||
|
while (remainingLine.length > 0) {
|
||||||
|
let foundArrow = false;
|
||||||
|
let arrowIndex = -1;
|
||||||
|
let foundArrowChar = '';
|
||||||
|
|
||||||
|
// Find the first arrow in the remaining text
|
||||||
|
for (const arrow of arrowChars) {
|
||||||
|
const idx = remainingLine.indexOf(arrow);
|
||||||
|
if (idx !== -1 && (arrowIndex === -1 || idx < arrowIndex)) {
|
||||||
|
arrowIndex = idx;
|
||||||
|
foundArrowChar = arrow;
|
||||||
|
foundArrow = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (foundArrow) {
|
||||||
|
// Add text before arrow (if any)
|
||||||
|
if (arrowIndex > 0) {
|
||||||
|
const beforeArrow = this.escapeXml(remainingLine.substring(0, arrowIndex));
|
||||||
|
xml += `<w:r>
|
||||||
|
<w:rPr>
|
||||||
|
<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/>
|
||||||
|
<w:sz w:val="16"/>
|
||||||
|
<w:szCs w:val="16"/>
|
||||||
|
<w:shd w:val="clear" w:color="auto" w:fill="F5F5F5"/>
|
||||||
|
<w:noProof/>
|
||||||
|
</w:rPr>
|
||||||
|
<w:t xml:space="preserve">${beforeArrow}</w:t>
|
||||||
|
</w:r>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add arrow in red
|
||||||
|
const escapedArrow = this.escapeXml(foundArrowChar);
|
||||||
|
xml += `<w:r>
|
||||||
|
<w:rPr>
|
||||||
|
<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/>
|
||||||
|
<w:sz w:val="16"/>
|
||||||
|
<w:szCs w:val="16"/>
|
||||||
|
<w:color w:val="FF0000"/>
|
||||||
|
<w:shd w:val="clear" w:color="auto" w:fill="F5F5F5"/>
|
||||||
|
<w:noProof/>
|
||||||
|
</w:rPr>
|
||||||
|
<w:t xml:space="preserve">${escapedArrow}</w:t>
|
||||||
|
</w:r>`;
|
||||||
|
|
||||||
|
// Continue with remaining text
|
||||||
|
remainingLine = remainingLine.substring(arrowIndex + foundArrowChar.length);
|
||||||
|
} else {
|
||||||
|
// No more arrows, add remaining text
|
||||||
|
const escapedRemaining = this.escapeXml(remainingLine);
|
||||||
|
xml += `<w:r>
|
||||||
|
<w:rPr>
|
||||||
|
<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/>
|
||||||
|
<w:sz w:val="16"/>
|
||||||
|
<w:szCs w:val="16"/>
|
||||||
|
<w:shd w:val="clear" w:color="auto" w:fill="F5F5F5"/>
|
||||||
|
<w:noProof/>
|
||||||
|
</w:rPr>
|
||||||
|
<w:t xml:space="preserve">${escapedRemaining}</w:t>
|
||||||
|
</w:r>`;
|
||||||
|
remainingLine = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// No arrows, just add the line normally
|
||||||
|
const escapedLine = this.escapeXml(line);
|
||||||
|
xml += `<w:r>
|
||||||
|
<w:rPr>
|
||||||
|
<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/>
|
||||||
|
<w:sz w:val="16"/>
|
||||||
|
<w:szCs w:val="16"/>
|
||||||
|
<w:shd w:val="clear" w:color="auto" w:fill="F5F5F5"/>
|
||||||
|
<w:noProof/>
|
||||||
|
</w:rPr>
|
||||||
|
<w:t xml:space="preserve">${escapedLine}</w:t>
|
||||||
|
</w:r>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
xml += `</w:p>`;
|
||||||
|
});
|
||||||
|
|
||||||
|
return xml;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse inline formatting (bold, italic, code)
|
||||||
|
*/
|
||||||
|
parseInlineFormatting(text) {
|
||||||
|
let xml = '';
|
||||||
|
let pos = 0;
|
||||||
|
|
||||||
|
// Patterns for inline formatting
|
||||||
|
const patterns = [
|
||||||
|
{ regex: /\*\*\*(.+?)\*\*\*/g, bold: true, italic: true },
|
||||||
|
{ regex: /\*\*(.+?)\*\*/g, bold: true },
|
||||||
|
{ regex: /\*(.+?)\*/g, italic: true },
|
||||||
|
{ regex: /`(.+?)`/g, code: true }
|
||||||
|
];
|
||||||
|
|
||||||
|
// Simple approach: process text sequentially
|
||||||
|
let remaining = text;
|
||||||
|
|
||||||
|
while (remaining.length > 0) {
|
||||||
|
let foundMatch = false;
|
||||||
|
let earliestPos = remaining.length;
|
||||||
|
let matchedPattern = null;
|
||||||
|
let match = null;
|
||||||
|
|
||||||
|
// Find earliest match
|
||||||
|
for (const pattern of patterns) {
|
||||||
|
pattern.regex.lastIndex = 0;
|
||||||
|
const m = pattern.regex.exec(remaining);
|
||||||
|
if (m && m.index < earliestPos) {
|
||||||
|
earliestPos = m.index;
|
||||||
|
matchedPattern = pattern;
|
||||||
|
match = m;
|
||||||
|
foundMatch = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (foundMatch) {
|
||||||
|
// Add text before match
|
||||||
|
if (earliestPos > 0) {
|
||||||
|
xml += this.createRunXml(remaining.substring(0, earliestPos));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add formatted text
|
||||||
|
xml += this.createRunXml(match[1], matchedPattern.bold, matchedPattern.italic, matchedPattern.code);
|
||||||
|
|
||||||
|
remaining = remaining.substring(earliestPos + match[0].length);
|
||||||
|
} else {
|
||||||
|
// No more matches, add remaining text
|
||||||
|
xml += this.createRunXml(remaining);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return xml;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a run (text segment) XML
|
||||||
|
*/
|
||||||
|
createRunXml(text, bold = false, italic = false, code = false) {
|
||||||
|
if (!text) return '';
|
||||||
|
|
||||||
|
const escapedText = this.escapeXml(text);
|
||||||
|
let propsXml = '<w:rPr>';
|
||||||
|
|
||||||
|
if (bold) propsXml += '<w:b/>';
|
||||||
|
if (italic) propsXml += '<w:i/>';
|
||||||
|
if (code) {
|
||||||
|
propsXml += '<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas"/>';
|
||||||
|
propsXml += '<w:sz w:val="20"/>';
|
||||||
|
}
|
||||||
|
|
||||||
|
propsXml += '</w:rPr>';
|
||||||
|
|
||||||
|
return `<w:r>${propsXml}<w:t xml:space="preserve">${escapedText}</w:t></w:r>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Escape XML special characters
|
||||||
|
*/
|
||||||
|
escapeXml(text) {
|
||||||
|
return text
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = WordTemplateExporter;
|
||||||
Binary file not shown.
Reference in New Issue
Block a user