File size: 11,750 Bytes
59bb0ce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 | /**
* Export markdown content to a Word document (.docx)
* Uses the docx library to create properly formatted documents
*/
import {
Document,
Paragraph,
TextRun,
HeadingLevel,
Table,
TableRow,
TableCell,
WidthType,
BorderStyle,
Packer,
AlignmentType
} from "docx";
/**
* Simple markdown parser for converting to docx elements
*/
function parseMarkdown(markdown) {
const lines = markdown.split("\n");
const elements = [];
let inCodeBlock = false;
let codeContent = [];
let inTable = false;
let tableRows = [];
let listItems = [];
let listType = null; // "ul" or "ol"
const flushList = () => {
if (listItems.length > 0) {
elements.push({
type: listType === "ol" ? "orderedList" : "bulletList",
items: [...listItems]
});
listItems = [];
listType = null;
}
};
const flushTable = () => {
if (tableRows.length > 0) {
elements.push({
type: "table",
rows: [...tableRows]
});
tableRows = [];
inTable = false;
}
};
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Code block handling
if (line.startsWith("```")) {
if (inCodeBlock) {
elements.push({
type: "codeBlock",
content: codeContent.join("\n")
});
codeContent = [];
inCodeBlock = false;
} else {
flushList();
flushTable();
inCodeBlock = true;
}
continue;
}
if (inCodeBlock) {
codeContent.push(line);
continue;
}
// Table handling
if (line.includes("|") && line.trim().startsWith("|")) {
flushList();
const cells = line.split("|").slice(1, -1).map(c => c.trim());
// Skip separator row
if (cells.every(c => /^[-:]+$/.test(c))) {
continue;
}
tableRows.push(cells);
inTable = true;
continue;
} else if (inTable) {
flushTable();
}
// Empty line
if (!line.trim()) {
flushList();
continue;
}
// Headings
const headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
if (headingMatch) {
flushList();
elements.push({
type: "heading",
level: headingMatch[1].length,
content: headingMatch[2]
});
continue;
}
// Horizontal rule
if (/^[-*_]{3,}$/.test(line.trim())) {
flushList();
elements.push({ type: "hr" });
continue;
}
// Blockquote
if (line.startsWith(">")) {
flushList();
elements.push({
type: "blockquote",
content: line.replace(/^>\s*/, "")
});
continue;
}
// Ordered list
const olMatch = line.match(/^(\d+)\.\s+(.+)$/);
if (olMatch) {
if (listType === "ul") flushList();
listType = "ol";
listItems.push(olMatch[2]);
continue;
}
// Unordered list
const ulMatch = line.match(/^[-*+]\s+(.+)$/);
if (ulMatch) {
if (listType === "ol") flushList();
listType = "ul";
listItems.push(ulMatch[1]);
continue;
}
// Regular paragraph
flushList();
elements.push({
type: "paragraph",
content: line
});
}
// Flush any remaining items
flushList();
flushTable();
return elements;
}
/**
* Parse inline formatting (bold, italic, code, links)
*/
function parseInlineFormatting(text) {
const runs = [];
let remaining = text;
while (remaining.length > 0) {
// Bold and italic: ***text***
let match = remaining.match(/^\*\*\*(.+?)\*\*\*/);
if (match) {
runs.push(new TextRun({ text: match[1], bold: true, italics: true, font: "Calibri" }));
remaining = remaining.slice(match[0].length);
continue;
}
// Bold: **text** or __text__
match = remaining.match(/^(\*\*|__)(.+?)(\*\*|__)/);
if (match) {
runs.push(new TextRun({ text: match[2], bold: true, font: "Calibri" }));
remaining = remaining.slice(match[0].length);
continue;
}
// Italic: *text* or _text_
match = remaining.match(/^(\*|_)(.+?)(\*|_)/);
if (match) {
runs.push(new TextRun({ text: match[2], italics: true, font: "Calibri" }));
remaining = remaining.slice(match[0].length);
continue;
}
// Inline code: `code`
match = remaining.match(/^`([^`]+)`/);
if (match) {
runs.push(new TextRun({
text: match[1],
font: "Consolas",
shading: { fill: "E8E8E8" }
}));
remaining = remaining.slice(match[0].length);
continue;
}
// Link: [text](url)
match = remaining.match(/^\[([^\]]+)\]\(([^)]+)\)/);
if (match) {
runs.push(new TextRun({
text: match[1],
color: "0563C1",
underline: {},
font: "Calibri"
}));
remaining = remaining.slice(match[0].length);
continue;
}
// Regular text (take until next special character or end)
match = remaining.match(/^[^*_`\[]+/);
if (match) {
runs.push(new TextRun({ text: match[0], font: "Calibri" }));
remaining = remaining.slice(match[0].length);
continue;
}
// Single special character that didn't match formatting
runs.push(new TextRun({ text: remaining[0], font: "Calibri" }));
remaining = remaining.slice(1);
}
return runs;
}
/**
* Convert parsed elements to docx sections
*/
function elementsToDocx(elements) {
const children = [];
for (const el of elements) {
switch (el.type) {
case "heading":
const headingLevels = {
1: HeadingLevel.HEADING_1,
2: HeadingLevel.HEADING_2,
3: HeadingLevel.HEADING_3,
4: HeadingLevel.HEADING_4,
5: HeadingLevel.HEADING_5,
6: HeadingLevel.HEADING_6
};
children.push(
new Paragraph({
heading: headingLevels[el.level] || HeadingLevel.HEADING_1,
children: parseInlineFormatting(el.content),
spacing: { before: 280, after: 120 }
})
);
break;
case "paragraph":
children.push(
new Paragraph({
children: parseInlineFormatting(el.content),
spacing: { after: 280, line: 276 }
})
);
break;
case "bulletList":
for (let i = 0; i < el.items.length; i++) {
children.push(
new Paragraph({
bullet: { level: 0 },
children: parseInlineFormatting(el.items[i]),
spacing: { after: i === el.items.length - 1 ? 200 : 60 }
})
);
}
break;
case "orderedList":
for (let idx = 0; idx < el.items.length; idx++) {
children.push(
new Paragraph({
numbering: { reference: "default-numbering", level: 0 },
children: parseInlineFormatting(el.items[idx]),
spacing: { after: idx === el.items.length - 1 ? 200 : 60 }
})
);
}
break;
case "codeBlock":
children.push(
new Paragraph({
children: [
new TextRun({
text: el.content,
font: "Consolas",
size: 20
})
],
shading: { fill: "F5F5F5" },
spacing: { before: 200, after: 200 }
})
);
break;
case "blockquote":
children.push(
new Paragraph({
children: parseInlineFormatting(el.content),
indent: { left: 720 },
border: {
left: { style: BorderStyle.SINGLE, size: 24, color: "CCCCCC" }
},
spacing: { before: 200, after: 200 }
})
);
break;
case "table":
const tableRows = el.rows.map((row, rowIdx) =>
new TableRow({
children: row.map(cell =>
new TableCell({
children: [new Paragraph({ children: parseInlineFormatting(cell) })],
shading: rowIdx === 0 ? { fill: "E8E8E8" } : undefined
})
)
})
);
children.push(
new Table({
rows: tableRows,
width: { size: 100, type: WidthType.PERCENTAGE }
})
);
break;
case "hr":
children.push(
new Paragraph({
border: { bottom: { style: BorderStyle.SINGLE, size: 6, color: "CCCCCC" } },
spacing: { before: 400, after: 400 }
})
);
break;
}
}
return children;
}
/**
* Export markdown content to Word document and trigger download
*/
export async function exportToWord(markdown, filename = "document") {
const elements = parseMarkdown(markdown);
const children = elementsToDocx(elements);
const doc = new Document({
numbering: {
config: [
{
reference: "default-numbering",
levels: [
{
level: 0,
format: "decimal",
text: "%1.",
alignment: AlignmentType.START
}
]
}
]
},
sections: [
{
children
}
]
});
const blob = await Packer.toBlob(doc);
// Trigger download
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `${filename.replace(/[^a-zA-Z0-9-_]/g, "_")}.docx`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
|