Swagger+spring boot 轉換為html,PDF文件等

前言

使用Swagger將Restlet APIs轉換為html和PDF文檔。

主要是使用Swagger2Markup。官網提供了兩種方式:
You can use Swagger2Markup to convert your contract-first Swagger YAML file into a human-readable format and combine it with hand-written documentation.

  1. you can choose the code-first approach and use Swagger2Markup together with Swagger JAX-RS, springfox or spring-restdocs.

  2. If you are Gradle or Maven user, you can also use the Swagger2Markup Gradle Plugin or Swagger2markup Maven Plugin.

我所使用的環境:Spring Boot + Gradle。
所以我使用的Swagger 是 springfox,如果你是Restlet JAX-RS等,可以使用restlet-framework(這些都可以在swagger的開源集合中找到)。

由于我的項目使用的是Gradle構建的,所以我使用的是Swagger2Markup Gradle Plugin。

官網提供了一個完整的Demo,可以生成html和pdf:http://swagger2markup.github.io/swagger2markup/1.3.1/#_demo

官方Demo是使用Swagger2Markup Gradle Plugin插件生成的,當然你也可以使用MAVEN插件,插件的使用例子如下:
Swagger2Markup Gradle Plugin:https://github.com/Swagger2Markup/swagger2markup-gradle-project-template
Swagger2Markup Maven Plugin:https://github.com/Swagger2Markup/swagger2markup-maven-project-template

轉換為 html或PDF的步驟

  1. 通過編寫junit測試類生成一個實時的swagger.json。
  2. 將swagger.json轉換為AsciiDoc。
  3. 增加AsciiDoc相關文檔,具體可以參考Swagger2Markup Gradle PluginSwagger2Markup Maven Plugin文檔。
  4. 將生成的asciiDoc通過AsciiDoc plugin轉換為HTML和PDF.
  5. 將生成的html和pdf拷貝到可執行的jar包中,并部署他就可以讓外界訪問了。
    (圖片來源:http://www.cnblogs.com/softidea/p/6251249.html
    Paste_Image.png

按照上述步驟開始編輯自己的應用。

1.在build.gradle中添加相關依賴和插件

buildscript {
    repositories {
        mavenCentral()
        //*********以下為swagger轉換 pdf需要************//
        jcenter()
        maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
        //*********以上為swagger轉換 pdf需要************//
        mavenLocal()
    }
    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE'
        //*********以下為swagger轉換 pdf需要************//
        //asciidoc 插件
        classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.3'
        classpath 'org.asciidoctor:asciidoctorj-pdf:1.5.0-alpha.10.1'
        //swagger2markup 插件
        classpath 'io.github.swagger2markup:swagger2markup-spring-restdocs-ext:1.2.0'
        classpath 'io.github.swagger2markup:swagger2markup-gradle-plugin:1.2.0'
        //*********以上為swagger轉換 pdf需要************//
    }
}

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'spring-boot'
//*********以下為swagger轉換 pdf需要************//
apply plugin: 'org.asciidoctor.convert'
apply plugin: 'io.github.swagger2markup'
apply plugin: 'io.spring.dependency-management'
//*********以上為swagger轉換 pdf需要************//

version = '1.2.0'

tasks.withType(JavaCompile) {
    sourceCompatibility = "1.8"
    targetCompatibility = "1.8"
    options.deprecation = true
}

repositories {
    mavenCentral()
    //*********以下為swagger轉換 pdf需要************//
    jcenter()
    maven { url 'https://repo.spring.io/snapshot' }
    maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
    //*********以上為swagger轉換 pdf需要************//
    mavenLocal()
}


ext {
    //設置springfox版本
    springfoxVersion = '2.5.0'
}

dependencies {
    //json
    compile "org.codehaus.jackson:jackson-mapper-asl:1.9.12"
    /*fastjson*/
    compile "com.alibaba:fastjson:1.1.39"
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.springframework.boot:spring-boot-starter-actuator'
    compile 'com.google.guava:guava:18.0'
    compile 'net.logstash.logback:logstash-logback-encoder:4.5.1'
    compile("com.fasterxml.jackson.dataformat:jackson-dataformat-smile:2.6.5")
    compile("com.fasterxml.jackson.module:jackson-module-afterburner:2.6.5")
    //*********以下為swagger轉換 pdf需要************//
    compile 'io.swagger:swagger-annotations:1.5.6'
    compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.6.1'
    compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.1'
    testCompile "io.springfox:springfox-bean-validators:${springfoxVersion}"
    testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc'
    //*********以上為swagger轉換 pdf需要************//
    testCompile 'org.springframework.boot:spring-boot-starter-test'
    testCompile 'junit:junit'
    testCompile 'com.fasterxml.jackson.module:jackson-module-jsonSchema:2.6.5'
}

2.在build.gradle中設置swagger.json和asciiDoc生成路徑,且配置到SystemProperty中,方便代碼中使用。

