Example usage for com.itextpdf.text FontFactory getFont

List of usage examples for com.itextpdf.text FontFactory getFont

Introduction

In this page you can find the example usage for com.itextpdf.text FontFactory getFont.

Prototype


public static Font getFont(final String fontname, final float size, final int style, final BaseColor color) 

Source Link

Document

Constructs a Font-object.

Usage

From source file:SessionBean.ReportMgt.ReportMgtBean.java

License:Open Source License

public void createProductReport(Long productId, Integer startYear, Integer startMonth, Integer endYear,
        Integer endMonth) {//w  w  w .  j a v a  2s  .  co m
    try {
        System.out.print("start");
        ItemEntity item = em.find(ItemEntity.class, productId);
        String RESULT;
        String reportTitle;

        if (startYear.equals(endYear) && startMonth.equals(endMonth)) {
            RESULT = "d:/ProductReport-" + item.getId() + "-" + startYear + "." + startMonth + ".pdf";
            reportTitle = startYear + "." + startMonth;
        } else {
            RESULT = "d:/ProductReport-" + item.getId() + "-" + startYear + "." + startMonth + "-" + endYear
                    + "." + endMonth + ".pdf";
            reportTitle = startYear + "." + startMonth + "-" + endYear + "." + endMonth;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Document document = new Document();
        PdfWriter.getInstance(document, baos);
        document.open();
        Image image = Image.getInstance("d:/logo-4227.png");
        image.scaleAbsolute(150, 50);
        document.add(image);

        document.add(new Paragraph("WineXpress Product Sales Report",
                FontFactory.getFont(FontFactory.TIMES_BOLD, 18, Font.BOLD, BaseColor.BLACK)));
        document.add(new Paragraph("Item " + item.getId() + ": " + item.getItemName() + ", " + item.getVitage(),
                FontFactory.getFont(FontFactory.TIMES_BOLD, 18, Font.BOLD, BaseColor.RED)));
        document.add(new Paragraph("Generated Time: " + new Date().toString(),
                FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.PLAIN, BaseColor.BLACK)));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(
                "--------------------------------------------------------------------------------------------------------------------------"));

        PdfPTable table = new PdfPTable(5);
        table.getDefaultCell().setBorder(0);
        //            PdfPCell cell= new PdfPCell(new Paragraph("Wine Name"));
        //           cell.setColspan(4);
        //            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        //            cell.setBackgroundColor(BaseColor.BLACK);
        //           table.addCell(cell);
        table.addCell("Period");
        table.addCell("Sales");
        table.addCell("Revenue");
        table.addCell("Cost");
        table.addCell("Profit");
        table.addCell(" ");
        table.addCell("(bottle)");
        table.addCell("(SGD)");
        table.addCell("(SGD)");
        table.addCell("(SGD)");

        Integer totalSales = 0;
        Double totalRevenue = 0D;
        Double totalCost = 0D;
        Double totalProfit = 0D;

        Query q1;
        q1 = em.createQuery("select i from PurchaseEntity i");
        Query q2;
        q2 = em.createQuery("select i from ItemEntity i");
        System.out.print("2");
        List<ItemEntity> itemList = q2.getResultList();
        List<PurchaseEntity> purchaseList = q1.getResultList();
        System.out.print("3");

        for (int y = startYear; y <= endYear; y++) {

            for (int m = startMonth - 1; m <= endMonth - 1; m++) {
                Integer sales = 0;
                Double revenue = 0D;
                Double cost = 0D;
                System.out.print("loop");
                for (PurchaseEntity p : purchaseList) {
                    System.out.print("looploop1");
                    Long orderId = p.getOrderId();
                    OrderEntity order = em.find(OrderEntity.class, orderId);
                    ItemEntity item1 = em.find(ItemEntity.class, order.getItemId());
                    System.out.print("looploop2");
                    if (item1.getId().equals(item.getId()) && p.getPurchasedDate().get(Calendar.MONTH) == m
                            && p.getPurchasedDate().get(Calendar.YEAR) == y) {
                        sales += p.getQuantity();
                        revenue += p.getTotalPrice();
                        cost += p.getQuantity() * item.getCost();
                        System.out.print("looploop3");
                    }
                }
                Double profit = revenue - cost;
                totalSales += sales;
                totalRevenue += revenue;
                totalCost += cost;
                totalProfit += profit;
                int n = m + 1;
                table.addCell(y + "-" + n);
                table.addCell(sales.toString());
                table.addCell(revenue.toString());
                table.addCell(cost.toString());
                table.addCell(profit.toString());
            }
        }
        document.add(table);

        document.add(new Paragraph(
                "--------------------------------------------------------------------------------------------------------------------------"));

        PdfPTable table2 = new PdfPTable(5);
        table2.getDefaultCell().setBorder(0);

        table2.addCell(" ");
        table2.addCell(totalSales.toString());
        table2.addCell(totalRevenue.toString());
        table2.addCell(totalCost.toString());
        table2.addCell(totalProfit.toString());

        document.add(table2);
        document.add(new Paragraph(
                "--------------------------------------------------------------------------------------------------------------------------"));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));

        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph("Copyright  2015 All rights reserved | WineXpress",
                FontFactory.getFont(FontFactory.TIMES_BOLD, 12, BaseColor.BLACK)));
        document.close();
        FileOutputStream fos = new FileOutputStream(RESULT);
        fos.write(baos.toByteArray());
        fos.close();
        System.out.println("created");

        Calendar generatedTime = Calendar.getInstance();
        ReportEntity report = new ReportEntity("ProductReport-" + item.getId() + "-" + reportTitle,
                item.getId().toString(), RESULT, generatedTime);
        em.persist(report);
        em.flush();

    } catch (Exception e) {
    }
}

