title: Serving PDF files from a Database via a JSP
body: <p>Im doing a .PDF download code for Java. I am meeting a problem whereby I am able download the .PDF formatted file. The size of the file was correct, but when I open the .PDF file, it is empty inside. Any solution?</p>
  
  <pre><code>&lt;%@ page import="java.io.*,java.util.*,java.sql.*"%&gt;
  &lt;%
      int id = 0;
      if (request.getParameter("id") != null &amp;&amp; request.getParameter("id") != "")
      {
          id = Integer.parseInt(request.getParameter("id").toString());
      }
  
      String connectionURL = "jdbc:mysql://localhost:3306/MajorProjectDB";
      String url = request.getParameter("WEB_URL");
      String Content = new String("");
      Statement stmt = null;
      Connection con = null;
  
      try
      {
          String filename = "data" + id + ".pdf";
          Class.forName("com.mysql.jdbc.Driver").newInstance();
          con = DriverManager.getConnection(connectionURL, "cdsadmin2", "enjoyit");
          stmt = con.createStatement();
          String qry = "select * from paper where PAPER_ID=" + id;
          ResultSet rst = stmt.executeQuery(qry);
          if (rst.next())
          {
              Content = rst.getString("Paper_Data");
          }
          out.println(Content);
          byte requestBytes[] = Content.getBytes();
          ByteArrayInputStream bis = new ByteArrayInputStream(requestBytes);
          response.reset();
          response.setContentType("application/pdf");
          response.setHeader("cache-control", "no-cache");
          response.setHeader("Content-disposition", "attachment; filename=" + filename);
  
          byte[] buf = new byte[1024];
          int len;
          while ((len = bis.read(buf)) &gt; 0)
          {
              response.getOutputStream().write(buf, 0, len);
          }
          bis.close();
          response.getOutputStream().flush();
      }
      catch (Exception e)
      {
          e.printStackTrace();
      }
  %&gt;
  </code></pre>