Example usage for com.itextpdf.text Font BOLD

List of usage examples for com.itextpdf.text Font BOLD

Introduction

In this page you can find the example usage for com.itextpdf.text Font BOLD.

Prototype

int BOLD

To view the source code for com.itextpdf.text Font BOLD.

Click Source Link

Document

this is a possible style.

Usage

From source file:modelo.GenerarPDF.java

public void nuevoReporteVentasMueble(ArrayList<Producto> Datos) throws IOException {
    // Se crea el documento Document
    // Se crea el OutputStream para el fichero donde queremos dejar el pdf.
    Document documento = null;/* w  w w .j a v  a  2s  .  co  m*/
    try {
        //Direccion root
        FileOutputStream ficheroPdf = new FileOutputStream(
                "C:\\Users\\panle\\Documents\\ReporteVentasMueble.pdf");
        //FileOutputStream ficheroPdf = new FileOutputStream("user.dir/tmp", "ReporteProductos.pdf");
        //File tempfile = new File("user.dir/tmp", "tempfile.txt");    
        documento = new Document();
        // Se asocia el documento al OutputStream y se indica que el espaciado entre
        // lineas sera de 20. Esta llamada debe hacerse antes de abrir el documento
        PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);

        // Se abre el documento
        documento.open();
        documento.add(new Paragraph("REPORTE VENTAS POR MUEBLE", FontFactory.getFont("ARIAL", // fuente
                16, // tamao
                Font.ITALIC, // estilo
                BaseColor.BLACK))); // color

        PdfPTable tabla = new PdfPTable(3);//#campos(columnas) para la tabla
        Font font = new Font(FontFamily.COURIER, 6, Font.BOLD, BaseColor.BLACK);
        PdfPCell cell = new PdfPCell(new Phrase("Celdas", font));

        documento.add(new Paragraph("\n"));

        Image img = Image.getInstance("C:\\Users\\logo.png");
        documento.add(img);
        documento.add(new Paragraph("\n"));

        int conta = 0;

        cell.setBorder(Rectangle.TITLE);
        tabla.addCell("DESCRIPCION");
        tabla.addCell("REFERENCIA");
        tabla.addCell("TIPO");

        while (conta < Datos.size()) {
            cell.setBorder(Rectangle.NO_BORDER);
            tabla.addCell(Datos.get(conta).getDESCRIPCION());
            tabla.addCell(Datos.get(conta).getREFERENCIA());
            tabla.addCell(Datos.get(conta).getTIPO());
            conta++;
        }

        documento.add(tabla);
        documento.close();

    } catch (FileNotFoundException | DocumentException e) {
        System.out.println("Error al generar Reporte Productos, por:");
        e.printStackTrace();
    }
}

From source file:Modelo.generatePDF.java

