title: Creating PDFs in a Web Application iText
body: <p>I know this may be stupid question i am gonna put here since i am a complete java noob. may be you guys can help me out to get this problem solved. </p>
  
  <p>I am working on an application where a user would need the result dislayed on jsp page in pdf form, and the pdf is being generated as output stream in HTTP request, means when a user clicks on a button(on jsp) to generate PDF with result i.e. PDF getting generated on fly and sent to client browser. </p>
  
  <p>Using iText, i am able to generate custom generated pdfs on the fly</p>
  
  <p>Heres the Code snippet</p>
  
  <pre><code>public class PdfSample extends HttpServlet {
  
      public PdfSample() {
          super();
      }
  
          //connection to DB.... code goes here.....
  
      public void doPost(HttpServletRequest req, HttpServletResponse resp)
              throws ServletException, IOException {
          doGet(req, resp);
      }
  
      public void doGet(HttpServletRequest req, HttpServletResponse resp)
              throws javax.servlet.ServletException, java.io.IOException {
          DocumentException ex = null;
          ByteArrayOutputStream baosPDF = null;
          try {
              baosPDF = generatePDFDocumentBytes(req, this.getServletContext());
              StringBuffer sbFilename = new StringBuffer();
              sbFilename.append("filename_");
              sbFilename.append(System.currentTimeMillis());
              sbFilename.append(".pdf");
              resp.setHeader("Cache-Control", "max-age=30");
              resp.setContentType("application/pdf");
              StringBuffer sbContentDispValue = new StringBuffer();
              sbContentDispValue.append("inline");
              sbContentDispValue.append("; filename=");
              sbContentDispValue.append(sbFilename);
              resp.setHeader("Content-disposition", sbContentDispValue.toString());
              resp.setContentLength(baosPDF.size());
              ServletOutputStream sos;
              sos = resp.getOutputStream();
              baosPDF.writeTo(sos);
              sos.flush();
          } catch (DocumentException dex) {
              resp.setContentType("text/html");
              PrintWriter writer = resp.getWriter();
              writer.println(this.getClass().getName() + " caught an exception: "
                      + dex.getClass().getName() + "&lt;br&gt;");
              writer.println("&lt;pre&gt;");
              dex.printStackTrace(writer);
              writer.println("&lt;/pre&gt;");
          } finally {
              if (baosPDF != null) {
                  baosPDF.reset();
              }
          }
      }
  
      protected ByteArrayOutputStream generatePDFDocumentBytes(
              final HttpServletRequest req, final ServletContext ctx)
              throws DocumentException
      {
          Document doc = new Document();
          ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
          PdfWriter docWriter = null;
          try {
              docWriter = PdfWriter.getInstance(doc, baosPDF);
              doc.addAuthor("Sample");
              doc.addCreationDate();
              doc.addProducer();
              doc.addCreator("Sample");
              doc.addTitle("Sample Report");
              doc.setPageSize(PageSize.LETTER);
              doc.open();
              String strServerInfo = ctx.getServerInfo();
              if (strServerInfo != null) {
              }
              doc.add(makeHTTPParameterInfoElement(req));
          } catch (DocumentException dex) {
              baosPDF.reset();
              throw dex;
          } finally {
              if (doc != null) {
                  doc.close();
              }
              if (docWriter != null) {
                  docWriter.close();
              }
          }
  
          if (baosPDF.size() &lt; 1) {
              throw new DocumentException("document has " + baosPDF.size()
                      + " bytes");
          }
          return baosPDF;
      }
      protected Element makeHTTPParameterInfoElement(final HttpServletRequest req) {
          Table tab = null;
          tab = makeTable("", "White Color Car", "Black Color Car", "Total");
          return (Element) tab;
      }
      private static Table makeTable(final String firstColumnTitle,
              final String secondColumnTitle, final String thirdColumnTitle,
              final String fourthColumnTitle) {
  
          Paragraph paragraph, paragraph1;
          int val1 = 0;
          int val2 = 0;
          int val3 = 0;
          int val4 = 0;
          Table tab = null;
          try {
              tab = new Table(4);
  
          } catch (BadElementException ex) {
              throw new RuntimeException(ex);
          }
          Cell c = null;
          try {
          paragraph = new Paragraph("Car Report");
          paragraph.setAlignment(1);
          c = new Cell(paragraph);
          c.setColspan(tab.getColumns());
          } catch (Exception e1) {
              // TODO Auto-generated catch block
              e1.printStackTrace();
          }
          tab.setBorderWidth(1);
          tab.setBorderColor(Color.BLACK);
          tab.setPadding(2);
          tab.setSpacing(3);
          tab.setBackgroundColor(Color.WHITE);
          tab.addCell(c);
          tab.addCell(new Cell(firstColumnTitle));
          tab.addCell(new Cell(secondColumnTitle));
          tab.addCell(new Cell(thirdColumnTitle));
          tab.addCell(new Cell(fourthColumnTitle));
          tab.endHeaders();
  
          String startDate1 = "01/06/2011";
          String endDate1 = "11/09/2011";
  
          SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
          try {
              Date startDate = sdf1.parse(startDate1);
              Date endDate = sdf1.parse(endDate1);
              java.sql.Date sdate = new java.sql.Date(startDate.getTime());
              java.sql.Date edate = new java.sql.Date(endDate.getTime());
  
               String newWhiteColor = "select count(*) from .......";
           String newBlackColor = "select count(*) from .......";
           String totalWhiteColor= "select count(*) from .....";
           String totalBlackColor = "select count(*) from .......";
  
                      Connection connection = null;
              PreparedStatement preparedStatement = null;
              PreparedStatement preparedStatement1 = null;
              PreparedStatement preparedStatement2 = null;
              PreparedStatement preparedStatement3 = null;
  
              ResultSet resultSet = null;
              ResultSet resultSet1 = null;
              ResultSet resultSet2 = null;
              ResultSet resultSet3 = null;
  
              connection = getSimpleConnection1();
  
              // New Car recently sold out - White Color
              preparedStatement = connection
                      .prepareStatement(newWhiteColor);
              resultSet = preparedStatement.executeQuery();
              while (resultSet.next()) {
                  val1 = resultSet.getInt(1);
              }
  
              // New Car recently sold out - Black Color
              preparedStatement3 = connection
                      .prepareStatement(newBlackColor);
              resultSet3 = preparedStatement3.executeQuery();
              while (resultSet3.next()) {
                  val2 = resultSet3.getInt(1);
              }
  
              // Total White Color cars sold out
              preparedStatement1 = connection
                      .prepareStatement(totalWhiteColor);
              resultSet1 = preparedStatement1.executeQuery();
              while (resultSet1.next()) {
                  val3 = resultSet1.getInt(1);
              }
  
              // Total Black Color cars sold out
              preparedStatement2 = connection
                      .prepareStatement(totalBlackColor);
              resultSet2 = preparedStatement2.executeQuery();
              while (resultSet2.next()) {
                  val4 = resultSet2.getInt(1);
              }
  
              Integer newWhite = val1;
              Integer newBlack = val2;
              Integer totalWhite = val3;
              Integer totalBlack = val4;
                  Integer totalNewCars = newWhite + new Black;
              Integer totalCars= totalWhite + totalBlack ;
  
              tab.addCell(new Cell("New Cars Sold Out"));
              tab.addCell(new Cell(newWhite.toString()));
              tab.addCell(new Cell(newBlack.toString()));
                  tab.addCell(new Cell(totalNewCars.toString()));
              tab.addCell(new Cell("Total Cars Sold out"));
              tab.addCell(new Cell(totalWhite.toString()));
              tab.addCell(new Cell(totalBlack.toString()));
              tab.addCell(new Cell(totalCars.toString()));
  
          } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
  
          return tab;
      }
  
  
  }
  </code></pre>
  
  <p>The Above code fetching the data (count) from the database by making the connection and displaying in cells. with the above code i am able to create pdf on fly and output as showing below. </p>
  
  <pre><code>-------------------------------------------------------------------------------------------------- 
  Car Report
  --------------------------------------------------------------------------------------------------
                     | White Color Car          |Black Color Car       |  Total                
  --------------------------------------------------------------------------------------------------
    New Cars Sold out|         5                |      8               |    13
  --------------------------------------------------------------------------------------------------
  Total Cars Sold Out|        6                 |      4               |    10
  --------------------------------------------------------------------------------------------------
  </code></pre>
  
  <p><strong>Query 1)</strong> How Can I align the car report in Center?</p>
  
  <p><strong>Query 2)</strong> Data and text are being displayed inside a cell, how can i set the border of the cell to "0".</p>
  
  <p><strong>Query 3)</strong> How can i color a particular cell ( the blank one)?</p>
  
  <p><strong>Query 4)</strong> Is it possible to Insert a image on top of the header of the pdf?</p>
  
  <p>Any help would be greatly appreciated !!!!!</p>