Example usage for com.itextpdf.text Rectangle Rectangle

List of usage examples for com.itextpdf.text Rectangle Rectangle

Introduction

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

Prototype

public Rectangle(final float llx, final float lly, final float urx, final float ury) 

Source Link

Document

Constructs a Rectangle -object.

Usage

From source file:mkl.testarea.itext5.pdfcleanup.StrictPdfCleanUpProcessor.java

License:Open Source License

/**
 * Deletes redact annotations from the page and substitutes them with either OverlayText or RO object if it's needed.
 *//*from   www .j ava  2  s  .  com*/
private void deleteRedactAnnots(int pageNum) throws IOException, DocumentException {
    Set<String> indirRefs = redactAnnotIndirRefs.get(pageNum);

    if (indirRefs == null || indirRefs.isEmpty()) {
        return;
    }

    PdfReader reader = pdfStamper.getReader();
    PdfContentByte canvas = pdfStamper.getOverContent(pageNum);
    PdfDictionary pageDict = reader.getPageN(pageNum);
    PdfArray annotsArray = pageDict.getAsArray(PdfName.ANNOTS);

    // j is for access annotRect (i can be decreased, so we need to store additional index,
    // indicating current position in ANNOTS array in case if we don't remove anything
    for (int i = 0, j = 0; i < annotsArray.size(); ++i, ++j) {
        PdfIndirectReference annotIndRef = annotsArray.getAsIndirectObject(i);
        PdfDictionary annotDict = annotsArray.getAsDict(i);

        if (indirRefs.contains(annotIndRef.toString()) || indirRefs.contains(getParentIndRefStr(annotDict))) {
            PdfStream formXObj = annotDict.getAsStream(PdfName.RO);
            PdfString overlayText = annotDict.getAsString(PdfName.OVERLAYTEXT);

            if (fillCleanedArea && formXObj != null) {
                PdfArray rectArray = annotDict.getAsArray(PdfName.RECT);
                Rectangle annotRect = new Rectangle(rectArray.getAsNumber(0).floatValue(),
                        rectArray.getAsNumber(1).floatValue(), rectArray.getAsNumber(2).floatValue(),
                        rectArray.getAsNumber(3).floatValue());

                insertFormXObj(canvas, pageDict, formXObj, clippingRects.get(j), annotRect);
            } else if (fillCleanedArea && overlayText != null && overlayText.toUnicodeString().length() > 0) {
                drawOverlayText(canvas, clippingRects.get(j), overlayText, annotDict.getAsString(PdfName.DA),
                        annotDict.getAsNumber(PdfName.Q), annotDict.getAsBoolean(PdfName.REPEAT));
            }

            annotsArray.remove(i--); // array size is changed, so we need to decrease i
        }
    }

    if (annotsArray.size() == 0) {
        pageDict.remove(PdfName.ANNOTS);
    }
}

From source file:Modelo.CotizacionDAO.java

