39 lines
1.4 KiB
TypeScript
39 lines
1.4 KiB
TypeScript
|
|
/**
|
||
|
|
* 导出文本为 Markdown / PDF
|
||
|
|
*/
|
||
|
|
|
||
|
|
export function downloadMarkdown(content: string, title = '导出内容') {
|
||
|
|
const now = new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')
|
||
|
|
const markdown = `# ${title}\n\n> 导出时间: ${new Date().toLocaleString('zh-CN')}\n\n${content}\n`
|
||
|
|
const blob = new Blob([markdown], { type: 'text/markdown; charset=utf-8' })
|
||
|
|
const url = URL.createObjectURL(blob)
|
||
|
|
const a = document.createElement('a')
|
||
|
|
a.href = url
|
||
|
|
a.download = `${title.replace(/\s+/g, '_')}_${now}.md`
|
||
|
|
document.body.appendChild(a)
|
||
|
|
a.click()
|
||
|
|
document.body.removeChild(a)
|
||
|
|
URL.revokeObjectURL(url)
|
||
|
|
}
|
||
|
|
|
||
|
|
export function printAsPdf(content: string, title = '导出内容') {
|
||
|
|
const w = window.open('', '_blank', 'width=800,height=600')
|
||
|
|
if (!w) return
|
||
|
|
w.document.write(`
|
||
|
|
<!DOCTYPE html>
|
||
|
|
<html><head><meta charset="utf-8">
|
||
|
|
<title>${title}</title>
|
||
|
|
<style>
|
||
|
|
body { font-family: system-ui, sans-serif; max-width: 800px; margin: 0 auto; padding: 2rem; line-height: 1.7; }
|
||
|
|
pre { white-space: pre-wrap; background: #f5f5f5; padding: 1rem; border-radius: 6px; }
|
||
|
|
</style></head>
|
||
|
|
<body><h1>${title}</h1><p><em>导出时间: ${new Date().toLocaleString('zh-CN')}</em></p><pre>${escapeHtml(content)}</pre></body></html>
|
||
|
|
`)
|
||
|
|
w.document.close()
|
||
|
|
setTimeout(() => w.print(), 300)
|
||
|
|
}
|
||
|
|
|
||
|
|
function escapeHtml(text: string) {
|
||
|
|
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
||
|
|
}
|