设置服务器响应内容后损坏的 PDF
我目前正在对服务器进行休息调用以签署 pdf 文档。
我正在发送 pdf(二进制内容)并检索签名 pdf 的二进制内容。 当我从 inputStream 获取二进制内容时:
try (InputStream inputStream = conn.getInputStream()) {
if (inputStream != null) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String lines;
while ((lines = br.readLine()) != null) {
output += lines;
}
}
}
}
signedPdf.setBinaryContent(output.getBytes());
(signedPdf 是具有 byte[] 属性的 DTO) 但是当我尝试使用响应 pdf: 的内容设置 pdf 的内容
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(signedPdf);
pdf.setContent(signedPdf);
并尝试打开它时,它说 pdf 已损坏且无法修复。
有人遇到过类似的事情吗?我是否还需要为输出流设置内容长度?
I am currently making rest calls to a server for signing a pdf document.
I am sending a pdf(binary content) and retrieving the binary content of the signed pdf.
When i get the binary content from the inputStream:
try (InputStream inputStream = conn.getInputStream()) {
if (inputStream != null) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String lines;
while ((lines = br.readLine()) != null) {
output += lines;
}
}
}
}
signedPdf.setBinaryContent(output.getBytes());
(signedPdf is a DTO with byte[] attribute)
but when i try to set the content of the pdf with the content of the response pdf:
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(signedPdf);
pdf.setContent(signedPdf);
and try to open it, it says that the pdf is damaged and cannot be repaired.
Anyone encountered something similar? Do i need to set the content-length as well for the output stream?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
PDF 是二进制数据。当以文本(在 Java 中始终是 Unicode)形式读取 PDF 时,会损坏 PDF。
这也是一种浪费:一个字节作为 char 会使内存使用量增加一倍,并且
有两种转换:使用某种编码从字节到字符串,反之亦然。
从 UTF-8 转换时,甚至可能会出现 UTF-8 格式错误。
是否使用 BufferedInputStream 取决于预期的 PDF 大小等。
此外
new String(byte[], Charset)
和String.getBytes(Charset)
具有显式 Charset (如StandardCharsets.UTF_8< /code>) 优于默认字符集重载版本。它们使用当前的平台编码,因此提供不可移植的代码。在其他平台/计算机上的行为有所不同。
PDF is binary data. One corrupts the PDF when reading as text (which in Java is always Unicode).
Also it is a waste: a byte as char would double the memory usages, and
there are two conversions: from bytes to String and vice versa, using some encoding.
When converting from UTF-8 even UTF-8 format errors may be raised.
Whether to use a
BufferedInputStream
depends, for instance on the expected PDF size.Furthermore
new String(byte[], Charset)
andString.getBytes(Charset)
with explicit Charset (likeStandardCharsets.UTF_8
) are preferable over a default Charset overloaded version. Those use the current platform encoding, and hence delivers non-portable code. Behaving differently on an other platform/computer.