UXInteract / task_008 /solution /code /convert.js
DojiSum's picture
Publish the current 141-task UXInteract release
ef987bb verified
Raw History Blame Contribute Delete
3.27 kB
const fs = require('node:fs/promises');
const path = require('node:path');
const {chromium} = require('playwright');
function escapeHtml(text) {
return text.replace(/[&<>"']/g, ch => ({'&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;'}[ch]));
}
function renderInlineMath(text) {
return text.replace(/\\\(\s*\\sqrt\{([^}]+)\}\s*\\\)/g, 'sqrt($1)');
}
function inline(text) {
// Code spans are escaped, but not interpreted as Markdown or math.
return text.split(/(`[^`]*`)/g).map(part => {
if (part.startsWith('`') && part.endsWith('`')) return `<code>${escapeHtml(part.slice(1, -1))}</code>`;
return escapeHtml(renderInlineMath(part)).replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
}).join('');
}
function renderMarkdown(markdown) {
return markdown.replace(/\r\n/g, '\n').split('\n').map(line => {
const heading = line.match(/^\s{0,3}(#{1,6})\s+(.+)$/);
if (heading) return `<h${heading[1].length}>${inline(heading[2])}</h${heading[1].length}>`;
return line.trim() ? `<p>${inline(line)}</p>` : '<div class="blank"></div>';
}).join('\n');
}
async function writePdf(browser, inputPath, outputPath) {
const markdown = await fs.readFile(inputPath, 'utf8');
const page = await browser.newPage();
try {
await page.route(/^https?:/, route => route.abort());
await page.setContent(`<!doctype html><html lang="en"><head><meta charset="utf-8">
<style>
body { font: 11pt/1.6 "Noto Sans CJK SC", sans-serif; color: #161616; }
p { margin: 0 0 7pt; white-space: pre-wrap; overflow-wrap: anywhere; }
h1,h2,h3,h4,h5,h6 { break-after: avoid; overflow-wrap: anywhere; }
h1 { font-size: 22pt; } code { font-family: monospace; overflow-wrap: anywhere; }
.blank { height: 6pt; }
</style></head><body>${renderMarkdown(markdown)}</body></html>`);
await page.evaluate(() => document.fonts.ready);
await fs.mkdir(path.dirname(outputPath), {recursive: true});
await page.pdf({path: outputPath, format: 'A4', printBackground: true,
margin: {top: '18mm', bottom: '18mm', left: '18mm', right: '18mm'}});
} finally { await page.close(); }
}
async function withBrowser(action) {
const browser = await chromium.launch({headless: true, args: ['--no-sandbox']});
try { return await action(browser); } finally { await browser.close(); }
}
async function convertMarkdownToPdf(inputPath, outputPath) {
return withBrowser(browser => writePdf(browser, inputPath, outputPath));
}
async function convertBatch(inputDir, outputDir) {
await fs.mkdir(outputDir, {recursive: true});
const entries = await fs.readdir(inputDir, {withFileTypes: true});
await withBrowser(async browser => {
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
if (!entry.isFile() || !entry.name.endsWith('.md')) continue;
await writePdf(browser, path.join(inputDir, entry.name), path.join(outputDir, entry.name.slice(0, -3) + '.pdf'));
}
});
}
if (require.main === module) {
const [inputDir = 'samples', outputDir = 'out'] = process.argv.slice(2);
convertBatch(inputDir, outputDir).catch(error => { console.error(error); process.exitCode = 1; });
}
module.exports = {convertBatch, convertMarkdownToPdf, renderInlineMath, renderMarkdown};