public void writePdf(OutputStream outputStream, Cotizacion x, int idcotizacion) throws Exception {

    DateFormat df = new SimpleDateFormat("dd/MM/YYYY");
    Calendar cdos = Calendar.getInstance();
    Date datediamas = new Date();
    Date dateaniomas = new Date();
    cdos.add(Calendar.DATE, 1);/*  w w  w  . ja  v  a 2 s .  co m*/
    datediamas = cdos.getTime();
    String fechadiamas = df.format(datediamas);
    cdos.add(Calendar.YEAR, 1);
    dateaniomas = cdos.getTime();
    String fechavencimiento = df.format(dateaniomas);

    Document document = new Document(PageSize.LETTER, 50, 50, 50, 30);
    Font boldFontTitulo = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
    Font boldFontTexto = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD);
    Font FontTexto = new Font(Font.FontFamily.HELVETICA, 10);

    // document.setPageSize(null);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);

    Image imagen = Image.getInstance("http://54.67.56.185/BSeguros_pa18/img/BSeguroLogo.png");
    //      Image imagen = Image.getInstance("D:\\ALEX\\Bseguros\\web\\img\\Aseguradoras\\BSeguroLogo.png");
    Image imagen2 = Image.getInstance(
            "http://54.67.56.185/BSeguros_pa18/img/Aseguradoras/" + x.getId_aseguradora() + ".png");
    //Image imagen2 = Image.getInstance("D:\\ALEX\\Bseguros\\web\\img\\Aseguradoras\\Mapfre.png");

    document.open();

    PdfContentByte canvas = writer.getDirectContent();
    Rectangle rect = new Rectangle(36, 36, 579, 756);
    rect.setBorder(Rectangle.BOX);
    rect.setBorderWidth(2);
    canvas.rectangle(rect);

    document.addTitle("Cotizacion");
    document.addSubject("Cotizacion");
    document.addKeywords("Cotizacion, seguros");
    document.addAuthor("BSeguro");
    document.addCreator("Bseguro");

    imagen.scaleAbsoluteHeight(30f);
    imagen.setAbsolutePosition(45f, 720f);
    imagen2.scaleAbsoluteHeight(30f);
    imagen2.setAbsolutePosition(450f, 720f);
    document.add(imagen);
    document.add(imagen2);

    Paragraph paragraph2 = new Paragraph("DATOS DE TU POLIZA", boldFontTitulo);
    paragraph2.setAlignment(Element.ALIGN_CENTER);
    document.add(paragraph2);

    //creas una tabla con un ancho de 3 celdas, el salto a la siguiente fila sera automatico
    PdfPTable table = new PdfPTable(3);
    table.getDefaultCell().setBorder(0);
    PdfPCell cell;

    Paragraph saltodelinea = new Paragraph(" ");
    document.add(saltodelinea);

    document.add(new Paragraph(" Datos de tu poliza folio: " + "BC" + x.getId_aseguradora().substring(0, 1)
            + x.getMetododepago().substring(0, 1) + ": 0000" + idcotizacion, boldFontTitulo));
    document.add(new Paragraph(" Vigencia de la poliza del: " + fechadiamas + " al: " + fechavencimiento,
            boldFontTitulo));
    document.add(saltodelinea);

    document.add(new Paragraph(" Datos del Contratante: ", boldFontTitulo));
    //document.add(saltodelinea);

    //agrego otra tabla
    table = new PdfPTable(6);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(0);
    table.addCell(new Paragraph("Nombre: ", boldFontTexto));
    PdfPCell celdaNombre = new PdfPCell(
            new Paragraph(x.getNombre_contratante() + " " + x.getApellido_paterno(), FontTexto));
    celdaNombre.setColspan(5);
    celdaNombre.setBorder(0);
    table.addCell(celdaNombre);
    table.addCell(new Paragraph("RFC : ", boldFontTexto));
    PdfPCell celdaRFC = new PdfPCell(new Paragraph(x.getRfc(), FontTexto));
    celdaRFC.setColspan(5);
    celdaRFC.setBorder(0);
    table.addCell(celdaRFC);
    table.addCell(new Paragraph("Direccion: ", boldFontTexto));
    PdfPCell celdaDir = new PdfPCell(
            new Paragraph(x.getCall() + ", " + x.getNo_ext() + ", " + x.getNo_int() + ", " + x.getColonia()
                    + ", " + x.getDelegacion() + ", " + x.getEstado() + ", " + x.getCp(), FontTexto));
    celdaDir.setColspan(5);
    celdaDir.setBorder(0);
    table.addCell(celdaDir);
    table.addCell(new Paragraph("Email: ", boldFontTexto));
    table.addCell(AddCell(x.getMail(), 5));
    table.addCell(new Paragraph("Telefono ", boldFontTexto));
    PdfPCell celdaTel = new PdfPCell(new Paragraph(x.getTelefono(), FontTexto));
    celdaTel.setColspan(5);
    celdaTel.setBorder(0);
    table.addCell(celdaTel);

    document.add(table);
    document.add(saltodelinea);

    document.add(new Paragraph(" Datos del Vehiculo: ", boldFontTitulo));
    //      document.add(saltodelinea);

    //agrego otra tabla
    table = new PdfPTable(6);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(0);
    table.addCell(new Paragraph("Marca: ", boldFontTexto));
    table.addCell(AddCell(x.getId_marca(), 5));
    table.addCell(new Paragraph("Modelo:", boldFontTexto));
    table.addCell(AddCell(x.getId_anio().toString(), 5));
    table.addCell(new Paragraph("Tipo: ", boldFontTexto));
    table.addCell(AddCell(x.getId_submarca(), 5));
    table.addCell(new Paragraph("Version:  ", boldFontTexto));
    table.addCell(AddCell(x.getId_modelo(), 5));
    table.addCell(new Paragraph("No. De Serie: ", boldFontTexto));
    table.addCell(AddCell(x.getSerie(), 5));

    document.add(table);
    document.add(saltodelinea);

    document.add(new Paragraph(" Informacion de la Poliza: ", boldFontTitulo));
    //    document.add(saltodelinea);

    //agrego otra tabla
    table = new PdfPTable(6);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(0);
    table.addCell(new Paragraph("Pago: ", boldFontTexto));
    table.addCell(AddCell(x.getTipo_pago(), 5));
    table.addCell(new Paragraph("Aseguradora: ", boldFontTexto));
    table.addCell(AddCell(x.getId_aseguradora(), 5));

    document.add(table);
    document.add(saltodelinea);

    document.add(new Paragraph(" Detalles de la Cobertura: Cobertura Amplia ", boldFontTitulo));
    //  document.add(saltodelinea);

    //agrego otra tabla
    table = new PdfPTable(3);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(0);
    table.addCell(new Paragraph("Cobertura ", boldFontTexto));
    table.addCell(new Paragraph("Responsabilidad Civil", boldFontTexto));
    table.addCell(new Paragraph("Deducible ", boldFontTexto));
    table.addCell(new Paragraph("Daos Materiales", FontTexto));
    table.addCell(new Paragraph("Valor Comercial", FontTexto));
    table.addCell(new Paragraph("5%", FontTexto));
    table.addCell(new Paragraph("Robo Total", FontTexto));
    table.addCell(new Paragraph("Valor Comercial", FontTexto));
    table.addCell(new Paragraph("10%", FontTexto));
    table.addCell(new Paragraph("Responsabilidad Civil", FontTexto));
    table.addCell(new Paragraph("$4,000,000.00", FontTexto));
    table.addCell(new Paragraph("", FontTexto));
    table.addCell(new Paragraph("Gastos Medicos Ocupantes", FontTexto));
    table.addCell(new Paragraph("$500,000.00", FontTexto));
    table.addCell(new Paragraph("", FontTexto));
    table.addCell(new Paragraph("Asistencia Legal", FontTexto));
    table.addCell(new Paragraph("Amparada", FontTexto));
    table.addCell(new Paragraph("", FontTexto));
    table.addCell(new Paragraph("Asistencia Vial", FontTexto));
    table.addCell(new Paragraph("Amparada", FontTexto));
    table.addCell(new Paragraph("", FontTexto));

    document.add(table);
    document.add(saltodelinea);

    document.add(new Paragraph(" Informacion del Pago ", boldFontTitulo));
    document.add(new Paragraph(" Instrumento de Pago: " + x.getMetododepago(), boldFontTexto));

    //agrego otra tabla
    table = new PdfPTable(6);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(0);
    table.addCell(AddCell("Concepto ", 2));
    table.addCell(AddCell("Monto", 4));
    table.addCell(AddCell("Prima Total ", 2));
    table.addCell(AddCell(x.getMonto(), 4));
    table.addCell(AddCell("Prima Inicial", 2));
    table.addCell(AddCell(x.getMonto(), 4));
    table.addCell(AddCell("Pago Subsecuente ", 2));
    table.addCell(AddCell("0", 4));

    document.add(table);
    document.add(saltodelinea);

    if (x.getCobertura_auto_siempre() == true) {

        document.add(new Paragraph(" Informacion de Modulos HDI ", boldFontTitulo));
        table = new PdfPTable(6);
        table.setWidthPercentage(100);
        table.getDefaultCell().setBorder(0);
        table.addCell(AddCell("Modulos ", 2));
        table.addCell(AddCell("Contratados", 4));
        table.addCell(AddCell("HDI - Autos por Siempre ", 2));
        table.addCell(AddCell("$ 1,799.00", 4));
        document.add(table);

    } else {
        if (x.getCobertura_auto_amante() == true) {

            document.add(new Paragraph(" Informacion de Modulos HDI ", boldFontTitulo));
            table = new PdfPTable(6);
            table.setWidthPercentage(100);
            table.getDefaultCell().setBorder(0);
            table.addCell(AddCell("Modulos ", 2));
            table.addCell(AddCell("Contratados", 4));
            table.addCell(AddCell("HDI - Amante de los Autos ", 2));
            table.addCell(AddCell("$ 1,799.00", 4));
            document.add(table);

        } else {

        }
        document.add(saltodelinea);
    }
    document.add(new Paragraph("* Estaras asegurado a partir de las 12 horas del siguiente dia habil.",
            boldFontTexto));

    document.close();

}

