Example usage for com.itextpdf.text Phrase Phrase

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

Introduction

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

Prototype

public Phrase(final float leading, final String string) 

Source Link

Document

Constructs a Phrase with a certain leading and a certain String.

Usage

From source file:comisionesafis.informes.LiquidacionComisiones.java

private void printCabeceraColumnas(PdfPTable table) {

    PdfPCell celda;/*  ww  w .  j a  v a2 s. c  om*/

    Font font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
    celda = new PdfPCell(new Phrase("NUMERO DE PLIZA", font));
    celda.setBorder(Rectangle.TOP + Rectangle.BOTTOM + Rectangle.LEFT);
    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(celda);
    celda = new PdfPCell(new Phrase("FECHA DE VENCIMIENTO", font));
    celda.setBorder(Rectangle.TOP + Rectangle.BOTTOM);
    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(celda);
    celda = new PdfPCell(new Phrase("FORMA DE PAGO", font));
    celda.setBorder(Rectangle.TOP + Rectangle.BOTTOM);
    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(celda);
    celda = new PdfPCell(new Phrase("BASE COMISIN", font));
    celda.setBorder(Rectangle.TOP + Rectangle.BOTTOM);
    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(celda);
    celda = new PdfPCell(new Phrase("IMPORTE", font));
    celda.setBorder(Rectangle.TOP + Rectangle.BOTTOM + Rectangle.RIGHT);
    celda.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(celda);

}

From source file:comisionesafis.informes.LiquidacionComisiones.java

private void printResumenContable(PdfPTable tabla, Double total, String codAgente) {

    ResultSet rsAgente;//from  w  w  w .jav a2 s  .  c om
    Statement stmt;
    String sSQL = "";
    Double retencion;
    Double liquido;
    String patron = "dd/MM/yyyy";
    SimpleDateFormat formato = new SimpleDateFormat(patron);
    String fecha = (formato.format(new Date()));
    String cuenta;

    try {
        // SELECT para extraer todos los cdigos de los agentes con Recibos
        sSQL = "SELECT * ";
        sSQL += "  FROM Agentes";
        sSQL += " WHERE CodAgente ='" + codAgente + "'";
        stmt = conexion.createStatement();
        rsAgente = stmt.executeQuery(sSQL);

        PdfPCell celda;
        Font font;

        // Primera fila de datos
        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase(" ", font));
        celda.setColspan(3);
        celda.setBorder(Rectangle.TOP);
        tabla.addCell(celda);

        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase("TOTAL ", font));
        celda.setBorder(Rectangle.TOP);
        celda.setHorizontalAlignment(Element.ALIGN_LEFT);
        tabla.addCell(celda);

        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase(Numeros.formateaDosDecimales(total), font));
        celda.setBorder(Rectangle.TOP);
        celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
        tabla.addCell(celda);

        // Segunda fila de datos
        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase(" ", font));
        celda.setColspan(3);
        celda.setBorder(Rectangle.NO_BORDER);
        tabla.addCell(celda);

        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase("I.R.P.F. " + rsAgente.getString("RetencionPorcentaje") + "%", font));
        celda.setBorder(Rectangle.NO_BORDER);
        celda.setHorizontalAlignment(Element.ALIGN_LEFT);
        tabla.addCell(celda);

        retencion = total * (Double.parseDouble(rsAgente.getString("RetencionPorcentaje")) / 100);
        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase(Numeros.formateaDosDecimales(retencion), font));
        celda.setBorder(Rectangle.NO_BORDER);
        celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
        tabla.addCell(celda);

        // Tercera fila de datos
        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase(" ", font));
        celda.setColspan(3);
        celda.setBorder(Rectangle.BOTTOM);
        tabla.addCell(celda);

        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase("L?QUIDO ", font));
        celda.setBorder(Rectangle.BOTTOM);
        celda.setHorizontalAlignment(Element.ALIGN_LEFT);
        tabla.addCell(celda);

        liquido = total - retencion;
        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase(Numeros.formateaDosDecimales(liquido), font));
        celda.setBorder(Rectangle.BOTTOM);
        celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
        tabla.addCell(celda);

        // Cuenta
        cuenta = rsAgente.getString("Banco") + " ";
        cuenta += rsAgente.getString("Sucursal") + " ";
        cuenta += rsAgente.getString("DC") + " ";
        cuenta += rsAgente.getString("Cuenta") + " ";

        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase("CTA n " + cuenta, font));
        celda.setColspan(5);
        celda.setBorder(Rectangle.NO_BORDER);
        tabla.addCell(celda);

        // Firma
        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase("En Madrid a " + fecha, font));
        celda.setColspan(5);
        celda.setBorder(Rectangle.NO_BORDER);
        tabla.addCell(celda);

        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase("V.Bo. ", font));
        celda.setColspan(5);
        celda.setBorder(Rectangle.NO_BORDER);
        tabla.addCell(celda);

        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase(" ", font));
        celda.setColspan(5);
        celda.setBorder(Rectangle.NO_BORDER);
        tabla.addCell(celda);

        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase(" ", font));
        celda.setColspan(5);
        celda.setBorder(Rectangle.NO_BORDER);
        tabla.addCell(celda);

        font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
        celda = new PdfPCell(new Phrase("PELAYO VIDA", font));
        celda.setColspan(5);
        celda.setBorder(Rectangle.NO_BORDER);
        tabla.addCell(celda);

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

}