ext {
    //asciiDoc生成路徑
    asciiDocOutputDir = file("${buildDir}/asciidoc/generated")
    //swagger.json生成路徑
    swaggerOutputDir = file("${buildDir}/swagger")
    snippetsOutputDir = file("${buildDir}/asciidoc/snippets")
    //設置springfox版本
    springfoxVersion = '2.5.0'
}

test {
    //設置一些systemProperty
    systemProperty 'io.springfox.staticdocs.outputDir', swaggerOutputDir
    systemProperty 'io.springfox.staticdocs.snippetsOutputDir', snippetsOutputDir
    systemProperty 'io.springfox.staticdocs.asciiDocOutputDir',asciiDocOutputDir
}

3.編寫測試類生成swagger.json

也可以直接生成asciiDoc,跳過生成swagger.json然后通過swagger.json生成asciiDoc這一步,具體代碼請參考:http://swagger2markup.github.io/swagger2markup/1.3.1/#_spring_boot_and_springfox

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@AutoConfigureRestDocs(outputDir = "build/asciidoc/snippets")
@SpringBootTest(classes = {CommonToolsApplication.class, SwaggerAutoConfiguration.class})
@AutoConfigureMockMvc
public class Swagger2MarkupTest {

    private static final Logger LOG = LoggerFactory.getLogger(Swagger2MarkupTest.class);

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void createSpringfoxSwaggerJson() throws Exception {
        //String designFirstSwaggerLocation = Swagger2MarkupTest.class.getResource("/swagger.yaml").getPath();
        //獲取生成swagger.json路徑,已經在build.gradle中配置
        String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
        //本項目api路徑
        MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andReturn();

        MockHttpServletResponse response = mvcResult.getResponse();
        String swaggerJson = response.getContentAsString();
        Files.createDirectories(Paths.get(outputDir));
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)){
            writer.write(swaggerJson);
        }
    }
}

其中CommonToolsApplication為spring boot 啟動類,SwaggerAutoConfiguration為Swagger配置類

@SpringBootApplication
public class CommonToolsApplication {

    public static void main(String[] args) {
        SpringApplication.run(CommonToolsApplication.class, args);
    }
}
@Configuration
@EnableSwagger2
public class SwaggerAutoConfiguration {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //配置掃描的基礎包
                .apis(RequestHandlerSelectors.basePackage("com.ops.commons.web"))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2構建RESTful APIs")
                .description("Controller中入參最好使用SpringMVC注解:@RequestBody,@RequestParam,@PathVariable<br>"
                        + "返回使用@ResponseBody或者ResponseEntity,區別:ResponseEntity可以包含Header和HttpStatus")
                .version("1.0")
                .build();
    }
}

4.添加AsciiDoc相關文檔

打開官方Demo。將src/doc/asciidoc下面的文件拷貝到自己項目中。

5.將swagger.json生成asciiDoc文件

當增加Swagger2Markup Gradle Plugin插件時,他會自動增加一個convertSwagger2markup任務,當然你可以覆蓋他。
在build.gradle中覆寫convertSwagger2markup task:

convertSwagger2markup {
    //執行該task時先運行test,主要是運行Swagger2MarkupTest,讓其生成swagger.json
    dependsOn test
    //入參為swagger.json
    swaggerInput "${swaggerOutputDir}/swagger.json"
    outputDir asciiDocOutputDir
    config = [
            'swagger2markup.pathsGroupedBy' : 'TAGS',
            'swagger2markup.extensions.springRestDocs.snippetBaseUri': snippetsOutputDir.getAbsolutePath()]
}

6.將asciiDoc轉換為html和PDF。

在build.gradle中添加

asciidoctor {
    //依賴上面的swagger.json轉換為asciiDoc任務,方便直接運行該任務時,先運行convertSwagger2markup
    dependsOn convertSwagger2markup
    sources {
        include 'index.adoc'
    }
    backends = ['html5', 'pdf']
    attributes = [
            doctype: 'book',
            toc: 'left',
            toclevels: '3',
            numbered: '',
            sectlinks: '',
            sectanchors: '',
            hardbreaks: '',
            generated: asciiDocOutputDir
    ]
}

7.將生成的html和PDF拷貝到項目中

因為生成的文件時放在build下面的,拷貝到項目中,當啟動了項目后,用戶可以直接通過瀏覽器查看

jar {
    dependsOn asciidoctor
    //將生成的html和PDF拷貝到項目中
    from ("${asciidoctor.outputDir}/html5") {
        into 'static/docs'
    }
    from ("${asciidoctor.outputDir}/pdf") {
        into 'static/docs'
    }
}

ok,完成。

現在你可以運行gradle clean asciidoctor命令,查看生成的文檔了,html路徑:build\asciidoc\html5;pdf路徑:build\asciidoc\pdf。

完整build.gradle