From source file:Subordinate.request.java

private void jLabel15MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel15MouseClicked
    Document document = new Document();
    try {/*ww  w . java  2 s  .co m*/
        PdfWriter.getInstance(document, new FileOutputStream("printreq.pdf"));
        document.open();

        SimpleDateFormat td = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        String tdnow = td.format(now);

        Paragraph paragraph = new Paragraph(ALLBITS);
        paragraph.add(new Paragraph(tdnow));
        paragraph.add(new Paragraph("Request : \n\n",
                FontFactory.getFont(FontFactory.COURIER_BOLD, 20, Font.BOLD, BaseColor.DARK_GRAY)));
        document.add(paragraph);
        PdfPTable table = new PdfPTable(2);
        table.addCell("ID Request :");
        table.addCell(request.intGetter("idRequest") + "");
        table.addCell("Request type :");
        table.addCell(request.stringGetter("requestType"));
        table.addCell("Client name :");
        table.addCell(request.stringGetter("clientName"));
        table.addCell("Phone number :");
        table.addCell(request.stringGetter("clientTel"));
        table.addCell("Address 1 :");
        table.addCell(request.stringGetter("address1"));
        table.addCell("Address 2 :");
        table.addCell(request.stringGetter("address2"));
        document.add(table);
        document.close();
        /* Open Pdf */
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN)) {
            desktop.open(new File("printreq.pdf"));
        } else {
            System.out.println("Open is not supported");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Subordoante.Sub.java

public void openPDF() {
    Document document = new Document();
    try {//from w w w .  jav a  2s  .c  o m
        PdfWriter.getInstance(document, new FileOutputStream("printreq.pdf"));
        document.open();
        SimpleDateFormat td = new SimpleDateFormat("yyyy-MM-dd");
        Date now = new Date();
        String tdnow = td.format(now);
        Paragraph paragraph = new Paragraph(ALLBITS);
        paragraph.add(new Paragraph(tdnow));
        paragraph.add(new Paragraph("Request : \n\n",
                FontFactory.getFont(FontFactory.TIMES, 20, Font.BOLD, BaseColor.DARK_GRAY)));
        document.add(paragraph);
        PdfPTable table = new PdfPTable(2);
        table.addCell("ID Request :");
        table.addCell(request.intGetter("idRequest") + "");
        table.addCell("Request type :");
        table.addCell(request.stringGetter("requestNet"));
        table.addCell("Client name :");
        table.addCell(request.stringGetter("clientName"));
        table.addCell("Phone number :");
        table.addCell(request.stringGetter("clientTel"));
        table.addCell("Address  :");
        table.addCell(request.stringGetter("address1"));
        if (request.stringGetter("requestType").equalsIgnoreCase("Transfer")) {
            table.addCell("Transfer address:");
            table.addCell(request.stringGetter("address2"));
        } else if (request.stringGetter("requestType").equalsIgnoreCase("Maintenance")) {
            table.addCell("Problem :");
            table.addCell(request.stringGetter("problem"));
        } else
            ;

        document.add(table);
        document.close();
        /* Open Pdf */
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN)) {
            desktop.open(new File("printreq.pdf"));
        } else {
            System.out.println("Open is not supported");
        }
    } catch (DocumentException | IOException ex) {
    }
}