From source file:comisionesafis.informes.LiquidacionComisionesCabecera.java

@Override
public void onStartPage(PdfWriter writer, Document document) {
    Font fontFecha = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT,
            new Phrase("11/04/2014", fontFecha), 500, 830, 0);
    Font fontPaginaNum = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT,
            new Phrase("Pgina " + document.getPageNumber(), fontPaginaNum), 500, 823, 0);
    Font fontLIQ03 = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT,
            new Phrase("LIQ03_0202", fontLIQ03), 500, 816, 0);
    Font fontTitulo = new Font(Font.FontFamily.COURIER, 12, Font.NORMAL);
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
            new Phrase("LIQUIDACIN DE COMISIONES: Marzo 2014", fontTitulo), 300, 800, 0);
    Font fontDireccion = new Font(Font.FontFamily.COURIER, 10, Font.NORMAL);
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT,
            new Phrase("PELAYO MUTUA DE SEGUROS", fontDireccion), 400, 750, 0);
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT,
            new Phrase("CL SANTA ENGRACIA, 67", fontDireccion), 400, 730, 0);
}

From source file:comisionesafis.informes.LiquidacionComisionesPie.java

@Override
public void onEndPage(PdfWriter writer, Document document) {
    Font font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT,
            new Phrase("Ejemplar para el mediador", font), 60, 20, 0);
}

From source file:control.ReportHandler.java

