Swagger2实现API文档的静态部署并支持导出PDF

Swagger2实现API文档的静态部署并支持导出PDF

  • 如何使用
    • 1、导包
    • 2、加载配置类
    • 3、在Controller里使用
    • 4、运行项目
  • 静态部署
    • 1、引入依赖
    • 2、配置插件
    • 3、编写测试程序,用来生成adoc文件
    • 4、生成PDF文档并解决中文乱码问题
  • 参考

如何使用

1、导包

		<dependency>
			<groupId>io.springfoxgroupId>
			<artifactId>springfox-swagger2artifactId>
			<version>2.8.0version>
		dependency>
		<dependency>
			<groupId>io.springfoxgroupId>
			<artifactId>springfox-swagger-uiartifactId>
			<version>2.8.0version>
		dependency>

2、加载配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/swagger/**").addResourceLocations("classpath:/static/swagger/");
    }
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            //加了ApiOperation注解的类,才生成接口文档
            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            //包下的类,才生成接口文档
            .apis(RequestHandlerSelectors.basePackage("com.tpm.fis.modules"))
            .paths(PathSelectors.any())
            .build()
            .securitySchemes(security());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("API文档的标题 ")
            .description("SpringBoot+MyBatis+Vue")
            .termsOfServiceUrl("http://xxxx")
            .version("3.0")
            .build();
    }
}

3、在Controller里使用

/**
 * 系统配置信息
 * 
 * @author
 * @email
 * @date 2016年12月4日 下午6:55:53
 */
@RestController
@RequestMapping("/sys/config")
@Api(tags = "i、参数管理", description = " ")
public class SysConfigController extends AbstractController {
	@Autowired
	private SysConfigService sysConfigService;
	
	/**
	 * 所有配置列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("sys:config:list")
	@ApiOperation(value = "参数列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "page", value = "页码",  dataType = "int", required = true,paramType = "query", defaultValue = "1"),
			@ApiImplicitParam(name = "limit", value = "每页条数",  dataType = "int", required = true,paramType = "query", defaultValue = "10"),
			@ApiImplicitParam(name = "sidx", value = "排序字段",  dataType = "String", required = false,paramType = "query" ),
			@ApiImplicitParam(name = "order", value = "排序方式,如:asc、desc",  dataType = "String", required = false,paramType = "query"),
			@ApiImplicitParam(name = "key", value = "参数名",  dataType = "String", required = false,paramType = "query")
	})
	public R list(@RequestParam Map<String, Object> params){
		PageUtils page = sysConfigService.queryPage(params);

		return R.ok().put("page", page);
	}
	
	
	/**
	 * 配置信息
	 */
	@GetMapping("/info/{id}")
	@RequiresPermissions("sys:config:info")
	@ApiOperation(value = "获取参数信息")
	public R info(@PathVariable("id") Long id){
		SysConfigEntity config = sysConfigService.selectById(id);
		
		return R.ok().put("config", config);
	}
	
	/**
	 * 保存配置
	 */
	@SysLog("保存配置")
	@PostMapping("/save")
	@RequiresPermissions("sys:config:save")
	@ApiOperation(value = "添加参数")
	public R save(@RequestBody SysConfigEntity config){
		ValidatorUtils.validateEntity(config);

		sysConfigService.save(config);
		
		return R.ok();
	}
	
	/**
	 * 修改配置
	 */
	@SysLog("修改配置")
	@PostMapping("/update")
	@RequiresPermissions("sys:config:update")
	@ApiOperation(value = "修改参数")
	public R update(@RequestBody SysConfigEntity config){
		ValidatorUtils.validateEntity(config);
		
		sysConfigService.update(config);
		
		return R.ok();
	}
	
	/**
	 * 删除配置
	 */
	@SysLog("删除配置")
	@PostMapping("/delete")
	@RequiresPermissions("sys:config:delete")
	@ApiOperation(value = "删除参数")
	public R delete(@RequestBody Long[] ids){
		sysConfigService.deleteBatch(ids);
		
		return R.ok();
	}

}

4、运行项目

浏览器输入http://localhost:8080/swagger-ui.html看看吧

静态部署

1、引入依赖

        <dependency>
            <groupId>io.github.swagger2markupgroupId>
            <artifactId>swagger2markupartifactId>
            <version>1.3.1version>
        dependency>
        <dependency>
            <groupId>org.asciidoctorgroupId>
            <artifactId>asciidoctorj-pdfartifactId>
            <version>1.5.0-alpha.10.1version>
            <scope>testscope>
        dependency>

2、配置插件

   <plugin>
                <groupId>io.github.swagger2markupgroupId>
                <artifactId>swagger2markup-maven-pluginartifactId>
                <version>1.3.1version>
                <configuration>
                    <swaggerInput>http://localhost:8080/v2/api-docsswaggerInput>
                    <outputDir>src/docs/asciidoc/generatedoutputDir>
                    <config>
                        <swagger2markup.markupLanguage>ASCIIDOCswagger2markup.markupLanguage>
                    config>
                configuration>
            plugin>
            <plugin>
                <groupId>org.asciidoctorgroupId>
                <artifactId>asciidoctor-maven-pluginartifactId>
                <version>1.5.6version>
                <configuration>
                    <sourceDirectory>src/docs/asciidoc/generatedsourceDirectory>
                    <outputDirectory>src/docs/asciidoc/htmloutputDirectory>
                    <backend>htmlbackend>
                    <sourceHighlighter>coderaysourceHighlighter>
                    <attributes>
                        <toc>lefttoc>
                    attributes>
                configuration>
            plugin>

3、编写测试程序,用来生成adoc文件

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DemoApplicationTests {

    @Test
    public void generateAsciiDocs() throws Exception {
        //    输出Ascii格式
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withGeneratedExamples()
                .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
                .build();

        Swagger2MarkupConverter.from(new URL("http://localhost:8093/Kanban/v2/api-docs"))
                .withConfig(config)
                .build()
                .toFile(Paths.get("src/docs/asciidoc/generated/api"));
    }
    @Test
    public void generatePDF() {
        //样式
        String style = "pdf-style=E:\\themes\\theme.yml";
        //字体
        String fontsdir = "pdf-fontsdir=E:\\fonts";
        //需要指定adoc文件位置
        String adocPath = "D:\\workspace\\work\\intellijidea\\Kanban\\src\\docs\\asciidoc\\generated\\api.adoc";
        AsciidoctorInvoker.main(new String[]{"-a",style,"-a",fontsdir,"-b","pdf",adocPath});
    }
}

4、生成PDF文档并解决中文乱码问题

1、把https://github.com/asciidoctor/asciidoctor这个项目download下来,把目录下的data目录拷贝到E盘根目录下(当然哪都行啦)
2、去下载一个中文字体,后缀是.ttf结尾的,放到data/fonts目录里
3、复制data/themes/default-theme.yml为theme.yml,打开theme.yml并搜索mplus1p开头的文件名,换成5.2下载的中文字体
4、运行测试程序中的generatePDF生成pdf文件

参考

史上最简单的Swagger2实现API文档的静态部署并支持导出PDF并解决中文乱码问题

你可能感兴趣的:(Swagger2实现API文档的静态部署并支持导出PDF)