From source file:tprog.web.DescargarPDF.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    URL wsdlLocation = new URL(getServletContext().getInitParameter("wsdl"));
    webservice.PublicadorService service = new webservice.PublicadorService(wsdlLocation);
    webservice.Publicador proxy = service.getPublicadorPort();
    System.out.println("Llego hasta el servlet");
    //response.setContentType("application/pdf");
    try {//from   w  w w.  j  a  v a2 s  . c  o  m
        String idReservaString = request.getParameter("idReserva");
        response.setContentType("application/pdf");
        Integer idReserva = Integer.parseInt(idReservaString);
        WrapperVerFactura wrapper = proxy.verFactura(idReserva);
        DtFacturaF dtf = wrapper.getFactura();
        Set<DtServicioF> servicios = new HashSet(dtf.getServicios());
        Set<DtPromocionF> promociones = new HashSet(dtf.getPromociones());
        String fecha = Integer.toString(dtf.getFecha().getDay()) + "-"
                + Integer.toString(dtf.getFecha().getMonth()) + "-" + Integer.toString(dtf.getFecha().getYear())
                + "\n";
        //creo el documento pdf dinmicamente : no s donde se guarda
        //pero se genera a demanda siempre
        Document document = new Document();
        PdfWriter.getInstance(document, response.getOutputStream());
        document.open();
        document.add(new Paragraph("Detalles de la Factura",
                FontFactory.getFont("arial", 22, Font.ITALIC, BaseColor.BLACK)));
        document.add(new Paragraph(" "));
        //ingreso los datos de la factura
        document.add(new Paragraph("Id de la Reserva: " + idReservaString));
        document.add(new Paragraph("Fecha: " + fecha));
        document.add(new Paragraph("Cliente: " + dtf.getNicknameCliente()));
        document.add(new Paragraph("Monto: $" + dtf.getMonto()));
        document.add(new Paragraph(" "));
        //tabla para los servicios
        if (!servicios.isEmpty()) {
            document.add(new Paragraph("Servicios"));
            document.add(new Paragraph(" "));
            PdfPTable table = new PdfPTable(5);
            table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
            table.addCell("Item");
            table.addCell("Nombre");
            table.addCell("Cantidad");
            table.addCell("Precio");
            table.addCell("Proveedor");
            table.getDefaultCell().setBackgroundColor(null);
            int i = 1;
            for (DtServicioF servicio : servicios) {
                table.addCell(Integer.toString(i));
                table.addCell(servicio.getNombre());
                table.addCell(Integer.toString(servicio.getCantidad()));
                table.addCell(Double.toString(servicio.getPrecio()));
                table.addCell(servicio.getNicknameProveedor());
                i++;
            }
            document.add(table);
            document.add(new Paragraph(" "));
        }
        //tabla para las promos
        if (!promociones.isEmpty()) {
            document.add(new Paragraph("Promociones"));
            document.add(new Paragraph(" "));
            PdfPTable table = new PdfPTable(5);
            table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
            table.addCell("Item");
            table.addCell("Nombre");
            table.addCell("Cantidad");
            table.addCell("Precio");
            table.addCell("Proveedor");
            table.getDefaultCell().setBackgroundColor(null);
            int i = 1;
            for (DtPromocionF promocion : promociones) {
                table.addCell(Integer.toString(i));
                table.addCell(promocion.getNombre());
                table.addCell(Integer.toString(promocion.getCantidad()));
                table.addCell(Double.toString(promocion.getPrecio()));
                table.addCell(promocion.getNicknameProveedor());
                i++;
            }

            document.add(table);
            document.add(new Paragraph(" "));
        }
        document.close();
        //         session.setAttribute("descargaOK", "La descarga se complet correctamente.");
        response.sendRedirect("VerPerfil");
    } catch (DocumentException de) {
        throw new IOException(de.getMessage());
    }
}

