Example usage for com.itextpdf.text.pdf PdfPTable setSpacingAfter

List of usage examples for com.itextpdf.text.pdf PdfPTable setSpacingAfter

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfPTable setSpacingAfter.

Prototype

public void setSpacingAfter(final float spacing) 

Source Link

Document

Sets the spacing after this table.

Usage

From source file:se.billes.pdf.renderer.request.factory.TableFactory.java

License:Open Source License

public PdfPTable createTable(float widthInPs) {
    PdfPTable table = new PdfPTable(1);
    table.setTotalWidth(widthInPs);/*from w w  w.  j  a v  a  2 s. c  om*/
    table.setLockedWidth(true);
    table.setSpacingBefore(0);
    table.setSpacingAfter(0);
    return table;
}

From source file:servlet.GenerarPDF.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w ww  .  j  a va  2 s.  c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    Document document = new Document();

    try {
        ConexionDB sqlite = new ConexionDB();
        java.sql.Connection cn = sqlite.Conectar();
        Statement st = cn.createStatement();
        ResultSet rs = st.executeQuery("SELECT * FROM mascotas;");

        response.setContentType("APPLICATION/download");
        response.setHeader("Content-Disposition", "filename=Mascotas.pdf");
        PdfWriter.getInstance(document, response.getOutputStream());
        document.open();

        Image image = Image.getInstance(
                "C:/Users/Cristian/Documents/NetBeansProjects/adopc-mascotas/web/imagenes/logo9.png");
        image.scaleAbsolute(100, 100);
        document.add(image);

        Paragraph preface = new Paragraph("LOVE MY PET");
        preface.setAlignment(Element.ALIGN_CENTER);
        document.add(preface);

        PdfPTable table = new PdfPTable(5); // 3 columns.
        table.setWidthPercentage(100); //Width 100%
        table.setSpacingBefore(10f); //Space before table
        table.setSpacingAfter(10f); //Space after table

        //Set Column widths
        float[] columnWidths = { 1f, 1f, 1f, 1f, 1f };
        table.setWidths(columnWidths);

        PdfPCell cellusuario = new PdfPCell(new Paragraph("usario"));
        cellusuario.setBorderColor(BaseColor.BLUE);
        cellusuario.setPaddingLeft(10);
        cellusuario.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellusuario.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell celltipo = new PdfPCell(new Paragraph("tipo"));
        celltipo.setBorderColor(BaseColor.BLUE);
        celltipo.setPaddingLeft(10);
        celltipo.setHorizontalAlignment(Element.ALIGN_CENTER);
        celltipo.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cellnombre = new PdfPCell(new Paragraph("nombre"));
        cellnombre.setBorderColor(BaseColor.BLUE);
        cellnombre.setPaddingLeft(10);
        cellnombre.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellnombre.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cellraza = new PdfPCell(new Paragraph("raza"));
        cellraza.setBorderColor(BaseColor.BLUE);
        cellraza.setPaddingLeft(10);
        cellraza.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellraza.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell celledad = new PdfPCell(new Paragraph("edad"));
        celledad.setBorderColor(BaseColor.BLUE);
        celledad.setPaddingLeft(10);
        celledad.setHorizontalAlignment(Element.ALIGN_CENTER);
        celledad.setVerticalAlignment(Element.ALIGN_MIDDLE);

        table.addCell(cellusuario);
        table.addCell(celltipo);
        table.addCell(cellnombre);
        table.addCell(cellraza);
        table.addCell(celledad);

        while (rs.next()) {

            PdfPCell cell1 = new PdfPCell(new Paragraph(rs.getString(1)));
            cell1.setPaddingLeft(1);
            cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell1.setBackgroundColor(BaseColor.LIGHT_GRAY);
            cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell1);

            PdfPCell cell2 = new PdfPCell(new Paragraph(rs.getString(2)));
            cell2.setPaddingLeft(2);
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell2.setBackgroundColor(BaseColor.LIGHT_GRAY);
            cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell2);

            PdfPCell cell3 = new PdfPCell(new Paragraph(rs.getString(3)));
            cell3.setPaddingLeft(3);
            cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell3.setBackgroundColor(BaseColor.LIGHT_GRAY);
            cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell3);

            PdfPCell cell4 = new PdfPCell(new Paragraph(rs.getString(4)));
            cell4.setPaddingLeft(4);
            cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell4.setBackgroundColor(BaseColor.LIGHT_GRAY);
            cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell4);

            PdfPCell cell5 = new PdfPCell(new Paragraph(rs.getString(5)));
            cell5.setPaddingLeft(5);
            cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell5.setBackgroundColor(BaseColor.LIGHT_GRAY);
            cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell5);

        }

        document.add(table);
        //Add more content here
        cn.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    document.close();
}

