### Full Configuration Example for Markdown-DOCX Conversion (JavaScript) Source: https://context7.com/vace/markdown-docx/llms.txt Illustrates a comprehensive configuration setup for the markdown-docx converter. This example demonstrates various options including GitHub Flavored Markdown, image handling, footnote and HTML ignoring, math rendering engine selection, and document properties. It also shows how to override document properties during the conversion process. ```javascript import { MarkdownDocx, Packer } from 'markdown-docx'; import fs from 'node:fs/promises'; async function fullConfiguration() { const markdown = `# Complete Example This shows all configuration options. ![Image](https://example.com/image.png) [^1]: Footnote reference
HTML content
$$ x^2 + y^2 = r^2 $$ [^1]: Footnote content here`; const converter = new MarkdownDocx(markdown, { // Markdown parsing options gfm: true, // GitHub Flavored Markdown breaks: false, // Convert \n to
pedantic: false, // Conform to original markdown.pl // Image handling ignoreImage: false, // Skip all images imageAdapter: customAdapter, // Custom image loader // Feature toggles ignoreFootnote: false, // Skip footnotes ignoreHtml: false, // Skip inline HTML // Math rendering math: { engine: 'katex', // 'katex' or 'builtin' libreOfficeCompat: false, // Optimize for LibreOffice katexOptions: { throwOnError: false, strict: false } }, // Document properties document: { title: 'My Document', creator: 'Author Name', description: 'Document description', subject: 'Subject matter', keywords: 'keyword1, keyword2', category: 'Documentation', revision: '1.0', company: 'Company Name', manager: 'Manager Name' } }); const doc = await converter.toDocument({ title: 'Override Title', creator: 'Override Creator' }); const buffer = await Packer.toBuffer(doc); await fs.writeFile('complete-example.docx', buffer); } async function customAdapter(token) { // Custom implementation return { type: 'png', data: buffer, width: 800, height: 600 }; } fullConfiguration(); ``` ``` -------------------------------- ### Install markdown-docx Package Source: https://context7.com/vace/markdown-docx/llms.txt Installs the markdown-docx package and its peer dependencies using npm or pnpm. This is the initial step to integrate the library into your project. ```bash npm install markdown-docx pnpm add markdown-docx ``` -------------------------------- ### Markdown to DOCX Conversion CLI Tool (Bash) Source: https://context7.com/vace/markdown-docx/llms.txt Provides examples of using the markdown-docx command-line interface for converting Markdown files to DOCX format. It covers installation, basic conversion with input/output options, automatic output filename generation, batch conversion using a for loop, and integration with npm scripts. ```bash # Install globally npm install -g markdown-docx # Basic conversion markdown-docx --input document.md --output document.docx # Short form markdown-docx -i README.md -o README.docx # Auto-generate output filename (README.docx) markdown-docx -i README.md # Batch conversion script for file in docs/*.md; do markdown-docx -i "$file" -o "${file%.md}.docx" done # With npm scripts in package.json # { # "scripts": { # "convert": "markdown-docx -i docs/manual.md -o output/manual.docx" # } # } npm run convert ``` -------------------------------- ### Install markdown-docx via npm, yarn, or pnpm Source: https://github.com/vace/markdown-docx/blob/main/README.md Instructions for installing the markdown-docx library using popular package managers like npm, yarn, and pnpm. This is the first step before using the library in your project. ```bash # Using npm npm install markdown-docx # Using yarn yarn add markdown-docx # Using pnpm pnpm add markdown-docx ``` -------------------------------- ### Use markdown-docx CLI for conversion Source: https://github.com/vace/markdown-docx/blob/main/README.md Demonstrates how to use the command-line interface (CLI) tool provided by markdown-docx to convert Markdown files to DOCX. It covers global installation and basic usage with input and output file specifications. ```bash # Install globally npm install -g markdown-docx # Basic usage markdown-docx --input input.md --output output.docx # Short form markdown-docx -i input.md -o output.docx ``` -------------------------------- ### Configure Math Rendering Options in markdown-docx Source: https://github.com/vace/markdown-docx/blob/main/README.md Provides an example of configuring math rendering options, specifically for LaTeX equations using KaTeX. It shows how to set the engine and potentially enable `libreOfficeCompat` for better rendering in LibreOffice. ```typescript const doc = await markdownDocx(markdown, { math: { engine: 'katex', libreOfficeCompat: false // set true if LibreOffice rendering looks off } }) ``` -------------------------------- ### Convert Markdown to DOCX using markdownDocx Function (Node.js) Source: https://context7.com/vace/markdown-docx/llms.txt Demonstrates the default export function of markdown-docx to convert a Markdown string into a DOCX document. It uses `fs` for file writing and `Packer.toBuffer` to generate the DOCX buffer. This example includes basic Markdown elements like headings, lists, tables, code blocks, blockquotes, and images. ```javascript import fs from 'node:fs/promises'; import markdownDocx, { Packer } from 'markdown-docx'; async function convertMarkdownToDocx() { const markdown = `# Project Report ## Executive Summary This report demonstrates the **key findings** of our research. - Finding 1: Performance improved by 40% - Finding 2: User satisfaction increased - Finding 3: Cost reduction achieved ### Data Analysis | Metric | Before | After | Change | |--------|--------|-------|--------| | Speed | 100ms | 60ms | +40% | | Users | 1000 | 1500 | +50% | ```python def calculate_improvement(before, after): return ((after - before) / before) * 100 ``` > **Note:** All measurements were taken under controlled conditions. ![Chart](https://example.com/chart.png)`; try { const doc = await markdownDocx(markdown, { gfm: true, ignoreImage: false }); const buffer = await Packer.toBuffer(doc); await fs.writeFile('report.docx', buffer); console.log('Document created successfully!'); } catch (error) { console.error('Conversion failed:', error); } } convertMarkdownToDocx(); ``` -------------------------------- ### Customize Document Styles Source: https://github.com/vace/markdown-docx/blob/main/README.md Modify the default styling of the generated DOCX document by directly accessing and updating style properties from the imported `styles`, `colors`, `classes`, and `numbering` objects. Examples include changing hyperlink colors or code block text colors to achieve a desired visual appearance. ```javascript import { styles, colors, classes, numbering } from 'markdown-docx'; // Example: customize docs link color styles.default.hyperlink.run.color = '0077cc'; styles.markdown.code.run.color = '000000'; ``` -------------------------------- ### Render Math with Different Engines (JavaScript) Source: https://context7.com/vace/markdown-docx/llms.txt Demonstrates how to convert Markdown with math equations to DOCX using the markdown-docx library. It showcases three different math rendering engines: KaTeX with default settings, KaTeX optimized for LibreOffice compatibility, and a built-in simple renderer. The output is saved as DOCX files. ```javascript import { markdownDocx, Packer } from 'markdown-docx'; import fs from 'node:fs/promises'; async function mathDocument() { const markdown = `## Matrices ```math \begin{bmatrix} a & b \\ c & d \end{bmatrix} ``` Greek letters: $\alpha$, $\beta$, $\gamma$, $\pi$, $\omega`; // KaTeX rendering (default, best compatibility) const katexDoc = await markdownDocx(markdown, { math: { engine: 'katex', libreOfficeCompat: false, katexOptions: { throwOnError: false, displayMode: false } } }); const katexBuffer = await Packer.toBuffer(katexDoc); await fs.writeFile('physics-katex.docx', katexBuffer); // LibreOffice compatible rendering const libreDoc = await markdownDocx(markdown, { math: { engine: 'katex', libreOfficeCompat: true } }); const libreBuffer = await Packer.toBuffer(libreDoc); await fs.writeFile('physics-libre.docx', libreBuffer); // Builtin simple renderer const builtinDoc = await markdownDocx(markdown, { math: { engine: 'builtin' } }); const builtinBuffer = await Packer.toBuffer(builtinDoc); await fs.writeFile('physics-builtin.docx', builtinBuffer); console.log('Math documents created with different engines!'); } mathDocument(); ``` ``` -------------------------------- ### Advanced DOCX Conversion with MarkdownDocx Class Source: https://github.com/vace/markdown-docx/blob/main/README.md Illustrates advanced usage by instantiating the MarkdownDocx class directly for more control over the conversion process. This allows passing options during initialization and calling `toDocument` to generate the DOCX, then saving it. ```javascript import { MarkdownDocx, Packer } from 'markdown-docx'; import fs from 'node:fs/promises'; async function convertWithOptions() { const markdown = await fs.readFile('input.md', 'utf-8'); // Create instance with options const converter = new MarkdownDocx(markdown) // Generate document const doc = await converter.toDocument({ title: 'My Document', creator: 'markdown-docx', description: 'Generated from Markdown' }); // Save to file const buffer = await Packer.toBuffer(doc); await fs.writeFile('output.docx', buffer); } ``` -------------------------------- ### Browser Usage: Convert Markdown to DOCX and Trigger Download Source: https://context7.com/vace/markdown-docx/llms.txt Shows how to use the markdown-docx library in a browser environment to convert Markdown text to a DOCX file and initiate a browser download. This function takes a Markdown string as input and generates a downloadable DOCX file. ```javascript import markdownDocx, { Packer } from 'markdown-docx'; async function convertInBrowser(markdownText) { const markdown = `# Meeting Notes **Date:** 2025-12-02 **Attendees:** Alice, Bob, Charlie ## Agenda 1. Project status review 2. Budget discussion 3. Next steps ## Action Items - [ ] Alice: Prepare budget report - [ ] Bob: Update timeline - [x] Charlie: Send meeting invite ## Key Decisions > We agreed to move forward with the new architecture proposal. `; try { const doc = await markdownDocx(markdown, { gfm: true, ignoreImage: false }); const buffer = await Packer.toBuffer(doc); // Trigger download in the browser const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'meeting-notes.docx'; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); a.remove(); console.log('Download initiated!'); } catch (error) { console.error('Browser conversion failed:', error); } } // Example usage (assuming markdownText is defined) // const myMarkdown = "..."; // convertInBrowser(myMarkdown); ``` -------------------------------- ### Render Math Equations with KaTeX and LibreOffice Compatibility Source: https://github.com/vace/markdown-docx/blob/main/README.md Enable LibreOffice compatibility mode when using the KaTeX math engine. This mode adjusts rendering to favor simpler constructs, improving the appearance of equations in LibreOffice by using operator-based rendering for sums/integrals and bracketed forms for matrices, while Word still renders these correctly. ```typescript import markdownDocx, { Packer } from 'markdown-docx' const doc = await markdownDocx(markdown, { math: { engine: 'katex', libreOfficeCompat: true } }) ``` -------------------------------- ### Custom Image Handling in DOCX Conversion Source: https://context7.com/vace/markdown-docx/llms.txt Implements a custom image adapter for markdown-docx to handle image fetching, validation, and conversion. It supports both HTTP(S) URLs and local file paths, with error handling for unsupported types or fetch failures. Dependencies include image-size, node:fs/promises, and node:path. ```javascript import { MarkdownDocx, Packer } from 'markdown-docx'; import fs from 'node:fs/promises'; import path from 'node:path'; async function customImageHandling() { const markdown = `# Product Catalog ## Featured Products ![Product 1](./images/product1.jpg) ![Product 2](https://cdn.example.com/product2.png) ![Logo](./assets/logo.gif)`; const customImageAdapter = async (token) => { const href = token.href; try { let buffer; if (href.startsWith('http')) { const response = await fetch(href); if (!response.ok) { console.warn(`Failed to fetch: ${href}`); return null; } buffer = Buffer.from(await response.arrayBuffer()); } else { const imagePath = path.resolve(process.cwd(), href); buffer = await fs.readFile(imagePath); } const sizeOf = require('image-size'); const { width, height, type } = sizeOf(buffer); const supportedTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp']; if (!supportedTypes.includes(type)) { console.warn(`Unsupported image type: ${type}`); return null; } return { type: type === 'jpeg' ? 'jpg' : type, data: buffer, width: width, height: height }; } catch (error) { console.error(`Image processing error for ${href}:`, error); return null; } }; const converter = new MarkdownDocx(markdown, { imageAdapter: customImageAdapter, ignoreImage: false }); const doc = await converter.toDocument(); const buffer = await Packer.toBuffer(doc); await fs.writeFile('catalog.docx', buffer); console.log('Catalog created with custom images!'); } customImageHandling(); ``` -------------------------------- ### Convert Markdown to DOCX using markdown-docx library Source: https://github.com/vace/markdown-docx/blob/main/tests/article.md This snippet demonstrates how to use the 'markdown-docx' library to convert Markdown content from a file into a DOCX document buffer. It reads the Markdown file, processes it using the library, and then packs the document into a buffer for further use (e.g., downloading). Requires 'markdown-docx' and 'fs' modules. ```javascript import markdownDocx, { Packer } from 'markdown-docx'; // Read markdown content const markdown = await fs.readFile('input.md', 'utf-8'); const doc = await markdownDocx(markdown); const buffer = await Packer.toBuffer(doc); ``` -------------------------------- ### Render Math Equations with Builtin Engine Source: https://github.com/vace/markdown-docx/blob/main/README.md Configure the markdown-docx library to use the 'builtin' math engine for rendering equations. This option provides a simpler text-based output, potentially improving compatibility with certain environments or for minimal rendering needs. It's a fallback when KaTeX or other advanced rendering is not desired. ```typescript import markdownDocx, { Packer } from 'markdown-docx' // Fallback to builtin (simple text) renderer const doc = await markdownDocx(markdown, { math: { engine: 'builtin' } }) ``` -------------------------------- ### Convert Markdown to DOCX in Browser Source: https://context7.com/vace/markdown-docx/llms.txt Converts Markdown content to a DOCX file directly in the browser using the markdown-docx library. It generates a downloadable DOCX file for the user. Dependencies include the markdown-docx library and the Packer utility. ```javascript async function convertInBrowser(markdown) { try { const doc = await markdownDocx(markdown, { gfm: true, ignoreImage: false }); const blob = await Packer.toBlob(doc); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'meeting-notes.docx'; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); console.log('Download initiated!'); } catch (error) { console.error('Conversion error:', error); } } // Usage with event listener document.getElementById('convert-btn').addEventListener('click', () => { const markdown = document.getElementById('markdown-input').value; convertInBrowser(markdown); }); ``` -------------------------------- ### Define Custom Image Adapter Source: https://github.com/vace/markdown-docx/blob/main/README.md Implement a custom image adapter for the markdown-docx library by defining a function that conforms to the `ImageAdapter` interface. This function takes a Markdown image token and should return a Promise resolving to `MarkdownImageItem` data, allowing for custom image fetching logic, such as handling specific protocols or authentication. ```typescript const imageAdapter: (token: Tokens.Image) => Promise ``` -------------------------------- ### Render LaTeX Mathematical Equations in DOCX Source: https://context7.com/vace/markdown-docx/llms.txt Generates a DOCX document that includes mathematical equations written in LaTeX. The library supports both inline ($...$) and display ($$...$$) math expressions. Dependencies include markdown-docx and Packer. ```javascript import markdownDocx, { Packer } from 'markdown-docx'; import fs from 'node:fs/promises'; async function mathDocument() { const markdown = `# Physics Equations ## Classical Mechanics Einstein's mass-energy equivalence: $E=mc^2$ ## Quantum Mechanics Schrödinger equation: $$ i\hbar\frac{\partial}{\partial t}\Psi(\mathbf{r},t) = \hat{H}\Psi(\mathbf{r},t) $$ ## Calculus Quadratic formula: $$ x = \frac{-b \pm \sqrt{b^2-4ac}}{2a} $$ Sum notation: $\sum_{i=1}^{n} i = \frac{n(n+1)}{2}$ Integral: $\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2}$ `; const doc = await markdownDocx(markdown); const buffer = await Packer.toBuffer(doc); await fs.writeFile('math-equations.docx', buffer); console.log('Document with math equations created!'); } mathDocument(); ``` -------------------------------- ### Convert Markdown to DOCX in Browser Source: https://github.com/vace/markdown-docx/blob/main/README.md Shows how to convert Markdown text to a DOCX document directly in a web browser. The generated DOCX file is then offered as a download to the user. It utilizes the Packer utility to create a blob and trigger a download. ```javascript import markdownDocx, { Packer } from 'markdown-docx'; async function convertMarkdownToDocx(markdownText) { // Convert to docx const doc = await markdownDocx(markdownText); // Generate blob for download const blob = await Packer.toBlob(doc); // Create download link const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'document.docx'; a.click(); // Clean up URL.revokeObjectURL(url); } // Example usage with a textarea document.getElementById('convert-btn').addEventListener('click', () => { const markdown = document.getElementById('markdown-input').value; convertMarkdownToDocx(markdown); }); ``` -------------------------------- ### Customize Document Styling with markdown-docx Source: https://context7.com/vace/markdown-docx/llms.txt Applies custom styles to a DOCX document generated from Markdown, including heading colors, hyperlink colors, and code block formatting. This allows for brand guideline adherence and enhanced readability. Dependencies include markdown-docx, Packer, and styles utilities. ```javascript import markdownDocx, { Packer, styles } from 'markdown-docx'; import fs from 'node:fs/promises'; async function customStyledDocument() { // Customize heading colors styles.default.heading1.run.color = 'FF0000'; // Red styles.default.heading2.run.color = '0000FF'; // Blue styles.default.heading3.run.color = '00AA00'; // Green // Customize hyperlink color styles.default.hyperlink.run.color = '0077CC'; // Customize code style styles.markdown.code.run.color = '000000'; styles.markdown.code.run.font = 'Consolas'; styles.markdown.code.paragraph.shading = { fill: 'F5F5F5', type: 'clear', color: 'auto' }; const markdown = `# Brand Guidelines Document ## Primary Colors This document uses our **brand colors** throughout. ### Code Standards ```javascript const brandColors = { primary: '#FF0000', secondary: '#0000FF', accent: '#00AA00' }; ``` Visit our website: [Company Site](https://example.com)`; const doc = await markdownDocx(markdown); const buffer = await Packer.toBuffer(doc); await fs.writeFile('brand-doc.docx', buffer); console.log('Branded document created!'); } customStyledDocument(); ``` -------------------------------- ### CSS Syntax Highlighting Source: https://github.com/vace/markdown-docx/blob/main/tests/markdown.md This CSS code defines font faces and styles for web page elements, including responsive design considerations for printing. It sets custom fonts and colors, and imports external stylesheets for print media. ```css @font-face { font-family: Chunkfive; src: url('Chunkfive.otf'); } body, .usertext { color: #F0F0F0; background: #600; font-family: Chunkfive, sans-serif; } @import url(print.css); @media print { a[href^=http]::after { content: attr(href) } } ``` -------------------------------- ### JavaScript Code Highlighting Function Source: https://github.com/vace/markdown-docx/blob/main/tests/markdown.md This JavaScript function, $initHighlight, is designed to process and highlight code blocks. It includes error handling and checks for specific CSS classes to conditionally apply highlighting. It exports the function for external use. ```javascript function $initHighlight(block, cls) { try { if (cls.search(/\bno\-highlight\b/) != -1) return process(block, true, 0x0F) + ` class="${cls}"`; } catch (e) { /* handle exception */ } for (var i = 0 / 2; i < classes.length; i++) { if (checkCondition(classes[i]) === undefined) console.log('undefined'); } } export $initHighlight; ``` -------------------------------- ### Advanced DOCX Conversion with MarkdownDocx Class (Node.js) Source: https://context7.com/vace/markdown-docx/llms.txt Utilizes the `MarkdownDocx` class for advanced conversion options, including mathematical equations (LaTeX via KaTeX), footnotes, and custom document metadata. It generates a DOCX file named 'technical-doc.docx'. ```javascript import { MarkdownDocx, Packer } from 'markdown-docx'; import fs from 'node:fs/promises'; async function advancedConversion() { const markdown = `# Technical Documentation ## Mathematical Formulas Einstein's equation: $E=mc^2$ Quadratic formula: $$ <0xC2><0xA0>x = \frac{-b \pm \sqrt{b^2-4ac}}{2a} $$ ## Code Example ```javascript function fibonacci(n) { return n <= 1 ? n : fibonacci(n-1) + fibonacci(n-2); } ``` [^1]: Reference note explaining the equation [^1]: This is a footnote with detailed information.`; const converter = new MarkdownDocx(markdown, { gfm: true, ignoreImage: false, ignoreFootnote: false, math: { engine: 'katex', libreOfficeCompat: false } }); try { const doc = await converter.toDocument({ title: 'Technical Documentation', creator: 'Engineering Team', description: 'Generated from Markdown', subject: 'API Documentation', keywords: 'technical, documentation, API' }); const buffer = await Packer.toBuffer(doc); await fs.writeFile('technical-doc.docx', buffer); console.log('Technical document created!'); } catch (error) { console.error('Error:', error); } } advancedConversion(); ``` -------------------------------- ### Convert Markdown to DOCX in Node.js Source: https://github.com/vace/markdown-docx/blob/main/README.md Demonstrates how to convert a Markdown file to DOCX format in a Node.js environment. It reads a Markdown file, converts it using markdownDocx, and saves the output as a DOCX file using the Packer utility. ```javascript import fs from 'node:fs/promises'; import markdownDocx, { Packer } from 'markdown-docx'; async function convertMarkdownToDocx() { // Read markdown content const markdown = await fs.readFile('input.md', 'utf-8'); // Convert to docx const doc = await markdownDocx(markdown); // Save to file const buffer = await Packer.toBuffer(doc); await fs.writeFile('output.docx', buffer); console.log('Conversion completed successfully!'); } convertMarkdownToDocx(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.