public void generatePDFFactura(String url, Object cliente_proveedor, ArrayList<ArticuloPedido> articulos,
        double suma) {
    try {//from w w  w.  j  a  v  a 2s . c o  m
        Document documento = new Document();//Creamos el documento
        FileOutputStream ficheroPdf = new FileOutputStream(url + "_factura.pdf");//Abrimos el flujo y le asignamos nombre al pdf y su direccion
        PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);//Instanciamos el documento con el fichero

        documento.open();//Abrimos el documento

        Cliente c = (Cliente) cliente_proveedor;

        documento.add(new Paragraph("FACTURA", FontFactory.getFont("arial", 30, Font.BOLD, BaseColor.BLACK)));//Le indicamos el tipo de letra, el tamanio, el estilo y el color de la letra
        documento.add(new Paragraph(" "));//Realiza un salto de linea
        documento.add(new Paragraph("---DATOS--- "));//Crea un parrafo con el String que le introduzcamos
        //Le decimos que nos imprima el Dni, Nombre y Apellidos del cliente, contenidos en el objeto Cliente y le indicamos el tipo de letra, tamanio, estilo y color de la letra
        documento.add(new Paragraph("DNI: " + c.getDni(),
                FontFactory.getFont("arial", 25, Font.BOLD, BaseColor.BLACK)));
        documento.add(new Paragraph("NOMBRE: " + c.getNombre(),
                FontFactory.getFont("arial", 25, Font.BOLD, BaseColor.BLACK)));
        documento.add(new Paragraph("APELLIDOS: " + c.getApellidos(),
                FontFactory.getFont("arial", 25, Font.BOLD, BaseColor.BLACK)));
        documento.add(new Paragraph(" "));
        documento.add(new Paragraph(" "));

        int cont = 0;//Este contador se usara para que cuando sea la primera vez que inserta datos en la tabla inserte los nombres de las columnas en vez de datos
        PdfPTable tabla = new PdfPTable(3);//Creamos una tabla de tres columnas

        //Insertaremos todos los articulos del pedido
        Iterator it = articulos.iterator();
        while (it.hasNext()) {
            if (cont == 0) {
                tabla.addCell("NOMBRE");
                tabla.addCell("PRECIO");
                tabla.addCell("CANTIDAD");
            }
            //Imprimimos en el PDF los nombres de los articulos del pedido, su precio y la cantidad comprada
            ArticuloPedido artPed = (ArticuloPedido) it.next();
            tabla.addCell(artPed.getArticulo().getNombre());
            tabla.addCell(Double.toString(artPed.getArticulo().getPrecio()));
            tabla.addCell(Integer.toString(artPed.getCantidad()));
            suma = suma + artPed.getArticulo().getPrecio() * artPed.getArticulo().getCantidad();//Imprimimos el coste de cada articulo en relacion a su cantidad
            cont++;
        }

        documento.add(tabla);//Aadimos la tabla al documento

        documento.add(new Paragraph(""));
        documento.add(new Paragraph("TOTAL: " + suma + " ",
                FontFactory.getFont("arial", 25, Font.NORMAL, BaseColor.RED)));//Imprimimos el coste total del pedido
        documento.close();//Cerramos el flujo con el documento

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

From source file:modelo.GeneratorPDF.java

public static void main(String[] args) {
    // criao do documento 
    Document document = new Document(PageSize.A4, 72, 72, 72, 72);
    try {/*from  ww  w. j  a  v a 2  s.c o m*/
        PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\Amanda\\Desktop\\teste.pdf"));

        document.open();
        Font f = new Font(FontFamily.COURIER, 20, Font.BOLD);

        // adicionando um pargrafo no documento 
        Paragraph p1 = new Paragraph("Gerando PDF - Java", f);
        p1.setAlignment(Element.ALIGN_CENTER);
        document.add(p1);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    document.close();
}

From source file:modelo.plantillaPDF.java

public void pdf(int tiquet, int idOrden, String codOrden) {
    try {//from   ww w  .j  ava  2 s .c  om

        String sql = "Select * from tiquet where idorden = '" + idOrden + "' and tiquet='" + tiquet + "'";
        rs = Consultar(sql);
        int id = 0;
        int numTiquet = 0;
        String ob = "";
        tiquet verTiquet = new tiquet();
        colores verColor = new colores();
        String colorUno = "";
        String colorDos = "";
        System.out.print("id de la orden en el tiquet:" + idOrden);
        ArrayList<String> lista = new ArrayList<String>();
        int c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, c6 = 0, c7 = 0, c8 = 0, c9 = 0, c10 = 0, c11 = 0, c12 = 0,
                c13 = 0, c14 = 0, c15 = 0;
        int c16 = 0, c17 = 0, c18 = 0, c19 = 0, c20 = 0, c21 = 0, c22 = 0, c23 = 0, c24 = 0, c25 = 0, c26 = 0,
                c27 = 0, c28 = 0, c29 = 0;
        int c30 = 0, c31 = 0, c32 = 0;
        //rs.last();
        int cuantos = rs.getRow();
        //System.out.print("puestos:" + cuantos+ "orden: " + codOrden + "tiquet: " + tiquet);

        //Fecha actual en formato completo:
        //Tue Sep 23 01:18:48 CEST 2014
        Date fechaActual = new Date();
        // System.out.println(fechaActual);
        // System.out.println("---------------------------------------------");

        //Formateando la fecha:
        DateFormat formatoHora = new SimpleDateFormat("HH-mm-ss");
        DateFormat formatoFecha = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat Fecha = new SimpleDateFormat("dd/MM/yyyy");
        //  System.out.println("Fecha: "+formatoFecha.format(fechaActual)+" Son las: "+formatoHora.format(fechaActual));

        //Directorio destino para las descargas
        File folder = new File("c:\\seiya\\tiquets");

        //Crea el directorio de destino en caso de que no exista
        folder.mkdirs();
        String fe = Fecha.format(fechaActual);

        int numeroAleatorio = (int) (Math.random() * 2500 + 1);
        //Nombre del fichero <strong>PDF</strong> Resultante de la ejecucion
        String dir = "C:\\seiya\\tiquets\\Tiquet_" + tiquet + ".pdf";
        ;
        // El archivo pdf que vamos a generar
        FileOutputStream fileOutputStream = new FileOutputStream(dir);

        //Creacion del documento con un tamao y unos margenes predeterminados
        Document document = new Document(PageSize.LETTER, 10, 10, 10, 1);

        //A DocWriter class for PDF con Java.
        //When this PdfWriter is added to a certain PdfDocument,
        //the <strong>PDF</strong> representation of every Element added to this Document will be written to the outputstream.
        //PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        // Obtener la instancia del PdfWriter
        PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
        //LEADING = separacion entre lineas del documento
        writer.setInitialLeading(16);
        Rectangle rct = new Rectangle(36, 54, 559, 788);
        //Definimos un nombre y un tamao para el PageBox los nombres posibles son: crop?, trim?, art? and bleed?.
        writer.setBoxSize("art", rct);
        //Opens the document.
        //You have to open the document before you can begin to add content to the body of the document.
        document.open();
        //**************************************************************
        //Ejemplos de TABLE

        //Aadir tabla 15 columnas
        PdfPTable table = new PdfPTable(15);
        //   PdfPTable tabla = new PdfPTable(15);
        PdfPCell celda;
        //Aadir CABECERA

        PdfPCell cell;
        Image image = Image.getInstance("logo/logo.png");
        //    String col = "jhon";
        cell = new PdfPCell(image);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setColspan(4);
        cell.setRowspan(7);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("Calle 12 # 6-68 Nia Ceci"));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setColspan(6);
        cell.setRowspan(2);

        table.addCell(cell);

        while (rs.next()) {

            c1 = rs.getInt(1);
            c2 = rs.getInt(2);
            c3 = rs.getInt(3);
            c4 = rs.getInt(4);
            c5 = rs.getInt(5);
            c6 = rs.getInt(8);
            c7 = rs.getInt(9);
            c8 = rs.getInt(10);
            c9 = rs.getInt(11);
            c10 = rs.getInt(12);
            c11 = rs.getInt(13);
            c12 = rs.getInt(14);
            c13 = rs.getInt(15);
            c14 = rs.getInt(16);
            c15 = rs.getInt(17);
            c16 = rs.getInt(18);
            c17 = rs.getInt(19);
            c18 = rs.getInt(21);
            c19 = rs.getInt(22);
            c20 = rs.getInt(23);
            c21 = rs.getInt(24);
            c22 = rs.getInt(25);
            c23 = rs.getInt(26);
            c24 = rs.getInt(28);
            c25 = rs.getInt(29);
            c26 = rs.getInt(30);
            c27 = rs.getInt(31);
            c28 = rs.getInt(32);

            colorUno = verColor.consultarNombreColorUno(c4);
            colorDos = verColor.consultarNombreColorDos(c5);
            ob = verTiquet.ConsultaObservacion(tiquet);

            System.out.print("Color Uno: " + colorUno);

            //cell.setBackgroundColor(BaseColor.BLUE);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("TIKET #:"));
            cell.setColspan(2);
            cell.setRowspan(2);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            //cell.setBackgroundColor(BaseColor.GRAY);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("" + tiquet));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.ORANGE);
            cell.setColspan(3);
            cell.setRowspan(2);
            table.addCell(cell);
            //Aadir dos filas de celdas sin formato

            cell = new PdfPCell(new Phrase("Tel: 5783364"));
            cell.setColspan(6);
            cell.setRowspan(2);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.CYAN);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("REF:"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.ORANGE);
            cell.setColspan(2);
            cell.setRowspan(2);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("" + c6));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.ORANGE);
            cell.setColspan(3);
            cell.setRowspan(2);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("calzadoseiya@gmail.com"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(6);
            cell.setRowspan(2);//para eliminar espacio cabecera reemplazo el 2 por 3
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("PARES:"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.ORANGE);
            cell.setColspan(2);
            cell.setRowspan(2);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("" + c7));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.ORANGE);
            cell.setColspan(3);
            cell.setRowspan(2);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("FECHA"));//espacio intermedio cabecera
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(2);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(fe));//espacio intermedio cabecera
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(4);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("ORDEN:"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.ORANGE);
            cell.setColspan(2);
            cell.setRowspan(1);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("" + codOrden));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.ORANGE);
            cell.setColspan(3);
            cell.setRowspan(1);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("CORTADA"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(4);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(""));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(11);
            cell.setRowspan(1);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("GUARNICION"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(4);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(""));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(11);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("MONTADA"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(4);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(""));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(11);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("EMPLANTILLADA"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(4);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(""));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(11);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("COLOR 1:"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(3);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(colorUno));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(4);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("COLOR 2:"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(3);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(colorDos));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(5);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("OBSERVACION"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(4);
            cell.setRowspan(2);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(ob));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(11);
            cell.setRowspan(2);
            table.addCell(cell);

            table.addCell("21");
            table.addCell("22");
            table.addCell("23");
            table.addCell("24");
            table.addCell("25");
            table.addCell("26");
            table.addCell("27");
            table.addCell("28");
            table.addCell("29");
            table.addCell("30");
            table.addCell("31");
            table.addCell("32");
            table.addCell("33");
            table.addCell("34");
            table.addCell("35");

            table.addCell(" " + c8);
            table.addCell(" " + c9);
            table.addCell(" " + c10);
            table.addCell(" " + c11);
            table.addCell(" " + c12);
            table.addCell(" " + c13);
            table.addCell(" " + c14);
            table.addCell(" " + c15);
            table.addCell(" " + c16);
            table.addCell(" " + c17);
            table.addCell(" " + c18);
            table.addCell(" " + c19);
            table.addCell(" " + c20);
            table.addCell(" " + c21);
            table.addCell(" " + c22);

            table.addCell("36");
            table.addCell("37");
            table.addCell("38");
            table.addCell("39");
            table.addCell("40");
            table.addCell("41");
            table.addCell("42");
            table.addCell("43");
            table.addCell("44");
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");

            table.addCell(" " + c23);
            table.addCell(" " + c24);
            table.addCell(" " + c25);
            table.addCell(" " + c26);
            table.addCell(" " + c27);
            table.addCell(" " + c28);
            table.addCell(" " + c29);
            table.addCell(" " + c30);
            table.addCell(" " + c31);
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");

            document.add(table);
            String cadena = "";
            for (int i = 1; i <= 4; i++) {
                //Chunk chunkSeparador =  new Chunk(SEPARADOR);
                // document.add(chunkSeparador);
                // document.add(Chunk.NEWLINE);

                PdfPTable tabla = new PdfPTable(15);
                if (i == 1)
                    cadena = "EMPLANTILLADA";
                if (i == 2)
                    cadena = "MONTADA";

                if (i == 3) {
                    cadena = "GUARNICION";

                }
                if (i == 4)
                    cadena = "CORTADA";

                cell = new PdfPCell(
                        new Phrase("------------------------------------------------------------------------"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(15);
                cell.setRowspan(1);
                tabla.addCell(cell);

                cell = new PdfPCell(new Phrase("CALZADO SEIYA"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(5);
                cell.setRowspan(1);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase(cadena));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(4);
                cell.setRowspan(1);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase("TIQUET #"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(3);
                cell.setRowspan(1);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase("" + tiquet));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(3);
                cell.setRowspan(1);
                tabla.addCell(cell);

                cell = new PdfPCell(new Phrase("PARES:"));
                cell.setHorizontalAlignment(Font.BOLD);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(2);
                cell.setRowspan(1);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase("" + c7));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(3);
                cell.setRowspan(1);
                tabla.addCell(cell);

                cell = new PdfPCell(new Phrase(""));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(4);
                cell.setRowspan(1);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase("REF:"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(3);
                cell.setRowspan(1);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase("" + c6));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(3);
                cell.setRowspan(1);
                tabla.addCell(cell);

                cell = new PdfPCell(new Phrase("COLOR 1:"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(3);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase(colorUno));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(4);
                tabla.addCell(cell);

                cell = new PdfPCell(new Phrase("COLOR 2:"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(3);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase(colorDos));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(5);
                tabla.addCell(cell);

                tabla.addCell("21");
                tabla.addCell("22");
                tabla.addCell("23");
                tabla.addCell("24");
                tabla.addCell("25");
                tabla.addCell("26");
                tabla.addCell("27");
                tabla.addCell("28");
                tabla.addCell("29");
                tabla.addCell("30");
                tabla.addCell("31");
                tabla.addCell("32");
                tabla.addCell("33");
                tabla.addCell("34");
                tabla.addCell("35");

                tabla.addCell(" " + c8);
                tabla.addCell(" " + c9);
                tabla.addCell(" " + c10);
                tabla.addCell(" " + c11);
                tabla.addCell(" " + c12);
                tabla.addCell(" " + c13);
                tabla.addCell(" " + c14);
                tabla.addCell(" " + c15);
                tabla.addCell(" " + c16);
                tabla.addCell(" " + c17);
                tabla.addCell(" ");
                tabla.addCell(" " + c20);
                tabla.addCell(" " + c21);
                tabla.addCell(" " + c22);
                tabla.addCell(" " + c23);

                tabla.addCell("36");
                tabla.addCell("37");
                tabla.addCell("38");
                tabla.addCell("39");
                tabla.addCell("40");
                tabla.addCell("41");
                tabla.addCell("42");
                tabla.addCell("43");
                tabla.addCell("44");
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");

                tabla.addCell(" " + c24);
                tabla.addCell(" " + c25);
                tabla.addCell(" " + c26);
                tabla.addCell(" " + c27);
                tabla.addCell(" " + c28);
                tabla.addCell(" " + c29);
                tabla.addCell(" " + c30);
                tabla.addCell(" " + c31);
                tabla.addCell(" " + c32);
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");

                document.add(tabla);

            }

            //document.add(new Paragraph(new Date().toString()));
            //FIN Ejemplos de TABLE
            //**************************************************************

            //**************************************************************
            // Cierre del documento
            document.close();
        }

    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

From source file:mvjce.PDF.java

public static void create(int sino) {// sino = SI.No
    // TODO code application logic here
    try {//from w  ww  . j a v a2s . c  om
        //Create Document instance.
        Document document = new Document();

        //Create OutputStream instance.
        OutputStream outputStream = new FileOutputStream(
                new File("/home/narein/NetBeansProjects/" + sem + cl + "/" + usn + ".pdf"));

        //Create PDFWriter instance.
        PdfWriter.getInstance(document, outputStream);

        //Open the document.
        document.open();
        //image position
        Image imageCenter = Image.getInstance("/home/narein/Downloads/mvj.png");
        //imageCenter.setAlignment(Image.MIDDLE);
        imageCenter.setAbsolutePosition(235, 780);
        imageCenter.scaleAbsolute(146f, 53f);
        //Permanently affiliated para
        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.addCell(getCell(
                "\n\n\nPermanently affiliated to VTU, Govt. of Karnataka\nApproved by AICTE, New Delhi\nNear ITPB, Bengaluru- 560067\n\n"
                        + hod_name + ", HOD - " + dep,
                PdfPCell.ALIGN_LEFT));
        table.addCell(getCell("\n\n\n\nPh: 080-42991000\nFax: 080-28452443\nWebsite: www.mvjce.edu.in\nEmail: "
                + hod_email + "\n\n", PdfPCell.ALIGN_RIGHT));
        //line across pdf
        final LineSeparator lineSeparator = new LineSeparator();
        Chunk linebreak = new Chunk(lineSeparator);
        Phrase p = new Phrase("\nPROGRESS REPORT\n",
                new Font(FontFamily.TIMES_ROMAN, 10, Font.UNDERLINE | Font.BOLD));
        Paragraph para = new Paragraph(p);
        para.setAlignment(Element.ALIGN_CENTER);
        Chunk glue = new Chunk(new VerticalPositionMark());
        Paragraph p1 = new Paragraph("\nRef:", new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD));
        p1.add(new Chunk(glue));
        //get current date
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yyyy");
        LocalDate localDate = LocalDate.now();
        //add date to pdf
        p1.add(new Phrase("Date: " + dtf.format(localDate) + "\n",
                new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD)));
        Phrase dear_prnts = new Phrase("Dear Parents,\n", new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD));
        Phrase The_acad = new Phrase(
                "                  The academic performance of your ward Mr/Ms " + name + " of Semester " + sem
                        + " bearing the USN " + usn + " is as follows,\n\n",
                new Font(FontFamily.TIMES_ROMAN, 9));
        Phrase Rem = new Phrase("Remarks\n", new Font(FontFamily.TIMES_ROMAN, 10, Font.UNDERLINE | Font.BOLD));
        Phrase your_ward = new Phrase(
                "\nYour ward's overall performance is Good / Satisfactory / Poor / Very Poor\n",
                new Font(FontFamily.TIMES_ROMAN, 9));
        Phrase you_are = new Phrase("\nYou are requested to:\n",
                new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD));
        Phrase req = new Phrase("");
        Paragraph para2 = new Paragraph(
                "1) Advice your ward to attend classes regularly\n2) Note that he/she may likely be detainedfrom appearing for examinations\n"
                        + "3) Advice your ward to improve in Test/Exam performance particularly in subject\n4) Meet the Head of the Department\n5) Meet the principal\n",
                new Font(FontFamily.TIMES_ROMAN, 9));
        Chunk glue1 = new Chunk(new VerticalPositionMark());
        Paragraph p3 = new Paragraph("\nSIGNATURE:\n\nNAME OF PROCTOR:\n\nCONTACT NUMBER:",
                new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD));
        p3.add(new Chunk(glue1));
        p3.add(new Phrase(
                "SIGNATURE OF HOD\n\n            Kindly attend the Parent Teacher Meeting to be held on the date informed to your ward.\n",
                new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD)));
        Phrase Note = new Phrase("\nNOTE:", new Font(FontFamily.TIMES_ROMAN, 10, Font.UNDERLINE | Font.BOLD));
        Paragraph p4 = new Paragraph();
        p4.add(Note);
        p4.add(new Phrase(
                "  Parents are requested to contact the proctor (By Email/Letter/Phone) and confirm receipt of this feedback. Parents are also"
                        + "welcome to interact with proctors/subject faculty/ HOD for any discussion/clarification.\n",
                new Font(FontFamily.TIMES_ROMAN, 9)));
        //Add content to the document.
        document.add(imageCenter);
        document.add(table);
        document.add(linebreak);
        document.add(para);
        document.add(p1);
        document.add(dear_prnts);
        document.add(The_acad);
        document.add(createinternalsTable());
        if (internal.equals("1")) {
            document.add(new Phrase("\nPREVIOUS SEMESTER VTU RESULT\n\n",
                    new Font(FontFamily.TIMES_ROMAN, 10, Font.UNDERLINE | Font.BOLD)));
            document.add(createexternalTable());
        }
        document.add(Rem);
        document.add(your_ward);
        document.add(you_are);
        document.add(para2);
        document.add(p3);
        document.add(p4);
        //document.add(paragraph);document.add(paragraph1);

        //Close document and outputStream.
        document.close();
        outputStream.close();

        System.out.println("Pdf created successfully.");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:mvjce.PDF.java