From source file:modelo.plantillaPDF.java

public void pdf(int tiquet, int idOrden, String codOrden) {
    try {/*from   w w  w  .  j  av  a2s  . co  m*/

        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:net.ionescu.jhocr2pdf.Jhocr2pdf.java

License:Open Source License

public void addSpan(String coords, String text) {
    // parse the coordinates
    String[] coord = coords.split(" ");
    Rectangle rect = new Rectangle(Float.valueOf(coord[1]), Float.valueOf(coord[4]), Float.valueOf(coord[3]),
            Float.valueOf(coord[2]));

    canvas.saveState();//from  ww w  . jav  a2s . com
    canvas.beginText();
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
    canvas.setRGBColorFill(0xFF, 0, 0);
    canvas.setLineWidth(0);

    // calculate the font size
    float width = rect.getWidth() * xScaling;

    float tenWidth = bf.getWidthPointKerned(text, 10);
    float fontSize = 10 * width / tenWidth;

    canvas.setFontAndSize(bf, fontSize);
    canvas.showTextAlignedKerned(Element.ALIGN_LEFT, text, rect.getLeft() * xScaling,
            PageSize.A4.getHeight() - rect.getBottom() * yScaling - bf.getDescentPoint(text, fontSize), 0);
    canvas.endText();
    canvas.restoreState();

}

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 va  2 s .c  o m*/
        //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:objects.manipulate.java

public static void createPDF(String filename, String[] RESOURCES)
        throws DocumentException, FileNotFoundException, IOException {
    Document document = new Document();
    document.setMargins(0, 0, 0, 0);/*from w  w w  . java  2 s  .c o m*/
    Rectangle rectangle = new Rectangle(0, 0, 742, 960);
    document.setPageSize(rectangle);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    document.open();

    Image img;
    for (int i = 0; i < RESOURCES.length; i++) {
        //img = Image.getInstance(String.format("resources/img/%s", RESOURCES[i]));
        img = Image.getInstance(RESOURCES[i]);
        if (img.getScaledWidth() > 742 || img.getScaledHeight() > 960) {
            img.scaleToFit(742, 960);
        }

        document.add(img);
    }

    document.close();
}

From source file:om.edu.squ.squportal.portlet.tsurvey.dao.pdf.TeachingSurveyPdfImpl.java

License:Open Source License

/**
 * //www. ja  va  2  s.c o m
 * method name  : getPdfSurveyAnalysis
 * @param object
 * @param semesterYear
 * @param questionByYear
 * @param questionSetNo
 * @param byos
 * @param inputStream
 * @param res
 * @return
 * @throws DocumentException
 * @throws IOException
 * TeachingSurveyPdfImpl
 * return type  : OutputStream
 * 
 * purpose      : Generate PDF content
 *
 * Date          :   Mar 28, 2016 7:21:04 PM
 */
public OutputStream getPdfSurveyAnalysis(Object object, String semesterYear, String questionByYear,
        int questionSetNo, ByteArrayOutputStream byos, InputStream inputStream, ResourceResponse res)
        throws DocumentException, IOException {

    Font font = FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, BaseColor.BLACK);

    PdfReader pdfTemplate = new PdfReader(inputStream);
    PdfStamper pdfStamper = new PdfStamper(pdfTemplate, byos);
    Survey survey = (Survey) object;
    String sectionNos = "";
    String seatsTaken = "";
    DecimalFormat formatter = new DecimalFormat("###.##");

    String RIGHT = Constants.RIGHT;
    String CENTER = Constants.CENTER;
    String LEFT = Constants.LEFT;

    pdfStamper.getAcroFields().setField("txtCourse", survey.getCourseCode() + " / " + survey.getCourseName());
    pdfStamper.getAcroFields().setField("txtCollegeName", survey.getCollegeName());

    for (SurveyResponse resp : survey.getSurveyResponses()) {
        sectionNos = sectionNos + resp.getSectionNo() + " ";
        seatsTaken = String.valueOf(resp.getSeatsTaken());
    }

    pdfStamper.getAcroFields().setField("txtSectionNo", sectionNos);
    pdfStamper.getAcroFields().setField("txtDepartmentName", survey.getDepartmentName());
    pdfStamper.getAcroFields().setField("txtEmpName", survey.getEmpName());
    pdfStamper.getAcroFields().setField("txtStudentRegistered", seatsTaken);

    pdfStamper.getAcroFields().setField("txtSemesterYear", semesterYear);

    pdfStamper.getAcroFields().setGenerateAppearances(true);

    /* ****************** */

    PdfPTable table = new PdfPTable(13);

    table.addCell(getPdfCell("", 2, 0, font, LEFT));
    table.addCell(getPdfCell(
            UtilProperty.getMessage("prop.course.teaching.survey.analysis.course.teaching.items", null), 2, 0,
            font, CENTER));
    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.response.number", null), 0,
                    6, font, CENTER));
    table.addCell(getPdfCell(
            UtilProperty.getMessage("prop.course.teaching.survey.analysis.response.percentage", null), 2, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.mean", null), 0, 4,
            font, CENTER));

    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.disagree.strong", null), 0,
                    0, font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.disagree", null), 0,
            0, font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.agree", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.agree.strong", null),
            0, 0, font, CENTER));
    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.applicable.not", null), 0,
                    0, font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.total", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.sect", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.crs", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.dept", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.col", null), 0, 0,
            font, CENTER));

    /* ---------------------------------------------------------------------------- */
    table.addCell(getPdfCell("", 0, 0, font));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.course.items", null),
            0, 12, font, CENTER));

    int cTotal = 0;
    float cPctVal = 0f;
    float cSectionMean = 0f;
    float cCourseMean = 0f;
    float cDepart = 0f;
    float cCollege = 0f;
    int rowCount = 0;

    for (SurveyResponse sures : survey.getSurveyResponses()) {
        for (Analysis analysis : sures.getAnalysisList()) {
            if (analysis.getQuestion().equals("Q2") || analysis.getQuestion().equals("Q14")
                    || analysis.getQuestion().equals(questionByYear)) {
                /***  First part    ***/
                table.addCell(getPdfCell(analysis.getQuestion(), 0, 0, font));
                table.addCell(
                        getPdfCell(
                                UtilProperty.getMessage("prop.course.teaching.survey.analysis.set"
                                        + questionSetNo + ".question" + analysis.getQuestionLabel(), null),
                                0, 0, font, LEFT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongDisagree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDisAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getNotApplicable()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getTotal()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getPercentageResponse()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getSectionMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCourseMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDepartmentMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCollegeMean()), 0, 0, font, RIGHT));

                cTotal = cTotal + analysis.getTotal();
                cPctVal = cPctVal + analysis.getPercentageResponse();
                cSectionMean = cSectionMean + analysis.getSectionMean();
                cCourseMean = cCourseMean + analysis.getCollegeMean();
                cDepart = cDepart + analysis.getDepartmentMean();
                cCollege = cCollege + analysis.getCollegeMean();
                rowCount = rowCount + 1;

            }
        }
    }

    /***  First part - Summary   ***/
    table.addCell(getPdfCell(String.valueOf(""), 0, 0, font));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.summary", null), 0,
            0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(""), 0, 5, font));
    table.addCell(getPdfCell(String.valueOf(cTotal), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cPctVal / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cSectionMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCourseMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cDepart / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCollege / rowCount)), 0, 0, font, RIGHT));

    table.addCell(getPdfCell("", 0, 13, font));

    table.addCell(getPdfCell("", 0, 0, font));
    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.teaching.items", null), 0,
                    12, font, LEFT));

    cTotal = 0;
    cPctVal = 0f;
    cSectionMean = 0f;
    cCourseMean = 0f;
    cDepart = 0f;
    cCollege = 0f;
    rowCount = 0;
    for (SurveyResponse sures : survey.getSurveyResponses()) {
        for (Analysis analysis : sures.getAnalysisList()) {
            if (!(analysis.getQuestion().equals("Q2") || analysis.getQuestion().equals("Q14")
                    || analysis.getQuestion().equals(questionByYear))) {

                table.addCell(getPdfCell(analysis.getQuestion(), 0, 0, font));
                table.addCell(
                        getPdfCell(
                                UtilProperty.getMessage("prop.course.teaching.survey.analysis.set"
                                        + questionSetNo + ".question" + analysis.getQuestionLabel(), null),
                                0, 0, font, LEFT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongDisagree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDisAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getNotApplicable()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getTotal()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getPercentageResponse()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getSectionMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCourseMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDepartmentMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCollegeMean()), 0, 0, font, RIGHT));

                cTotal = cTotal + analysis.getTotal();
                cPctVal = cPctVal + analysis.getPercentageResponse();
                cSectionMean = cSectionMean + analysis.getSectionMean();
                cCourseMean = cCourseMean + analysis.getCollegeMean();
                cDepart = cDepart + analysis.getDepartmentMean();
                cCollege = cCollege + analysis.getCollegeMean();
                rowCount = rowCount + 1;

            }

        }

    }

    /***  Second part - Summary   ***/
    table.addCell(getPdfCell(String.valueOf(""), 0, 0, font));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.summary", null), 0,
            0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(""), 0, 5, font));
    table.addCell(getPdfCell(String.valueOf(cTotal), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cPctVal / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cSectionMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCourseMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cDepart / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCollege / rowCount)), 0, 0, font, RIGHT));

    if (!survey.getMessage().equals("")) {
        table.addCell(getPdfCell("", 0, 13, font));
        table.addCell(getPdfCell("", 0, 0, font));
        table.addCell(getPdfCell(survey.getMessage(), 0, 12, font, CENTER));
    }

    table.setTotalWidth(750);
    table.setLockedWidth(true);
    table.setWidths(new float[] { 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 });

    ColumnText column = new ColumnText(pdfStamper.getOverContent(1));
    Rectangle rectPage1 = new Rectangle(120, 20, 659, 480);

    column.setSimpleColumn(rectPage1);
    column.addElement(table);

    int status = column.go();

    pdfStamper.setFormFlattening(true);

    pdfStamper.close();

    pdfTemplate.close();

    res.setContentType("application/pdf");

    return res.getPortletOutputStream();

}

