markdown-to-html
将 PSUIP 格式的 Markdown 内容转换为 HTML 字符串,支持所有 PSUIP 扩展语法。
接口信息
- 方法:
POST - 地址:
https://study-env.dingdaoos.com/api/markdown-to-html - 请求头:
Content-Type: application/json
请求参数
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
markdown | string | 是 | - | PSUIP 格式的 Markdown 文本内容 |
width | number | 否 | 1024 | 画布宽度(像素),用于布局计算 |
height | number | 否 | 768 | 画布高度(像素),用于布局计算 |
参数详细说明
markdown
- 支持标准 Markdown 语法
- 支持 PSUIP 扩展语法:卡片组件、布局标签、图表语法等
- 支持多行文本,需要正确转义特殊字符
- 建议使用 UTF-8 编码
width & height
- 用于响应式布局计算
- 影响图表组件的显示尺寸
- 影响画廊布局的列数计算
- 单位为像素 (px)
请求示例
基础请求
{
"markdown": "# Hello PSUIP\n\n这是一个简单的示例。\n\n[primary][开始使用](https://example.com)",
"width": 800,
"height": 600
}卡片组件请求
{
"markdown": "<card:headerPrecentCard>\n ## 二、市场概述\n AI-PC 概念自 2023 年由英特尔提出后,迅速引发行业关注\n ### 中国市场\n <percentValue color={color.error.red8}>#### 15%</percentValue>\n AI-PC 出货量\n ### 全球市场 \n #### 25%\n AI-PC 渗透率\n ### 未来预测\n #### 40%\n 预计增长率\n</card:headerPrecentCard>",
"width": 1024,
"height": 768
}复杂布局请求
{
"markdown": "## 产品对比\n<layout:row>\n### 产品A\n<layout:column>\n#### 功能特性\n- 特性1\n- 特性2\n\n#### 价格信息\n$99/月\n</layout:column>\n\n### 产品B\n<layout:column>\n#### 功能特性\n- 特性1\n- 特性2\n\n#### 价格信息\n$199/月\n</layout:column>\n</layout:row>",
"width": 1200,
"height": 800
}响应格式
成功响应
HTTP 状态码:200 OK
Content-Type:application/json
响应体结构:
{
"success": true,
"html": "<!DOCTYPE html><html><head><meta charset=\"utf-8\"></head><body><div class=\"psuip-root\">...</div></body></html>"
}字段说明:
success: 布尔值,表示处理是否成功html: 完整的 HTML 文档字符串,包含所有必要的样式和脚本
错误响应
HTTP 状态码:400 Bad Request 或 500 Internal Server Error
响应体结构:
{
"success": false,
"error": "错误描述",
"code": "ERROR_CODE"
}常见错误代码:
INVALID_MARKDOWN: Markdown 语法错误INVALID_PARAMETERS: 参数格式错误PROCESSING_ERROR: 内容处理失败
使用示例
JavaScript (fetch)
async function convertMarkdownToHtml(markdown, width = 1024, height = 768) {
const response = await fetch('https://study-env.dingdaoos.com/api/markdown-to-html', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
markdown,
width,
height
})
});
const result = await response.json();
if (result.success) {
return result.html;
} else {
throw new Error(result.error);
}
}
// 使用示例
const markdown = `
# 产品介绍
<card:elegantStandard>
## 核心功能
### 智能分析
提供深度数据分析和智能洞察
[了解更多](https://example.com)
</card:elegantStandard>
`;
convertMarkdownToHtml(markdown)
.then(html => {
document.getElementById('content').innerHTML = html;
})
.catch(error => {
console.error('转换失败:', error);
});Python (requests)
import requests
import json
def convert_markdown_to_html(markdown, width=1024, height=768):
url = 'https://study-env.dingdaoos.com/api/markdown-to-html'
payload = {
'markdown': markdown,
'width': width,
'height': height
}
response = requests.post(url, json=payload)
if response.status_code == 200:
result = response.json()
if result['success']:
return result['html']
else:
raise Exception(result['error'])
else:
raise Exception(f'HTTP Error: {response.status_code}')
# 使用示例
markdown_content = """
# 数据报告
[chart:barh]| 部门 | 销售额 |
| --- | --- |
| 销售部 | 1250 |
| 市场部 | 980 |
"""
try:
html_output = convert_markdown_to_html(markdown_content)
print("转换成功!")
# 保存到文件或进一步处理
with open('output.html', 'w', encoding='utf-8') as f:
f.write(html_output)
except Exception as e:
print(f"转换失败: {e}")cURL
curl -X POST https://study-env.dingdaoos.com/api/markdown-to-html \
-H "Content-Type: application/json" \
-d '{
"markdown": "# Hello PSUIP\n\n这是一个简单的示例。\n\n[primary][开始使用](https://example.com)",
"width": 800,
"height": 600
}'错误处理
常见错误情况
-
Markdown 语法错误
- 卡片标签不匹配
- 布局标签嵌套错误
- 图表数据格式不正确
-
参数错误
- 缺少必填参数
markdown - 参数类型不正确
- JSON 格式错误
- 缺少必填参数
-
服务器错误
- 内存不足
- 渲染超时
- 依赖服务不可用
错误处理建议
- 验证输入:在发送请求前验证 Markdown 语法
- 异常捕获:使用 try-catch 处理网络和解析错误
- 重试机制:对于临时性错误实现重试逻辑
- 降级方案:提供基础的 Markdown 渲染作为后备
性能优化
请求优化
- 内容缓存:对相同内容使用客户端缓存
- 分批处理:大量内容分批处理
- 异步请求:使用异步方式避免阻塞
- 压缩传输:使用 gzip 压缩请求体
内容优化
- 图片压缩:使用适当尺寸的图片
- 数据精简:图表数据保持合理数量
- 布局简化:避免过度复杂的嵌套结构
- 缓存策略:实现内容级别的缓存机制
使用场景
1. 静态网站生成
// 批量转换 Markdown 文件为 HTML
const markdownFiles = await glob('content/**/*.md');
const htmlFiles = await Promise.all(
markdownFiles.map(async (file) => {
const markdown = await fs.readFile(file, 'utf-8');
const html = await convertMarkdownToHtml(markdown);
return { file, html };
})
);2. 实时预览
// 编辑器实时预览功能
let debounceTimer;
function onMarkdownChange(markdown) {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(async () => {
try {
const html = await convertMarkdownToHtml(markdown);
updatePreview(html);
} catch (error) {
showError(error.message);
}
}, 300);
}3. 内容管理系统
// CMS 中保存内容时预生成 HTML
async function saveContent(id, markdown) {
try {
const html = await convertMarkdownToHtml(markdown);
await database.save({
id,
markdown,
html,
updatedAt: new Date()
});
} catch (error) {
throw new Error(`保存失败: ${error.message}`);
}
}Last updated on