title: Displaying PDF from base64 string with Spring/Java
body: <p>I have a PDF saved as a base 64 CLOB in a database.</p>
  
  <p>As a functional test, I'm just trying to get it to display in my browser. I made a new endpoint in my controller and just put the base64 String into the controller, without even getting the PDF from the database, that looks like this:</p>
  
  <pre><code>@RequestMapping(value = "/output.pdf", method = RequestMethod.GET, produces = "application/pdf")
  public void makePDF(HttpServletResponse response) throws Exception {
      String value = "R04jArrrw45jNH6bV02="; //&lt;--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();
      }
  }
  </code></pre>
  
  <p>Whenever I hit the endpoint, I get a <code>Failed to load PDF document</code> message. I can't figure out why.</p>
  
  <p>I'm pretty new to this, so I'm having trouble figuring out what my next steps are. How do I get the PDF to display in the web browser?</p>
  
  <p><b> EDIT </b></p>
  
  <p>I was able to get this working, by using modifying my method to the following:</p>
  
  <pre><code>@RequestMapping(value = "/output.pdf", method = RequestMethod.GET, produces = "application/pdf")
  public void makePDF(HttpServletResponse response) throws Exception {
      try {
        String value = "R04jArrrw45jNH6bV02="; //&lt;--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();
      }
  }
  </code></pre>
  
  <p>Trying to understand exactly what I'm doing here, and why it worked. Obviously has something to do with Base64 decoding, and using the <code>Document</code> object.</p>