From source file:userInterface.SystemAdmin.PovertyAnalysisJPanel.java

private void downloadPDFJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_downloadPDFJButtonActionPerformed
    Document document = new Document();
    try {//from www.j av  a 2s .co m
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("AddTableExample.pdf"));
        document.open();

        Font helveticaBold = FontFactory.getFont(FontFactory.HELVETICA, 16, Font.NORMAL, new GrayColor(1));
        Font helveticaNormal = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new GrayColor(1));

        Paragraph paragraphOne = new Paragraph("Safety Meter Report", helveticaBold);
        document.add(paragraphOne);
        document.add(new Paragraph("  "));
        DefaultTableModel model = (DefaultTableModel) povertyJTable.getModel();
        int numRows = model.getRowCount();
        int numColum = model.getColumnCount();
        int i, j = 0;
        for (i = 0; i < numRows; i++) {
            Paragraph info = new Paragraph("Network Name is " + model.getValueAt(i, 0), helveticaNormal);
            Paragraph sectionContent3 = new Paragraph(
                    "Average Income of A Person is $" + model.getValueAt(i, 2), helveticaNormal);
            info.add(sectionContent3);
            Paragraph sectionContent1 = new Paragraph("Crime Rate is " + model.getValueAt(i, 6) + "%",
                    helveticaNormal);
            info.add(sectionContent1);
            Paragraph sectionContent2 = new Paragraph("Poverty Rate is " + model.getValueAt(i, 4) + "%",
                    helveticaNormal);
            info.add(sectionContent2);
            Paragraph sectionContent4 = new Paragraph(
                    "Percentage of People Having FireArms " + model.getValueAt(i, 3) + "%", helveticaNormal);
            info.add(sectionContent4);
            document.add(info);
            Paragraph space = new Paragraph("   ", helveticaNormal);
            document.add(space);
        }
        //document.add(table);
        document.close();
        writer.close();
        JOptionPane.showMessageDialog(povertyJTable, "Please visit Downloads folder to view your report");

    } catch (Exception e) {
        JOptionPane.showMessageDialog(povertyJTable, e);
    }
}

From source file:util.ImageExample.java

