【发布时间】:2017-12-07 02:20:41
【问题描述】:
我有一个 PDF 保存为数据库中的 base 64 CLOB。
作为一项功能测试,我只是想让它显示在我的浏览器中。我在控制器中创建了一个新端点,然后将 base64 字符串放入控制器,甚至没有从数据库中获取 PDF,如下所示:
@RequestMapping(value = "/output.pdf", method = RequestMethod.GET, produces = "application/pdf")
public void makePDF(HttpServletResponse response) throws Exception {
String value = "R04jArrrw45jNH6bV02="; //<--This is longer, but I shortened it for this question
byte[] imageByte = value.getBytes();
response.setContentType("application/pdf");
response.setContentLength(imageBytes.length);
response.getOutputStream().write(imageBytes);
} catch (Exception e) {
e.printStackTrace();
}
}
每当我到达端点时,我都会收到一条Failed to load PDF document 消息。我不知道为什么。
我对此很陌生,所以我无法弄清楚我的下一步是什么。如何让 PDF 在网络浏览器中显示?
编辑
通过将我的方法修改为以下内容,我能够使其正常工作:
@RequestMapping(value = "/output.pdf", method = RequestMethod.GET, produces = "application/pdf")
public void makePDF(HttpServletResponse response) throws Exception {
try {
String value = "R04jArrrw45jNH6bV02="; //<--This is longer, but I shortened it for this question
byte[] image = Base64.decodeBase64(value.getBytes());
Document document = new Document();
document.setPageSize(PageSize.LETTER);
PdfWriter.getInstance(document, response.getOutputStream());
Image labelImage = Image.getInstance(image);
labelImage.setAlignment(Image.TOP);
labelImage.scalePercent(new Float("35"));
document.open();
document.add(labelImage);
response.setContentType("application/pdf");
response.setContentLength(imageBytes.length);
response.getOutputStream().write(image);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
试图准确了解我在这里做什么,以及它为什么有效。显然和Base64解码有关,使用Document对象。
【问题讨论】:
-
因为您发送的不是 PDF 字节,而是 base-64 编码的 PDF 字节。您需要对字符串进行 base-64 解码,然后发送结果。
-
为什么是奇怪的存储格式?
-
@JBNizet - 我添加了使用 Base64 解码的内容,它删除了错误消息,但仍然不显示图像。但至少我正朝着正确的方向前进。谢谢。
-
@Kayaman - 这是将这些图像作为文件存储在服务器上的替代品。我们将使用无文件,并将这些图像作为 CLOB 存储在我们的数据库中。
-
为什么要将它们存储为 CLOB 而不是 BLOB?这是存储它们的最无意义的方式,并且可以避免这个问题。
标签: java spring image pdf base64