Compare commits

..
4 Commits
Author SHA1 Message Date
amitwhandClaude 58314efc7a Release v1.8.0: Enhanced Word Export in Batch Converter
Added enhanced Word export with template support to the batch file converter,
enabling batch conversion of markdown files to professionally-styled DOCX
documents using custom templates.

New Features:
- Added "DOCX (Enhanced)" option to batch converter format selection
- Integrated WordTemplateExporter with batch conversion workflow
- Batch converter now supports template-based Word export with:
  * Custom template preservation
  * Professional table styling (orange headers, white data rows)
  * Perfect ASCII art and flowchart alignment
  * Red-colored arrows in flowcharts
  * Markdown numbering stripped from headings and lists

Technical Changes:
- Modified performBatchConversion() to handle 'docx-enhanced' format
- Async/await pattern for WordTemplateExporter in batch processing
- Proper error handling and progress tracking for enhanced exports
- Updated version to v1.8.0 in package.json, main.js, and README.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 08:00:05 +05:30
amitwhandClaude 478b404135 Release v1.7.9: Enhanced Word Export with Template Support
Major Features:
- Template-based Word export with custom template selection
- File menu option to select and persist Word templates
- Table styling with orange headers and white data rows
- ASCII art and flowchart rendering with perfect alignment
- Red-colored arrows in flowcharts for enhanced visibility
- Markdown numbering stripped from headings and lists

Technical Improvements:
- Enhanced ASCII art detection for arrows and flowchart patterns
- Line-by-line rendering with no-wrap properties
- Arrow character detection and red coloring (↓→←↑)
- Template path persistence across sessions
- Word XML manipulation using PizZip

Files Modified:
- src/wordTemplateExporter.js: Enhanced ASCII art rendering, table styling
- src/main.js: Template selection function and menu integration
- CLAUDE.md: Comprehensive v1.7.9 documentation
- package.json: Version bump to 1.7.9

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 00:31:38 +05:30
amitwhandClaude 8be2651b0e Add Enhanced Word Export with native DOCX generation (v1.7.9)
- Created wordTemplateExporter.js module using docx npm package
- Added "DOCX (Enhanced)" option in File → Export menu
- Keyboard shortcut: Ctrl+Shift+W
- Full markdown support: headings, formatting, code, lists, tables
- No external dependencies (Pandoc/Python not required)
- Proper numbering configuration for lists
- Professional Word document output

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-26 23:54:00 +05:30
amitwhandClaude 922e74d671 Fix print preview to properly hide toolbar and show only markdown content
- Rewrote handlePrintPreview to explicitly hide all UI elements
- Store and restore original display values for clean restoration
- Make preview pane absolute positioned and full width for printing
- Hide toolbar, tab bar, status bar, editor pane, and dialogs
- Added proper timing for DOM updates before printing

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-26 23:36:28 +05:30
13 changed files with 962 additions and 28 deletions
+4 -1
View File
@@ -33,7 +33,10 @@
"Bash(git rm:*)",
"Bash(gh release view:*)",
"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": []
}
+137 -8
View File
@@ -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.
**Current Version**: v1.7.8
**Current Version**: v1.7.9
**Author**: Amit Haridas (amit.wh@gmail.com)
**License**: MIT
**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
### 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
**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
**Claude Assistant**: Development completed for v1.7.8 with critical bug fixes:
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
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
3. **Code Cleanup**: Removed auto-opening DevTools for production-ready build
**Last Updated**: October 27, 2025
**Claude Assistant**: Development completed for v1.7.9 with Template-Based Word Export:
- **Template Support**: Word XML manipulation using PizZip to preserve template branding and styles
- **Template Selection**: File menu option to choose custom Word templates, persisted across sessions
- **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).
+2
View File
@@ -138,6 +138,8 @@ npm run dist:all
## Version History
- **v1.8.0** - Added enhanced Word export with template support to batch converter
- **v1.7.9** - Enhanced Word Export with Template Support: Template-based DOCX generation with custom templates, table styling, ASCII art support, and red-colored flowchart arrows
- **v1.5.6** - (Your release notes here)
- **v1.5.5** - Refactored PDF export, simplified Pandoc pathing, and removed XLSX dependency.
- **v1.3.1** - Bug fixes: Fixed file associations for double-clicking .md files, corrected 50/50 layout alignment for editor/preview panes
Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