public void writeTotalEnrolledReport() throws DocumentException, FileNotFoundException {
    Document doc = new Document();

    Calendar c = Calendar.getInstance();
    String file = "" + c.get(Calendar.DAY_OF_MONTH) + "_" + (c.get(Calendar.MONTH) + 1) + "_"
            + c.get(Calendar.YEAR) + "_T_" + c.get(Calendar.HOUR_OF_DAY) + "_" + c.get(Calendar.MINUTE)
            + ".pdf";
    PdfWriter.getInstance(doc, new FileOutputStream(new File(his.His.reportEnrolledDir + "/" + file)));

    doc.open();/* www .j  a v  a 2  s  . c om*/

    PdfPTable totalTable = new PdfPTable(1);
    totalTable.setSpacingAfter(10f);
    PdfPTable tableP = new PdfPTable(4);
    PdfPTable tableGs = new PdfPTable(3);

    PdfPCell tableGsnameCell = new PdfPCell(new Phrase("Navn", columnFont));
    tableGsnameCell.setBackgroundColor(BaseColor.BLACK);
    PdfPCell tableGsbirthCell = new PdfPCell(new Phrase("Fdselsdag", columnFont));
    tableGsbirthCell.setBackgroundColor(BaseColor.BLACK);
    PdfPCell tableGsPersonCell = new PdfPCell(new Phrase("Person navn", columnFont));
    tableGsPersonCell.setBackgroundColor(BaseColor.BLACK);

    tableGs.addCell(tableGsnameCell);
    tableGs.addCell(tableGsbirthCell);
    tableGs.addCell(tableGsPersonCell);

    PdfPCell tablePnameCell = new PdfPCell(new Phrase("Navn", columnFont));
    tablePnameCell.setBackgroundColor(BaseColor.BLACK);
    PdfPCell tablePaddressCell = new PdfPCell(new Phrase("Adresse", columnFont));
    tablePaddressCell.setBackgroundColor(BaseColor.BLACK);
    PdfPCell tablePenrollerCell = new PdfPCell(new Phrase("Indskriver", columnFont));
    tablePenrollerCell.setBackgroundColor(BaseColor.BLACK);
    PdfPCell tablePtotalGuestsCell = new PdfPCell(new Phrase("Total gster", columnFont));
    tablePtotalGuestsCell.setBackgroundColor(BaseColor.BLACK);

    tableP.addCell(tablePnameCell);
    tableP.addCell(tablePaddressCell);
    tableP.addCell(tablePenrollerCell);
    tableP.addCell(tablePtotalGuestsCell);

    HashSet<Enrollment> enA = enR.getEnrollments();
    int totalCounter = 0;
    int totalCounter_NoHoene = 0;

    Iterator<Enrollment> enI = enA.iterator();

    while (enI.hasNext()) {
        totalCounter++;
        Enrollment en = enI.next();
        Person enP = en.getEnrolledPerson();
        if (!enP.isHoene()) {
            totalCounter_NoHoene++;
        }
        String nameP = enP.getFirstname() + " " + enP.getMiddlename() + " " + enP.getLastname();
        String addressP = enP.getAddress();

        User enU = en.getEnrolledByUser();
        String nameU = enU.getFirstname() + " " + enU.getMiddlename() + " " + enU.getLastname();

        Set<Guest> enGs = en.getGuests();
        String totalGs = String.valueOf(enGs.size());
        totalCounter += enGs.size();
        totalCounter_NoHoene += enGs.size();

        PdfPCell namePCell = new PdfPCell(new Phrase(nameP));
        PdfPCell birthPCell = new PdfPCell(new Phrase(addressP));

        PdfPCell nameUCell = new PdfPCell(new Phrase(nameU));

        PdfPCell totalGsCell = new PdfPCell(new Phrase(totalGs));

        tableP.addCell(namePCell);
        tableP.addCell(birthPCell);
        tableP.addCell(nameUCell);
        tableP.addCell(totalGsCell);

        Iterator<Guest> enGsI = enGs.iterator();

        while (enGsI.hasNext()) {
            Guest g = enGsI.next();

            String nameG = g.getFirstname() + " " + g.getMiddlename() + " " + g.getLastname();

            PdfPCell nameGCell = new PdfPCell(new Phrase(nameG));
            PdfPCell birthGCell = new PdfPCell(new Phrase(g.getBirthdayDate()));
            PdfPCell personGCell = new PdfPCell(new Phrase(nameP));

            tableGs.addCell(nameGCell);
            tableGs.addCell(birthGCell);
            tableGs.addCell(personGCell);
        }
    }

    PdfPCell totalCell = new PdfPCell(new Phrase("Total indskrevne: " + totalCounter));
    totalTable.addCell(totalCell);

    PdfPCell totalNoHoeneCell = new PdfPCell(
            new Phrase("Total indskrevne uden hner: " + totalCounter_NoHoene));
    totalTable.addCell(totalNoHoeneCell);

    doc.add(new Phrase("Personer"));
    doc.add(tableP);
    doc.add(totalTable);
    doc.add(new Phrase("Gster"));
    doc.add(tableGs);

    doc.close();

}

From source file:control.ReportHandler.java

public void writeTotalPersonReport() throws DocumentException, FileNotFoundException {
    Document doc = new Document(PageSize.A4.rotate());

    Calendar c = Calendar.getInstance();
    String file = "" + c.get(Calendar.DAY_OF_MONTH) + "_" + (c.get(Calendar.MONTH) + 1) + "_"
            + c.get(Calendar.YEAR) + "_T_" + c.get(Calendar.HOUR_OF_DAY) + "_" + c.get(Calendar.MINUTE)
            + ".pdf";
    PdfWriter.getInstance(doc, new FileOutputStream(new File(his.His.reportPersonsDir + "/" + file)));
    doc.open();//ww  w  .java 2  s.  c  om

    PdfPTable table = new PdfPTable(7);
    table.setWidths(new float[] { 10f, 10f, 10f, 10f, 5f, 5f, 5f });
    PdfPTable totalTable = new PdfPTable(1);

    PdfPCell nameCell = new PdfPCell(new Phrase("Navn", columnFont));
    nameCell.setBackgroundColor(BaseColor.BLACK);
    PdfPCell addressCell = new PdfPCell(new Phrase("Adresse", columnFont));
    addressCell.setBackgroundColor(BaseColor.BLACK);
    PdfPCell birthCell = new PdfPCell(new Phrase("Fdselsdag", columnFont));
    birthCell.setBackgroundColor(BaseColor.BLACK);
    PdfPCell createdCell = new PdfPCell(new Phrase("Oprettelsesdato", columnFont));
    createdCell.setBackgroundColor(BaseColor.BLACK);
    PdfPCell hoeneCell = new PdfPCell(new Phrase("Hne", columnFont));
    hoeneCell.setBackgroundColor(BaseColor.BLACK);
    PdfPCell reserveCell = new PdfPCell(new Phrase("Reserve", columnFont));
    reserveCell.setBackgroundColor(BaseColor.BLACK);
    PdfPCell oneOneCell = new PdfPCell(new Phrase("1-1", columnFont));
    oneOneCell.setBackgroundColor(BaseColor.BLACK);

    table.addCell(nameCell);
    table.addCell(addressCell);
    table.addCell(birthCell);
    table.addCell(createdCell);
    table.addCell(hoeneCell);
    table.addCell(reserveCell);
    table.addCell(oneOneCell);

    HashSet<Person> persons = peR.getPersons();
    Iterator<Person> personsI = persons.iterator();

    PdfPCell totalCell = new PdfPCell(new Phrase("Total: " + persons.size()));
    totalTable.addCell(totalCell);

    while (personsI.hasNext()) {
        Person p = personsI.next();

        String name = p.getFirstname() + " " + p.getMiddlename() + " " + p.getLastname();
        String hoene = "Nej";
        if (p.isHoene()) {
            hoene = "Ja";
        }
        String reserve = "Nej";
        if (p.isReserve()) {
            reserve = "Ja";
        }
        String oneOne = "Nej";
        if (p.isOneOne()) {
            oneOne = "Ja";
        }

        PdfPCell nameC = new PdfPCell(new Phrase(name));
        PdfPCell addressC = new PdfPCell(new Phrase(p.getAddress()));
        PdfPCell birthC = new PdfPCell(new Phrase(p.getBirthdayDate()));
        PdfPCell createdC = new PdfPCell(new Phrase(p.getCreationDate()));
        PdfPCell hoeneC = new PdfPCell(new Phrase(hoene));
        PdfPCell reserveC = new PdfPCell(new Phrase(reserve));
        PdfPCell oneOneC = new PdfPCell(new Phrase(oneOne));

        table.addCell(nameC);
        table.addCell(addressC);
        table.addCell(birthC);
        table.addCell(createdC);
        table.addCell(hoeneC);
        table.addCell(reserveC);
        table.addCell(oneOneC);
    }

    doc.add(new Phrase("Personer"));
    doc.add(table);
    doc.add(totalTable);

    doc.close();
}