buildscript {
    repositories {
        mavenCentral()
        //*********以下為swagger轉換 pdf需要************//
        jcenter()
        maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
        //*********以上為swagger轉換 pdf需要************//
        mavenLocal()
    }
    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE'
        //*********以下為swagger轉換 pdf需要************//
        //asciidoc 插件
        classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.3'
        classpath 'org.asciidoctor:asciidoctorj-pdf:1.5.0-alpha.10.1'
        //swagger2markup 插件
        classpath 'io.github.swagger2markup:swagger2markup-spring-restdocs-ext:1.2.0'
        classpath 'io.github.swagger2markup:swagger2markup-gradle-plugin:1.2.0'
        //*********以上為swagger轉換 pdf需要************//
    }
}

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'spring-boot'
//*********以下為swagger轉換 pdf需要************//
apply plugin: 'org.asciidoctor.convert'
apply plugin: 'io.github.swagger2markup'
apply plugin: 'io.spring.dependency-management'
//*********以上為swagger轉換 pdf需要************//

version = '1.2.0'

tasks.withType(JavaCompile) {
    sourceCompatibility = "1.8"
    targetCompatibility = "1.8"
    options.deprecation = true
    options.encoding = 'UTF-8'
    options.compilerArgs << "-Xlint:unchecked"
}

repositories {
    mavenCentral()
    //*********以下為swagger轉換 pdf需要************//
    jcenter()
    maven { url 'https://repo.spring.io/snapshot' }
    maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
    //*********以上為swagger轉換 pdf需要************//
    mavenLocal()
}


ext {
    //asciiDoc生成路徑
    asciiDocOutputDir = file("${buildDir}/asciidoc/generated")
    //swagger.json生成路徑
    swaggerOutputDir = file("${buildDir}/swagger")
    snippetsOutputDir = file("${buildDir}/asciidoc/snippets")
    //設置springfox版本
    springfoxVersion = '2.5.0'
}

dependencies {
    //servlet-api
    compile "javax.servlet:javax.servlet-api:3.1.0"
    //json
    compile "org.codehaus.jackson:jackson-mapper-asl:1.9.12"
    /*fastjson*/
    compile "com.alibaba:fastjson:1.1.39"
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.springframework.boot:spring-boot-starter-actuator'
    compile 'com.google.guava:guava:18.0'
    compile 'net.logstash.logback:logstash-logback-encoder:4.5.1'
    compile("com.fasterxml.jackson.dataformat:jackson-dataformat-smile:2.6.5")
    compile("com.fasterxml.jackson.module:jackson-module-afterburner:2.6.5")
    //*********以下為swagger轉換 pdf需要************//
    compile 'io.swagger:swagger-annotations:1.5.6'
    compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.6.1'
    compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.1'
    testCompile "io.springfox:springfox-bean-validators:${springfoxVersion}"
    testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc'
    //*********以上為swagger轉換 pdf需要************//
    testCompile 'org.springframework.boot:spring-boot-starter-test'
    testCompile 'junit:junit'
    testCompile 'com.fasterxml.jackson.module:jackson-module-jsonSchema:2.6.5'
}


test {
    //設置一些systemProperty
    systemProperty 'io.springfox.staticdocs.outputDir', swaggerOutputDir
    systemProperty 'io.springfox.staticdocs.snippetsOutputDir', snippetsOutputDir
    systemProperty 'io.springfox.staticdocs.asciiDocOutputDir',asciiDocOutputDir
}

convertSwagger2markup {
    //執行該task時先運行test,主要是運行Swagger2MarkupTest,讓其生成swagger.json
    dependsOn test
    swaggerInput "${swaggerOutputDir}/swagger.json"
    outputDir asciiDocOutputDir
    config = [
            'swagger2markup.pathsGroupedBy' : 'TAGS',
            'swagger2markup.extensions.springRestDocs.snippetBaseUri': snippetsOutputDir.getAbsolutePath()]
}

asciidoctor {
    //依賴上面的swagger.json轉換為asciiDoc任務,方便直接運行該任務時,先運行convertSwagger2markup
    dependsOn convertSwagger2markup
    sources {
        include 'index.adoc'
    }
    backends = ['html5', 'pdf']
    attributes = [
            doctype: 'book',
            toc: 'left',
            toclevels: '3',
            numbered: '',
            sectlinks: '',
            sectanchors: '',
            hardbreaks: '',
            generated: asciiDocOutputDir
    ]
}

jar {
    dependsOn asciidoctor
    //將生成的html和PDF拷貝到項目中
    from ("${asciidoctor.outputDir}/html5") {
        into 'static/docs'
    }
    from ("${asciidoctor.outputDir}/pdf") {
        into 'static/docs'
    }
}


參考文檔
官方文檔:http://swagger2markup.github.io/swagger2markup/1.3.1/
官方Demo:https://github.com/Swagger2Markup/spring-swagger2markup-demo
springfox官方文檔:http://springfox.github.io/springfox/docs/current/#usage-guide
http://www.cnblogs.com/softidea/p/6251249.html

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容