Example #1
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--;
   }
 }
Example #2
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());
    }
  }
  // --- 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;
  }