【问题标题】:JAVA- Best way to convert JSON to PDFJAVA - 将 JSON 转换为 PDF 的最佳方式
【发布时间】:2018-07-10 16:32:18
【问题描述】:

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

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

谢谢!

【问题讨论】:

  • 创建pdf的方法有很多。我建议您考虑的一件事是 json 和 pdf 之间的区别。
  • 创建pdf的方法有很多。我建议您考虑的一件事是 json 和 pdf 之间的区别。 Json 是一种数据格式,pdf 是一种文档格式。最大的不同是json是给电脑看的,pdf是给人看的。我建议为您的 pdf 设计一个不错的布局并使用从 json 提取的数据填充它,而不是显示 json 转储的 pdf。

标签: java json pdf spring-rest


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-08-14
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2010-09-27
    • 2012-02-29
    • 1970-01-01
    • 2021-08-24
    • 2013-06-23
    相关资源
    最近更新 更多