From source file:org.alex73.skarynka.scan.process.pdf.PdfCreator.java

License:Open Source License

public static void create(File outFile, File[] jpegs) throws Exception {
    Document pdf = new Document();
    pdf.setMargins(0, 0, 0, 0);//from  w  w  w .j  av  a 2s .  c  o m

    Image image0 = Jpeg.getInstance(jpegs[0].getPath());
    pdf.setPageSize(new Rectangle(0, 0, image0.getScaledWidth(), image0.getScaledHeight()));

    PdfWriter writer = PdfWriter.getInstance(pdf, new FileOutputStream(outFile));

    pdf.open();
    float minWidth = Float.MAX_VALUE, maxWidth = Float.MIN_VALUE, minHeight = Float.MAX_VALUE,
            maxHeight = Float.MIN_VALUE;
    for (File jpeg : jpegs) {

        Image image = Jpeg.getInstance(jpeg.getPath());

        float width, height;

        width = image.getScaledWidth();
        height = image.getScaledHeight();
        minWidth = Math.min(minWidth, width);
        maxWidth = Math.max(maxWidth, width);
        minHeight = Math.min(minHeight, height);
        maxHeight = Math.max(maxHeight, height);

        pdf.setPageSize(new Rectangle(0, 0, width, height));
        pdf.newPage();
        pdf.add(image);
    }

    pdf.close();
    writer.flush();
    writer.close();
}

