以 byte[]/JSON 形式发送 PDF 问题

发布于 2024-12-03 02:15:47 字数 520 浏览 1 评论 0原文

我正在尝试将生成的 PDF 文件(Apache FOP)发送给客户端。我知道这可以通过将数组写入响应流并在 servlet 中设置正确的内容类型、长度等来完成。我的问题是整个应用程序是基于它只会接收/发送 JSON 的想法构建的。在servlet的service()方法中,我有这样的:

  response.setContentType("application/json");
  reqBroker.process(request, response);

RequestBroker是处理JSON的类(杰克逊处理器),一切都是通用的,我无法更改它。最重要的是,我必须正确接收请求中的 JSON,才能访问数据并生成 pdf。所以这两行是必要的。但是当我发送响应时,我需要另一种内容类型,以便 pdf 在浏览器中正确显示。 到目前为止,我能够将字节数组作为 JSON 的一部分发送,但是我不知道如何在客户端上将数组显示为 PDF(如果这样的方式可能的话)。 我想要一些关于如何发送 pdf 并设置正确的标题而不弄乱 JSON 的建议。谢谢。

I am trying to send a generated PDF file (Apache FOP) to the client. I know this can be done by writing the array to the response stream and by setting the correct content type, length and so on in the servlet. My problem is that the whole app was built based on the idea that it will only receive/send JSON. In the servlet's service() method, I have this:

  response.setContentType("application/json");
  reqBroker.process(request, response);

RequestBroker is the class who processes the JSON (jackson processor), everything is generic and I cannot change it. On top of this, I have to receive the JSON from the request correctly, to access the data and generate my pdf. So those two lines are necessary. But when I send the response, I need to have another content type so that the pdf is displayed correctly in the browser.
So far, I am able to send the byte array as part of the JSON, but then I don't know how to display the array as PDF on the client (if smth like this is even possible).
I would like some suggestions on how can I send my pdf and set the right header, without messing with the JSON. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泪冰清 2024-12-10 02:15:47

JSON 和字节数组不能混合。

相反,您应该创建一个 并将其指向返回原始 PDF 的 URL。

JSON and byte arrays don't mix.

Instead, you should create an <iframe> and point it to a URL that returns a raw PDF.

冧九 2024-12-10 02:15:47

Take a look here:How to send pdf in json, it lists couple of approaches that you can consider. The easiest way is to convert the binary data into string by using Base64 compression. In C#, this would mean a call to Convert.FromBase64String. However this has space overhead as Base64 compression means around +33% more memory. If you can get away with it, this is the least complicated solution. in case additional size is an issue you can think about zipping it up.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文