public static PdfPCell getCell(String text, int alignment) {

    PdfPCell cell = new PdfPCell(new Phrase(text, new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD)));
    cell.setPadding(1);/*www  .  j  av  a  2s .co  m*/
    cell.setHorizontalAlignment(alignment);
    cell.setBorder(PdfPCell.NO_BORDER);
    return cell;
}

From source file:mvjce.PDF.java

public static PdfPTable createinternalsTable() {
    // a table with five columns
    PdfPTable table = new PdfPTable(5);
    float f[] = new float[] { 0.5f, 3f, 1f, 1f, 1.5f };
    try {/*from  w  w w .j av  a 2s .  co m*/
        table.setWidths(f);
    } catch (Exception e) {
        System.out.println(e);
    }
    // the cell object
    PdfPCell cell;
    // we add a cell with colspan 3
    cell = new PdfPCell(new Phrase("SI.No", new Font(FontFamily.TIMES_ROMAN, 9, Font.BOLD)));
    cell.setRowspan(3);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(cell);
    cell = new PdfPCell(new Phrase("SUBJECT TITLE", new Font(FontFamily.TIMES_ROMAN, 9, Font.BOLD)));
    cell.setRowspan(3);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(cell);
    cell = new PdfPCell(new Phrase("SUB CODE", new Font(FontFamily.TIMES_ROMAN, 9, Font.BOLD)));
    cell.setRowspan(3);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(cell);
    cell = new PdfPCell(
            new Phrase("Internal" + internal + " Test Marks", new Font(FontFamily.TIMES_ROMAN, 9, Font.BOLD)));
    cell.setRowspan(3);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(cell);
    cell = new PdfPCell(new Phrase("Attendance\nAS ON DATE", new Font(FontFamily.TIMES_ROMAN, 9, Font.BOLD)));
    cell.setRowspan(3);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(cell);

    for (int i = 1; i <= 8; i++) {
        table.addCell(new Phrase(Integer.toString(i), new Font(FontFamily.TIMES_ROMAN, 9)));
        table.addCell(new Phrase(sub[i - 1], new Font(FontFamily.TIMES_ROMAN, 9)));
        table.addCell(new Phrase(subcode[i - 1], new Font(FontFamily.TIMES_ROMAN, 9)));
        table.addCell(new Phrase(intr[i - 1], new Font(FontFamily.TIMES_ROMAN, 9)));
        table.addCell(new Phrase(att[i - 1], new Font(FontFamily.TIMES_ROMAN, 9)));
    }
    return table;
    //}catch(Exception e){System.out.println(e);}return null;
}

