/**
  * Constructs a <CODE>PdfPCell</CODE> with a <CODE>PdfPtable</CODE>. This constructor allows
  * nested tables.
  *
  * @param table The <CODE>PdfPTable</CODE>
  * @param style The style to apply to the cell (you could use getDefaultCell())
  * @since 2.1.0
  */
 public PdfPCell(PdfPTable table, PdfPCell style) {
   super(0, 0, 0, 0);
   borderWidth = 0.5f;
   border = BOX;
   column.setLeading(0, 1);
   this.table = table;
   table.setWidthPercentage(100);
   table.setExtendLastRow(true);
   column.addElement(table);
   if (style != null) {
     cloneNonPositionParameters(style);
     verticalAlignment = style.verticalAlignment;
     paddingLeft = style.paddingLeft;
     paddingRight = style.paddingRight;
     paddingTop = style.paddingTop;
     paddingBottom = style.paddingBottom;
     colspan = style.colspan;
     rowspan = style.rowspan;
     cellEvent = style.cellEvent;
     useDescender = style.useDescender;
     useBorderPadding = style.useBorderPadding;
     rotation = style.rotation;
   } else {
     setPadding(0);
   }
 }
 void setTable(PdfPTable table) {
   this.table = table;
   column.setText(null);
   image = null;
   if (table != null) {
     table.setExtendLastRow(verticalAlignment == Element.ALIGN_TOP);
     column.addElement(table);
     table.setWidthPercentage(100);
   }
 }
 /**
  * Adds an iText element to the cell.
  *
  * @param element
  */
 public void addElement(Element element) {
   if (table != null) {
     table = null;
     column.setText(null);
   }
   if (element instanceof PdfPTable) {
     ((PdfPTable) element).setSplitLate(false);
   } else if (element instanceof PdfDiv) {
     for (Element divChildElement : ((PdfDiv) element).getContent()) {
       if (divChildElement instanceof PdfPTable) {
         ((PdfPTable) divChildElement).setSplitLate(false);
       }
     }
   }
   column.addElement(element);
 }
Exemple #4
0
 /** This is a convenience function to make it easy to fill up the remaining table cells. */
 private void fillNullCells() {
   int itemsToAdd = 4 - (_itemsAdded % 4);
   while (itemsToAdd > 0) {
     PdfPCell c = new PdfPCell();
     c.setBorder(0);
     _table.addCell(c);
     itemsToAdd--;
   }
 }
Exemple #5
0
  /**
   * Constructor. Takes in a string representing where the file should be written to disk.
   *
   * @param fname
   * @throws DocumentException
   * @throws FileNotFoundException
   */
  public BarcodePdf(String fname) throws FileNotFoundException, DocumentException {

    _d = new Document();

    _writer = PdfWriter.getInstance(_d, new FileOutputStream(fname));

    _d.setMargins(25, 25, 25, 25);
    _d.open();

    _open = true;
    _rawContent = _writer.getDirectContent();

    _table = new PdfPTable(4);
    _table.setHorizontalAlignment(Element.ALIGN_CENTER);

    _itemsAdded = 0;
  }
