通过swagger2markup+asciidoctorj生成html和pdf文档并解决asciidoctorj生成的pdf文件中文显示不全问题(maven方式及java代码方式)
通过swagger2markup+asciidoctorj生成html和pdf文档(maven方式及java代码方式)
任务:通过同事的json文件生成相应的html和pdf文档
前言
开始时swagger2markup和asciidoctorj是什么都不知道,只能百度,看官方文档(翻译。。。),
遇到问题就一头雾水,完全不知道哪里出了问题,要怎么决解,百度上资料(中文?)也是寥寥无几,maven
也是没有系统学习过,导致很多小问题到了自己这里变成了大麻烦。在经历了一个星期的摸索,终于小有所成,
在此写下自己呕心沥血的过程,以免日后自己忘了,也给其他同僚多一份可以参考的资料。
如果有写的不好的地方,还望指出。
以下是我经历一个星期的各种碰撞过程
- 使用maven插件方法生成html和pdf文件(json文件生成adoc文件,adoc文件再生成html和pdf文件)
- 使用java代码方式生成adoc文件
- 使用java代码方式调用cmd执行mvn test命令生成html和pdf文件
出现问题:生成的pdf中文显示不全
解决:
- 使用asciidoctorj工具(单独)在cmd里生成pdf文件
- 使用java代码方式直接生成pdf文件(需adoc文件)
目录
生成html和pdf文档
1、使用maven插件方法生成html和pdf文件 (json文件生成adoc文件, adoc文件再生成html和pdf文件)
- 导入eclipse后发现只有几个可用
- 可以看到pom.xml文件内有如下配置文件
<!-- 一些参数 -->
<properties>
<java.version>1.8</java.version>
<swagger2markup.version>1.2.0</swagger2markup.version>
<asciidoctor.input.directory>${project.basedir}/src/docs/asciidoc</asciidoctor.input.directory>
<swagger.output.dir>${project.build.directory}/swagger</swagger.output.dir>
<swagger.snippetOutput.dir>${project.build.directory}/asciidoc/snippets</swagger.snippetOutput.dir>
<generated.asciidoc.directory>${project.build.directory}/asciidoc/generated</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>
<swagger.input>${swagger.output.dir}/swagger.json</swagger.input>
</properties>
<!-- 首先是两个远程仓库 -->
<pluginRepositories>
<pluginRepository>
<id>jcenter-snapshots</id>
<name>jcenter</name>
<url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url>
</pluginRepository>
<pluginRepository>
<id>jcenter-releases</id>
<name>jcenter</name>
<url>http://jcenter.bintray.com</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<repositories>
<repository>
<id>jcentral</id>
<name>bintray</name>
<url>http://jcenter.bintray.com</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>jcenter-snapshots</id>
<name>jcenter</name>
<url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url>
</repository>
</repositories>
<!-- 以下用于生成adoc文件的配置 -->
<plugin>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup-maven-plugin</artifactId>
<version>${swagger2markup.version}</version>
<dependencies>
<dependency>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup-import-files-ext</artifactId>
<version>${swagger2markup.version}</version>
</dependency>
<dependency>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup-spring-restdocs-ext</artifactId>
<version>${swagger2markup.version}</version>
</dependency>
</dependencies>
<configuration>
<swaggerInput>${swagger.input}</swaggerInput>
<outputDir>${generated.asciidoc.directory}</outputDir>
<config>
<swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage>
<swagger2markup.pathsGroupedBy>TAGS</swagger2markup.pathsGroupedBy>
<swagger2markup.extensions.dynamicOverview.contentPath>${project.basedir}/src/docs/asciidoc/extensions/overview</swagger2markup.extensions.dynamicOverview.contentPath>
<swagger2markup.extensions.dynamicDefinitions.contentPath>${project.basedir}/src/docs/asciidoc/extensions/definitions</swagger2markup.extensions.dynamicDefinitions.contentPath>
<swagger2markup.extensions.dynamicPaths.contentPath>${project.basedir}/src/docs/asciidoc/extensions/paths</swagger2markup.extensions.dynamicPaths.contentPath>
<swagger2markup.extensions.dynamicSecurity.contentPath>${project.basedir}src/docs/asciidoc/extensions/security/</swagger2markup.extensions.dynamicSecurity.contentPath>
<swagger2markup.extensions.springRestDocs.snippetBaseUri>${swagger.snippetOutput.dir}</swagger2markup.extensions.springRestDocs.snippetBaseUri>
<swagger2markup.extensions.springRestDocs.defaultSnippets>true</swagger2markup.extensions.springRestDocs.defaultSnippets>
</config>
</configuration>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>convertSwagger2markup</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- 以下配置用于生成html和pdf -->
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.3</version>
<dependencies>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj-pdf</artifactId>
<version>1.5.0-alpha.10.1</version>
</dependency>
<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>
<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>
<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>
- 将以上配置放入pom.xml后替换你的json文件到
${project.build.directory}1/swagger/swagger.json
- 运行maven test后将在
${project.build.directory}/asciidoc/html
和${project.build.directory}/asciidoc/pdf
目录下分别生成html和pdf文件
可能出现的异常
1.[ERROR] Failed to execute goal io.github.swagger2markup:swagger2markup-maven-plugin:1.2.0:convertSwagger2markup (default) on project csdnTest: Execution default of goal io.github.swagger2markup:swagger2markup-maven-plugin:1.2.0:convertSwagger2markup failed: Unable to load the mojo 'convertSwagger2markup' in the plugin 'io.github.swagger2markup:swagger2markup-maven-plugin:1.2.0' due to an API incompatibility: org.codehaus.plexus.component.repository.exception.ComponentLookupException: io/github/swagger2markup/Swagger2MarkupMojo : Unsupported major.minor version 52.0
<!-- 请使用JDK 1.8版本 -->
附图
1.新建一个maven项目
2.更改或添加至如下
pom.xml内容上面已经给出,你可能需要自己添加以下等配置
<build>
<plugins>
</plugins>
</build>
index.adoc文件内容为
include::{generated}/overview.adoc[]
include::{generated}/paths.adoc[]
include::{generated}/security.adoc[]
include::{generated}/definitions.adoc[]
swagger.json文件替换成你的文件
可参考:http://petstore.swagger.io/v2/swagger.json
3.执行以下操作后等程序运行完再刷新一下就能看到生成的文档了
2、使用java代码方式生成adoc文件
使用代码的方式相对较为灵活,下面上代码
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
public class Swagger2Markup {
//指定adoc文件生成路径
public Path outputDirectory = Paths.get("target/asciidoc/generated");
//通过配置文件生成swagger2markup的参数
public Swagger2MarkupConfig config;
public Swagger2Markup(String Json) throws Exception{
//读取配置文件
Configuration configuration = new Configurations().properties("config.properties");
config = new Swagger2MarkupConfigBuilder(configuration).build();
if(Json.startsWith("http")){
//获取远程json数据
createAdocFile(new URL(Json));
}else{
//获取本地json数据
createAdocFile(Paths.get(Json));
}
}
/**
* 通过url生成adoc文件
*/
public void createAdocFile(URL remoteSwaggerFile){
Swagger2MarkupConverter.from(remoteSwaggerFile)
.withConfig(config)
.build()
.toFolder(outputDirectory);
}
/**
* 通过json文件生成adoc文件
*/
public void createAdocFile(Path localSwaggerFile){
Swagger2MarkupConverter.from(localSwaggerFile)
.withConfig(config)
.build()
.toFolder(outputDirectory);
}
public static void main(String[] args) throws Exception{
//指定本地json文件路径
new Swagger2Markup("target/swagger/swagger.json");
//指定远程json文件路径
// new Swagger2Markup("http://petstore.swagger.io/v2/swagger.json");
}
}
config.properties文件内容如下
swagger2markup.markupLanguage = ASCIIDOC
swagger2markup.outputLanguage = EN
pom.xml文件内容:
<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>
<groupId>swaggerTest</groupId>
<artifactId>swaggerTest</artifactId>
<version>1.0</version>
<repositories>
<repository>
<id>jcentral</id>
<name>bintray</name>
<url>http://jcenter.bintray.com</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>jcenter-snapshots</id>
<name>jcenter</name>
<url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
</project>
运行main方法后将会在target/asciidoc/generated/下生成4个adoc文件
附图
3、使用代码方式调用cmd执行mvn test命令生成html和pdf文件
在用代码方式生成adoc文件之后就想着能不能再用代码的方式省略掉手工步骤,结果苦寻无门,最后想出了最笨的方法算是实现了。。。
结构图
文件内容
Swagger2Markup文件内容
package com.swaggerTest.base;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Paths;
public class Swagger2Markup {
public Swagger2Markup() throws Exception{
createHtmlFile();
}
/**
* 创建html和pdf文件
* @throws Exception
*/
public void createHtmlFile() throws Exception{
//获取pom.xml的绝对路径
String path = returnPath("pom.xml");
//生成bat文件的内容
StringBuilder batFileContent = new StringBuilder(path.substring(0, 2)).append("\r\n");
batFileContent.append("cd ").append(path.substring(0,path.length()-7)).append("\r\n");
batFileContent.append("mvn test");
//写入到bat文件
writeInBatFile("src/cmd/bat.bat",batFileContent.toString().replace("/", "\\"));
//生成vbs文件内容
StringBuilder vbsFileContent = new StringBuilder("Set ws = CreateObject(\"Wscript.Shell\")").append("\r\n");
vbsFileContent.append("ws.run \"cmd /c ").append(returnPath("src/cmd/bat.bat").replace("/", "\\")).append("\",vbhide");
//写入vbs文件
writeInBatFile("src/cmd/vbs.vbs",vbsFileContent.toString());
//生成执行vbs文件命令(用vbs隐藏bat文件执行时的窗口)
StringBuilder cmd = new StringBuilder("cmd /c CScript ").append(returnPath("src/cmd/vbs.vbs"));
System.out.println(cmd.toString());
Process process = Runtime.getRuntime().exec(cmd.toString());
System.out.println(process.waitFor());
}
/**
* 生成文件
* @param content
*/
public void writeInBatFile(String fileName,String content){
File batFile = new File(returnPath(fileName));
//如果文件存在,则删除
if(batFile != null && batFile.exists()){
batFile.delete();
}
try {
//创建gbk格式的文件(utf-8中文在cmd里乱码)
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(batFile),"GBK");
BufferedWriter bw = new BufferedWriter(out);
bw.write(content);
bw.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取指定文件路径
* @param filePath
* @return
*/
public String returnPath(String filePath){
return Paths.get(filePath).toAbsolutePath().toString();
}
public static void main(String[] args) throws Exception{
new Swagger2Markup();
}
}
pom.xml文件内容
<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>
<groupId>swaggerTest</groupId>
<artifactId>swaggerTest</artifactId>
<version>1.0</version>
<properties>
<asciidoctor.input.directory>${project.basedir}/src/docs/asciidoc</asciidoctor.input.directory>
<generated.asciidoc.directory>${project.build.directory}/asciidoc/generated</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>
<repositories>
<repository>
<id>jcentral</id>
<name>bintray</name>
<url>http://jcenter.bintray.com</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>jcenter-snapshots</id>
<name>jcenter</name>
<url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.3</version>
<dependencies>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj-pdf</artifactId>
<version>1.5.0-alpha.10.1</version>
</dependency>
<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>
<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>
<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>
index.adoc文件内容不变
include::{generated}/overview.adoc[]
include::{generated}/paths.adoc[]
include::{generated}/security.adoc[]
include::{generated}/definitions.adoc[]
asciidoc/generated/下的四个文件是上一节生成的。
运行main方法后刷新一下(生成pdf时间比较久)
解决上面生成的pdf文件中文显示不全问题
1、使用asciidoctorj工具(单独)在cmd里生成pdf文件
首先需要安装一个 Chocolatey (不想安装的可以跳过看下一个节点)
使用cmd.ext进行安装,运行一下命令
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
安装好后安装asciidoctorj
C:\> choco install asciidoctorj
C:\> where asciidoctorj
C:\ProgramData\chocolatey\bin\asciidoctorj.exe 进入asciidoctorj目录
C:\> asciidoctorj -b pdf index.adoc 生成pdf文件
如果全部安装完成后可以参考https://github.com/asciidoctor/asciidoctor-pdf/blob/master/docs/theming-guide.adoc#custom-fonts
在C:\ProgramData\chocolatey\lib\asciidoctorj\tools\asciidoctorj-1.5.6\lib目录下有一个asciidoctorj-pdf-1.5.0-alpha.16.jar文件
将gems\asciidoctor-pdf-1.5.0.alpha.16\data下的fonts文件夹和gems\asciidoctor-pdf-1.5.0.alpha.16\data\themes下的default-theme.yml文件复制到本地
替换fonts里的四个文件(正常字体,斜体,粗体,粗斜体)或者修改theme.yml(default-theme.yml)文件指向的字体
替换好后在cmd上运行命令 :
asciidoctorj -a pdf-style=d:\pdfTest\theme.yml -a pdf-fontsdir=d:\pdfTest\fonts -b pdf d:\pdfTest\index.adoc
将会在当前目录下生成pdf文件
2、使用java代码方式直接生成pdf文件(需adoc文件)
在用cmd运行的时候出现错误,发现其调用的是class文件,然后想着手动去调用他的main方法。
pom.xml文件需要添加依赖
<dependencies>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj-pdf</artifactId>
<version>1.5.0-alpha.10.1</version>
</dependency>
</dependencies>
代码部分,重点是最后一行就可以了
//样式
String style = "pdf-style=d:\\pdfTest\\theme.yml";
//字体
String fontsdir = "pdf-fontsdir=d:\\pdfTest\\fonts";
//需要指定adoc文件位置
String adocPath = "d:\\pdfTest\\index.adoc";
org.asciidoctor.cli.AsciidoctorInvoker.main(new String[]{"-a",style,"-a",fontsdir,"-b","pdf",adocPath});
- ${project.build.directory}是maven生成的文件的根目录:target的绝对路径 ↩