From source file:net.pflaeging.PortableSigner.PDFSigner.java

License:Open Source License

/** Creates a new instance of DoSignPDF */
public void doSignPDF(String pdfInputFileName, String pdfOutputFileName, String pkcs12FileName, String password,
        Boolean signText, String signLanguage, String sigLogo, Boolean finalize, String sigComment,
        String signReason, String signLocation, Boolean noExtraPage, float verticalPos, float leftMargin,
        float rightMargin, Boolean signLastPage, byte[] ownerPassword) throws PDFSignerException {
    try {//from   w  w w  .j  a  va2  s. c om
        //System.out.println("-> DoSignPDF <-");
        //System.out.println("Eingabedatei: " + pdfInputFileName);
        //System.out.println("Ausgabedatei: " + pdfOutputFileName);
        //System.out.println("Signaturdatei: " + pkcs12FileName);
        //System.out.println("Signaturblock?: " + signText);
        //System.out.println("Sprache der Blocks: " + signLanguage);
        //System.out.println("Signaturlogo: " + sigLogo);
        System.err.println("Position V:" + verticalPos + " L:" + leftMargin + " R:" + rightMargin);
        Rectangle signatureBlock;

        java.security.Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 2);

        pkcs12 = new GetPKCS12(pkcs12FileName, password);

        PdfReader reader = null;
        try {
            //                System.out.println("Password:" + ownerPassword.toString());
            if (ownerPassword == null)
                reader = new PdfReader(pdfInputFileName);
            else
                reader = new PdfReader(pdfInputFileName, ownerPassword);
        } catch (IOException e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle(
                "net/pflaeging/PortableSigner/i18n").getString(
                "CouldNotBeOpened"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("CouldNotBeOpened"), true, e.getLocalizedMessage());
        }
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(pdfOutputFileName);
        } catch (FileNotFoundException e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("CouldNotBeWritten"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("CouldNotBeWritten"), true, e.getLocalizedMessage());

        }
        PdfStamper stp = null;
        try {
            Date datum = new Date(System.currentTimeMillis());

            int pages = reader.getNumberOfPages();

            Rectangle size = reader.getPageSize(pages);
            stp = PdfStamper.createSignature(reader, fout, '\0', null, true);
            HashMap<String, String> pdfInfo = reader.getInfo();
            // thanks to Markus Feisst
            String pdfInfoProducer = "";

            if (pdfInfo.get("Producer") != null) {
                pdfInfoProducer = pdfInfo.get("Producer").toString();
                pdfInfoProducer = pdfInfoProducer + " (signed with PortableSigner " + Version.release + ")";
            } else {
                pdfInfoProducer = "Unknown Producer (signed with PortableSigner " + Version.release + ")";
            }
            pdfInfo.put("Producer", pdfInfoProducer);
            //System.err.print("++ Producer:" + pdfInfo.get("Producer").toString());
            stp.setMoreInfo(pdfInfo);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XmpWriter xmp = new XmpWriter(baos, pdfInfo);
            xmp.close();
            stp.setXmpMetadata(baos.toByteArray());
            if (signText) {
                String greet, signator, datestr, ca, serial, special, note, urn, urnvalue;
                int specialcount = 0;
                int sigpage;
                int rightMarginPT, leftMarginPT;
                float verticalPositionPT;
                ResourceBundle block = ResourceBundle
                        .getBundle("net/pflaeging/PortableSigner/Signatureblock_" + signLanguage);
                greet = block.getString("greeting");
                signator = block.getString("signator");
                datestr = block.getString("date");
                ca = block.getString("issuer");
                serial = block.getString("serial");
                special = block.getString("special");
                note = block.getString("note");
                urn = block.getString("urn");
                urnvalue = block.getString("urnvalue");

                //sigcomment = block.getString(signLanguage + "-comment");
                // upper y
                float topy = size.getTop();
                System.err.println("Top: " + topy * ptToCm);
                // right x
                float rightx = size.getRight();
                System.err.println("Right: " + rightx * ptToCm);
                if (!noExtraPage) {
                    sigpage = pages + 1;
                    stp.insertPage(sigpage, size);
                    // 30pt left, 30pt right, 20pt from top
                    rightMarginPT = 30;
                    leftMarginPT = 30;
                    verticalPositionPT = topy - 20;
                } else {
                    if (signLastPage) {
                        sigpage = pages;
                    } else {
                        sigpage = 1;
                    }
                    System.err.println("Page: " + sigpage);
                    rightMarginPT = Math.round(rightMargin / ptToCm);
                    leftMarginPT = Math.round(leftMargin / ptToCm);
                    verticalPositionPT = topy - Math.round(verticalPos / ptToCm);
                }
                if (!GetPKCS12.atEgovOID.equals("")) {
                    specialcount = 1;
                }
                PdfContentByte content = stp.getOverContent(sigpage);

                float[] cellsize = new float[2];
                cellsize[0] = 100f;
                // rightx = width of page
                // 60 = 2x30 margins
                // cellsize[0] = description row
                // cellsize[1] = 0
                // 70 = logo width
                cellsize[1] = rightx - rightMarginPT - leftMarginPT - cellsize[0] - cellsize[1] - 70;

                // Pagetable = Greeting, signatureblock, comment
                // sigpagetable = outer table
                //      consist: greetingcell, signatureblock , commentcell
                PdfPTable signatureBlockCompleteTable = new PdfPTable(2);
                PdfPTable signatureTextTable = new PdfPTable(2);
                PdfPCell signatureBlockHeadingCell = new PdfPCell(
                        new Paragraph(new Chunk(greet, new Font(Font.FontFamily.HELVETICA, 12))));
                signatureBlockHeadingCell.setPaddingBottom(5);
                signatureBlockHeadingCell.setColspan(2);
                signatureBlockHeadingCell.setBorderWidth(0f);
                signatureBlockCompleteTable.addCell(signatureBlockHeadingCell);

                // inner table start
                // Line 1
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(signator, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(GetPKCS12.subject, new Font(Font.FontFamily.COURIER, 10))));
                // Line 2
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(datestr, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(datum.toString(), new Font(Font.FontFamily.COURIER, 10))));
                // Line 3
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(ca, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(GetPKCS12.issuer, new Font(Font.FontFamily.COURIER, 10))));
                // Line 4
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(serial, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(new Paragraph(
                        new Chunk(GetPKCS12.serial.toString(), new Font(Font.FontFamily.COURIER, 10))));
                // Line 5
                if (specialcount == 1) {
                    signatureTextTable.addCell(new Paragraph(
                            new Chunk(special, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                    signatureTextTable.addCell(new Paragraph(
                            new Chunk(GetPKCS12.atEgovOID, new Font(Font.FontFamily.COURIER, 10))));
                }
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(urn, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable
                        .addCell(new Paragraph(new Chunk(urnvalue, new Font(Font.FontFamily.COURIER, 10))));
                signatureTextTable.setTotalWidth(cellsize);
                System.err.println(
                        "signatureTextTable Width: " + cellsize[0] * ptToCm + " " + cellsize[1] * ptToCm);
                // inner table end

                signatureBlockCompleteTable.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                Image logo;
                //                     System.out.println("Logo:" + sigLogo + ":");
                if (sigLogo == null || "".equals(sigLogo)) {
                    logo = Image.getInstance(
                            getClass().getResource("/net/pflaeging/PortableSigner/SignatureLogo.png"));
                } else {
                    logo = Image.getInstance(sigLogo);
                }

                PdfPCell logocell = new PdfPCell();
                logocell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
                logocell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                logocell.setImage(logo);
                signatureBlockCompleteTable.addCell(logocell);
                PdfPCell incell = new PdfPCell(signatureTextTable);
                incell.setBorderWidth(0f);
                signatureBlockCompleteTable.addCell(incell);
                PdfPCell commentcell = new PdfPCell(
                        new Paragraph(new Chunk(sigComment, new Font(Font.FontFamily.HELVETICA, 10))));
                PdfPCell notecell = new PdfPCell(
                        new Paragraph(new Chunk(note, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                //commentcell.setPaddingTop(10);
                //commentcell.setColspan(2);
                // commentcell.setBorderWidth(0f);
                if (!sigComment.equals("")) {
                    signatureBlockCompleteTable.addCell(notecell);
                    signatureBlockCompleteTable.addCell(commentcell);
                }
                float[] cells = { 70, cellsize[0] + cellsize[1] };
                signatureBlockCompleteTable.setTotalWidth(cells);
                System.err.println(
                        "signatureBlockCompleteTable Width: " + cells[0] * ptToCm + " " + cells[1] * ptToCm);
                signatureBlockCompleteTable.writeSelectedRows(0, 4 + specialcount, leftMarginPT,
                        verticalPositionPT, content);
                System.err.println(
                        "signatureBlockCompleteTable Position " + 30 * ptToCm + " " + (topy - 20) * ptToCm);
                signatureBlock = new Rectangle(30 + signatureBlockCompleteTable.getTotalWidth() - 20,
                        topy - 20 - 20, 30 + signatureBlockCompleteTable.getTotalWidth(), topy - 20);
                //                    //////
                //                    AcroFields af = reader.getAcroFields();
                //                    ArrayList names = af.getSignatureNames();
                //                    for (int k = 0; k < names.size(); ++k) {
                //                        String name = (String) names.get(k);
                //                        System.out.println("Signature name: " + name);
                //                        System.out.println("\tSignature covers whole document: " + af.signatureCoversWholeDocument(name));
                //                        System.out.println("\tDocument revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());
                //                        PdfPKCS7 pk = af.verifySignature(name);
                //                        X509Certificate tempsigner = pk.getSigningCertificate();
                //                        Calendar cal = pk.getSignDate();
                //                        Certificate pkc[] = pk.getCertificates();
                //                        java.util.ResourceBundle tempoid =
                //                                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/SpecialOID");
                //                        String tmpEgovOID = "";
                //
                //                        for (Enumeration<String> o = tempoid.getKeys(); o.hasMoreElements();) {
                //                            String element = o.nextElement();
                //                            // System.out.println(element + ":" + oid.getString(element));
                //                            if (tempsigner.getNonCriticalExtensionOIDs().contains(element)) {
                //                                if (!tmpEgovOID.equals("")) {
                //                                    tmpEgovOID += ", ";
                //                                }
                //                                tmpEgovOID += tempoid.getString(element) + " (OID=" + element + ")";
                //                            }
                //                        }
                //                        //System.out.println("\tSigniert von: " + PdfPKCS7.getSubjectFields(pk.getSigningCertificate()));
                //                        System.out.println("\tSigniert von: " + tempsigner.getSubjectX500Principal().toString());
                //                        System.out.println("\tDatum: " + cal.getTime().toString());
                //                        System.out.println("\tAusgestellt von: " + tempsigner.getIssuerX500Principal().toString());
                //                        System.out.println("\tSeriennummer: " + tempsigner.getSerialNumber());
                //                        if (!tmpEgovOID.equals("")) {
                //                            System.out.println("\tVerwaltungseigenschaft: " + tmpEgovOID);
                //                        }
                //                        System.out.println("\n");
                //                        System.out.println("\tDocument modified: " + !pk.verify());
                ////                Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal);
                ////                if (fails == null) {
                ////                    System.out.println("\tCertificates verified against the KeyStore");
                ////                } else {
                ////                    System.out.println("\tCertificate failed: " + fails[1]);
                ////                }
                //                    }
                //
                //                //////
            } else {
                signatureBlock = new Rectangle(0, 0, 0, 0); // fake definition
            }
            PdfSignatureAppearance sap = stp.getSignatureAppearance();
            //                sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null,
            //                        PdfSignatureAppearance.WINCER_SIGNED );
            sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null, null);
            sap.setReason(signReason);
            sap.setLocation(signLocation);
            //                if (signText) {
            //                    sap.setVisibleSignature(signatureBlock,
            //                            pages + 1, "PortableSigner");
            //                }
            if (finalize) {
                sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
            } else {
                sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
            }
            stp.close();

            /* MODIFY BY: Denis Torresan
            Main.setResult(
              java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("IsGeneratedAndSigned"),
              false,
              "");
                */

        } catch (Exception e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorWhileSigningFile"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("ErrorWhileSigningFile"), true, e.getLocalizedMessage());

        }
    } catch (KeyStoreException kse) {

        /* MODIFY BY: Denis Torresan
         Main.setResult(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorCreatingKeystore"),
            true, kse.getLocalizedMessage());
         */

        throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                .getString("ErrorCreatingKeystore"), true, kse.getLocalizedMessage());

    }
}

From source file:net.sf.texprinter.generators.PDFGenerator.java

License:Open Source License

/**
 * Generates a PDF file from a Question object.
 * /*from  w w w . j a  v  a  2  s.c  o  m*/
 * @param question The question.
 * @param filename The filename.
 */
public static void generate(Question question, String filename) {

    // wait window
    ProgressMessage pm = new ProgressMessage("TeXPrinter is printing your PDF file.");

    // start wait window
    //pm.start();

    // log message
    log.log(Level.INFO, "Starting PDF generation of {0}.", filename);

    // define a new PDF document
    Document document = null;

    // define a new PDF writer
    PdfWriter writer = null;

    // lets try
    try {

        // create a new PDF document
        document = new Document();

        // define a new PDF Writer
        writer = PdfWriter.getInstance(document, new FileOutputStream(filename));

        // set the PDF version
        writer.setPdfVersion(PdfWriter.VERSION_1_6);

        // open the document
        document.open();

        // set the title font
        Font titleFont = new Font(FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLACK);

        // set the chunk for the question title
        Chunk questionTitle = new Chunk(question.getQuestion().getTitle(), titleFont);

        // create a paragraph from that chunk
        Paragraph paragraphQuestionTitle = new Paragraph(questionTitle);

        // log message
        log.log(Level.INFO, "Adding the question title.");

        // add the question title to the document
        document.add(paragraphQuestionTitle);

        // set the asker font
        Font askerFont = new Font(FontFamily.HELVETICA, 10, Font.ITALIC, BaseColor.DARK_GRAY);

        // set the chunk for the asker
        Chunk questionAsker = new Chunk("Asked by " + question.getQuestion().getUser().getName() + " ("
                + question.getQuestion().getUser().getReputation() + ") on " + question.getQuestion().getDate()
                + " (" + String.valueOf(question.getQuestion().getVotes())
                + (question.getQuestion().getVotes() == 1 ? " vote" : " votes") + ")", askerFont);

        // create a paragraph from that chunk
        Paragraph paragraphQuestionAsker = new Paragraph(questionAsker);

        // log message
        log.log(Level.INFO, "Adding both asker and reputation.");

        // add the asker to the document
        document.add(paragraphQuestionAsker);

        // create a line separator
        LineSeparator line = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -5);

        // add the line to the document
        document.add(line);

        // add a new line
        document.add(Chunk.NEWLINE);

        // create a list of elements from the question objects
        List<Element> questionTextObjects = getPostText(question.getQuestion().getText());

        // log message
        log.log(Level.INFO, "Adding the question text.");

        // for each element
        for (Element questionTextObject : questionTextObjects) {

            // add it to the document
            document.add(questionTextObject);
        }

        // add a new line
        document.add(Chunk.NEWLINE);

        // create a new font for the comments title
        Font commentsTitleFont = new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLACK);

        // create a new chunk based on that font
        Chunk commentsTitle = new Chunk(
                "This question has " + question.getQuestion().getComments().size()
                        + ((question.getQuestion().getComments().size() == 1) ? " comment:" : " comments:"),
                commentsTitleFont);

        // create a paragraph from that chunk
        Paragraph paragraphCommentsTitle = new Paragraph(commentsTitle);

        // if there are comments to this question
        if (!question.getQuestion().getComments().isEmpty()) {

            // log message
            log.log(Level.INFO, "Adding the question comments.");

            // add that paragraph to the document
            document.add(paragraphCommentsTitle);

            // add a new line
            document.add(Chunk.NEWLINE);

            // get all the comments
            List<Comment> questionComments = question.getQuestion().getComments();

            // for each comment
            for (Comment questionComment : questionComments) {

                // get the elements of the comment text
                List<Element> questionCommentObjects = getPostText(questionComment.getText());

                // for each element
                for (Element questionCommentObject : questionCommentObjects) {

                    // add it to the document
                    document.add(questionCommentObject);
                }

                // create a new paragraph about the comment author
                Paragraph paragraphCommentAuthor = new Paragraph(questionComment.getAuthor() + " on "
                        + questionComment.getDate() + " (" + String.valueOf(questionComment.getVotes())
                        + (questionComment.getVotes() == 1 ? " vote" : " votes") + ")", askerFont);

                // set the alignment to the right
                paragraphCommentAuthor.setAlignment(Element.ALIGN_RIGHT);

                // add the paragraph to the document
                document.add(paragraphCommentAuthor);

                // add a new line
                document.add(Chunk.NEWLINE);
            }
        }

        // add a line separator
        document.add(line);

        // add two new lines
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);

        // get the list of answers
        List<Post> answersList = question.getAnswers();

        // if there are no answers
        if (answersList.isEmpty()) {

            // log message
            log.log(Level.INFO, "This question has no answers.");

            // create a new chunk
            Chunk noAnswersTitle = new Chunk("Sorry, this question has no answers yet.", titleFont);

            // create a paragraph from that chunk
            Paragraph paragraphNoAnswersTitle = new Paragraph(noAnswersTitle);

            // add the paragraph to the document
            document.add(paragraphNoAnswersTitle);

        } else {

            // log message
            log.log(Level.INFO, "Adding answers.");

            // there are answers, so create a counter for answers
            int answerCount = 1;

            // for each answer
            for (Post answer : answersList) {

                // log message
                log.log(Level.INFO, "Adding answer {0}.", answerCount);

                // set the message text as empty
                String answerAccepted = "";

                // if the answer is accepted
                if (answer.isAccepted()) {

                    // add that to the message
                    answerAccepted = " - Marked as accepted.";
                }

                // create a new chunk
                Chunk answerTitle = new Chunk("Answer #" + answerCount, titleFont);

                // create a paragraph from that chunk
                Paragraph paragraphAnswerTitle = new Paragraph(answerTitle);

                // add the paragraph to the document
                document.add(paragraphAnswerTitle);

                // increase the counter
                answerCount++;

                // create a new chunk
                Chunk questionAnswerer = new Chunk("Answered by " + answer.getUser().getName() + " ("
                        + answer.getUser().getReputation() + ") on " + answer.getDate() + answerAccepted + " ("
                        + String.valueOf(answer.getVotes()) + (answer.getVotes() == 1 ? " vote" : " votes")
                        + ")", askerFont);

                // create a paragraph from that chunk
                Paragraph paragraphQuestionAnswerer = new Paragraph(questionAnswerer);

                // add that paragraph to the document
                document.add(paragraphQuestionAnswerer);

                // add a line separator
                document.add(line);

                // add a new line
                document.add(Chunk.NEWLINE);

                // create a list of elements from the answer text
                List<Element> answerTextObjects = getPostText(answer.getText());

                // for each element
                for (Element answerTextObject : answerTextObjects) {

                    // add it to the document
                    document.add(answerTextObject);
                }

                // add a new line
                document.add(Chunk.NEWLINE);

                // create a new font style
                Font answerCommentsTitleFont = new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLACK);

                // create a new chunk
                Chunk answerCommentsTitle = new Chunk(
                        "This answer has " + answer.getComments().size()
                                + ((answer.getComments().size() == 1) ? " comment:" : " comments:"),
                        answerCommentsTitleFont);

                // create a paragraph from that chunk
                Paragraph paragraphAnswerCommentsTitle = new Paragraph(answerCommentsTitle);

                // if there are comments for that answer
                if (!answer.getComments().isEmpty()) {

                    // log message
                    log.log(Level.INFO, "Adding comments for answer {0}.", (answerCount - 1));

                    // add that paragraph to the document
                    document.add(paragraphAnswerCommentsTitle);

                    // add a new line
                    document.add(Chunk.NEWLINE);

                    // get all the comments
                    List<Comment> answerComments = answer.getComments();

                    // for each comment
                    for (Comment answerComment : answerComments) {

                        // create a list of elements from the comment text
                        List<Element> answerCommentObjects = getPostText(answerComment.getText());

                        // for each element
                        for (Element answerCommentObject : answerCommentObjects) {

                            // add it to the document
                            document.add(answerCommentObject);
                        }

                        // create a new paragraph for the comment author
                        Paragraph paragraphAnswerCommentAuthor = new Paragraph(
                                answerComment.getAuthor() + " on " + answerComment.getDate() + " ("
                                        + String.valueOf(answerComment.getVotes())
                                        + (answerComment.getVotes() == 1 ? " vote" : " votes") + ")",
                                askerFont);

                        // set the aligment to the right
                        paragraphAnswerCommentAuthor.setAlignment(Element.ALIGN_RIGHT);

                        // add the paragraph to the document
                        document.add(paragraphAnswerCommentAuthor);

                        // add a new line
                        document.add(Chunk.NEWLINE);
                    }
                }

                // add a line separator
                document.add(line);

                // add two new lines
                document.add(Chunk.NEWLINE);
                document.add(Chunk.NEWLINE);
            }
        }

        // log message
        log.log(Level.INFO, "PDF generation complete, closing {0}.", filename);

        // close the document
        document.close();

        // stop wait window
        pm.interrupt();

    } catch (IOException ioexception) {

        // stop wait window
        pm.interrupt();

        // log message
        log.log(Level.SEVERE, "An IO error occurred while trying to create the PDF file. MESSAGE: {0}",
                StringUtils.printStackTrace(ioexception));

        // critical error, exit
        Dialogs.showExceptionWindow();

    } catch (Exception exception) {

        // log message
        log.log(Level.SEVERE, "A generic error occurred while trying to create the PDF file. MESSAGE: {0}",
                StringUtils.printStackTrace(exception));

        // log message
        log.log(Level.INFO, "I will try to remove the remaining PDF file.");

        try {

            // log message
            log.log(Level.INFO, "Closing both document and writer.");

            // close the document
            document.close();

            // close the writer
            writer.close();

        } catch (Exception ex) {

            // log message
            log.log(Level.WARNING, "I could not close either document or writer. MESSAGE: {0}",
                    StringUtils.printStackTrace(ex));
        }

        try {

            // reference problematic file
            File target = new File(filename);

            // log message
            log.log(Level.INFO, "Opening problematic file {0}.", filename);

            // check if file exists
            if (target.exists()) {

                // log message
                log.log(Level.INFO, "File exists, trying to delete it.");

                // trying to remove it
                if (target.delete()) {

                    // log message
                    log.log(Level.INFO, "File {0} was successfully removed.", filename);

                } else {

                    // log message
                    log.log(Level.SEVERE, "File {0} could not be removed.", filename);

                }
            }
        } catch (SecurityException se) {

            // log message
            log.log(Level.SEVERE, "A security exception was raised. MESSAGE: {0}",
                    StringUtils.printStackTrace(se));

        }

        // stop wait window
        pm.interrupt();

        // critical error, exit
        Dialogs.showExceptionWindow();

    }
}

