首页 > 解决方案 > JAVA - 将 JSON 转换为 PDF 的最佳方式

问题描述

我有一个将 JSON 作为输出发送的 RESTFul Web 服务,但现在我需要修改该服务以返回 PDF [基本上将 JSON 转换为 PDF] 我已经阅读了许多帖子,其中指出将 JSON 转换为 XML,然后转换为 PDF 文档。

有没有更好的方法可以让我的服务直接将 JSON 转换为 PDF 并将该 PDF 作为响应发送。

谢谢!

标签: javajsonpdfspring-rest

解决方案


添加以下 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();

推荐阅读