使用 Spring/Java 从 base64 字符串显示 PDF

Displaying PDF from base64 string with Spring/Java

我在数据库中将 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对象。

堆栈溢出postBlob vs Clob and why you should not store binary data in Clobs

PDF 具有一般的基于文本的结构。但是,PDF 文件可以包含非 ASCII ("binary") 数据,因此应始终将其视为二进制文件,- 抱歉无法为此找到真实来源 link。

在这种情况下,可能会对数据进行有损编码,并解码编码的 Base-64。

流式传输之前使用 Base64 解码

Base64.decode(base64String, Base64.NO_WRAP)