From source file:control.ReportHandler.java

public void writeTotalUserReport() throws DocumentException, FileNotFoundException {
    Document doc = new Document(PageSize.A4.rotate());

    Calendar c = Calendar.getInstance();
    String file = "" + c.get(Calendar.DAY_OF_MONTH) + "_" + (c.get(Calendar.MONTH) + 1) + "_"
            + c.get(Calendar.YEAR) + "_T_" + c.get(Calendar.HOUR_OF_DAY) + "_" + c.get(Calendar.MINUTE)
            + ".pdf";
    PdfWriter.getInstance(doc, new FileOutputStream(new File(his.His.reportUsersDir + "/" + file)));
    doc.open();//from w w w .  j  ava  2s.com

    PdfPTable table = new PdfPTable(5);
    PdfPTable totalTable = new PdfPTable(1);

    PdfPCell colName = new PdfPCell(new Phrase("Navn", columnFont));
    colName.setBackgroundColor(BaseColor.BLACK);
    PdfPCell colBrugernavn = new PdfPCell(new Phrase("Brugernavn", columnFont));
    colBrugernavn.setBackgroundColor(BaseColor.BLACK);
    PdfPCell colCreated = new PdfPCell(new Phrase("Oprettelsesdato", columnFont));
    colCreated.setBackgroundColor(BaseColor.BLACK);
    PdfPCell colReserve = new PdfPCell(new Phrase("Reserve", columnFont));
    colReserve.setBackgroundColor(BaseColor.BLACK);
    PdfPCell colAdmin = new PdfPCell(new Phrase("Administrator", columnFont));
    colAdmin.setBackgroundColor(BaseColor.BLACK);

    table.addCell(colName);
    table.addCell(colBrugernavn);
    table.addCell(colCreated);
    table.addCell(colReserve);
    table.addCell(colAdmin);

    HashSet<User> users = usR.getUsers();
    Iterator<User> usI = users.iterator();

    PdfPCell totalCell = new PdfPCell(new Phrase("Total: " + users.size()));
    totalTable.addCell(totalCell);

    while (usI.hasNext()) {
        User u = usI.next();

        String name = u.getFirstname() + " " + u.getMiddlename() + " " + u.getLastname();
        String reserve = "Nej";
        if (u.isReserve()) {
            reserve = "Ja";
        }
        String admin = "Nej";
        if (u.isAdministrator()) {
            admin = "Ja";
        }

        PdfPCell nameC = new PdfPCell(new Phrase(name));
        PdfPCell usernameC = new PdfPCell(new Phrase(u.getUsername()));
        PdfPCell creationC = new PdfPCell(new Phrase(u.getCreationDate()));
        PdfPCell reserveC = new PdfPCell(new Phrase(reserve));
        PdfPCell adminC = new PdfPCell(new Phrase(admin));

        table.addCell(nameC);
        table.addCell(usernameC);
        table.addCell(creationC);
        table.addCell(reserveC);
        table.addCell(adminC);
    }

    doc.add(new Phrase("Brugere"));
    doc.add(table);
    doc.add(totalTable);

    doc.close();

}

