File size: 3,270 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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};