From source file:nl.avans.C3.BusinessLogic.InvoiceService.java

public void generateInvoice(String invoiceBSN, int[] behandelCode)
        throws DocumentException, FileNotFoundException, ClientNotFoundException, ParseException {
    Date date = new Date();
    String dt = new SimpleDateFormat("yyyy-MM-dd").format(date);
    String fileId = "invoice-" + dt + "-" + invoiceBSN;

    String companyName = companyService.getInsuranceCompany().getName();
    String companyAddress = companyService.getInsuranceCompany().getAddress();
    String companyPostalCode = companyService.getInsuranceCompany().getPostalCode();
    String companyCity = companyService.getInsuranceCompany().getCity();

    String companyKVK = Integer.toString(companyService.getInsuranceCompany().getKVK());
    String companyIBAN = "NL91ABNA0417164300";

    Client client = clientService.findClientByBSN(Integer.parseInt(invoiceBSN));
    String clientFirstName = client.getFirstName();
    String clientLastName = client.getLastName();
    String clientAddress = client.getAddress();
    String clientPostalCode = client.getPostalCode();
    String clientCity = client.getCity();
    boolean incasso = client.isIncasso();

    Date date2 = new Date();
    String dt2 = new SimpleDateFormat("dd-MM-yyyy").format(date2);
    String currentDate = dt2;/*from   w w w . ja  v a  2  s  .  c om*/
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    Calendar c = Calendar.getInstance();
    c.setTime(sdf.parse(dt2));
    c.add(Calendar.MONTH, 1);
    dt2 = sdf.format(c.getTime());
    String expirationDate = dt2;

    String invoiceNumber = dt + "-" + invoiceBSN;

    Font bfBold12 = new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(0, 0, 0));
    Font bf12 = new Font(FontFamily.TIMES_ROMAN, 12);

    // Creating new file
    Document doc = new Document();

    // Trying to parse the data to a new PDF
    PdfWriter.getInstance(doc, new FileOutputStream("generatedfiles/invoice/" + fileId + ".pdf"));

    // Opening the file
    doc.open();

    // Parsing the order details to the PDF
    doc.add(new Paragraph(companyName + "\n" + companyAddress + "\n" + companyPostalCode + " " + companyCity
            + "\n\n" + "KVK: " + companyKVK + "\nIBAN: " + companyIBAN + "\n\n\n" + clientFirstName + " "
            + clientLastName + "\n" + clientAddress + "\n" + clientPostalCode + " " + clientCity + "\n\n"
            + "Factuurdatum: " + currentDate + "\nVerloopdatum: " + expirationDate + "\n\n\n"
            + "Factuurnummer: " + invoiceNumber + "\n\n\n\n"));

    float[] columnWidths = { 2f, 2f, 2f, 2f, 2f };
    PdfPTable table = new PdfPTable(columnWidths);
    table.setWidthPercentage(100f);

    insertCell(table, "Behandelcode", Element.ALIGN_LEFT, 1, bfBold12);
    insertCell(table, "Behandelingnaam", Element.ALIGN_LEFT, 1, bfBold12);
    insertCell(table, "Aantal sessies", Element.ALIGN_LEFT, 1, bfBold12);
    insertCell(table, "Sessieduur", Element.ALIGN_LEFT, 1, bfBold12);
    insertCell(table, "Tarief", Element.ALIGN_LEFT, 1, bfBold12);
    table.setHeaderRows(1);

    List<Treatment> treatments = getTreatments(behandelCode);

    for (int i = 0; i < treatments.size(); i++) {
        insertCell(table, "" + treatments.get(i).getBehandelCode(), Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "" + treatments.get(i).getBehandelingNaam(), Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "" + treatments.get(i).getAantalSessies(), Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "" + treatments.get(i).getSessieDuur(), Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "" + treatments.get(i).getTariefBehandeling(), Element.ALIGN_RIGHT, 1, bf12);
    }

    //totaalbedrag zonder eigen risico
    double totaalBedrag = getTotaalBedrag(behandelCode);
    insertCell(table, "Totaalbedrag: ", Element.ALIGN_RIGHT, 4, bfBold12);
    insertCell(table, "" + totaalBedrag, Element.ALIGN_RIGHT, 1, bfBold12);

    //lege row
    insertCell(table, "", Element.ALIGN_RIGHT, 5, bf12);

    //huidig eigen risico
    double excess = insuranceContractService.getInsuranceContractByBSN(Integer.parseInt(invoiceBSN))
            .getExcess();
    insertCell(table, "Huidig eigen risico: ", Element.ALIGN_RIGHT, 4, bf12);
    insertCell(table, "" + excess, Element.ALIGN_RIGHT, 1, bf12);

    //totaal te betalen bedrag
    double teBetalenBedrag;
    double newExcess = excess - totaalBedrag;
    insertCell(table, "Te betalen bedrag: ", Element.ALIGN_RIGHT, 4, bfBold12);
    if (excess > 0) {
        if (excess > totaalBedrag) {
            insuranceContractService.updateInsuranceContractExcess(newExcess, insuranceContractService
                    .getInsuranceContractByBSN(Integer.parseInt(invoiceBSN)).getInsuranceContractID());
            insertCell(table, "" + totaalBedrag, Element.ALIGN_RIGHT, 1, bfBold12);
            teBetalenBedrag = totaalBedrag;
        } else {
            insuranceContractService.updateInsuranceContractExcess(0.00, insuranceContractService
                    .getInsuranceContractByBSN(Integer.parseInt(invoiceBSN)).getInsuranceContractID());
            insertCell(table, "" + excess, Element.ALIGN_RIGHT, 1, bfBold12);
            teBetalenBedrag = excess;
        }
    } else {
        insertCell(table, "0.0", Element.ALIGN_RIGHT, 1, bfBold12);
        teBetalenBedrag = 0.00;
    }

    Paragraph paragraph = new Paragraph("");
    paragraph.add(table);
    doc.add(paragraph);

    doc.add(new Paragraph("\n\n"));

    if (newExcess > 0) {
        doc.add(new Paragraph("U heeft nog " + newExcess + " eigen risico over."));
    } else {
        doc.add(new Paragraph("U heeft nog 0.0 eigen risico over."));
    }

    doc.add(new Paragraph("\n\n"));
    if (incasso == false) {
        if (teBetalenBedrag > 0) {
            doc.add(new Paragraph("We verzoeken u vriendelijk het bovenstaande bedrag van " + teBetalenBedrag
                    + " voor " + expirationDate
                    + " te voldoen op onze bankrekening onder vermelding van het factuurnummer " + invoiceNumber
                    + ". Voor vragen kunt u contact opnemen per e-mail."));
        } else {
            doc.add(new Paragraph(
                    "Omdat uw eigen risico op is worden er geen kosten in rekening gebracht voor de bovenstaande behandelingen."));
        }
    } else {
        doc.add(new Paragraph(
                "Het geld zal binnen 10 werkdagen van uw rekening afgeschreven worden door middel van een automatische incasso."));
    }

    // Closing the file
    doc.close();
}