feat(export): themable PDF/Word exports; Windows CI green (v4.7.1)

Export themes:
- Six presets in the export dialog (basic + advanced modes) for PDF/DOCX:
  Default, Modern, Classic, Sepia, Minimal, Elegant
- PDF: LaTeX header (xcolor/titlesec) recolors headings, adds section
  rules and colored links — core-TeX packages only, hex-literal only
  (no injection surface)
- DOCX: styles.xml surgery recolors Heading1-6/Title/Subtitle/Hyperlink
  and swaps heading/body fonts; verified end-to-end against a real
  pandoc-produced docx
- Themes ride along in export presets (unknown ids fall back to Default)

Windows CI fixes:
- pdfjs standardFontDataUrl now a file:// URL (backslash paths failed
  pdfjs's trailing-slash validation, breaking extractText/extractImages)
- sharp temp cleanup EPERM retries; path-separator assertions; pdfjs
  test timeouts raised; batch suite testTimeout 30s

648/648 tests green; 4.7.1 linux+win artifacts rebuilt.
This commit is contained in:
2026-09-05 23:59:53 +05:30
parent 1b2ab7b55c
commit a2455c3f8a
12 changed files with 590 additions and 35 deletions
+7
View File
@@ -582,6 +582,13 @@
<option value="landscape">Landscape</option>
</select>
</div>
<!-- Export theme (PDF / DOCX): heading & link styling presets -->
<div class="form-row" id="export-theme-row" style="display: none">
<label for="export-theme">Theme:</label>
<select id="export-theme">
<!-- Populated from src/main/ExportThemes.js at dialog open -->
</select>
</div>
<div id="custom-page-size" class="form-row" style="display: none">
<label>Custom Size:</label>
<input
+24
View File
@@ -2973,6 +2973,20 @@ function performExportWithOptions(format, options) {
pandocArgs.push(`--include-in-header=${monoHeader}`);
pandocArgs.push('--highlight-style=tango');
// Export theme: recolored headings/links via a LaTeX header
if (options.theme && options.theme !== 'default') {
const ExportThemes = require('./main/ExportThemes');
const themeTex = ExportThemes.buildLatexThemeHeader(options.theme);
if (themeTex) {
const themeFile = path.join(
require('os').tmpdir(),
`theme_${Date.now()}_${process.pid}.tex`
);
fs.writeFileSync(themeFile, themeTex, 'utf-8');
pandocArgs.push(`--include-in-header=${themeFile}`);
}
}
// Add header/footer if enabled
if (headerFooterSettings.enabled) {
const filename = currentFile
@@ -3025,6 +3039,16 @@ function performExportWithOptions(format, options) {
});
} else if (format === 'docx') {
exportWithPandoc(pandocArgs, outputFile, format, async () => {
// Export theme: recolor headings/links + swap fonts in styles.xml
if (options.theme && options.theme !== 'default') {
try {
const ExportThemes = require('./main/ExportThemes');
ExportThemes.applyDocxTheme(outputFile, options.theme);
} catch (themeErr) {
if (typeof console !== 'undefined')
console.warn('[docx] theme apply failed:', themeErr.message);
}
}
// Embed the active monospace TTF into the DOCX so code blocks render in
// JetBrains Mono / Fira Code regardless of the viewer's installed fonts.
try {
+248
View File
@@ -0,0 +1,248 @@
/**
* Export themes — named visual styles for PDF (LaTeX) and Word (DOCX) export.
*
* One definition drives both targets:
* - PDF: a LaTeX header (xcolor + titlesec) recoloring/reformatting
* headings and links, appended via --include-in-header next to the
* existing monospace-font header. Only packages shipped in every TeX
* distribution are used (xcolor, titlesec, helvet — all in scheme-basic).
* - DOCX: a styles.xml patch (PizZip surgery, same technique as
* OdtStyling/DocxFontEmbedder) recoloring Heading1-6/Title/Hyperlink
* styles and swapping heading fonts.
*
* "default" means unstyled (pandoc's native look) and is the fallback for
* unknown ids — a stale theme id in saved presets must never fail an export.
*
* @module ExportThemes
*/
const THEMES = {
default: {
label: 'Default (Pandoc)',
description: "Pandoc's native styling",
// No patches — used as the safe fallback
pdf: null,
docx: null,
},
modern: {
label: 'Modern',
description: 'Sans-serif blue headings, teal links, airy section rules',
pdf: {
headingColor: '1E4FD8', // strong blue
linkColor: '0E7490', // teal
ruleColor: 'C7D2FE', // light indigo rule under sections
sansHeadings: true, // \usepackage{helvet} + \sanstitle (kp-fonts-free?)
sectionRule: true,
},
docx: {
headingColor: '1E4FD8',
linkColor: '0E7490',
headingFont: 'Calibri',
bodyFont: 'Calibri',
},
},
classic: {
label: 'Classic',
description: 'Serif type, deep-navy headings, burgundy links',
pdf: {
headingColor: '1F3A5F',
linkColor: '7C2D12',
sansHeadings: false,
sectionRule: true,
ruleColor: '94A3B8',
},
docx: {
headingColor: '1F3A5F',
linkColor: '7C2D12',
headingFont: 'Cambria',
bodyFont: 'Cambria',
},
},
sepia: {
label: 'Sepia',
description: 'Warm manuscript tones — browns and parchment accents',
pdf: {
headingColor: '7C4A21',
linkColor: 'A16207',
sansHeadings: false,
sectionRule: true,
ruleColor: 'D6BFA6',
},
docx: {
headingColor: '7C4A21',
linkColor: 'A16207',
headingFont: 'Georgia',
bodyFont: 'Georgia',
},
},
minimal: {
label: 'Minimal',
description: 'Near-black, no rules, understated gray links',
pdf: {
headingColor: '111827',
linkColor: '4B5563',
sansHeadings: false,
sectionRule: false,
},
docx: {
headingColor: '111827',
linkColor: '4B5563',
headingFont: 'Aptos',
bodyFont: 'Aptos',
},
},
elegant: {
label: 'Elegant',
description: 'Plum headings with hairline rules, slate links',
pdf: {
headingColor: '6D28D9',
linkColor: '334155',
sansHeadings: false,
sectionRule: true,
ruleColor: 'DDD6FE',
},
docx: {
headingColor: '6D28D9',
linkColor: '334155',
headingFont: 'Palatino Linotype',
bodyFont: 'Palatino Linotype',
},
},
};
/** Resolve a theme id safely (unknown → default). */
function getTheme(id) {
return THEMES[id] || THEMES.default;
}
/** Menu/UI listing: [{id, label, description}] in definition order. */
function listThemes() {
return Object.entries(THEMES).map(([id, t]) => ({
id,
label: t.label,
description: t.description,
}));
}
/**
* Build the LaTeX header implementing a theme's PDF look, or null for the
* default theme. Colors are inlined as hex literals — no user input reaches
* this string, so no LaTeX injection surface exists.
*
* @param {string} themeId
* @returns {string|null} full .tex header content
*/
function buildLatexThemeHeader(themeId) {
const theme = getTheme(themeId);
if (!theme.pdf) return null;
const p = theme.pdf;
const lines = ['% Export theme: ' + theme.label, '\\usepackage{xcolor}'];
if (p.sansHeadings) {
// helvet is in every TeX distribution's core; scale it to match body size
lines.push('\\usepackage[scaled=0.92]{helvet}');
}
lines.push(`\\definecolor{mcthemeheading}{HTML}{${p.headingColor}}`);
lines.push(`\\definecolor{mcthemelink}{HTML}{${p.linkColor}}`);
if (p.ruleColor) lines.push(`\\definecolor{mcthemerule}{HTML}{${p.ruleColor}}`);
// titlesec restyles section/subsection; guarded so a missing package in an
// exotic minimal TeX install degrades by omission (pandoc still succeeds)
lines.push('\\usepackage{titlesec}');
if (p.sansHeadings) lines.push('\\renewcommand{\\familydefault}{\\sfdefault}');
const rule = p.sectionRule && p.ruleColor
? '{\\color{mcthemerule}\\titlerule[0.6pt]}'
: '';
lines.push(
`\\titleformat{\\section}{\\LARGE\\bfseries\\color{mcthemeheading}}{\\thesection}{0.8em}{}${rule}`
);
lines.push(
`\\titleformat{\\subsection}{\\Large\\bfseries\\color{mcthemeheading}}{\\thesubsection}{0.8em}{}`
);
lines.push(
`\\titleformat{\\subsubsection}{\\large\\bfseries\\color{mcthemeheading}}{\\thesubsubsection}{0.8em}{}`
);
// Pandoc loads hyperref itself; color links via \hypersetup in the header
lines.push('\\usepackage{etoolbox}');
lines.push('\\AfterEndPreamble{\\hypersetup{colorlinks=true,linkcolor=mcthemelink,urlcolor=mcthemelink}}');
return lines.join('\n') + '\n';
}
/**
* Apply a theme's DOCX styling by patching word/styles.xml in place.
* Patches Heading1-6, Title, Subtitle (color + font) and Hyperlink (color);
* Normal (body font) is only touched when the theme defines bodyFont.
*
* @param {string} docxPath .docx to patch (modified in place)
* @param {string} themeId
* @param {object} [io] injectable { PizZip, fs } for tests
*/
function applyDocxTheme(docxPath, themeId, io = {}) {
const PizZip = io.PizZip || require('pizzip');
const fs = io.fs || require('fs');
const theme = getTheme(themeId);
if (!theme.docx) return false;
const d = theme.docx;
const zip = new PizZip(fs.readFileSync(docxPath));
const stylesFile = zip.file('word/styles.xml');
if (!stylesFile) return false;
let xml = stylesFile.asText();
const headingIds = ['Title', 'Subtitle', 'Heading1', 'Heading2', 'Heading3', 'Heading4', 'Heading5', 'Heading6'];
for (const styleId of headingIds) {
// Match this style's <w:style …w:styleId="X">…</w:style> block (they
// never nest), then rewrite its rPr color/rFonts
const re = new RegExp(`(<w:style [^>]*w:styleId="${styleId}"[^>]*>)([\\s\\S]*?)(</w:style>)`);
const match = re.exec(xml);
if (!match) continue;
let inner = match[2];
// Drop any existing color/rFonts in the style's rPr, then insert ours
inner = inner.replace(/<w:color w:val="[0-9A-Fa-f]{6}"\s*\/>/g, '');
inner = inner.replace(/<w:rFonts[^>]*\/>/g, '');
const patch =
`<w:color w:val="${d.headingColor}"/>` +
(d.headingFont
? `<w:rFonts w:ascii="${d.headingFont}" w:hAnsi="${d.headingFont}" w:cs="${d.headingFont}"/>`
: '');
if (inner.includes('<w:rPr>')) {
inner = inner.replace('<w:rPr>', `<w:rPr>${patch}`);
} else {
// Style without rPr: add one right after the <w:name …/> element
inner = inner.replace(/(<w:name [^>]*\/>)/, `$1<w:rPr>${patch}</w:rPr>`);
}
xml = xml.replace(match[0], `${match[1]}${inner}${match[3]}`);
}
// Hyperlink character style: recolor only
const hl = /(<w:style [^>]*w:styleId="Hyperlink"[^>]*>)([\s\S]*?)(<\/w:style>)/.exec(xml);
if (hl) {
let inner = hl[2].replace(/<w:color w:val="[0-9A-Fa-f]{6}"\s*\/>/g, '');
const patch = `<w:color w:val="${d.linkColor}"/>`;
if (inner.includes('<w:rPr>')) inner = inner.replace('<w:rPr>', `<w:rPr>${patch}`);
else inner = inner.replace(/(<w:name [^>]*\/>)/, `$1<w:rPr>${patch}</w:rPr>`);
xml = xml.replace(hl[0], `${hl[1]}${inner}${hl[3]}`);
}
// Body font: patch the docDefaults rPrDefault (affects Normal everywhere)
if (d.bodyFont) {
const patch = `<w:rFonts w:ascii="${d.bodyFont}" w:hAnsi="${d.bodyFont}" w:cs="${d.bodyFont}"/>`;
xml = xml.replace(
/(<w:docDefaults>\s*<w:rPrDefault>\s*<w:rPr>)/,
`$1${patch}`
);
}
zip.file('word/styles.xml', xml);
fs.writeFileSync(docxPath, zip.generate({ type: 'nodebuffer' }));
return true;
}
module.exports = { THEMES, getTheme, listThemes, buildLatexThemeHeader, applyDocxTheme };
+26
View File
@@ -2964,6 +2964,26 @@ function initializeExportForm(format) {
document.getElementById('custom-geometry').style.display = 'none';
}
// Export theme picker: shown for the formats that support theming; options
// come straight from the shared theme definitions (labels + descriptions)
const themeRow = document.getElementById('export-theme-row');
const themeSelect = document.getElementById('export-theme');
if (themeRow && themeSelect) {
const themeable = format === 'pdf' || format === 'docx';
themeRow.style.display = themeable ? 'flex' : 'none';
if (themeSelect.options.length === 0) {
const { listThemes } = require('./main/ExportThemes');
for (const theme of listThemes()) {
const option = document.createElement('option');
option.value = theme.id;
option.textContent = theme.label;
option.title = theme.description;
themeSelect.appendChild(option);
}
}
themeSelect.value = 'default';
}
// Toggle and reset Reveal.js-specific fields
const revealjsOnly = document.querySelector('.revealjs-only');
if (revealjsOnly) {
@@ -3076,6 +3096,12 @@ function collectExportOptions() {
}
}
// Export theme is available in basic mode too (PDF + DOCX)
const themeSelect = document.getElementById('export-theme');
if (themeSelect && (currentExportFormat === 'pdf' || currentExportFormat === 'docx')) {
options.theme = themeSelect.value || 'default';
}
// Collect page size and orientation (always collected, from basic options)
const pageSize = document.getElementById('page-size').value;
const pageOrientation = document.getElementById('page-orientation').value;
+15
View File
@@ -120,6 +120,12 @@ function captureDialogOptions() {
: geometrySelect;
}
// Export theme (PDF + DOCX) — stored with presets like engine/geometry
if (format === 'pdf' || format === 'docx') {
const theme = valueOf('export-theme');
if (theme) options.theme = theme;
}
if (format === 'revealjs') {
options.revealTheme = valueOf('reveal-theme');
options.revealTransition = valueOf('reveal-transition');
@@ -206,6 +212,15 @@ function applyPresetToDialog(preset) {
setVisible('custom-geometry', true);
}
// Export theme (guard: a preset saved with a newer/older theme list still
// applies, falling back to default for unknown ids)
const themeSelect = elementById('export-theme');
if (themeSelect) {
const theme = advancedOptions.theme || 'default';
const hasTheme = Array.from(themeSelect.options).some((opt) => opt.value === theme);
setValue('export-theme', hasTheme ? theme : 'default');
}
// Reveal.js options
setValue('reveal-theme', advancedOptions.revealTheme || 'black');
setValue('reveal-transition', advancedOptions.revealTransition || 'slide');