java - JAVA - 将 JSON 转换为 PDF 的最佳方式
问题描述
我有一个将 JSON 作为输出发送的 RESTFul Web 服务,但现在我需要修改该服务以返回 PDF [基本上将 JSON 转换为 PDF] 我已经阅读了许多帖子,其中指出将 JSON 转换为 XML,然后转换为 PDF 文档。
有没有更好的方法可以让我的服务直接将 JSON 转换为 PDF 并将该 PDF 作为响应发送。
谢谢!
解决方案
添加以下 Maven 依赖项:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.56</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
使用 Gson 美化您的 JSON:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);
使用以下脚本创建 PDF 文件:
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("myJSON.pdf"));
document.open();
Font font = FontFactory.getFont(FontFactory.COURIER, 16, BaseColor.BLACK);
Chunk chunk = new Chunk(prettyJsonString, font);
document.add(chunk);
document.close();
推荐阅读
- javascript - 如何获取 Google 表单字段值并在 Appscript 中使用它来发送电子邮件
- c# - 如何在 UserControl 中创建大小一致的内部矩形?
- javascript - 从nodeJS连接到mysql,完全没有依赖关系
- qt - Mac 上的 Qt/Qml 应用程序窗口标题
- python - Sorted(list, key=itemgetter) 未在 Python 中正确排序项目列表
- python - 选择在字符串中包含值的行
- npm - Yarn Workspace,如何排除 node_modules 中的包文件?
- extjs4.2 - Extjs 4.2:如何在网格行编辑中使用多行行(换行列/行)动态设置按钮位置?
- amazon-web-services - 为什么我在 vpc 内的 lambda 可以从 vpc 外的 lambda 访问?
- r - as.POSIX 错误,无法转换特定日期