const fs = require('fs') const path = require('path') const input = process.argv[2] const output = process.argv[3] if (!input || !output) { console.error('Usage: node scripts/markdown-to-pdf.js ') process.exit(1) } const markdown = fs.readFileSync(input, 'utf8') function escapeHtml(value) { return value .replace(/&/g, '&') .replace(//g, '>') } function inlineFormat(value) { return escapeHtml(value) .replace(/`([^`]+)`/g, '$1') .replace(/\*\*([^*]+)\*\*/g, '$1') } function renderTable(lines) { const rows = lines .filter(line => line.trim()) .map(line => line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(cell => inlineFormat(cell.trim()))) if (rows.length < 2) return '' const head = rows[0] const body = rows.slice(2) return [ '', '' + head.map(cell => '').join('') + '', '', body.map(row => '' + row.map(cell => '').join('') + '').join('\n'), '', '
' + cell + '
' + cell + '
' ].join('\n') } function renderMarkdown(text) { const lines = text.replace(/\r\n/g, '\n').split('\n') const html = [] let paragraph = [] let list = [] let code = [] let inCode = false let table = [] function flushParagraph() { if (paragraph.length) { html.push('

' + inlineFormat(paragraph.join(' ')) + '

') paragraph = [] } } function flushList() { if (list.length) { html.push('') list = [] } } function flushTable() { if (table.length) { html.push(renderTable(table)) table = [] } } lines.forEach(line => { if (/^```/.test(line.trim())) { if (inCode) { html.push('
' + escapeHtml(code.join('\n')) + '
') code = [] inCode = false } else { flushParagraph() flushList() flushTable() inCode = true } return } if (inCode) { code.push(line) return } if (/^\|.*\|$/.test(line.trim())) { flushParagraph() flushList() table.push(line) return } flushTable() if (!line.trim()) { flushParagraph() flushList() return } const heading = line.match(/^(#{1,6})\s+(.+)$/) if (heading) { flushParagraph() flushList() const level = heading[1].length html.push('' + inlineFormat(heading[2]) + '') return } const image = line.match(/^!\[([^\]]*)\]\(([^)]+)\)$/) if (image) { flushParagraph() flushList() html.push('
' + escapeHtml(image[1]) + '
' + inlineFormat(image[1]) + '
') return } const listItem = line.match(/^- (.+)$/) if (listItem) { flushParagraph() list.push(listItem[1]) return } paragraph.push(line.trim()) }) flushParagraph() flushList() flushTable() return html.join('\n') } const body = renderMarkdown(markdown) const html = ` 零件改制功能设计方案 ${body} ` fs.writeFileSync(output, html, 'utf8')