From source file:control.ReportHandler.java

public void writeTotalQuarantineReport() throws DocumentException, FileNotFoundException {
    Document doc = new Document(PageSize.A4.rotate());

    Calendar c = Calendar.getInstance();
    String file = "" + c.get(Calendar.DAY_OF_MONTH) + "_" + (c.get(Calendar.MONTH) + 1) + "_"
            + c.get(Calendar.YEAR) + "_T_" + c.get(Calendar.HOUR_OF_DAY) + "_" + c.get(Calendar.MINUTE)
            + ".pdf";
    PdfWriter.getInstance(doc, new FileOutputStream(new File(his.His.reportQuarantinesDir + "/" + file)));
    doc.open();/*from www  . j  av  a  2 s . c  o m*/

    PdfPTable table = new PdfPTable(2);
    PdfPTable totalTable = new PdfPTable(1);

    PdfPCell colName = new PdfPCell(new Phrase("Navn", columnFont));
    colName.setBackgroundColor(BaseColor.BLACK);
    PdfPCell colBirth = new PdfPCell(new Phrase("Fdselsdag", columnFont));
    colBirth.setBackgroundColor(BaseColor.BLACK);

    table.addCell(colName);
    table.addCell(colBirth);
    ;

    HashSet<Quarantine> quarantines = quR.getQuarantines();
    Iterator<Quarantine> quI = quarantines.iterator();

    PdfPCell totalCell = new PdfPCell(new Phrase("Total: " + quarantines.size()));
    totalTable.addCell(totalCell);

    while (quI.hasNext()) {
        Quarantine qu = quI.next();

        Person p = qu.getPerson();

        String name = p.getFirstname() + " " + p.getMiddlename() + " " + p.getLastname();

        PdfPCell nameCell = new PdfPCell(new Phrase(name));
        PdfPCell birthCell = new PdfPCell(new Phrase(p.getBirthdayDate()));

        table.addCell(nameCell);
        table.addCell(birthCell);
    }

    doc.add(new Phrase("Karantner"));
    doc.add(table);
    doc.add(totalTable);

    doc.close();
}

From source file:controller.CCInstance.java

License:Open Source License

