以 byte[]/JSON 形式发送 PDF 问题
我正在尝试将生成的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
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.看这里:如何以 json 发送 pdf< /a>,它列出了您可以考虑的几种方法。最简单的方法是使用 Base64 压缩将二进制数据转换为字符串。在 C# 中,这意味着调用 Convert.FromBase64String。然而,这会产生空间开销,因为 Base64 压缩意味着内存增加约 33%。如果你能逃脱它,这是最简单的解决方案。如果额外的尺寸是一个问题,您可以考虑将其拉上拉链。
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.