+6 -2
View File
@@ -1,6 +1,6 @@
{
"name": "pan-converter",
"version": "1.7.8",
"version": "1.8.0",
"description": "Cross-platform Markdown editor and converter using Pandoc",
"main": "src/main.js",
"scripts": {
@@ -31,13 +31,17 @@
},
"dependencies": {
"codemirror": "^6.0.2",
"core-util-is": "^1.0.3",
"docx": "^9.5.1",
"docx4js": "^3.3.0",
"dompurify": "^3.2.6",
"electron-store": "^10.1.0",
"html2pdf.js": "^0.10.1",
"highlight.js": "^11.11.1",
"html2pdf.js": "^0.10.1",
"marked": "^16.2.1",
"pdf-lib": "^1.17.1",
"pdfkit": "^0.14.0",
"pizzip": "^3.2.0",
"tslib": "^2.8.1",
"xlsx": "^0.18.5"
},
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
View File
Binary file not shown.
+1
View File
@@ -516,6 +516,7 @@
<option value="html">HTML</option>
<option value="pdf">PDF</option>
<option value="docx">DOCX</option>
<option value="docx-enhanced">DOCX (Enhanced)</option>
<option value="latex">LaTeX</option>
<option value="rtf">RTF</option>
<option value="odt">ODT</option>
+109 -4
View File
@@ -3,6 +3,7 @@ const path = require('path');
const fs = require('fs');
const { exec } = require('child_process');
const { PDFDocument, rgb, degrees, StandardFonts } = require('pdf-lib');
const WordTemplateExporter = require('./wordTemplateExporter');
// Get the system Pandoc path
function getPandocPath() {
@@ -47,6 +48,7 @@ const store = {
let mainWindow;
let currentFile = null; // This will now represent the active tab's file
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
// Handle single instance lock for Windows file association
@@ -237,6 +239,7 @@ function createMenu() {
{ label: 'HTML', click: () => exportFile('html') },
{ label: 'PDF', click: () => exportFile('pdf') },
{ label: 'DOCX', click: () => exportFile('docx') },
{ label: 'DOCX (Enhanced)', click: () => exportWordWithTemplate(), accelerator: 'Ctrl+Shift+W' },
{ label: 'LaTeX', click: () => exportFile('latex') },
{ label: 'RTF', click: () => exportFile('rtf') },
{ label: 'ODT', click: () => exportFile('odt') },
@@ -249,6 +252,11 @@ function createMenu() {
]
},
{ type: 'separator' },
{
label: 'Select Word Template...',
click: selectWordTemplate
},
{ type: 'separator' },
{
label: 'Quit',
accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
@@ -467,7 +475,7 @@ function createMenu() {
type: 'info',
title: 'About 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.8.0\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• Enhanced Word export with template support (single file & batch)\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']
});
}
@@ -533,6 +541,65 @@ function showBatchConversionDialog() {
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
function showUniversalConverterDialog() {
mainWindow.webContents.send('show-universal-converter-dialog');
@@ -1365,7 +1432,7 @@ function performBatchConversion(inputFolder, outputFolder, format, options) {
const totalCount = markdownFiles.length;
// Process each file
const processNextFile = (index) => {
const processNextFile = async (index) => {
if (index >= markdownFiles.length) {
// All files processed
dialog.showMessageBox(mainWindow, {
@@ -1380,7 +1447,8 @@ function performBatchConversion(inputFolder, outputFolder, format, options) {
const inputFile = markdownFiles[index];
const relativePath = path.relative(inputFolder, inputFile);
const baseName = path.basename(relativePath, path.extname(relativePath));
const outputFile = path.join(outputFolder, relativePath.replace(/\.(md|markdown)$/i, `.${format}`));
const outputExtension = format === 'docx-enhanced' ? 'docx' : format;
const outputFile = path.join(outputFolder, relativePath.replace(/\.(md|markdown)$/i, `.${outputExtension}`));
// Create subdirectories in output folder if needed
const outputDir = path.dirname(outputFile);
@@ -1388,7 +1456,41 @@ function performBatchConversion(inputFolder, outputFolder, format, options) {
fs.mkdirSync(outputDir, { recursive: true });
}
// Build pandoc command
// Handle DOCX Enhanced format with WordTemplateExporter
if (format === 'docx-enhanced') {
try {
const content = fs.readFileSync(inputFile, 'utf-8');
const exporter = new WordTemplateExporter(wordTemplatePath);
await exporter.convert(content, outputFile);
completedCount++;
// Update progress
mainWindow.webContents.send('batch-progress', {
completed: index + 1,
total: totalCount,
currentFile: path.basename(inputFile),
success: true
});
// Process next file
processNextFile(index + 1);
} catch (error) {
// Update progress with error
mainWindow.webContents.send('batch-progress', {
completed: index + 1,
total: totalCount,
currentFile: path.basename(inputFile),
success: false
});
// Process next file even if this one failed
processNextFile(index + 1);
}
return;
}
// Build pandoc command for other formats
let pandocCmd = `${getPandocPath()} "${inputFile}" -o "${outputFile}"`;
// Add template if specified
@@ -1590,6 +1692,9 @@ function buildPandocCommand(content, format, outputPath) {
}
app.whenReady().then(() => {
// Load saved Word template path
wordTemplatePath = store.get('wordTemplatePath', null);
// Check for command line conversion requests
const args = process.argv.slice(2);
if (args.length >= 2 && (args[0] === '--convert' || args[0] === '--convert-to')) {
+84 -12
View File
@@ -1184,23 +1184,95 @@ function handlePrintPreview(withStyles) {
return;
}
// Add print style classes to body for styling control
// The @media print CSS will handle hiding toolbar/tabs automatically
if (!withStyles) {
document.body.classList.add('printing-no-styles');
}
document.body.classList.add('printing');
// Store original display values for restoration
const elementsToHide = [];
// 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(() => {
// Tell main process to print
ipcRenderer.send('do-print', { withStyles });
// Restore classes after print dialog appears
// Restore everything after print dialog opens
setTimeout(() => {
document.body.classList.remove('printing', 'printing-no-styles');
}, 1000);
}, 100);
// Restore hidden elements
elementsToHide.forEach(({ elem, display }) => {
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
+618
View File
@@ -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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
}
module.exports = WordTemplateExporter;
Binary file not shown.