From source file:org.alfresco.extension.countersign.action.executer.AbstractSignatureActionExecuter.java

License:Open Source License

/**
 * Get the signature block position, using the provided JSON for the box coordinates
 * and the selected page/*w w  w  . jav a 2 s  .  c  o  m*/
 * 
 * @param pageRect
 * @param box
 * @return
 */
protected Rectangle positionBlock(Rectangle pageRect, JSONObject box) {
    float startX = Float.parseFloat(String.valueOf(box.get("startX")));
    float startY = Float.parseFloat(String.valueOf(box.get("startY")));
    float endX = Float.parseFloat(String.valueOf(box.get("endX")));
    float endY = Float.parseFloat(String.valueOf(box.get("endY")));

    // make sure that the ll and ur coordinates match iText's expectations
    startY = pageRect.getHeight() - startY;
    endY = pageRect.getHeight() - endY;

    // create the rectangle to contain the signature from the corrected coordinates
    Rectangle r = new Rectangle(startX, startY, endX, endY);

    return r;
}

From source file:org.alfresco.extension.countersign.action.executer.AbstractSignatureActionExecuter.java

License:Open Source License

/**
 * Create a rectangle for the visible stamp using the selected position and block size
 * /*from   w w w  .ja  v  a  2  s  .c om*/
 * @param position
 * @param width
 * @param height
 * @return
 */
protected Rectangle positionBlock(String position, Rectangle pageRect, int width, int height) {

    float pageHeight = pageRect.getHeight();
    float pageWidth = pageRect.getWidth();

    Rectangle r = null;
    //Rectangle constructor(float llx, float lly, float urx, float ury)
    if (position.equals(POSITION_BOTTOMLEFT)) {
        r = new Rectangle(0, height, width, 0);
    } else if (position.equals(POSITION_BOTTOMRIGHT)) {
        r = new Rectangle(pageWidth - width, height, pageWidth, 0);
    } else if (position.equals(POSITION_TOPLEFT)) {
        r = new Rectangle(0, pageHeight, width, pageHeight - height);
    } else if (position.equals(POSITION_TOPRIGHT)) {
        r = new Rectangle(pageWidth - width, pageHeight, pageWidth, pageHeight - height);
    } else if (position.equals(POSITION_CENTER)) {
        r = new Rectangle((pageWidth / 2) - (width / 2), (pageHeight / 2) - (height / 2),
                (pageWidth / 2) + (width / 2), (pageHeight / 2) + (height / 2));
    }

    return r;
}