欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

利用swagger导出项目HTML和PDF离线api文档,解决pdf中文不全问题

程序员文章站 2024-01-27 17:25:58
...
  1. 程序结构
    利用swagger导出项目HTML和PDF离线api文档,解决pdf中文不全问题
  2. maven配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<artifactId>swagger-offline</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>swagger-offline</name>
	<description>生成离线的HTML和PDF api文档</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.10.RELEASE</version>
		<relativePath/>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>

		<snippetsDirectory>${project.build.directory}/generated-snippets</snippetsDirectory>
		<asciidoctor.input.directory>${project.basedir}/docs/asciidoc</asciidoctor.input.directory>
		<generated.asciidoc.directory>${project.build.directory}/asciidoc</generated.asciidoc.directory>
		<asciidoctor.html.output.directory>${project.build.directory}/asciidoc/html</asciidoctor.html.output.directory>
		<asciidoctor.pdf.output.directory>${project.build.directory}/asciidoc/pdf</asciidoctor.pdf.output.directory>
	</properties>

	<dependencies>

		<!--fastjson依赖-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.46</version>
		</dependency>

		<!--spring-boot依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<!--测试依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<!--web支持-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!--swagger2依赖-->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.6.1</version>
		</dependency>

		<!--swagger2-ui依赖-->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.6.1</version>
		</dependency>

		<!--离线文档-->
		<dependency>
			<groupId>org.springframework.restdocs</groupId>
			<artifactId>spring-restdocs-mockmvc</artifactId>
			<version>1.1.2.RELEASE</version>
			<scope>test</scope>
		</dependency>

		<!--生成静态文档-->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-staticdocs</artifactId>
			<version>2.6.1</version>
		</dependency>

		<!--lombok依赖-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.20</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<!--Maven通过Maven Surefire Plugin插件执行单元测试-->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
			</plugin>
			<!--通过Asciidoctor使得asciidoc生成其他的文档格式,例如:PDF 或者HTML5-->
			<plugin>
				<groupId>org.asciidoctor</groupId>
				<artifactId>asciidoctor-maven-plugin</artifactId>
				<version>1.5.3</version>
				<!--生成PDF-->
				<dependencies>
					<dependency>
						<groupId>org.asciidoctor</groupId>
						<artifactId>asciidoctorj-pdf</artifactId>
						<version>1.5.0-alpha.14</version>
					</dependency>
					<!-- Comment this section to use the default jruby artifact provided by the plugin -->
					<dependency>
						<groupId>org.jruby</groupId>
						<artifactId>jruby-complete</artifactId>
						<version>1.7.21</version>
					</dependency>
				</dependencies>

				<!--文档生成配置-->
				<configuration>
					<sourceDirectory>${asciidoctor.input.directory}</sourceDirectory>
					<sourceDocumentName>index.adoc</sourceDocumentName>
					<attributes>
						<doctype>book</doctype>
						<toc>left</toc>
						<toclevels>3</toclevels>
						<numbered></numbered>
						<hardbreaks></hardbreaks>
						<sectlinks></sectlinks>
						<sectanchors></sectanchors>
						<generated>${generated.asciidoc.directory}</generated>
					</attributes>
				</configuration>
				<!--因为每次执行只能处理一个后端,所以对于每个想要的输出类型,都是独立分开执行-->
				<executions>
					<!--html5-->
					<execution>
						<id>output-html</id>
						<phase>test</phase>
						<goals>
							<goal>process-asciidoc</goal>
						</goals>
						<configuration>
							<backend>html5</backend>
							<outputDirectory>${asciidoctor.html.output.directory}</outputDirectory>
						</configuration>
					</execution>
					<!--pdf-->
					<execution>
						<id>output-pdf</id>
						<phase>test</phase>
						<goals>
							<goal>process-asciidoc</goal>
						</goals>
						<configuration>
							<backend>pdf</backend>
							<outputDirectory>${asciidoctor.pdf.output.directory}</outputDirectory>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

</project>

  1. index.adoc

路径:项目名/docs/asciidoc/index.adoc

include::{generated}/overview.adoc[]
include::{generated}/definitions.adoc[]
include::{generated}/paths.adoc[]
  1. Swagger2配置
package com.yy.offline.config;

import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.yy.offline.controller"))
                    .paths(PathSelectors.any())
                    .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot利用swagger构建api文档,可以导出离线的HTML和PDF文档")
                .description("简单优雅的restfun风格")
                .termsOfServiceUrl("https://www.baidu.com/")
                .contact("baidu")
                .version("1.0")
                .build();
    }
}

  1. 实体类
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
 