public ImageExample(Calendar date, int settings, ArrayList<String> courses, String time, String eventAddress,
        int totalPrice, String comments, boolean kunde) throws Exception {
    this.date = date;
    this.settings = settings;
    this.courses = courses;
    this.time = time;
    this.eventAddress = eventAddress;
    this.totalPrice = totalPrice;
    this.comments = comments;
    this.fileName = "";
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    ge.getAllFonts();/*ww w  . j a  v a 2s.  c  om*/
    FontFactory.register("C:/Windows/Fonts/ARLRDBD.TTF", "Arial Rounded");
    Font font = FontFactory.getFont("Arial Rounded", 22, Font.NORMAL, new BaseColor(51, 102, 102));
    Document document = new Document();

    System.out.println("Pdf creation startet");
    try {
        if (kunde) {
            fileName = "grill" + new SimpleDateFormat("dd. MMMMM yyyy hhmm").format(date.getTime()) + ".pdf";
        } else {
            fileName = "grill" + new SimpleDateFormat("dd. MMMMM yyyy hhmm").format(date.getTime())
                    + "Prisliste.pdf";
        }

        FileOutputStream file = new FileOutputStream(new File("C:/Users/Mark/Desktop", fileName));
        PdfWriter writer = PdfWriter.getInstance(document, file);
        document.open();

        Image img = Image.getInstance("src/pictures/cirkles.png");
        img.scaleToFit(277, 277);
        img.setAbsolutePosition(40, PageSize.A4.getHeight() - img.getHeight());
        document.add(img);
        Chunk chunk = new Chunk("Grillmester 'Frankie'", font);
        chunk.setCharacterSpacing(3);
        Paragraph header = new Paragraph(chunk);
        header.setAlignment(Element.ALIGN_RIGHT);
        header.setSpacingBefore(15);
        document.add(header);
        Paragraph title = new Paragraph(
                "Tilbud angende d. " + new SimpleDateFormat("dd. MMMMM yyyy").format(date.getTime()) + ".",
                new Font(Font.FontFamily.TIMES_ROMAN, 20, Font.BOLD));
        title.setAlignment(Element.ALIGN_LEFT);
        title.setIndentationLeft(235);
        title.setSpacingBefore(100);
        title.setLeading(17);
        document.add(title);
        Paragraph subtitle = new Paragraph("(Arrangement til " + settings + " personer).",
                new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.ITALIC));
        subtitle.setAlignment(Element.ALIGN_LEFT);
        subtitle.setIndentationLeft(235);
        subtitle.setLeading(17);
        document.add(subtitle);
        Paragraph body = new Paragraph("\n\nDer er aftalt:\n\n", new Font(Font.FontFamily.TIMES_ROMAN, 18));
        body.setAlignment(Element.ALIGN_LEFT);
        body.setIndentationLeft(235);
        body.setLeading(17);
        for (String course : courses) {
            body.add(course + "\n\n");
        }
        body.add("\nServeres klokken " + time + " i " + eventAddress + ".");
        document.add(body);
        Paragraph ending = new Paragraph("\n\n\nPris: " + totalPrice + ",-kr.",
                new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD));
        ending.setAlignment(Element.ALIGN_LEFT);
        ending.setIndentationLeft(235);
        ending.setLeading(17);
        document.add(ending);
        if (!comments.equals("null")) {
            if (!comments.equals("")) {
                Paragraph comment = new Paragraph("\n\nKommentarer\n" + comments,
                        new Font(Font.FontFamily.TIMES_ROMAN, 18));
                comment.setAlignment(Element.ALIGN_LEFT);
                comment.setIndentationLeft(235);
                comment.setLeading(17);
                document.add(comment);
            }
        }

        Image footerImg = Image.getInstance("src/pictures/grillmester.png");
        footerImg.scaleToFit(210, 210);
        footerImg.setAbsolutePosition(40, 40);
        document.add(footerImg);

        Image img2 = Image.getInstance("src/pictures/Contact.png");
        img2.scaleToFit(250, 250);
        img2.setAbsolutePosition(20, PageSize.A4.getHeight() - img.getHeight() - 250);
        document.add(img2);

        document.close();

        System.out.println("Pdf finish");
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(e.getLocalizedMessage());
    }
}

From source file:utiles.FacturaPdf.java

/**
 * metodo que hace uso de la clase itext para generar archivos PDF recogiendo 
 * los datos para una factura//from  w  w w. j av  a  2s .  co m
 * @param _nombre recoge el cliente que realiza la reserva
 * @param _dni optiene la documentacion del cliente
 * @param _telefono se le pasa numero de contacto del cliente
 * @param _cantidad se indica numero de servicios que ha comprado
 * @param _servicio recoge el nombre del servicio comprado 
 * @param _fecha optiene fecha en la que el cliente tiene la "cita"
 * @param _total coste de todos los servicios comprados "cantidad*precio del servicio - la promocion"
 * @throws Exception 
 */

