Swagger UI Export Documentation
Generate static HTML documentation
Using Swagger2markup
Swagger2markup is a tool that can convert Swagger JSON or YAML files into AsciiDoc or Markdown documents. Combined with AsciiDoctor, the documentation can be converted to HTML or PDF format.
Add Maven dependencies:
Example
<dependency>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup</artifactId>
<version>1.3.3</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>2.2.2</version>
<dependencies>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj-pdf</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>
<configuration>
<sourceDirectory>target/asciidoc</sourceDirectory>
<outputDirectory>target/generated-docs</outputDirectory>
<backend>html5</backend> <!-- or 'pdf' -->
<attributes>
<toc>left</toc>
<toclevels>3</toclevels>
</attributes>
</configuration>
</plugin>
</plugins>
</build>
Create a test class to generate documentation:
Example
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.URL;
import java.nio.file.Paths;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class SwaggerDocumentationTest {
@Test
public void generateAsciiDoc() throws Exception {
// Set output directory
final String outputDir = "target/asciidoc";
// Swagger2Markup configuration
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.ASCIIDOC)
.withOutputLanguage(java.util.Locale.CHINA)
.withGeneratedExamples()
.withPathsGroupedBy(io.github.swagger2markup.GroupBy.TAGS)
.build();
// Generate AsciiDoc files from OpenAPI JSON files
Swagger2MarkupConverter.from(new URL("http://localhost:8080/v3/api-docs"))
.withConfig(config)
.build()
.toFolder(Paths.get(outputDir));
}
}
Run the test and generate documentation:
# 生成 AsciiDoc mvn test # 将 AsciiDoc 转换为 HTML mvn asciidoctor:process-asciidoc # 生成的文档位于 target/generated-docs 目录
Generate PDF documentation
Using Asciidoctor-PDF
Based on the previously generated AsciiDoc files, you can use Asciidoctor-PDF to generate PDF documentation:
1. Modify Maven configuration:
Example
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>2.2.2</version>
<dependencies>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj-pdf</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>
<configuration>
<sourceDirectory>target/asciidoc</sourceDirectory>
<outputDirectory>target/generated-docs</outputDirectory>
<backend>pdf</backend>
<attributes>
<toc>left</toc>
<toclevels>3</toclevels>
<icons>font</icons>
<source-highlighter>coderay</source-highlighter>
<pagenums>true</pagenums>
<pdf-stylesdir>${project.basedir}/src/main/resources/theme</pdf-stylesdir>
<pdf-style>custom</pdf-style>
<pdf-fontsdir>${project.basedir}/src/main/resources/fonts</pdf-fontsdir>
</attributes>
</configuration>
</plugin>
Customize PDF stylesrc/main/resources/theme/custom-theme.yml:
Example
catalog:
# Chinese font configuration
Noto Sans SC:
normal: NotoSansSC-Regular.ttf
bold: NotoSansSC-Bold.ttf
italic: NotoSansSC-Regular.ttf
bold_italic: NotoSansSC-Bold.ttf
# English font configuration
Roboto:
normal: Roboto-Regular.ttf
bold: Roboto-Bold.ttf
italic: Roboto-Italic.ttf
bold_italic: Roboto-BoldItalic.ttf
fallbacks:
- Noto Sans SC
- Roboto
page:
layout: portrait
margin: [0.75in, 1in, 0.75in, 1in]
size: A4
base:
font_color: #333333
font_family: Noto Sans SC
font_size: 10
line_height_length: 17
line_height: $base_line_height_length / $base_font_size
title_page:
align: center
logo:
image: image:logo.png[pdfwidth=60%]
title:
top: 40%
font_size: 24
font_color: #262626
subtitle:
font_size: 18
font_style: bold_italic
font_color: #666666
authors:
font_size: 14
font_color: #181818
revision:
font_size: 12
font_color: #181818
header:
height: 0.75in
line_height: 1
border_color: #dddddd
border_width: 0.25
font_size: 10
background_color: #f5f5f5
padding: [4, 4, 4, 4]
vertical_align: middle
footer:
height: 0.75in
line_height: 1
border_color: #dddddd
border_width: 0.25
font_size: 10
padding: [4, 4, 4, 4]
vertical_align: middle
heading:
font_color: #262626
font_family: Roboto
h1_font_size: 18
h2_font_size: 16
h3_font_size: 14
h4_font_size: 12
h5_font_size: 10
h6_font_size: 10
line_height: 1.2
margin_bottom: $base_line_height_length
link:
font_color: #1565C0
code:
font_family: Courier
font_size: 9
background_color: #f5f5f5
border_color: #dddddd
border_radius: 4
Generate PDF documentation:
mvn asciidoctor:process-asciidoc@pdf
Use tools to export directly
Using the wkhtmltopdf tool
1. Install wkhtmltopdf:
# Ubuntu/Debian sudo apt-get install wkhtmltopdf # CentOS/RHEL sudo yum install wkhtmltopdf # macOS brew install wkhtmltopdf
2. Create an export scriptexport-docs.sh:
Example
# Set variables
SWAGGER_URL="http://localhost:8080/swagger-ui/index.html"
OUTPUT_DIR="./api-docs"
FILENAME="api-documentation.pdf"
HTML_FILENAME="api-documentation.html"
# Create output directory
mkdir -p $OUTPUT_DIR
# Use curl to download HTML documentation
echo Downloading Swagger UI HTML...
curl -s $SWAGGER_URL > $OUTPUT_DIR/$HTML_FILENAME
# Use wkhtmltopdf to generate PDF
echo Generating PDF documentation...
wkhtmltopdf \
--enable-javascript \
--javascript-delay 5000 \
--no-stop-slow-scripts \
--page-size A4 \
--title API Documentation \
--margin-top 20 \
--margin-right 20 \
--margin-bottom 20 \
--margin-left 20 \
--header-line \
--header-center API Documentation Center \
--footer-line \
--footer-center Page [page] / [topage] \
--footer-right Generation date:$(date +%Y-%m-%d)" \
$OUTPUT_DIR/$HTML_FILENAME $OUTPUT_DIR/$FILENAME
echo Document generated:
echo "HTML: $OUTPUT_DIR/$HTML_FILENAME"
echo "PDF: $OUTPUT_DIR/$FILENAME"
3. Run the script:
chmod +x export-docs.sh ./export-docs.sh
Export PDF using Puppeteer
For Node.js environments, you can use Puppeteer to export PDF.
1. Create an export scriptexport-pdf.js:
Example
const path = require('path');
const fs = require('fs');
(async () => {
// Create output directory
const outputDir = path.join(__dirname, 'api-docs');
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
// Launch browser
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Visit Swagger UI page
await page.goto('http://localhost:8080/swagger-ui/index.html', {
waitUntil: 'networkidle0',
timeout: 60000
});
// Wait for Swagger UI to finish loading
await page.waitForSelector('.swagger-ui .information-container', { timeout: 10000 });
// Expand all API nodes
await page.evaluate(() => {
document.querySelectorAll('.opblock').forEach(el => {
if (!el.classList.contains('is-open')) {
el.querySelector('.opblock-summary').click();
}
});
});
// Wait for expand animation to complete
await page.waitForTimeout(2000);
// Add custom header and footer styles
await page.addStyleTag({
content: `
@page {
margin: 20mm 15mm;
}
.page-header {
width: 100%;
text-align: center;
font-size: 16px;
color: #333;
padding: 10px 0;
border-bottom: 1px solid #ddd;
}
.page-footer {
width: 100%;
text-align: center;
font-size: 12px;
color: #666;
padding: 10px 0;
border-top: 1px solid #ddd;
}
`
});
// Generate PDF
await page.pdf({
path: path.join(outputDir, 'api-documentation.pdf'),
format: 'A4',
printBackground: true,
displayHeaderFooter: true,
headerTemplate: `<div class="page-header">API Documentation Center</div>`,
footerTemplate: `<div class="page-footer">
<span>Page number<span class="pageNumber"></span> / <span class="totalPages"></span></span>
<span style="margin-left: 20px;">Generation date: ${new Date().toLocaleDateString()}</span>
</div>`,
margin: {
top: '40px',
bottom: '40px',
left: '20px',
right: '20px'
}
});
// Generate HTML
const htmlContent = await page.content();
fs.writeFileSync(path.join(outputDir, 'api-documentation.html'), htmlContent);
// Close browser
await browser.close();
console.log('Document generated in directory:', outputDir);
})();
2. Install dependencies and run:
npm install puppeteer node export-pdf.js
Summary
Swagger UI is a powerful API documentation tool. With proper configuration and usage, it can greatly improve API usability and development efficiency.
Through the above content, we have learned about the basic concepts, integration methods, documentation writing, custom configuration, documentation publishing, style customization, and documentation export of Swagger UI.
Remember the following key points:
- Choose a Swagger integration method suitable for your project's technology stack
- Carefully design and write API documentation annotations or comments
- Customize Swagger UI interface and styles as needed
- Add branding to make the documentation more professional
- Choose appropriate documentation publishing and export methods
- Follow best practices to ensure documentation accuracy and security
By using Swagger UI appropriately, you can provide professional, interactive documentation for your API, making it easier to understand and use.
Other extensions