@ApiModel(value = "User", description = "用户信息描述")
public class User {
    /**
     * 学号
     */
    @ApiModelProperty("证件号")
    private int id;
    /**
     * 姓名
     */
    @ApiModelProperty("姓名")
    private String name;
    /**
     * 年龄
     */
    @ApiModelProperty("年龄")
    private int age;
    /**
     * 性别
     */
    @ApiModelProperty("性别")
    private String sex;
    /**
     * 住址
     */
    @ApiModelProperty("家庭住址")
    private String address;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}
  1. Controller
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
/**
 1. @Title:
 2. @ClassName: UserController.java
 3. @Description:
 4.  5. @Copyright 2016-2018 - Powered By 研发中心
 6. @author: 王延飞
 7. @date:  2018-01-22 16:08
 8. @version V1.0
 */
@Controller
@RequestMapping(value = "/user", produces =  MediaType.APPLICATION_JSON_VALUE)
@Api(value = "用户信息查询", description = "用户基本信息操作API", tags = "UserApi", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public class UserController {
    @ApiOperation(value = "/getUser", notes = "根据姓名查询用户信息")
    @RequestMapping(value = "getUser", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public User getUser(@RequestParam("name") String name){
        User user = new User();
        user.setId(123456);
        user.setName(name);
        user.setAge(25);
        user.setAddress("河南郑州");
        user.setSex("男");
        return user;
    }
    @ApiOperation(value = "/addUser", notes = "添加一个用户")
    @RequestMapping(value = "addUser", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public User addUser(@RequestBody User user){
        return user;
    }
}
  1. 测试类
package com.yy.offline;

import com.alibaba.fastjson.JSON;
import com.yy.offline.pojo.User;
import io.github.robwin.markup.builder.MarkupLanguage;
import io.github.robwin.swagger2markup.GroupBy;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import springfox.documentation.staticdocs.SwaggerResultHandler;

import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@AutoConfigureMockMvc
@AutoConfigureRestDocs(outputDir = "target/generated-snippets")
@RunWith(SpringRunner.class)
@SpringBootTest
public class Swagger2OfflineApplicationTests {

	private String snippetDir = "target/generated-snippets";
	private String outputDir  = "target/asciidoc";
	@Autowired
	private MockMvc mockMvc;
	@After
	public void Test() throws Exception {
		// 得到swagger.json,写入outputDir目录中
		mockMvc.perform(get("/v2/api-docs").accept(MediaType.APPLICATION_JSON))
				.andDo(SwaggerResultHandler.outputDirectory(outputDir).build())
				.andExpect(status().isOk())
				.andReturn();
		// 读取上一步生成的swagger.json转成asciiDoc,写入到outputDir
		// 这个outputDir必须和插件里面<generated></generated>标签配置一致
		Swagger2MarkupConverter.from(outputDir + "/swagger.json")
				.withPathsGroupedBy(GroupBy.TAGS)// 按tag排序
				.withMarkupLanguage(MarkupLanguage.ASCIIDOC)// 格式
				.withExamples(snippetDir)
				.build()
				.intoFolder(outputDir);// 输出
	}

	@Test
	public void addUserTest() throws Exception{
		User user = new User();
		user.setId("123");
		user.setName("FLY");
		user.setAge(25);
		mockMvc.perform(post("/user/addUser").contentType(MediaType.APPLICATION_JSON)
				.content(JSON.toJSONString(user))
				.accept(MediaType.APPLICATION_JSON))
				.andExpect(status().is2xxSuccessful())
				.andDo(MockMvcRestDocumentation.document("addUser", preprocessResponse(prettyPrint())));
	}

	@Test
	public void getUserTest() throws Exception {
		mockMvc.perform(get("/user/getUser").param("name", "FLY")
				.accept(MediaType.APPLICATION_JSON))
				.andExpect(status().isOk())
				.andDo(MockMvcRestDocumentation.document("getUser", preprocessResponse(prettyPrint())));

	}

}

  1. 测试

mvn clean test

生成的PDF和HTML文件:target/asciidoc/html and target/asciidoc/pdf
  1. html
    利用swagger导出项目HTML和PDF离线api文档,解决pdf中文不全问题

  2. pdf
    利用swagger导出项目HTML和PDF离线api文档,解决pdf中文不全问题

  3. pdf中文不全

修改jar包

利用swagger导出项目HTML和PDF离线api文档,解决pdf中文不全问题

替换字体文件
利用swagger导出项目HTML和PDF离线api文档,解决pdf中文不全问题
修改主题配置文件
default-theme.yml配置文件
利用swagger导出项目HTML和PDF离线api文档,解决pdf中文不全问题
修改完,运行命令

mvn asciidoctor:process-asciidoc
mvn generate-resources

可以看到,新生成的PDF文件没有再出现乱码和字体丢失现象,问题完美解决!

源码:https://github.com/yy19951002/test/tree/master/swagger-offline