title: Using iText to create PDF
body: <p>I'm trying to create a PDF using iText and I'm having a great deal of difficulty.  In short, what I want to do is:</p>
  
  <ul>
  <li>Read in a template pdf</li>
  <li>Make a copy in memory of the template</li>
  <li>Draw a table on the copy</li>
  <li>Write the copy pdf to an outputstream</li>
  </ul>
  
  <p>So far, it's looking like this</p>
  
  <pre><code>// read in template pdf
  InputStream templateStream = getServletContext().getResourceAsStream(labelsTemplate);
  PdfReader reader = new PdfReader(templateStream);
  
  // create a table in a new document
  Document document = new Document();
  PdfCopy copy = new PdfCopy(document, os);
  document.open();
  
  PdfPTable table = new PdfPTable(2);
  PdfPCell cell;
  cell = new PdfPCell(new Phrase("row 1; cell 1"));
  table.addCell(cell);
  cell = new PdfPCell(new Phrase("row 1; cell 2"));
  table.addCell(cell);
  document.add(table);
  </code></pre>
  
  <p>Can someone explain how I can make a copy of the template once I've used PdfReader to read it?  Is there a way to write the table onto the template copy and not a new document?</p>
  
  <p>For future references, here's what I've done:</p>
  
  <pre><code>response.setContentType("application/pdf");
  response.setHeader("Content-Disposition", "inline;filename=\"scheduler-labels.pdf\"");
  ServletOutputStream os = response.getOutputStream();
  
  // read in template pdf
  InputStream templateStream = getServletContext().getResourceAsStream(labelsTemplate);
  PdfReader reader = new PdfReader(templateStream);
  
  // make new pdf document to draw table and output to memory
  Document document = new Document(reader.getPageSize(1));
  ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
  PdfWriter.getInstance(document, baos);
  
  // write table
  document.open();
  PdfPTable table = new PdfPTable(2);
  table.setWidthPercentage(110);
  PdfPCell cell;
  cell = new PdfPCell(new Phrase("row 1; cell 1"));
  table.addCell(cell);
  cell = new PdfPCell(new Phrase("row 1; cell 2"));
  table.addCell(cell);
  cell = new PdfPCell(new Phrase("row 2; cell 1"));
  table.addCell(cell);
  cell = new PdfPCell(new Phrase("row 2; cell 2"));
  table.addCell(cell);
  document.add(table);
  document.close();
  
  // read in newly generated table pdf
  PdfReader tableReader = new PdfReader(baos.toByteArray());
  ByteArrayOutputStream baosCombined = new ByteArrayOutputStream();
  PdfStamper stamper = new PdfStamper(tableReader, baosCombined);
  
  // get a page from the template pdf
  PdfImportedPage page = stamper.getImportedPage(reader, 1);
  
  // add to background of table pdf
  PdfContentByte background;
  background = stamper.getUnderContent(1);
  background.addTemplate(page, 0, 0);
  
  stamper.close();
  tableReader.close();
  reader.close();
  
  // write to servlet output
  baosCombined.writeTo(os);
  os.flush();
  os.close();
  </code></pre>