public final boolean signPdf(final String pdfPath, final String destination, final CCSignatureSettings settings,
        final SignatureListener sl) throws CertificateException, IOException, DocumentException,
        KeyStoreException, SignatureFailedException, FileNotFoundException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException {
    PrivateKey pk;//from   www.ja va 2 s  . com

    final PdfReader reader = new PdfReader(pdfPath);
    pk = getPrivateKeyFromAlias(settings.getCcAlias().getAlias());

    if (getCertificationLevel(pdfPath) == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) {
        String message = Bundle.getBundle().getString("fileDoesNotAllowChanges");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new SignatureFailedException(message);
    }

    if (reader.getNumberOfPages() - 1 < settings.getPageNumber()) {
        settings.setPageNumber(reader.getNumberOfPages() - 1);
    }

    if (null == pk) {
        String message = Bundle.getBundle().getString("noSmartcardFound");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    if (null == pkcs11ks.getCertificateChain(settings.getCcAlias().getAlias())) {
        String message = Bundle.getBundle().getString("certificateNullChain");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }
    final ArrayList<Certificate> embeddedCertificateChain = settings.getCcAlias().getCertificateChain();
    final Certificate owner = embeddedCertificateChain.get(0);
    final Certificate lastCert = embeddedCertificateChain.get(embeddedCertificateChain.size() - 1);

    if (null == owner) {
        String message = Bundle.getBundle().getString("certificateNameUnknown");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    final X509Certificate X509C = ((X509Certificate) lastCert);
    final Calendar now = Calendar.getInstance();
    final Certificate[] filledMissingCertsFromChainInTrustedKeystore = getCompleteTrustedCertificateChain(
            X509C);

    final Certificate[] fullCertificateChain;
    if (filledMissingCertsFromChainInTrustedKeystore.length < 2) {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()];
        for (int i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
    } else {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()
                + filledMissingCertsFromChainInTrustedKeystore.length - 1];
        int i = 0;
        for (i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
        for (int f = 1; f < filledMissingCertsFromChainInTrustedKeystore.length; f++, i++) {
            fullCertificateChain[i] = filledMissingCertsFromChainInTrustedKeystore[f];
        }
    }

    // Leitor e Stamper
    FileOutputStream os = null;
    try {
        os = new FileOutputStream(destination);
    } catch (FileNotFoundException e) {
        String message = Bundle.getBundle().getString("outputFileError");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new IOException(message);
    }

    // Aparncia da Assinatura
    final char pdfVersion;
    switch (Settings.getSettings().getPdfVersion()) {
    case "/1.2":
        pdfVersion = PdfWriter.VERSION_1_2;
        break;
    case "/1.3":
        pdfVersion = PdfWriter.VERSION_1_3;
        break;
    case "/1.4":
        pdfVersion = PdfWriter.VERSION_1_4;
        break;
    case "/1.5":
        pdfVersion = PdfWriter.VERSION_1_5;
        break;
    case "/1.6":
        pdfVersion = PdfWriter.VERSION_1_6;
        break;
    case "/1.7":
        pdfVersion = PdfWriter.VERSION_1_7;
        break;
    default:
        pdfVersion = PdfWriter.VERSION_1_7;
    }

    final PdfStamper stamper = (getNumberOfSignatures(pdfPath) == 0
            ? PdfStamper.createSignature(reader, os, pdfVersion)
            : PdfStamper.createSignature(reader, os, pdfVersion, null, true));

    final PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setSignDate(now);
    appearance.setReason(settings.getReason());
    appearance.setLocation(settings.getLocation());
    appearance.setCertificationLevel(settings.getCertificationLevel());
    appearance.setSignatureCreator(SIGNATURE_CREATOR);
    appearance.setCertificate(owner);

    final String fieldName = settings.getPrefix() + " " + (1 + getNumberOfSignatures(pdfPath));
    if (settings.isVisibleSignature()) {
        appearance.setVisibleSignature(settings.getPositionOnDocument(), settings.getPageNumber() + 1,
                fieldName);
        appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION);
        if (null != settings.getAppearance().getImageLocation()) {
            appearance.setImage(Image.getInstance(settings.getAppearance().getImageLocation()));
        }

        com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFactory
                .getFont(settings.getAppearance().getFontLocation(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0)
                .getBaseFont());

        font.setColor(new BaseColor(settings.getAppearance().getFontColor().getRGB()));
        if (settings.getAppearance().isBold() && settings.getAppearance().isItalic()) {
            font.setStyle(Font.BOLD + Font.ITALIC);
        } else if (settings.getAppearance().isBold()) {
            font.setStyle(Font.BOLD);
        } else if (settings.getAppearance().isItalic()) {
            font.setStyle(Font.ITALIC);
        } else {
            font.setStyle(Font.PLAIN);
        }

        appearance.setLayer2Font(font);
        String text = "";
        if (settings.getAppearance().isShowName()) {
            if (!settings.getCcAlias().getName().isEmpty()) {
                text += settings.getCcAlias().getName() + "\n";
            }
        }
        if (settings.getAppearance().isShowReason()) {
            if (!settings.getReason().isEmpty()) {
                text += settings.getReason() + "\n";
            }
        }
        if (settings.getAppearance().isShowLocation()) {
            if (!settings.getLocation().isEmpty()) {
                text += settings.getLocation() + "\n";
            }
        }
        if (settings.getAppearance().isShowDate()) {
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            SimpleDateFormat sdf = new SimpleDateFormat("Z");
            text += df.format(now.getTime()) + " " + sdf.format(now.getTime()) + "\n";
        }
        if (!settings.getText().isEmpty()) {
            text += settings.getText();
        }

        PdfTemplate layer2 = appearance.getLayer(2);
        Rectangle rect = settings.getPositionOnDocument();
        Rectangle sr = new Rectangle(rect.getWidth(), rect.getHeight());
        float size = ColumnText.fitText(font, text, sr, 1024, PdfWriter.RUN_DIRECTION_DEFAULT);
        ColumnText ct = new ColumnText(layer2);
        ct.setRunDirection(PdfWriter.RUN_DIRECTION_DEFAULT);
        ct.setAlignment(Element.ALIGN_MIDDLE);
        int align;
        switch (settings.getAppearance().getAlign()) {
        case 0:
            align = Element.ALIGN_LEFT;
            break;
        case 1:
            align = Element.ALIGN_CENTER;
            break;
        case 2:
            align = Element.ALIGN_RIGHT;
            break;
        default:
            align = Element.ALIGN_LEFT;
        }

        ct.setSimpleColumn(new Phrase(text, font), sr.getLeft(), sr.getBottom(), sr.getRight(), sr.getTop(),
                size, align);
        ct.go();
    } else {
        appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, fieldName);
    }

    // CRL <- Pesado!
    final ArrayList<CrlClient> crlList = null;

    // OCSP
    OcspClient ocspClient = new OcspClientBouncyCastle();

    // TimeStamp
    TSAClient tsaClient = null;
    if (settings.isTimestamp()) {
        tsaClient = new TSAClientBouncyCastle(settings.getTimestampServer(), null, null);
    }

    final String hashAlg = getHashAlgorithm(X509C.getSigAlgName());

    final ExternalSignature es = new PrivateKeySignature(pk, hashAlg, pkcs11Provider.getName());
    final ExternalDigest digest = new ProviderDigest(pkcs11Provider.getName());

    try {
        MakeSignature.signDetached(appearance, digest, es, fullCertificateChain, crlList, ocspClient, tsaClient,
                0, MakeSignature.CryptoStandard.CMS);
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, true, "");
        }
        return true;
    } catch (Exception e) {
        os.flush();
        os.close();
        new File(destination).delete();
        if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_CANCELED".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("userCanceled"));
        } else if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("noPermissions"));
        } else if (e instanceof ExceptionConverter) {
            String message = Bundle.getBundle().getString("timestampFailed");
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, message);
            }
            throw new SignatureFailedException(message);
        } else {
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, Bundle.getBundle().getString("unknownErrorLog"));
            }
            controller.Logger.getLogger().addEntry(e);
        }
        return false;
    }
}