Exemple #6
0
  /**
   * Adds an item to the page for printing. If the document was not successfully opened, or if the
   * item has an invalid barcode, no action will be taken and a negative Result will be returned.
   *
   * @param item
   */
  public Result addItem(Item item) {
    if (!_open) {
      return new Result(false, "Cannot add a product to an unopened file.");
    }
    if (!item.getBarcode().isValid()) {
      return new Result(false, "Cannot print an invalid barcode.");
    }

    // Generate the barcode image:
    BarcodeEAN codeEAN = new BarcodeEAN();
    codeEAN.setCodeType(com.itextpdf.text.pdf.Barcode.UPCA);
    codeEAN.setCode(item.getBarcode().toString());
    Image bcimage = codeEAN.createImageWithBarcode(_rawContent, null, null);

    // Add some text to a chunk, and the image to a chunk.
    Font font = new Font(Font.FontFamily.HELVETICA, 8);
    Chunk c1 =
        new Chunk(
            item.getProductDescription()
                + "\n"
                + item.getShortEntryDateString()
                + " -> "
                + item.getShortExpirationDateString()
                + "\n\n");
    c1.setFont(font);
    Phrase p = new Phrase(c1);
    Chunk c2 = new Chunk(bcimage, 0, 0);
    p.add(c2);

    PdfPCell cell = new PdfPCell(p);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setPadding(10);
    cell.setBorder(0);
    _table.addCell(cell);

    _itemsAdded++;

    return new Result(true, "Barcode added successfully.");
  }
  public void generaPdf() {
    Document documento = new Document();
    FileOutputStream ficheroPdf;
    PdfPTable tabla_emple, tabla_proyec, tabla_relacional;
    empleados = consultas.recogerEmpleados();
    ProjectX = consultas.recogerProyectos();
    ArrayList<Empleado> relacional;

    try {
      ficheroPdf = new FileOutputStream("ejemplo.PDF");
      PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);
    } catch (Exception ex) {
      System.out.println(ex.toString());
    }
    try {
      // abrimos el documento para editarlo
      documento.open();
      // aqui agregamos todo el contenido del PDF...

      documento.add(
          new Paragraph(
              "Este informe es una manera de imprimir la informacion, en forma de tablas, de la base de datos"));
      documento.add(new Paragraph(" "));
      // ***************TABLA DE LOS EMPLEADOS**************
      documento.add(new Paragraph("Empleados de la compañia:"));
      documento.add(new Paragraph(" "));
      // inicio la tabla con las 4 columnas de los empleados
      tabla_emple = new PdfPTable(4);
      // cada 4 addCell, es una fila nueva
      tabla_emple.addCell("NIF");
      tabla_emple.addCell("Nombre");
      tabla_emple.addCell("Apellidos");
      tabla_emple.addCell("Fecha de Nacimiento");
      for (Empleado e : empleados) {
        tabla_emple.addCell(e.getNif());
        tabla_emple.addCell(e.getNombre());
        tabla_emple.addCell(e.getApellido());
        tabla_emple.addCell(e.getFechaNacimiento());
      }
      documento.add(tabla_emple);
      documento.add(new Paragraph(" "));

      // *********TABLA DE LOS PROYECTOS************
      documento.add(new Paragraph("Proyectos actuales en la compañia:"));
      documento.add(new Paragraph(" "));
      tabla_proyec = new PdfPTable(5);
      tabla_proyec.addCell("Titulo");
      tabla_proyec.addCell("Fecha de Inicio");
      tabla_proyec.addCell("Fecha de Entrega");
      tabla_proyec.addCell("Descripcion");
      tabla_proyec.addCell("Nº Maximo de empleados");
      for (Proyecto p : ProjectX) {
        tabla_proyec.addCell(p.getTitulo());
        tabla_proyec.addCell(p.getFechaInicio());
        tabla_proyec.addCell(p.getFechaFin());
        tabla_proyec.addCell(p.getDescripcion());
        tabla_proyec.addCell(String.valueOf(p.getMaxEmple()));
      }
      documento.add(tabla_proyec);
      documento.add(new Paragraph(" "));

      // TABLA RELACIONAL
      documento.add(new Paragraph("Tabla relacional de empleados por proyecto"));
      documento.add(new Paragraph(" "));
      tabla_relacional = new PdfPTable(4);

      for (Proyecto p : ProjectX) {
        Paragraph titulos = new Paragraph(p.getTitulo());
        titulos.setAlignment(1);
        PdfPCell celda = new PdfPCell(titulos);
        celda.setColspan(4);
        celda.setRowspan(2);
        tabla_relacional.addCell(celda);
        tabla_relacional.addCell("NIF");
        tabla_relacional.addCell("Nombre");
        tabla_relacional.addCell("Apellidos");
        tabla_relacional.addCell("Fecha de Nacimiento");
        relacional = consultas.recogerEmpleProy(p.getId());
        for (Empleado er : relacional) {
          tabla_relacional.addCell(er.getNif());
          tabla_relacional.addCell(er.getNombre());
          tabla_relacional.addCell(er.getApellido());
          tabla_relacional.addCell(er.getFechaNacimiento());
        }
        Paragraph fin = new Paragraph(" ");
        titulos.setAlignment(1);

        PdfPCell celda2 = new PdfPCell(fin);
        celda2.setColspan(4);
        celda2.setRowspan(2);
      }
      documento.add(tabla_relacional);

      documento.add(new Paragraph(" "));
      documento.add(new Paragraph("Desarrollador del programa: Jairo Gallardo Zorrilla"));
      documento.add(new Paragraph("Cliente: Manuel Torres"));
      documento.add(new Paragraph(""));

      // cerramos el documento y se genera
      JOptionPane.showMessageDialog(null, "El archivo pdf se ha generado correctamente");
      documento.close();
    } catch (Exception ex) {
      System.out.println(ex.toString());
    }
  }
 /**
  * Sets the vertical alignment for the cell. It could be <CODE>Element.ALIGN_MIDDLE</CODE> for
  * example.
  *
  * @param verticalAlignment The vertical alignment
  */
 public void setVerticalAlignment(int verticalAlignment) {
   if (table != null) table.setExtendLastRow(verticalAlignment == Element.ALIGN_TOP);
   this.verticalAlignment = verticalAlignment;
 }
  // --- GENERATE PDF DOCUMENT BYTES -------------------------------------------------------------
  public ByteArrayOutputStream generatePDFDocumentBytes(
      final HttpServletRequest req, String type, String title, Hashtable parameters)
      throws Exception {
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    docWriter = PdfWriter.getInstance(doc, baosPDF);
    this.req = req;

    String sURL = req.getRequestURL().toString();
    if (sURL.indexOf("openclinic", 10) > 0) {
      sURL = sURL.substring(0, sURL.indexOf("openclinic", 10));
    }

    String sContextPath = req.getContextPath() + "/";
    HttpSession session = req.getSession();
    String sProjectDir = (String) session.getAttribute("activeProjectDir");

    this.url = sURL;
    this.contextPath = sContextPath;
    this.projectDir = sProjectDir;

    try {
      doc.addProducer();
      doc.addAuthor(user.person.firstname + " " + user.person.lastname);
      doc.addCreationDate();
      doc.addCreator("OpenClinic Software");
      Rectangle rectangle = null;
      doc.setPageSize(PageSize.A4);
      doc.setMargins(10, 10, 10, 10);
      doc.setJavaScript_onLoad("print();\r");
      doc.open();

      PdfPTable table = new PdfPTable(1);
      table.setWidthPercentage(100);
      if (type.equalsIgnoreCase("piechart")) {
        KeyValue[] values = new KeyValue[parameters.size()];
        Enumeration pars = parameters.keys();
        int n = 0;
        while (pars.hasMoreElements()) {
          String parameterkey = (String) pars.nextElement();
          values[n] = new KeyValue(parameterkey, (String) parameters.get(parameterkey));
          n++;
        }
        table.addCell(
            createKPGSPieChartCell(
                values, ScreenHelper.getTranNoLink("web", title, sPrintLanguage)));
      }
      doc.add(table);
    } catch (Exception e) {
      baosPDF.reset();
      e.printStackTrace();
    } finally {
      if (doc != null) doc.close();
      if (docWriter != null) docWriter.close();
    }

    if (baosPDF.size() < 1) {
      throw new DocumentException("document has no bytes");
    }

    return baosPDF;
  }