public static void ITextHelloWorld(String _nombre, String _dni, String _telefono, String _cantidad,
        String _servicio, String _fecha, String _total) throws Exception {
    Document document = new Document();
    Paragraph parrafo, paragraph_2, parrafo2, parrafo3, parrafo4;

    Image imagen = Image.getInstance("src/icon/Spa.jpg");

    // Le indicamos donde se guardara el archivo
    PdfWriter.getInstance(document, new FileOutputStream("src/pdfGenerados/" + "Factura_" + _nombre + "_"
            + _servicio + "_" + _cantidad + "_" + _total + ".pdf"));

    // Este codigo genera una tabla de 2 columnas
    PdfPTable table = new PdfPTable(7);
    table.setWidthPercentage(100);
    String nombre = _nombre;
    String dni = _dni;
    String telefono = _telefono;
    String cantidad = _cantidad;
    String servicio = _servicio;
    String fecha = _fecha;
    String total = _total + " ";
    // addCell() agrega una celda a la tabla, el cambio de fila
    // ocurre automaticamente al llenar la fila
    table.addCell("Nombre");
    table.addCell("Dni");
    table.addCell("Telefono");
    table.addCell("Cantidad");
    table.addCell("Servicio");
    table.addCell("Fecha reserva");
    table.addCell("Precio total");

    table.addCell(nombre);
    table.addCell(dni);
    table.addCell(telefono);
    table.addCell(cantidad);
    table.addCell(servicio);
    table.addCell(fecha);
    table.addCell(total);

    document.open();

    //Creamos una cantidad significativa de paginas para probar el encabezado

    parrafo = new Paragraph("Gracias por confiar en nuestros servicios SpaRelajate");
    paragraph_2 = new Paragraph(" FACTURA ");
    parrafo2 = new Paragraph("           ");
    parrafo3 = new Paragraph("           ");
    parrafo4 = new Paragraph("           ");

    //este codigo hace que se nos centre tanto el texto como la imagen
    parrafo.setAlignment(Element.ALIGN_CENTER);
    paragraph_2.setAlignment(Element.ALIGN_CENTER);
    parrafo2.setAlignment(Element.ALIGN_CENTER);
    imagen.setAlignment(Element.ALIGN_CENTER);
    paragraph_2.setFont(new Font(FontFactory.getFont("Helvetica", 40, Font.BOLD, BaseColor.BLACK)));
    //aade la documentacion que tendra el pdf

    document.add(parrafo4);
    document.add(parrafo4);
    document.add(imagen);
    document.add(parrafo4);
    document.add(parrafo4);
    document.add(paragraph_2);
    document.add(parrafo3);
    document.add(parrafo4);
    document.add(parrafo4);
    document.add(parrafo4);
    document.add(parrafo4);
    document.add(table);
    document.add(parrafo4);
    document.add(parrafo2);
    document.add(parrafo3);
    document.add(parrafo4);
    document.add(parrafo4);
    document.add(parrafo4);
    document.add(parrafo4);
    document.add(parrafo4);
    document.add(parrafo2);
    document.add(parrafo);
    document.close();

}

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;/*  w  w w.  ja  va  2  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;
}

From source file:views.Clientes.java

private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
    try {//from   w ww.  j av  a2  s  .c o m
        OutputStream file = new FileOutputStream(new File("C:\\CuotaSoft\\Historial.pdf"));
        Document document = new Document();
        PdfWriter writer;

        writer = PdfWriter.getInstance(document, file);

        document.open();
        // Se agrega titulo y datos del cliente
        Paragraph p = new Paragraph("Historial de Cliente \n",
                FontFactory.getFont("Arial", 16, Font.BOLD, BaseColor.BLACK));
        p.setAlignment(Element.ALIGN_CENTER);
        Paragraph pNumero = new Paragraph("N Cliente: " + txtNroCliente.getText(),
                FontFactory.getFont("Arial", 12, Font.NORMAL, BaseColor.BLACK));
        Paragraph pNombre = new Paragraph(
                "Nombre Cliente: " + txtNombre.getText() + " " + txtApellido.getText(),
                FontFactory.getFont("Arial", 12, Font.NORMAL, BaseColor.BLACK));
        Paragraph pProductos = new Paragraph("Productos Comprados: ",
                FontFactory.getFont("Arial", 14, Font.BOLD, BaseColor.BLACK));
        pProductos.setAlignment(Element.ALIGN_CENTER);
        Paragraph pSaldo = new Paragraph("Saldo:  $" + txtSaldo.getText(),
                FontFactory.getFont("Arial", 14, Font.BOLD, BaseColor.BLACK));
        pSaldo.setAlignment(Element.ALIGN_RIGHT);
        //se agregan paragraphs
        document.add(p);
        document.add(pNumero);
        document.add(pNombre);
        document.add(pSaldo);
        document.add(new Paragraph("\n"));
        document.add(pProductos);
        document.add(new Paragraph("\n"));

        //se agrega tabla productos
        PdfPTable pTablaProducto = new PdfPTable(4);

        float[] mediaCeldasProductos = { 3.30f, 3.50f, 3.50f, 3.70f };

        pTablaProducto.setWidths(mediaCeldasProductos);
        pTablaProducto.addCell(new Paragraph("Producto", FontFactory.getFont("Arial", 12)));
        pTablaProducto.addCell(new Paragraph("Cantidad", FontFactory.getFont("Arial", 12)));
        pTablaProducto.addCell(new Paragraph("Precio", FontFactory.getFont("Arial", 12)));
        pTablaProducto.addCell(new Paragraph("Total", FontFactory.getFont("Arial", 12)));

        ArrayList<Venta> listaProductos = ctrlVenta.listByCliente(Integer.parseInt(txtID.getText()));

        for (Venta v : listaProductos) {
            Producto prod = ctrlProducto.buscarPorID(v.getProducto().getIdProducto());

            pTablaProducto.addCell(new Paragraph(prod.getNombreProducto(), FontFactory.getFont("Arial", 10)));
            pTablaProducto.addCell(
                    new Paragraph(String.valueOf(v.getCantidadVenta()), FontFactory.getFont("Arial", 10)));
            pTablaProducto.addCell(new Paragraph("$" + String.valueOf(prod.getPrecioProducto()),
                    FontFactory.getFont("Arial", 10)));
            pTablaProducto.addCell(
                    new Paragraph("$" + String.valueOf(v.getMontoVenta()), FontFactory.getFont("Arial", 10)));

        }

        document.add(pTablaProducto);

        Paragraph pTotalCompra = new Paragraph("Total Compras: " + txtTotalCompras.getText(),
                FontFactory.getFont("Arial", 12, Font.BOLD, BaseColor.BLACK));
        pTotalCompra.setAlignment(Element.ALIGN_RIGHT);
        document.add(pTotalCompra);
        document.add(new Paragraph("\n"));

        Paragraph pAbonos = new Paragraph("Abonos: ",
                FontFactory.getFont("Arial", 14, Font.BOLD, BaseColor.BLACK));
        pAbonos.setAlignment(Element.ALIGN_CENTER);

        document.add(pAbonos);

        document.add(new Paragraph("\n"));
        PdfPTable tablaAbonos = new PdfPTable(3);

        float[] mediaCeldasAbonos = { 3.30f, 3.50f, 3.50f };

        tablaAbonos.setWidths(mediaCeldasAbonos);
        tablaAbonos.addCell(new Paragraph("Fecha", FontFactory.getFont("Arial", 12)));
        tablaAbonos.addCell(new Paragraph("Monto", FontFactory.getFont("Arial", 12)));
        tablaAbonos.addCell(new Paragraph("Saldo", FontFactory.getFont("Arial", 12)));

        ArrayList<Abono> listaAbonos = ctrlAbono.listByCliente(txtID.getText());
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        if (listaAbonos.size() > 0) {
            for (Abono a : listaAbonos) {

                tablaAbonos.addCell(
                        new Paragraph(sdf.format(a.getFechaAbono()), FontFactory.getFont("Arial", 10)));
                tablaAbonos.addCell(new Paragraph("$" + String.valueOf(a.getMontoAbono()),
                        FontFactory.getFont("Arial", 10)));
                tablaAbonos.addCell(new Paragraph("$" + String.valueOf(a.getSaldoAbono()),
                        FontFactory.getFont("Arial", 10)));
            }

        }
        document.add(tablaAbonos);

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

    } catch (FileNotFoundException ex) {
        Logger.getLogger(Clientes.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(Clientes.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Clientes.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(Clientes.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        File file = new File("C:\\CuotaSoft\\Historial.pdf");
        Desktop.getDesktop().open(file);
    } catch (Exception e) {
        e.printStackTrace();
    }
}