Swagger UI 导出文档

把规范导出成 PDF、HTML、Markdown,交给不装 Swagger UI 的读者。

Intermediate
Key Points导出本质是「把规范渲染成另一种静态格式」:PDF 靠浏览器打印,HTML/Markdown 靠 widdershins 或 redoc-cli。

三种导出方式

TargetToolCommand
HTML (single file)redoc-cliredoc-cli build openapi.yaml -o api.html
Markdownwiddershinswiddershins openapi.yaml -o api.md
PDFbrowser printSwagger UI → Ctrl/Cmd+P → Save as PDF

单文件 HTML

redoc-cli inlines the spec into one HTML file you can email; the consumer needs no environment at all.

Bash
npx redoc-cli build openapi.yaml -o api-docs.html --title "User API 1.0.0"

Markdown

Bash
npx widdershins --language_shell bash --summary openapi.yaml -o api.md

PDF 的正确做法

  1. 先用 docExpansion: full 打开全部接口,否则打印出来只有标题
  2. 隐藏顶部栏和「试一试」按钮:tryItOutEnabled: false
  3. 在打印 CSS 里去掉折叠箭头、展开全部 details
  4. 用 A4 横向,代码块加 page-break-inside: avoid
CSS
@media print {
  .swagger-ui .topbar, .swagger-ui .try-out, .swagger-ui .models { display: none; }
  .swagger-ui .opblock-body { display: block !important; }
  pre { page-break-inside: avoid; }
  @page { size: A4 landscape; margin: 12mm; }
}
Always stamp exported docs with the API version and generation time. After a PDF is forwarded three times, nobody knows which API version it describes.

放进 CI

YAML
- name: Export API docs
  run: |
    npx redoc-cli build openapi.yaml -o dist/api.html
    npx widdershins openapi.yaml -o dist/api.md
- uses: actions/upload-artifact@v4
  with:
    name: api-docs
    path: dist/

Friends & Partners