From source file:Controller.ControllerCompra.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w w w.jav  a 2s .c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    if (request.getParameter("action") != null) {
        //int estado = 0;
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        String action = request.getParameter("action");
        switch (action) {
        case "Registrar": {
            String documentoUsuario = (request.getParameter("documentoUsuario"));
            String facturaProveedor = (request.getParameter("txtNumeroFactura"));
            String nombreProveedor = (request.getParameter("txtNombre"));
            int lenght = Integer.parseInt(request.getParameter("size"));
            int totalCompra = Integer.parseInt(request.getParameter("txtTotalCompra"));
            listObjDetalleMovimientos = new ArrayList<>();
            for (int i = 0; i < lenght; i++) {
                _objDetalleMovimiento = new ObjDetalleMovimiento();
                _objDetalleMovimiento
                        .setIdArticulo(Integer.parseInt(request.getParameter("lista[" + i + "][idArticulo]")));
                _objDetalleMovimiento
                        .setCantidad(Integer.parseInt(request.getParameter("lista[" + i + "][cantidad]")));
                _objDetalleMovimiento.setPrecioArticulo(
                        Integer.parseInt(request.getParameter("lista[" + i + "][precioArticulo]")));
                _objDetalleMovimiento.setTotalDetalleMovimiento(
                        _objDetalleMovimiento.getCantidad() * _objDetalleMovimiento.getPrecioArticulo());
                _objDetalleMovimiento.setDescuento(lenght);
                listObjDetalleMovimientos.add(_objDetalleMovimiento);
            }
            _objUsuario.setDocumentoUsuario(documentoUsuario);
            _objCompra.setFacturaProveedor(facturaProveedor);
            _objCompra.setNombreProveedor(nombreProveedor);
            _objCompra.setTotalCompra(totalCompra);
            daoModelCompra = new ModelCompra();
            String salida = Mensaje(daoModelCompra.Add(_objCompra, _objUsuario, listObjDetalleMovimientos),
                    "La compra ha sido registrada", "Ha ocurrido un error");
            daoModelCompra.Signout();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(salida);
            break;
        }
        case "Consultar": {
            int id = Integer.parseInt(request.getParameter("id"));
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(consultarDetalle(id));
            break;
        }
        case "Enlistar": {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(getTableCompra());
            break;
        }
        //<editor-fold defaultstate="collapsed" desc="PDF mediante iText">
        case "Imprimir": {
            response.setContentType("application/pdf");
            try {
                Locale loc = Locale.getDefault();
                NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(loc);
                //Primero obtengo el id del Movimiento
                int id = Integer.parseInt(request.getParameter("id"));
                //Obtengo el reporte a manera de Map
                Map material = reporte(id);
                //Topo ese reporte y lo divido, primero en la compra y luego el detalle
                Map<String, String> compra = (Map) material.get("Compra");
                List<Map> detalle = (List) material.get("Detalle");
                //Creo el documento y obtengo el canal de comunicacion con el servidor, para luego enviar el documento.
                Document document = new Document();
                OutputStream os = response.getOutputStream();
                //Creo una instancia a partir del documento y del canal
                PdfWriter.getInstance(document, os);
                //Abro el documento
                document.open();
                Image logo = Image.getInstance(url + "/public/images/logo.png");
                logo.scaleAbsolute(new Rectangle(logo.getPlainWidth() / 4, logo.getPlainHeight() / 4));
                document.add(logo);
                //Creo una fuente para la letra en negrilla
                final Font helveticaBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
                //Escribo y agrego un primer parrafo con los datos basicos de la compra                        
                Paragraph headerDerecha = new Paragraph();
                headerDerecha.add(new Chunk("Nombre del Proveedor: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("nombreProveedor") + "\n"));
                headerDerecha.add(new Chunk("Factura del Proveedor: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("facturaProveedor") + "\n"));
                headerDerecha.add(new Chunk("Fecha Compra: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("fechaCompra") + "\n"));
                //Escribo y agrego un segundo parrafo con los datos basicos de Stelarte  
                Paragraph headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Stelarte.Decoracion \n", helveticaBold));
                headerIzquierda.add(new Chunk("Direccin: ", helveticaBold));
                headerIzquierda.add(new Chunk("Calle Falsa 123 # 12a34\n"));
                headerIzquierda.add(new Chunk("Telfono: ", helveticaBold));
                headerIzquierda.add(new Chunk("2583697 \n"));
                //Agrego los dos anteriores parrafos al Header
                PdfPTable header = new PdfPTable(2);
                header.getDefaultCell().setBorder(0);
                header.addCell(headerIzquierda);
                header.addCell(headerDerecha);
                header.setWidthPercentage(100f);
                header.setSpacingAfter(20);
                document.add(header);
                //Creo la tabla del detalle
                PdfPTable tablaDetalle = new PdfPTable(new float[] { 1, 3, 2, 2 });
                tablaDetalle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                //Creo el titulo, le quito el borde, le digo que ocupara cuatro columnas y que ser centrado
                PdfPCell tituloCell = new PdfPCell(new Phrase("Detalle de Compra", helveticaBold));
                tituloCell.setBorder(0);
                tituloCell.setColspan(4);
                tituloCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                tablaDetalle.addCell(tituloCell);
                //Aqui creo cada cabecera
                tablaDetalle.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
                tablaDetalle.addCell(new Phrase("ID", helveticaBold));
                tablaDetalle.addCell(new Phrase("Nombre", helveticaBold));
                tablaDetalle.addCell(new Phrase("Cantidad", helveticaBold));
                tablaDetalle.addCell(new Phrase("Valor", helveticaBold));
                tablaDetalle.getDefaultCell().setBackgroundColor(null);
                //Aqui agrego la tabla cada articulo.
                for (Map<String, String> next : detalle) {
                    tablaDetalle.addCell(next.get("idArticulo"));
                    tablaDetalle.addCell(next.get("descripcionArticulo"));
                    tablaDetalle.addCell(next.get("cantidad"));
                    tablaDetalle
                            .addCell(currencyFormatter.format(Integer.parseInt(next.get("precioArticulo"))));
                }
                //Creo el Footer
                headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Total: ", helveticaBold));
                headerIzquierda
                        .add(new Chunk(currencyFormatter.format(Integer.parseInt(compra.get("totalCompra")))));
                PdfPCell footerCell = new PdfPCell(headerIzquierda);
                footerCell.setBorder(0);
                footerCell.setColspan(4);
                footerCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                tablaDetalle.addCell(footerCell);
                //Establesco el tamao  y posicion de la tabla, luego la agrego al documento
                tablaDetalle.setWidthPercentage(100f);
                tablaDetalle.setHorizontalAlignment(Element.ALIGN_RIGHT);
                document.add(tablaDetalle);
                //Cierro el documento y lo envio con flush.
                document.close();
                response.setHeader("Content-Disposition", "attachment;filename=\"reporte.pdf\"");
                os.flush();
                os.close();
            } catch (DocumentException de) {
                throw new IOException(de.getMessage());
            }
            break;
        }
        //</editor-fold>
        //<editor-fold defaultstate="collapsed" desc="PDF mediante iReports">
        case "Imprimir2": {
            try {
                int id = Integer.parseInt(request.getParameter("id"));
                String source = url + "/reports/newReport1.jrxml";
                JasperPrint jasperPrint = null;
                JasperReport jasperReport = null;
                JasperDesign jasperDesign = null;
                System.out.println(source);
                String reportPath = request.getServletContext().getRealPath("reports") + "\\newReport1.jrxml";
                jasperDesign = JRXmlLoader.load(reportPath);
                jasperReport = JasperCompileManager.compileReport(jasperDesign);
                jasperPrint = JasperFillManager.fillReport(jasperReport, reporte(id),
                        daoModelCompra.getConnection());
                JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
            } catch (Exception ex) {
                for (StackTraceElement ruta : ex.getStackTrace()) {
                    System.err.println(ruta);
                }
            }
        }
            break;
        //</editor-fold>

        }
    }

}