From source file:servlet.SalesReportPDF.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w  w . j  a  v  a  2s.  c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        Document document = new Document();
        List<ArrayList> data = productSession.getEventList();
        List<ArrayList> sessions = getAllProductDetailsLocal.getAllSessions();

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        //get current date time with Date()
        Date date = new Date();
        //System.out.println(dateFormat.format(date));

        @SuppressWarnings("unused")
        PdfWriter pdfWriter = PdfWriter.getInstance(document,
                new FileOutputStream("C:/Users/Yong Jing Ying/Desktop/EventRecords.pdf"));
        document.open();
        document.add(new Paragraph("Management Report",
                FontFactory.getFont(FontFactory.TIMES_BOLD, 18, Font.BOLD, BaseColor.BLUE)));
        document.add(new Paragraph("PDF created on " + dateFormat.format(date).toString() + "\n",
                FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
        document.add(new Paragraph(
                "------------------------------------------------------------------------------------",
                FontFactory.getFont(FontFactory.TIMES_BOLD, 18, Font.BOLD, BaseColor.BLACK)));

        for (int i = 0; i < data.size(); i++) {
            document.add(new Paragraph(data.get(i).get(1).toString() + " Event Details ",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            document.add(new Paragraph("Event Type : " + data.get(i).get(4).toString() + "\nStart Date : "
                    + data.get(i).get(2).toString() + "\nEnd Date : " + data.get(i).get(3).toString()
                    + "\nProperty Name : " + data.get(i).get(5).toString() + "\nNo of Category : "
                    + data.get(i).get(6).toString() + "\nPromotions : " + data.get(i).get(7).toString()
                    + "\n\n"));
            document.add(new Paragraph("Session",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            PdfPTable table = new PdfPTable(6);
            //table.addCell("item1");
            table.setSpacingBefore(5);
            table.setSpacingAfter(5);
            table.setWidths(new int[] { 1, 2, 3, 3, 3, 3 });
            table.setWidthPercentage(100);
            PdfPCell cell;
            cell = new PdfPCell(new Phrase("No:",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            cell.setBackgroundColor(BaseColor.CYAN);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("Name:",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            cell.setBackgroundColor(BaseColor.CYAN);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("Description:",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            cell.setBackgroundColor(BaseColor.CYAN);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("Start:",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            cell.setBackgroundColor(BaseColor.CYAN);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("End:",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            cell.setBackgroundColor(BaseColor.CYAN);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("TicketPrices:",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            cell.setBackgroundColor(BaseColor.CYAN);
            table.addCell(cell);

            for (int j = 0; j < sessions.size(); j++) {
                if (sessions.get(j).get(1).toString().equals(data.get(i).get(4).toString())
                        && sessions.get(j).get(0).toString().equals(data.get(i).get(0).toString())) {
                    cell = new PdfPCell(new Phrase(sessions.get(j).get(8).toString()));
                    cell.setBackgroundColor(BaseColor.WHITE);
                    table.addCell(cell);
                    cell = new PdfPCell(new Phrase(sessions.get(j).get(4).toString()));
                    cell.setBackgroundColor(BaseColor.WHITE);
                    table.addCell(cell);
                    cell = new PdfPCell(new Phrase(sessions.get(j).get(5).toString()));
                    cell.setBackgroundColor(BaseColor.WHITE);
                    table.addCell(cell);
                    cell = new PdfPCell(new Phrase(sessions.get(j).get(6).toString()));
                    cell.setBackgroundColor(BaseColor.WHITE);
                    table.addCell(cell);
                    cell = new PdfPCell(new Phrase(sessions.get(j).get(7).toString()));
                    cell.setBackgroundColor(BaseColor.WHITE);
                    table.addCell(cell);
                    cell = new PdfPCell(new Phrase(sessions.get(j).get(9).toString()));
                    cell.setBackgroundColor(BaseColor.WHITE);
                    table.addCell(cell);
                }

            }
            document.add(table);
            document.add(new Paragraph("\n"));
            document.add(new Paragraph("Alert",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            table = new PdfPTable(6);
            //table.addCell("item1");
            table.setSpacingBefore(5);
            table.setSpacingAfter(5);
            table.setWidths(new int[] { 1, 2, 2, 3, 3, 3 });
            table.setWidthPercentage(100);
            cell = new PdfPCell(new Phrase("No:",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            cell.setBackgroundColor(BaseColor.GREEN);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("Alert Type:",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            cell.setBackgroundColor(BaseColor.GREEN);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("Below Sales:",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            cell.setBackgroundColor(BaseColor.GREEN);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("In-Charged Email:",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            cell.setBackgroundColor(BaseColor.GREEN);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("Start:",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            cell.setBackgroundColor(BaseColor.GREEN);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("End:",
                    FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, BaseColor.BLACK)));
            cell.setBackgroundColor(BaseColor.GREEN);
            table.addCell(cell);

            for (int j = 0; j < sessions.size(); j++) {
                if (sessions.get(j).get(1).toString().equals(data.get(i).get(4).toString())
                        && sessions.get(j).get(0).toString().equals(data.get(i).get(0).toString())
                        && sessions.get(j).size() == 15) {

                    cell = new PdfPCell(new Phrase(sessions.get(j).get(8).toString()));
                    cell.setBackgroundColor(BaseColor.WHITE);
                    table.addCell(cell);
                    cell = new PdfPCell(new Phrase(sessions.get(j).get(10).toString()));
                    cell.setBackgroundColor(BaseColor.WHITE);
                    table.addCell(cell);
                    cell = new PdfPCell(new Phrase(sessions.get(j).get(11).toString()));
                    cell.setBackgroundColor(BaseColor.WHITE);
                    table.addCell(cell);
                    cell = new PdfPCell(new Phrase(sessions.get(j).get(12).toString()));
                    cell.setBackgroundColor(BaseColor.WHITE);
                    table.addCell(cell);
                    cell = new PdfPCell(new Phrase(sessions.get(j).get(13).toString()));
                    cell.setBackgroundColor(BaseColor.WHITE);
                    table.addCell(cell);
                    cell = new PdfPCell(new Phrase(sessions.get(j).get(14).toString()));
                    cell.setBackgroundColor(BaseColor.WHITE);
                    table.addCell(cell);
                }

            }
            document.add(table);
            document.add(new Paragraph("\n\n"));

        }
        document.close();

        Thread.sleep(1000);

        PrintWriter out = response.getWriter();
        String fileName = "EventRecords.pdf";
        String filePath = "C:/Users/Yong Jing Ying/Desktop/";
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");

        FileInputStream fi = new FileInputStream("C:/Users/Yong Jing Ying/Desktop/EventRecords.pdf");
        int i;
        while ((i = fi.read()) != -1) {
            out.write(i);
        }

        out.close();
        fi.close();
    } catch (Exception ex) {
        Logger.getLogger(SalesReportPDF.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Servlets.PDF.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/pdf");
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);

    try {// w  w  w . ja  v a  2  s . c om
        //obtengo datos de cliente,  reserva y total
        String rreserva = request.getParameter("reserva");
        String rcliente = request.getParameter("cliente");
        String rtotal = request.getParameter("total");
        //String rtipo = request.getParameter("esProv");

        // Obtener datos de cliente e items de reserva
        DtUsuario dtu = getDtUsuario(rcliente);
        String nombre = dtu.getNombre();
        String apellido = dtu.getApellido();
        String servicios = "";
        String promos = "";
        java.util.List<DtItemReserva> dtItems = listarItems(Integer.parseInt(rreserva)).getItems();
        Iterator<DtItemReserva> iter = dtItems.iterator();
        DtItemReserva dtItem;

        // Crear y abrir documento

        String HomeDeUSuario = System.getProperty("user.home");

        String ruta = HomeDeUSuario + "/Factura Reserva " + rreserva + ".pdf";

        FileOutputStream archivo = new FileOutputStream(ruta);

        PdfWriter writer = PdfWriter.getInstance(document, archivo);

        document.open();

        Date date = new Date();

        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        String fecha = dateFormat.format(date);

        // Agregar marcador inicial

        // Crear y agregar prrafo simple
        Paragraph paragraph1 = new Paragraph();
        Image imagen = Image.getInstance("http://localhost:8084/Help4TravelingWeb/img/logo-icon2.png");
        imagen.scaleAbsolute(200f, 200f);

        imagen.setAbsolutePosition(10, 650);
        imagen.setSpacingAfter(20);
        paragraph1.add(imagen);
        document.add(paragraph1);
        //fecha
        Paragraph fecha1 = new Paragraph(fecha);

        //encabezado
        Paragraph futuros = new Paragraph("Futuros Tecnologos SRL");
        Paragraph rut = new Paragraph("RUT 123456789012");
        Paragraph direccion = new Paragraph(" Av. Gral. Rivera 3629");
        Paragraph telefono = new Paragraph(" Tel: 555-5412");
        Paragraph nombre_empresa = new Paragraph(" Help4Travelling");

        //datos cliente
        String nombrecliente = nombre.toUpperCase() + " " + apellido.toUpperCase();
        String direccioncliente = " ";
        String rutcliente = "consumidor final".toUpperCase();
        Paragraph cliente = new Paragraph("Cliente: " + nombrecliente);
        Paragraph dircliente = new Paragraph("Direccion: " + direccioncliente);
        Paragraph rutcli = new Paragraph("RUT: " + rutcliente);

        //datos boleta

        String factura = rreserva;
        Paragraph tipodoc = new Paragraph("Contado");
        Paragraph Nfac = new Paragraph(" N  " + factura);

        //alineaciones

        //fecha 
        fecha1.setAlignment(Element.ALIGN_RIGHT);

        //encabezado
        futuros.setAlignment(Element.ALIGN_CENTER);
        rut.setAlignment(Element.ALIGN_CENTER);
        direccion.setAlignment(Element.ALIGN_CENTER);
        telefono.setAlignment(Element.ALIGN_CENTER);

        //nombre empresa
        nombre_empresa.setAlignment(Element.ALIGN_LEFT);
        nombre_empresa.setSpacingBefore(10);
        nombre_empresa.setSpacingAfter(30);

        //datos de boleta
        tipodoc.setAlignment(Element.ALIGN_RIGHT);
        Nfac.setAlignment(Element.ALIGN_RIGHT);

        document.add(fecha1);
        document.add(futuros);
        document.add(rut);
        document.add(direccion);
        document.add(telefono);
        document.add(nombre_empresa);
        document.add(tipodoc);
        document.add(Nfac);
        document.add(cliente);
        document.add(dircliente);
        document.add(rutcli);

        PdfPTable tabla = new PdfPTable(4);
        tabla.setSpacingBefore(25);
        tabla.setSpacingAfter(25);

        //creo encabezado de tabla
        PdfPCell codigo = new PdfPCell(new Phrase("Proveedor".toUpperCase()));
        PdfPCell descripcion = new PdfPCell(new Phrase("descripcion".toUpperCase()));
        PdfPCell ecantidad = new PdfPCell(new Phrase("cantidad".toUpperCase()));
        PdfPCell eprecio = new PdfPCell(new Phrase("precio".toUpperCase()));

        tabla.setHeaderRows(1);
        tabla.setWidthPercentage(100f);

        //alineamos las frases del cabezal
        codigo.setHorizontalAlignment(Element.ALIGN_CENTER);
        descripcion.setHorizontalAlignment(Element.ALIGN_CENTER);
        ecantidad.setHorizontalAlignment(Element.ALIGN_CENTER);
        eprecio.setHorizontalAlignment(Element.ALIGN_CENTER);

        //agrego cabezal de tabla
        tabla.addCell(codigo);
        tabla.addCell(descripcion);
        tabla.addCell(ecantidad);
        tabla.addCell(eprecio);

        //obtengo datos de la reserva para imprimir las distintas rows

        while (iter.hasNext()) {
            dtItem = iter.next();
            Integer cantidad = dtItem.getCantidad();
            String oferta = dtItem.getOferta().getNombre();
            String precio;
            String proveedor;
            if (existeServicio(oferta)) {
                proveedor = getNkProveedorServicio(oferta);
                DtServicio dts = getDtServicio(oferta, proveedor);
                precio = String.valueOf(dts.getPrecio());
            } else {
                proveedor = getNkProveedorPromocion(oferta);
                DtPromocion dtp = getDTPromocion(oferta, proveedor);
                precio = dtp.getDescuento();
            }
            /*  String item = "<li>Nombre: <em>" + oferta + "</em>"
                + " - Cantidad: <em>" + cantidad + "</em>"
                + " - $:<em>" + precio + "</em>"
                + " - Proveedor: <em>" + proveedor + "</em></li>";*/
            //creo encabezado de tabla
            PdfPCell iproveedor = new PdfPCell(new Phrase(proveedor.toUpperCase()));

            PdfPCell icantidad = new PdfPCell(new Phrase(cantidad.toString()));
            PdfPCell iprecio = new PdfPCell(new Phrase(precio.toUpperCase()));

            tabla.setHeaderRows(1);

            //alineamos las frases del cabezal
            iproveedor.setHorizontalAlignment(Element.ALIGN_CENTER);
            icantidad.setHorizontalAlignment(Element.ALIGN_CENTER);
            iprecio.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabla.addCell(iproveedor);
            if (existeServicio(oferta)) {
                PdfPCell idescripcion = new PdfPCell(new Phrase("servicio: " + oferta));
                idescripcion.setHorizontalAlignment(Element.ALIGN_CENTER);
                tabla.addCell(idescripcion);
            } else {
                PdfPCell idescripcion = new PdfPCell(new Phrase("Promo: " + oferta));
                idescripcion.setHorizontalAlignment(Element.ALIGN_CENTER);
                tabla.addCell(idescripcion);
            }
            tabla.addCell(icantidad);
            tabla.addCell(iprecio);
        }

        /*      // las distintas rows de los articulos
              tabla.addCell(proveedor);
              tabla.addCell(oferta);
              tabla.addCell(cantidad);
              tabla.addCell(precio);
        */
        //el ulimo de la tabla que da el total

        PdfPCell celdaFinal = new PdfPCell(new Paragraph(""));
        PdfPCell celdaTotal = new PdfPCell(new Paragraph("total:"));
        PdfPCell celdaPrecioTotal = new PdfPCell(new Paragraph(rtotal));
        // Indicamos cuantas columnas ocupa la celda
        celdaFinal.setColspan(2);

        celdaTotal.setHorizontalAlignment(Element.ALIGN_RIGHT);
        celdaPrecioTotal.setHorizontalAlignment(Element.ALIGN_RIGHT);

        tabla.addCell(celdaFinal);
        tabla.addCell(celdaTotal);
        tabla.addCell(celdaPrecioTotal);
        document.add(tabla);
        document.close();
        if (request.getParameter("dispositivo").equals("true"))
            response.sendRedirect("Movil.Reservas.jsp");
        else
            response.sendRedirect("Usuario.jsp");
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:simz1.ManagerHomeScreen.java

private void btnGenerateReportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerateReportActionPerformed
    int reply = JOptionPane.showConfirmDialog(null, "Do you wish to fianlize Accounts Report now?", "",
            JOptionPane.YES_NO_OPTION);
    if (reply == JOptionPane.YES_OPTION) {
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        try {/*from  w  w  w  .  ja va2  s .  c  o m*/
            String date = today.replace(":", "_");
            //New PDF File will be created as ACCReport2016_01_01 //today's date
            PdfWriter.getInstance(document,
                    new FileOutputStream("C:\\#SIMZ\\Account Reports\\ACCReport" + date + "" + ".pdf"));
            document.open();
            Image image2 = Image.getInstance("C:\\#SIMZ\\logo1.jpg");
            document.add(image2);
            Paragraph paragraph1 = new Paragraph(
                    "Perera and Sons Bakers(pvt)Ltd.\nAddress: 1/52, Galle Road,Colombo 03.\nT.P:0112552225\n\n");
            document.add(paragraph1);
            paragraph1 = new Paragraph("                Finalized Accounts Report - " + today + "",
                    FontFactory.getFont(FontFactory.HELVETICA, 18));
            document.add(paragraph1);
            //adding a table
            PdfPTable t = new PdfPTable(3);
            t.setSpacingBefore(25);
            t.setSpacingAfter(25);

            t.addCell(new PdfPCell(new Phrase("Description")));
            t.addCell(new PdfPCell(new Phrase("Credit(Rs.)")));
            t.addCell(new PdfPCell(new Phrase("Debit(Rs.)")));
            int rows = tblIncome.getRowCount();

            for (int i = 0; i < rows; i++) {
                t.addCell(new PdfPCell(new Phrase(tblIncome.getValueAt(i, 0) + "")));
                if (tblIncome.getValueAt(i, 1) == null) {
                    t.addCell(new PdfPCell(new Phrase("-")));
                } else {
                    t.addCell(new PdfPCell(new Phrase(tblIncome.getValueAt(i, 1) + "")));
                }
                if (tblIncome.getValueAt(i, 2) == null) {
                    t.addCell(new PdfPCell(new Phrase("-")));
                } else {
                    t.addCell(new PdfPCell(new Phrase(tblIncome.getValueAt(i, 2) + "")));
                }
            }
            document.add(t);
            float totalIncome = 0;
            for (int i = 0; i < rows; i++) {
                if (tblIncome.getValueAt(i, 1) != null) {
                    totalIncome = totalIncome + Float.parseFloat(tblIncome.getValueAt(i, 1).toString());
                } else {
                    totalIncome = totalIncome + 0;
                }
            }
            paragraph1 = new Paragraph("Total Income (Rs.) : " + totalIncome + "");
            document.add(paragraph1);
            float totalExpences = 0;
            for (int i = 0; i < rows; i++) {
                if (tblIncome.getValueAt(i, 2) != null) {
                    totalExpences = totalExpences + Float.parseFloat(tblIncome.getValueAt(i, 2).toString());
                } else {
                    totalExpences = totalExpences + 0;
                }
            }
            DecimalFormat roundValue = new DecimalFormat("###.##");
            float expense = Float.parseFloat(roundValue.format(totalExpences));
            paragraph1 = new Paragraph("Total Expence (Rs.) : " + expense + "");
            document.add(paragraph1);
            float profit = 0;
            profit = totalIncome - expense;
            totProfit = profit;
            trigger1 = 1;
            paragraph1 = new Paragraph("Total Profit (Rs.) : " + profit + "" + "\n\n");
            document.add(paragraph1);
            String name = dbOps.getName(name1.getText());
            paragraph1 = new Paragraph("Report Generated By : " + name);
            document.add(paragraph1);
            //view report
            int reply1 = JOptionPane.showConfirmDialog(null,
                    "Finalized Accounts Report named ACCReportToday'sDate successfully generated.\nDo you want to view the report?",
                    "", JOptionPane.YES_NO_OPTION);
            if (reply1 == JOptionPane.YES_OPTION) {
                if ((new File("C:\\#SIMZ\\Account Reports\\ACCReport" + date + "" + ".pdf")).exists()) {

                    Process p = Runtime.getRuntime()
                            .exec("rundll32 url.dll,FileProtocolHandler C:\\#SIMZ\\Account Reports\\ACCReport"
                                    + date + "" + ".pdf");
                    p.waitFor();
                }
            }
        } catch (Exception ex) {
            System.out.println(ex);
            JOptionPane.showMessageDialog(this, "File already exists!!!");
        }
        document.close();
    }
}

From source file:simz1.ManagerHomeScreen.java

private void btnFinalReportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFinalReportActionPerformed
    int reply = JOptionPane.showConfirmDialog(null, "Do you wish to fianlize Products Report now?", "",
            JOptionPane.YES_NO_OPTION);
    if (reply == JOptionPane.YES_OPTION) {
        Document document = new Document(PageSize.A4);
        try {//from   w  w  w. j a va2  s .c  o m
            String date = today.replace(":", "_");
            //New PDF File will be created as ProReport2016_01_01 //today's date
            PdfWriter.getInstance(document,
                    new FileOutputStream("C:\\#SIMZ\\Product Reports\\ProReport" + date + "" + ".pdf"));
            document.open();
            Image image2 = Image.getInstance("C:\\#SIMZ\\logo1.jpg");
            document.add(image2);
            Paragraph paragraph1 = new Paragraph(
                    "Perera and Sons Bakers(pvt)Ltd.\nAddress: 1/52, Galle Road,Colombo 03.\nT.P:0112552225\n\n");
            document.add(paragraph1);
            //Following blank space is for the alignment of the topic
            paragraph1 = new Paragraph("                Finalized Products Report - " + today + "",
                    FontFactory.getFont(FontFactory.HELVETICA, 18));
            document.add(paragraph1);
            //adding a table
            PdfPTable t = new PdfPTable(3);
            t.setSpacingBefore(25);
            t.setSpacingAfter(25);
            t.addCell(new PdfPCell(new Phrase("Product Name")));
            t.addCell(new PdfPCell(new Phrase("Received Quantity")));
            t.addCell(new PdfPCell(new Phrase("Remained Quantity")));
            int rows = tblReports.getRowCount();
            for (int i = 0; i < rows; i++) {
                t.addCell(new PdfPCell(new Phrase(tblReports.getValueAt(i, 0) + "")));
                if (tblReports.getValueAt(i, 1) == null) {
                    t.addCell(new PdfPCell(new Phrase("-")));
                } else {
                    t.addCell(new PdfPCell(new Phrase(tblReports.getValueAt(i, 1) + "")));
                }
                if (tblReports.getValueAt(i, 2) == null) {
                    t.addCell(new PdfPCell(new Phrase("-")));
                } else {
                    t.addCell(new PdfPCell(new Phrase(tblReports.getValueAt(i, 2) + "")));
                }
            }
            document.add(t);
            paragraph1 = new Paragraph("Expired Item Details");
            document.add(paragraph1);
            PdfPTable t2 = new PdfPTable(2);
            t2.setSpacingBefore(25);
            t2.setSpacingAfter(25);
            t2.addCell(new PdfPCell(new Phrase("Product Name")));
            t2.addCell(new PdfPCell(new Phrase("Remained Quantity")));
            String dateToday = today.replace(":", "-");
            ResultSet rs = dbOps.getExpiredItemList(dateToday);
            while (rs.next()) {
                t2.addCell(new PdfPCell(new Phrase(rs.getString(1))));
                t2.addCell(new PdfPCell(new Phrase(rs.getString(3))));
            }
            document.add(t2);
            String user = dbOps.getName(name1.getText());
            paragraph1 = new Paragraph("Report Generated By : " + user);
            document.add(paragraph1);
            //view report
            int reply1 = JOptionPane.showConfirmDialog(null,
                    "Finalized Products Report named ProReportToday'sDate successfully generated.\nDo you want to view the report?",
                    "", JOptionPane.YES_NO_OPTION);
            trigger2 = 1;
            if (reply1 == JOptionPane.YES_OPTION) {
                if ((new File("C:\\#SIMZ\\Product Reports\\ProReport" + date + "" + ".pdf")).exists()) {

                    Process p = Runtime.getRuntime()
                            .exec("rundll32 url.dll,FileProtocolHandler C:\\#SIMZ\\Product Reports\\ProReport"
                                    + date + "" + ".pdf");
                    p.waitFor();
                }
            }

        } catch (SQLException | HeadlessException | IOException | InterruptedException | DocumentException ex) {
            System.out.println(ex);
            JOptionPane.showMessageDialog(this, "File already exists!!!");
        }
        document.close();
    }
}

From source file:src.servlets.ManageAdmin.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from   w w w.  jav  a 2 s. c o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Map m = request.getParameterMap();
    if (m.containsKey("GetPDF")) {
        try {
            String Report = getServletContext().getRealPath("") + "admin\\PDF_Report.pdf";

            FileOutputStream file = new FileOutputStream(Report);
            Document document = new Document();
            document.addAuthor("K00140908");
            PdfWriter.getInstance(document, file);
            ///////////////////////ADDING THE FILES TO PDF////////////////////
            //Inserting Image in PDF
            String uploadPath = getServletContext().getRealPath("") + "images\\logo.gif";

            Image img = Image.getInstance(uploadPath);

            img.scaleAbsolute(120f, 60f);// width,height of image in float

            //            Inserting Title in PDF  ORIGINAL
            //            Font fontTitle=new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.WHITE);
            //            Chunk title=new Chunk("PDF GENERATION in Java with iText", fontTitle);
            //            title.setBackground(new BaseColor(255,102,0), 1f, 1f, 1f, 3f);
            //            title.setLineHeight(30f);
            //            title.setUnderline(BaseColor.BLACK,5f,0.5f,2f,0.5f,PdfContentByte.LINE_CAP_ROUND);
            Font fontTitle = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLACK);
            Chunk title = new Chunk("Lit Realty System Report", fontTitle);
            title.setLineHeight(30f);

            //Inserting Table in PDF
            PdfPTable table = new PdfPTable(3);
            table.setWidthPercentage(100); // Sets the width percentage that the table will occupy in the page
            table.setSpacingAfter(10f);
            table.setSpacingBefore(15f);
            table.setWidths(new float[] { 2f, 2f, 2f }); // Sets relative width of table

            Font fontHeader = new Font(Font.FontFamily.HELVETICA, 15, Font.BOLD, BaseColor.BLUE);
            PdfPCell headercell = new PdfPCell(new Phrase("Property Photo", fontHeader)); // Creates new cell in table
            headercell.setBackgroundColor(new BaseColor(230, 230, 243));
            headercell.setPaddingBottom(5f);
            table.addCell(headercell);

            headercell = new PdfPCell(new Phrase("Property ID", fontHeader));
            headercell.setBackgroundColor(new BaseColor(233, 233, 233));
            headercell.setPaddingBottom(5f);
            table.addCell(headercell);

            headercell = new PdfPCell(new Phrase("Price", fontHeader));
            headercell.setBackgroundColor(new BaseColor(233, 233, 233));
            headercell.setPaddingBottom(5f);
            table.addCell(headercell);

            PdfPCell cell1 = new PdfPCell(img, false);

            table.addCell(cell1);
            table.addCell("134000");
            table.addCell("213445");
            table.addCell("134000");

            //Inserting List
            com.itextpdf.text.List list = new com.itextpdf.text.List(true, 30);
            list.add(new ListItem("Example1"));
            list.add(new ListItem("Example2"));
            list.add(new ListItem("Example3"));

            //Adding elements into PDF Document
            document.open();

            document.add(img);
            document.add(title);

            document.add(Chunk.NEWLINE);
            document.add(table);

            document.newPage();
            document.add(new Chunk("List of Examples").setUnderline(+1f, -5f));
            document.add(list);

            document.newPage();
            document.add(new Chunk("List of Examples").setUnderline(+1f, -5f));
            document.add(list);

            document.newPage();
            document.add(new Chunk("List of Properts By Agent X").setUnderline(+1f, -5f));
            //////////////////////GET Propertys From Entity///////////////
            List<Properties> allPropertiesList = PropertiesDB.getAllProperties();

            PdfPTable propertyTable = new PdfPTable(3);
            PdfPCell propertyHeadingcell1 = new PdfPCell(new Phrase("Photo"));
            PdfPCell propertyHeadingcell2 = new PdfPCell(new Phrase("Property ID"));
            PdfPCell propertyHeadingcell3 = new PdfPCell(new Phrase("Price"));

            propertyHeadingcell1.setBorder(Rectangle.NO_BORDER);
            propertyHeadingcell2.setBorder(Rectangle.NO_BORDER);
            propertyHeadingcell3.setBorder(Rectangle.NO_BORDER);

            propertyTable.addCell(propertyHeadingcell1);
            propertyTable.addCell(propertyHeadingcell2);
            propertyTable.addCell(propertyHeadingcell3);

            document.add(Chunk.NEWLINE);

            String uploadPathforPropertyPhoto = getServletContext().getRealPath("")
                    + "images\\properties\\thumbnails\\";

            Image propertyThumbnail;

            img.scaleAbsolute(120f, 60f);// width,height of image in float

            for (Properties anProperty : allPropertiesList) {
                propertyThumbnail = Image.getInstance(uploadPathforPropertyPhoto + anProperty.getPhoto());
                PdfPCell propertycell1 = new PdfPCell(propertyThumbnail, false);
                propertycell1.setPaddingBottom(20);
                PdfPCell propertycell2 = new PdfPCell(new Phrase(anProperty.getListingNum().toString()));
                PdfPCell propertycell3 = new PdfPCell(new Phrase(anProperty.getPrice().toString()));

                propertycell1.setBorder(Rectangle.NO_BORDER);
                propertycell2.setBorder(Rectangle.NO_BORDER);
                propertycell3.setBorder(Rectangle.NO_BORDER);

                propertyTable.addCell(propertycell1);
                propertyTable.addCell(propertycell2);
                propertyTable.addCell(propertycell3);

            }
            document.add(Chunk.NEWLINE);
            document.add(propertyTable);
            //////////////////////GET Propertys From Entity///////////////

            document.close();
            file.close();

            System.out.println("Pdf created successfully ! :)");

            String filePath = Report;
            File downloadFile = new File(filePath);
            FileInputStream inStream = new FileInputStream(downloadFile);

            // if you want to use a relative path to context root:
            String relativePath = getServletContext().getRealPath("");
            System.out.println("relativePath = " + relativePath);

            // obtains ServletContext
            ServletContext context = getServletContext();

            // gets MIME type of the file
            String mimeType = context.getMimeType(filePath);
            if (mimeType == null) {
                // set to binary type if MIME mapping not found
                mimeType = "application/octet-stream";
            }
            System.out.println("MIME type: " + mimeType);

            // modifies response
            response.setContentType(mimeType);
            response.setContentLength((int) downloadFile.length());

            // forces download
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
            response.setHeader(headerKey, headerValue);

            // obtains response's output stream
            OutputStream outStream = response.getOutputStream();

            byte[] buffer = new byte[4096];
            int bytesRead = -1;

            while ((bytesRead = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }

            inStream.close();
            outStream.close();
            /////////////////

            processRequest(request, response);
        } catch (DocumentException ex) {
            Logger.getLogger(ManageAdmin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:tn.com.hitechart.eds.Util.pdfRpport.FirstPdf.java

private void createTable(Section subCatPart) throws BadElementException {

    //-------------------------- TAB POINTAGE -------------------//
    PdfPTable table = new PdfPTable(8);
    table.setTotalWidth(PageSize.A4.rotate().getWidth() - 10);
    table.setLockedWidth(true);// ww  w  . j  a v a 2s . c  o  m
    // t.setBorderColor(BaseColor.GRAY);
    // t.setPadding(4);
    // t.setSpacing(4);
    // t.setBorderWidth(1);
    //----------- C1 --------------//
    PdfPCell c1 = new PdfPCell(new Phrase("Date Rapport"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    c1.setBorder(Rectangle.NO_BORDER);
    table.addCell(c1);
    //----------- C2 --------------//
    c1 = new PdfPCell(new Phrase("Technicien"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    c1.setBorder(Rectangle.NO_BORDER);
    table.addCell(c1);
    //----------- C3 --------------//
    c1 = new PdfPCell(new Phrase("Poinatge"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    //----------- C4 --------------//
    c1 = new PdfPCell(new Phrase("Matin"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    //----------- C5 --------------//
    c1 = new PdfPCell(new Phrase("Aprs-Midi"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    //----------- C6 --------------//
    c1 = new PdfPCell(new Phrase("Rapport Journalier", catFont));
    c1.setBorder(Rectangle.NO_BORDER);
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    c1.setColspan(3);
    table.addCell(c1);
    //----------- C7 --------------//

    //----------- C8 --------------//

    table.setHeaderRows(1);

    //----------- R2 --------------//
    //----------- C1 --------------//
    c1 = new PdfPCell(new Phrase(tabDatapointage[0], dataFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    c1.setRowspan(2);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase(user.getLogin(), dataFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    c1.setRowspan(2);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Arrive"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase(tabDatapointage[1], dataFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase(tabDatapointage[2], dataFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase(""));
    c1.setBorder(Rectangle.NO_BORDER);
    table.addCell(c1);
    //----------- C7 --------------//

    c1 = new PdfPCell(new Phrase(""));
    c1.setBorder(Rectangle.NO_BORDER);
    table.addCell(c1);
    //----------- C8 --------------//

    c1 = new PdfPCell(new Phrase(""));
    c1.setBorder(Rectangle.NO_BORDER);
    table.addCell(c1);

    //----------- R3 --------------//

    c1 = new PdfPCell(new Phrase("Sortie"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase(tabDatapointage[3], dataFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase(tabDatapointage[4], dataFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase(""));
    c1.setBorder(Rectangle.NO_BORDER);
    table.addCell(c1);
    //----------- C7 --------------//
    c1 = new PdfPCell(new Phrase(""));
    c1.setBorder(Rectangle.NO_BORDER);
    table.addCell(c1);
    //----------- C8 --------------//
    c1 = new PdfPCell(new Phrase(""));
    c1.setBorder(Rectangle.NO_BORDER);
    table.addCell(c1);
    table.setSpacingAfter(10);
    subCatPart.add(table);

    //-------------------------- END TAB POINTAGE -------------------//
    // TODO: 20/01/2017
    //--------------------------------- TASK ---------------------//
    PdfPTable tableTask = new PdfPTable(5);

    tableTask.setTotalWidth(PageSize.A4.rotate().getWidth() - 10);
    tableTask.setLockedWidth(true);

    PdfPCell c2 = new PdfPCell(new Phrase("Dossiers Traits", catFont));
    c2.setHorizontalAlignment(Element.ALIGN_CENTER);
    c2.setColspan(5);
    c2.setBorder(Rectangle.NO_BORDER);
    tableTask.addCell(c2);

    tableTask.setHeaderRows(1);

    c2 = new PdfPCell(new Phrase("NDoss.", dataFont));
    c2.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableTask.addCell(c2);

    c2 = new PdfPCell(new Phrase("Client", dataFont));
    c2.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableTask.addCell(c2);

    c2 = new PdfPCell(new Phrase("Dure", dataFont));
    c2.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableTask.addCell(c2);

    c2 = new PdfPCell(new Phrase("Mission", dataFont));
    c2.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableTask.addCell(c2);

    c2 = new PdfPCell(new Phrase("Resultat", dataFont));
    c2.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableTask.addCell(c2);
    if (tasks.isEmpty()) {
        c2 = new PdfPCell(new Phrase("Aucune  Tache a t trait", catFontempty));
        c2.setHorizontalAlignment(Element.ALIGN_CENTER);
        c2.setColspan(5);
        tableTask.addCell(c2);
    } else {

        if (!dossiers.isEmpty()) {
            for (Dossier d : dossiers) {

                tableTask.addCell(d.getNumDoss());
                tableTask.addCell(d.getClient());
                tableTask.addCell(convertLongtoDurationfr(d.getTimeDuration()));
                tableTask.addCell(td.getTaskById(d.get_idTask()).getType());
                tableTask.addCell(td.getTaskById(d.get_idTask()).getRes());
            }
        }

    }

    tableTask.setSpacingAfter(10);

    subCatPart.add(tableTask);

    //-------------------------- END TAB TASK -------------------//
    // TODO: 20/01/2017  tab achat
    //-------------------------- TAB ACHAT -------------------//

    PdfPTable tableAchat = new PdfPTable(3);

    tableAchat.setTotalWidth(PageSize.A4.rotate().getWidth() - 10);
    tableAchat.setLockedWidth(true);

    PdfPCell c3 = new PdfPCell(new Phrase("Frais Engags", catFont));
    c3.setHorizontalAlignment(Element.ALIGN_CENTER);
    c3.setColspan(3);
    c3.setBorder(Rectangle.NO_BORDER);
    tableAchat.addCell(c3);

    tableAchat.setHeaderRows(1);
    c3 = new PdfPCell(new Phrase("N.Doss.", dataFont));
    c3.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableAchat.addCell(c3);

    c3 = new PdfPCell(new Phrase("Dsignation", dataFont));
    c3.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableAchat.addCell(c3);

    c3 = new PdfPCell(new Phrase("Montant TCC", dataFont));
    c3.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableAchat.addCell(c3);
    if (achats.isEmpty()) {
        c3 = new PdfPCell(new Phrase("la liste des achats est vide", catFontempty));
        c3.setHorizontalAlignment(Element.ALIGN_CENTER);
        c3.setColspan(3);
        tableAchat.addCell(c3);
    } else {

        for (Achat achat : achats) {

            tableAchat.addCell(String.valueOf(achat.getNumDoss()));
            tableAchat.addCell(achat.getDesignation());
            tableAchat.addCell(String.valueOf(achat.getPrix()));
        }
    }
    tableAchat.setSpacingAfter(10);
    subCatPart.add(tableAchat);
    //-------------------------- END TAB ACHAT -------------------//

    // TODO: 20/01/2017  tab composant
    //-------------------------- TAB COMPOSANT -------------------//

    PdfPTable tableComp = new PdfPTable(3);

    tableComp.setTotalWidth(PageSize.A4.rotate().getWidth() - 10);
    tableComp.setLockedWidth(true);

    PdfPCell c4 = new PdfPCell(new Phrase("Composants", catFont));
    c4.setHorizontalAlignment(Element.ALIGN_CENTER);
    c4.setColspan(3);
    c4.setBorder(Rectangle.NO_BORDER);
    tableComp.addCell(c4);
    tableComp.setHeaderRows(1);

    c4 = new PdfPCell(new Phrase("N.Doss.", dataFont));
    c4.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableComp.addCell(c4);

    c4 = new PdfPCell(new Phrase("Dsignation", dataFont));
    c4.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableComp.addCell(c4);

    c4 = new PdfPCell(new Phrase("Quantit", dataFont));
    c4.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableComp.addCell(c4);

    if (comps.isEmpty()) {
        c4 = new PdfPCell(new Phrase("la liste des composants est vide", catFontempty));
        c4.setHorizontalAlignment(Element.ALIGN_CENTER);
        c4.setColspan(3);
        tableComp.addCell(c4);
    } else {
        for (Composant comp : comps) {

            tableComp.addCell(String.valueOf(comp.getNumDoss()));
            tableComp.addCell(comp.getName());
            tableComp.addCell(String.valueOf(comp.getQte()));
        }
    }
    tableComp.setSpacingAfter(10);
    subCatPart.add(tableComp);
    //-------------------------- END TAB COMPOSANT -------------------//

    // TODO: 20/01/2017  tab message
    //-------------------------- TAB MESSAGE -------------------//

    PdfPTable tableMsg = new PdfPTable(2);

    tableMsg.setTotalWidth(PageSize.A4.rotate().getWidth() - 10);
    tableMsg.setLockedWidth(true);

    PdfPCell c5 = new PdfPCell(new Phrase("Message  Transmettre", catFont));
    c5.setHorizontalAlignment(Element.ALIGN_CENTER);
    c5.setColspan(3);
    c5.setBorder(Rectangle.NO_BORDER);
    tableMsg.addCell(c5);

    c5 = new PdfPCell(new Phrase("N.Doss.", dataFont));
    c5.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableMsg.addCell(c5);

    tableMsg.setHeaderRows(1);
    c5 = new PdfPCell(new Phrase("Message", dataFont));
    c5.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableMsg.addCell(c5);

    tableMsg.setHeaderRows(1);
    if (msgs.isEmpty()) {
        c5 = new PdfPCell(new Phrase("Aucun message", catFontempty));
        c5.setHorizontalAlignment(Element.ALIGN_CENTER);
        c5.setColspan(3);
        tableMsg.addCell(c5);
    } else {
        for (Message msg : msgs) {

            tableMsg.addCell(String.valueOf(msg.getNumDoss()));
            tableMsg.addCell(msg.getMsg());
        }
    }
    tableMsg.setSpacingAfter(10);
    subCatPart.add(tableMsg);
    //-------------------------- END TAB MESSAGE -------------------//

    // TODO: 20/01/2017  tab Activitee
    //-------------------------- TAB ACTIVITEE -------------------//

    PdfPTable tableAct = new PdfPTable(2);

    tableAct.setTotalWidth(PageSize.A4.rotate().getWidth() - 10);
    tableAct.setLockedWidth(true);

    PdfPCell c6 = new PdfPCell(new Phrase("Autre Activites", catFont));
    c6.setHorizontalAlignment(Element.ALIGN_CENTER);
    c6.setColspan(2);
    c6.setBorder(Rectangle.NO_BORDER);
    tableAct.addCell(c6);

    tableAct.setHeaderRows(1);

    c6 = new PdfPCell(new Phrase("N.Doss.", dataFont));
    c6.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableAct.addCell(c6);

    c6 = new PdfPCell(new Phrase("Dure", dataFont));
    c6.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableAct.addCell(c6);
    if (autreActs.isEmpty()) {
        c6 = new PdfPCell(new Phrase("Aucune autre Activite a t effectu", catFontempty));
        c6.setHorizontalAlignment(Element.ALIGN_CENTER);
        c6.setColspan(3);
        tableAct.addCell(c6);
    } else {

        for (Task autreA : autreActs) {

            tableAct.addCell(String.valueOf(autreA.getType()));
            tableAct.addCell(autreA.getNumDoss());
        }

    }
    tableAct.setSpacingAfter(10);
    subCatPart.add(tableAct);
    //-------------------------- END TAB MESSAGE -------------------//
}

From source file:utils.PrintInvoice.java

public void getDocument() {
    try {//from ww  w.jav  a 2s  . c o  m
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream("SaleBill#" + salebill.getId() + ".pdf"));

        document.open();
        ////////////////////////////////////////////////////////////////////////////////////
        ///////////////////Start Document Here/////////////////////////////////
        PdfContentByte directContent = writer.getDirectContent();
        Paragraph p1 = new Paragraph("SALE BILL");
        p1.setFont(FONT[4]);
        p1.setAlignment(Element.ALIGN_CENTER);

        document.add(p1);
        //show the company details here.
        Phrase company = new Phrase(new Chunk("BIO PHARMA\nAKOT 444101(M.S)", FONT[3]));
        document.add(company);
        document.add(new Phrase(
                "\nLicense No : 20B : AK-88888\n                     21B : AK-88889\n       Mobile : "
                        + SessionClass.getInstance().getMobileNumber(),
                FONT[2]));

        //            Phrase mobNum  = new Phrase("    Mobile : "+SessionClass.getInstance().getMobileNumber() );
        //            mobNum.setFont(FONT[2]);
        //            ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, mobNum, 35, 710, 0);

        System.out.println(dateFormatter.format(salebill.getBillDate()));
        //show the invoice details
        //  String txt = "Bill No. : " + salebill.getId()+"\nBill Date : " + dateFormatter.format(salebill.getBillDate()) +;
        Phrase invoiceDetails = new Phrase("Bill No. : " + salebill.getId());
        ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, invoiceDetails, 400, 693, 0);
        invoiceDetails = new Phrase("Bill Date : " + dateFormatter2.format(salebill.getBillDate()));
        ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, invoiceDetails, 400, 681, 0);
        invoiceDetails = new Phrase("Mode of Payment : " + salebill.getMode());
        ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, invoiceDetails, 400, 668, 0);

        //show the customer details
        Customer c = salebill.getCustomerId();
        Phrase custDetails = new Phrase("SOLD TO", FONT[3]);
        ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails, 35, 693, 0);
        custDetails = new Phrase(c.getCompanyName());
        ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails, 35, 681, 0);
        custDetails = new Phrase(c.getSiteAddress());
        ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails, 35, 668, 0);
        custDetails = new Phrase("Licence : " + c.getLicenceNo());
        ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails, 35, 655, 0);

        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);

        //Item Particulars are shown here
        PdfPTable table = new PdfPTable(7);
        table.setTotalWidth(new float[] { 175, 80, 80, 50, 50, 50, 75 });
        table.setHeaderRows(1);

        //headers
        table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
        table.addCell("Particulars");
        table.addCell("Batch");
        table.addCell("Expiry");
        table.addCell("MRP");
        table.addCell("Rate");
        table.addCell("Qnty");
        table.addCell("SubTotal");
        table.getDefaultCell().setBackgroundColor(null);
        table.setSpacingAfter(5.0f);

        List<SaleBillPharmaItem> items = salebill.getSaleBillPharmaItemList();
        for (int i = 0; i < items.size(); i++) {
            PdfPCell desc = new PdfPCell(new Phrase(items.get(i).getItemName()));

            table.addCell(desc);

            PdfPCell batch = new PdfPCell(new Phrase(items.get(i).getBatch()));

            table.addCell(batch);

            PdfPCell expiry = null;
            Date tDate = null;
            try {
                tDate = dateFormatter2.parse(items.get(i).getExpDate());
            } catch (ParseException ex) {
                Logger.getLogger(PrintInvoice.class.getName()).log(Level.SEVERE, null, ex);
            }

            expiry = new PdfPCell(new Phrase(dateFormatter.format(tDate)));

            table.addCell(expiry);

            PdfPCell mrp = new PdfPCell(new Phrase(items.get(i).getMrp() + ""));
            //                 //mrp.setBorderColor(BaseColor.WHITE);
            //                 mrp.setBorderColorLeft(BaseColor.BLACK);
            //                 mrp.setBorderColorRight(BaseColor.WHITE);
            table.addCell(mrp);
            PdfPCell rate = new PdfPCell(new Phrase(items.get(i).getItemRate() + ""));
            //                 //rate.setBorderColor(BaseColor.WHITE);
            //                 rate.setBorderColorLeft(BaseColor.BLACK);
            //                 rate.setBorderColorRight(BaseColor.WHITE);
            table.addCell(rate);
            PdfPCell quantity = new PdfPCell(new Phrase(items.get(i).getQnty() + ""));
            //                 //quantity.setBorderColor(BaseColor.WHITE);
            //                 quantity.setBorderColorLeft(BaseColor.BLACK);
            //                 quantity.setBorderColorRight(BaseColor.WHITE);
            table.addCell(quantity);
            PdfPCell subtotal = new PdfPCell(new Phrase(items.get(i).getAmt() + ""));
            //                 //subtotal.setBorderColor(BaseColor.WHITE);
            //                 subtotal.setBorderColorLeft(BaseColor.BLACK);
            //                 subtotal.setBorderColorRight(BaseColor.WHITE);
            table.addCell(subtotal);

        }

        //now show the sub details
        //PdfPCell finalCell = new PdfPCell(new Phrase("Total VAT Amt : Rs " + salebill.getTotalVat() + "                     Total Amount : Rs "));
        //Todo change code here to show vat amount when there is vat number
        PdfPCell finalCell = new PdfPCell(
                new Phrase("Total VAT Amt : Rs " + salebill.getTotalVat() + "           Total Amount : Rs "));
        finalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        finalCell.setColspan(6);
        table.addCell(finalCell);
        table.addCell("" + salebill.getTotalAmt());

        PdfPCell cdCell = new PdfPCell(new Phrase("Cash Discount (2 %) : (-) Rs"));
        cdCell.setColspan(6);
        cdCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell(cdCell);
        table.addCell("" + salebill.getDiscount());

        PdfPCell finalAmtCell = new PdfPCell(new Phrase("Final Amount : Rs"));
        finalAmtCell.setColspan(6);
        finalAmtCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell(finalAmtCell);
        table.addCell("" + salebill.getFinalAmt());

        document.add(table);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);

        Paragraph sign = new Paragraph(new Chunk("Authorized signatory\n(BIO PHARMA)"));
        sign.setAlignment(Element.ALIGN_RIGHT);
        document.add(sign);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);

        document.add(Chunk.NEWLINE);

        Paragraph p = new Paragraph("THANK YOU FOR YOUR BUSINESS");
        p.setFont(FONT[4]);
        p.setAlignment(Element.ALIGN_CENTER);
        document.add(p);

        ///////////////////End Documnet here//////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////
        document.close(); // no need to close PDFwriter?

    } catch (DocumentException | FileNotFoundException e) {
        //LOGGER
        e.printStackTrace();
        Stage dialogStage = new Stage();
        dialogStage.setTitle("Printing Error");
        dialogStage.initModality(Modality.WINDOW_MODAL);
        dialogStage.setScene(new Scene(VBoxBuilder.create()
                .children(new Text(
                        "The file to be printed is already open \n. Please close the file and Print Again"))
                .alignment(Pos.CENTER).padding(new Insets(50)).build()));
        dialogStage.show();
    }

}

From source file:validator.Invoice.java

public static boolean printInvoice(HttpServletResponse response)
        throws DocumentException, FileNotFoundException {
    Document document = new Document();
    java.net.URL path = LogData.class.getResource("/");
    String destinationDir;/*from   w  ww.  j  a v a2  s. c  om*/
    destinationDir = path.toString();
    destinationDir = destinationDir.substring(destinationDir.lastIndexOf(":") + 1,
            destinationDir.indexOf("WEB-INF"));
    String filePath = destinationDir + "invoice" + "/";
    ;
    File fileName = new File(filePath);
    if (!fileName.exists()) {
        fileName.mkdir();
    }

    filePath = filePath + "invoice" + ".pdf";
    PdfWriter.getInstance(document, new FileOutputStream(filePath));
    document.open();
    Paragraph paragraph1 = new Paragraph("Invoice");
    paragraph1.setAlignment(Element.ALIGN_CENTER);

    paragraph1.setFont(FontFactory.getFont(FontFactory.COURIER, 18, Font.BOLD, new CMYKColor(0, 255, 0, 0)));
    Paragraph datePara = new Paragraph("Date :" + new Date());
    datePara.setAlignment(Element.ALIGN_RIGHT);

    File file = new File(filePath);
    PdfPTable table = new PdfPTable(2);
    table.setSpacingBefore(25);
    table.setWidthPercentage(100);
    table.setSpacingAfter(25);

    PdfPCell c1 = new PdfPCell(new Phrase("Description"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    c1 = new PdfPCell(new Phrase(" Amount "));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    table.setHeaderRows(1);
    table.addCell("         " + "   ");
    table.addCell("         " + "  ");
    table.addCell("          Total Balance amount :");
    table.addCell("         " + "   ");
    Paragraph amountPara = new Paragraph("\nPaid Amount:  ");
    Paragraph forCom = new Paragraph("\n For Company: ");
    document.open();
    document.add(paragraph1);
    document.add(datePara);
    document.add(table);
    document.add(amountPara);
    document.add(forCom);
    document.close();
    streamImageFile(file, response);

    return true;
}