Example usage for com.itextpdf.text Image getInstance

List of usage examples for com.itextpdf.text Image getInstance

Introduction

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

Prototype

public static Image getInstance(final Image image) 

Source Link

Document

gets an instance of an Image

Usage

From source file:control.AdminPDF.java

public static void generarInforme(ArrayList<Tarea> tareas, String usuario) {

    try {/*from  w w w  . j  ava2  s. co m*/
        //Creamos la carpeta donde se almacenaran las facturas
        // Si quieres que las facturas se guarden en una carpeta del computador, 
        // aca colocas la ruta donde quieres que se guarden en lugar de src/facturas, 
        // tanto al crear carpeta y laFactura (de tipo File) y al crear archivo (de tipo FileOutputStream)
        //Ejemplo:  File carpeta = new File("D:\\facturas"); 
        //          FileOutputStream archivo = new FileOutputStream("D:\\facturas" + consecutivo + ".pdf");
        //          File laFactura = new File("src/facturas" + consecutivo + ".pdf");

        File carpeta = new File("web/pdfs");
        System.out.println(carpeta.exists());
        if (!carpeta.exists()) {
            carpeta.mkdirs();
        }
        String[] list = carpeta.list();
        consecutivo = list.length;
        System.out.println("Consecutivo es: " + consecutivo);
        int total = 0;
        FileOutputStream archivo = new FileOutputStream("web/pdfs/" + consecutivo + ".pdf");
        Document documento = new Document();
        PdfWriter.getInstance(documento, archivo);
        documento.open();
        Paragraph titulo = new Paragraph("Resumen de Actividades");
        titulo.setAlignment(Element.ALIGN_CENTER);
        documento.add(titulo);

        documento.add(new Paragraph(
                "------------------------------------------------------------------------------------------------------------------------------"));
        documento.add(new Paragraph("Usuario: " + usuario));
        documento.add(new Paragraph(" "));
        //         documento.add(new Paragraph("------------------------------------------------------------------------------------------------------------------------------"));
        documento.add(new Paragraph(" "));
        documento.add(new Paragraph(" "));
        //         documento.add(new Paragraph(" "));
        //         documento.add(new Paragraph(" "));
        documento.add(new Paragraph("  "));
        PdfPTable tabla = new PdfPTable(7);
        Image image = Image.getInstance("../EasyTasks/web/images/logo.png");

        //         tabla.addCell(image);
        Paragraph nombreBase = new Paragraph("Nombre ");
        Paragraph descripcionBase = new Paragraph("Descripcion     ");
        Paragraph fechaBase = new Paragraph("Fecha ");
        Paragraph prioridadBase = new Paragraph("Prioridad  ");
        Paragraph tagsBase = new Paragraph("Tags");
        Paragraph categoriaBase = new Paragraph("Categoria  ");
        Paragraph ubicacionBase = new Paragraph("Ubicacion    ");

        //         tabla.addCell(image);
        tabla.addCell(nombreBase);
        tabla.addCell(descripcionBase);
        tabla.addCell(fechaBase);
        tabla.addCell(prioridadBase);
        tabla.addCell(tagsBase);
        tabla.addCell(categoriaBase);
        tabla.addCell(ubicacionBase);
        for (int i = 0; i < tareas.size(); i++) {

            Tarea tareaNueva = tareas.get(i);
            Paragraph nombre = new Paragraph(tareaNueva.getNombre());
            Paragraph descripcion = new Paragraph(tareaNueva.getDescripcion());
            Paragraph fecha = new Paragraph(tareaNueva.getFechaLimite() + "");
            Paragraph prioridad = new Paragraph(tareaNueva.getPrioridad());
            Paragraph tags = null;
            for (int k = 0; k < tareaNueva.getTags().size(); k++) {
                tags = new Paragraph(tareaNueva.getTags().get(k));
            }
            Paragraph categoria = new Paragraph(tareaNueva.getCategoria());
            Paragraph ubicacion = new Paragraph(
                    tareaNueva.getUbiLatitud() + ", " + tareaNueva.getUbiLongitud());
            //            Paragraph tost = new Paragraph(tareaNueva.toStringSimple());

            tabla.addCell(nombre);
            tabla.addCell(descripcion);
            tabla.addCell(fecha);
            tabla.addCell(prioridad);
            tabla.addCell(tags);
            tabla.addCell(categoria);
            tabla.addCell(ubicacion);
            //            tabla.addCell(tost);

        }

        //         FileReader fr = new FileReader("src/archivos/pedidos.txt");
        //         BufferedReader bwa = new BufferedReader(fr);
        //         String elProducto = bwa.readLine();
        //         while (elProducto != null) {
        //            if (!elProducto.equalsIgnoreCase("")) {
        //               System.out.println("El producto: " + elProducto);
        //               String[] elProductoConPrecio = elProducto.split("-");
        //               Paragraph producto = new Paragraph(elProductoConPrecio[0]);
        //               Paragraph precio = new Paragraph(elProductoConPrecio[1]);
        //               total += Integer.parseInt(elProductoConPrecio[1]);
        //               precio.setAlignment(Element.ALIGN_RIGHT);
        //               tabla.addCell(producto);
        //               tabla.addCell(precio);
        //               elProducto = bwa.readLine();
        //            }
        //         }
        //         if (!darIva().equals("") && !darIva().equals("0")) {
        //            tabla.addCell("Subtotal");
        //            Paragraph elSubTotal = new Paragraph("" + total);
        //            elSubTotal.setAlignment(Element.ALIGN_RIGHT);
        //            tabla.addCell(elSubTotal);
        //            tabla.addCell("Iva (" + darIva() + ")");
        //            int iva = total * Integer.parseInt(darIva()) / 100;
        //            tabla.addCell("" + iva);
        //            int precioConIva = total + iva;
        //            tabla.addCell("Total");
        //            Paragraph elTotal = new Paragraph("" + precioConIva);
        //            elTotal.setAlignment(Element.ALIGN_RIGHT);
        //            tabla.addCell(elTotal);
        //         } else {
        //            tabla.addCell("Total");
        //            Paragraph elTotal = new Paragraph("" + total);
        //            elTotal.setAlignment(Element.ALIGN_RIGHT);
        //            tabla.addCell(elTotal);
        //         }
        documento.add(tabla);
        documento.add(new Paragraph(
                "----------------------------------------------------------------------------------------------"));
        documento.add(new Paragraph("Muchas gracias por utilizar nuestro servicio,"));
        documento.add(new Paragraph(""));
        //         Image image = Image.getInstance("logo.png");
        documento.addCreator("EasyTask Team");
        documento.add(image);
        documento.addCreationDate();
        //         PdfPCell cell2 = new PdfPCell(image, true);

        //         tabla.addCell(cell2);
        documento.add(new Paragraph(""));
        documento.add(new Paragraph("         EasyTask Team"));
        documento.close();
        File elInforme = new File("../EasyTasks/web/pdfs/" + usuario + ".pdf");
        Desktop.getDesktop().open(elInforme);
        //         BufferedWriter br = new BufferedWriter(new FileWriter("src//pedidos.txt"));
        //         br.write("");
        //         br.close();
        //         fr.close();
        //         bwa.close();
        archivo.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(AdminPDF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(AdminPDF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(AdminPDF.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
    }

}

From source file:control.ModificaPrestamo.java

public boolean generapdf(String path) throws DocumentException, FileNotFoundException {
    boolean estado = false;
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(path));
    document.open();// w  ww  .  ja  v  a  2  s  . c  o m

    Image img = null;
    try {
        img = Image.getInstance("src/img/imgen.jpg");
        img.scaleAbsolute(80f, 50f);
        img.setAbsolutePosition(470f, 750f);
        document.add(img);
    } catch (BadElementException ex) {
        Logger.getLogger(nuevoReporte.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(nuevoReporte.class.getName()).log(Level.SEVERE, null, ex);
    }

    Paragraph paragraph1 = new Paragraph("Solicitante: " + Solicitante.getText());
    Paragraph paragraph2 = new Paragraph("Proyecto: " + Proyecto.getText());
    Paragraph paragraph3 = new Paragraph(
            "Fecha y hora del prestamo: " + fecha.getText() + " " + hora.getText());
    Paragraph paragraph4 = new Paragraph("Fecha de entrega: " + fecha1.getText());

    document.add(paragraph1);
    document.add(paragraph2);
    document.add(paragraph3);
    document.add(paragraph4);
    Paragraph tmp = new Paragraph("");
    tmp.setSpacingBefore(10);
    document.add(tmp);
    PdfPTable table = new PdfPTable(4);
    table.addCell("Id Equipo");
    table.addCell("Equipo");
    table.addCell("Accesorios");
    table.addCell("Descripcion");
    Object[][] tabla = this.getTableData(tabReporte);
    for (Object[] o : tabla)
        for (Object e : o) {
            table.addCell((String) e);
        }

    document.add(table);
    System.out.println(clausula1.getText() + " " + clausula2.getText());
    Paragraph paragraph5 = new Paragraph("Clausula 1: " + clausula1.getText());
    Paragraph paragraph6 = new Paragraph("Clausula 2: " + clausula2.getText());
    document.add(paragraph5);
    document.add(paragraph6);
    tmp = new Paragraph("");
    tmp.setSpacingBefore(10);
    document.add(tmp);
    Paragraph p = new Paragraph("Firma del solicitante: ");
    p.add(new Chunk(new DottedLineSeparator()));
    p.add("   Firma del prestador: ");
    p.add(new Chunk(new DottedLineSeparator()));
    document.add(p);

    //PdfPTable firma = new PdfPTable(1);
    //firma.addCell("Firma");
    //document.add(new Paragraph(""));
    //document.add(firma);
    document.close();
    return true;
}

From source file:Control.PdfBiglietto.java

/**
 * Funzione che costruisce il file PDF//from   w  ww. jav  a2  s  . c  o m
 * @param nomeFile Nome del file PDF
 * @param stream Stream sul quale verr scritto il pdf
 * @throws DocumentException
 * @throws BadElementException
 * @throws IOException 
 */
public void costruisciPdf(String nomeFile, OutputStream stream)
        throws DocumentException, BadElementException, IOException {
    SimpleDateFormat dataNormale = new SimpleDateFormat("dd/MM/YYYY");

    Document biglietto = new Document();
    //PdfWriter.getInstance(biglietto, new FileOutputStream(nomeFile));
    PdfWriter.getInstance(biglietto, stream);

    biglietto.open();
    biglietto.addAuthor(autore);
    biglietto.addCreationDate();
    biglietto.addCreator(autore);
    biglietto.addTitle(titolo);
    //dati inseriti nel QRCode
    int contatorePrenotazioni = 1; //usato per avere due prenotazioni per ogni pagina
    for (Prenotazione p : prenotazioni) {
        contatorePrenotazioni++;

        StringBuilder sb = new StringBuilder();
        sb.append(p.getId());
        sb.append("|");
        sb.append(p.getUtente().getNome());
        sb.append("|");
        sb.append(p.getPrezzo());
        sb.append("|");
        sb.append(p.getSala().getId());
        sb.append("|");
        sb.append(p.getPosto().getRiga());
        sb.append("|");
        sb.append(p.getPosto().getColonna());
        sb.append("|");
        sb.append(p.getSpettacolo().getFilm().getTitolo());
        sb.append("|");
        sb.append(dataNormale.format(p.getSpettacolo().getData_ora().getTime()));

        Paragraph completo = new Paragraph();
        completo.setSpacingAfter(80.0f);
        //in caso di problemi al QRcode (dimensioni eccessive, aspetti strani, etc), controllare la stringa in ingresso.
        QRCode qrBiglietto = new QRCode(sb.toString());

        Paragraph titolo = new Paragraph(p.getSpettacolo().getFilm().getTitolo());
        titolo.add("\nPrenotazione a nome dell'utente:  " + p.getUtente().getNome());
        titolo.add("   Id Spettacolo: " + Integer.toString(p.getSpettacolo().getId()));

        Paragraph info = new Paragraph();
        info.add("Lo spettacolo si terr il giorno: ");
        info.add(dataNormale.format(p.getSpettacolo().getData_ora().getTime()));
        info.add("\nID Prenotazione: " + Integer.toString(p.getId()));
        Paragraph sala = new Paragraph();
        sala.add("Sala: " + p.getSala().getNome());
        sala.add(" Il tuo posto  nella riga: " + p.getPosto().getRiga() + " e colonna: "
                + p.getPosto().getColonna());

        Paragraph prezzo = new Paragraph("Pagamento:" + Double.toString(p.getPrezzo()));
        prezzo.add(" Euro");

        Paragraph fondo = new Paragraph("Biglietto emesso in data: " + dataNormale.format(new Date()));
        fondo.add("\n Mostra questo qrCode all'addetto del cinema: ");

        Image qrCode = Image.getInstance(qrBiglietto.getQrcode().toByteArray());
        qrCode.setAlignment(Image.TOP);

        if (contatorePrenotazioni % 2 == 0)
            biglietto.newPage();

        completo.add(titolo);
        completo.add(info);
        completo.add(sala);
        completo.add(prezzo);
        completo.add(fondo);
        completo.add(qrCode);

        biglietto.add(completo);
    }
    biglietto.close();
}

From source file:Controlador.ControladorCrearPase.java

public void generaPDF(String Prueba, String Causa, Integer idCita, Integer idPaciente, Integer idPersona)
        throws FileNotFoundException, DocumentException, IOException {

    Calendar cal = Calendar.getInstance();
    String time = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(cal.getTime());
    String timename = new SimpleDateFormat("yyyyMMddHHmm").format(cal.getTime());

    File file = new File("PaseServicio" + timename + ".pdf");
    FileOutputStream fileout = new FileOutputStream(file);
    Document document = new Document();
    PdfWriter writer;/*from w w w.ja  v  a2 s . com*/
    writer = PdfWriter.getInstance(document, fileout);

    Font fuente = new Font();
    Font fuente2 = new Font();
    Font fuente3 = new Font();

    // fuente.setColor(BaseColor.BLUE);
    fuente.setStyle(Font.UNDERLINE | Font.BOLDITALIC);
    fuente2.setStyle(Font.BOLD);
    fuente2.setSize(12);
    fuente3.setSize(20);
    fuente3.setStyle(Font.BOLD);

    document.open();
    document.add(new Paragraph("\n \n \n \n \n"));
    document.add(new Paragraph("Clinica Mdica INFTEL", fuente3));

    String imageUrl = "src/Imagen/logo.png";
    //  String imagen="src\Imagen\logo.png"; 
    Image image = Image.getInstance(imageUrl);
    image.setAbsolutePosition(300, 750);
    image.scalePercent(80f);
    document.add(image);

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

    document.add(new Paragraph("DATOS DEL PACIENTE", fuente));
    document.add(new Paragraph(" "));
    document.add(
            new Paragraph("Apellidos y Nombre : " + paciente.getApellidos() + ", " + paciente.getNombre()));
    document.add(new Paragraph("NIF : " + paciente.getNif()));
    document.add(new Paragraph("NSS : " + paciente.getNumSS()));
    document.add(new Paragraph("Direccion : " + paciente.getDireccion()));
    document.add(new Paragraph("Telefono : " + paciente.getTelefono()));
    document.add(new Paragraph("Email : " + paciente.getEmail()));
    document.add(new Paragraph("ID Paciente : " + idPaciente));

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

    document.add(new Paragraph("DATOS ", fuente));
    document.add(new Paragraph(" "));
    document.add(new Paragraph(" "));

    document.add(new Paragraph("Prueba : ", fuente2));
    document.add(new Paragraph(Prueba));
    document.add(new Paragraph(" "));
    document.add(new Paragraph(" "));

    document.add(new Paragraph("Causa : ", fuente2));
    document.add(new Paragraph(Causa));
    document.add(new Paragraph(" "));
    document.add(new Paragraph(" "));

    absText(writer, time, 450, 50);

    document.close();
    File myfile = new File("PaseServicio" + timename + ".pdf");
    Desktop.getDesktop().open(myfile);
}

From source file:Controlador.EmailWithPdf.java

/**
 * Writes the content of a PDF file (using iText API)
 * to the {@link OutputStream}./* ww  w. j a v  a 2s .c  o  m*/
 * @param outputStream {@link OutputStream}.
 * @throws Exception
 */
public void writePdf(OutputStream outputStream) throws Exception {
    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, 12);

    // document.setPageSize(null);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    Image imagen = Image.getInstance("D:\\ALEX\\Bseguros\\web\\img\\Aseguradoras\\BSeguroLogo.png");
    Image imagen2 = Image.getInstance("D:\\ALEX\\Bseguros\\web\\img\\Aseguradoras\\mapfre.png");

    DateFormat df = new SimpleDateFormat("dd/MM/YYYY");
    Calendar cdos = Calendar.getInstance();
    Date datediamas = new Date();
    Date dateaniomas = new Date();
    cdos.add(Calendar.DATE, 1);
    datediamas = cdos.getTime();
    String fechadiamas = df.format(datediamas);
    cdos.add(Calendar.YEAR, 1);
    dateaniomas = cdos.getTime();
    String fechavencimiento = df.format(dateaniomas);
    document.open();

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

    //         Rectangle rect= new Rectangle(36,108);
    //         rect.setBorder(Rectangle.BOX);
    //         
    //rect.setBorderColor(BaseColor.BLACK);
    //rect.setBorderWidth(2);
    //document.add(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" + fechadiamas + " hasta: " + fechavencimiento,
            boldFontTitulo);
    Paragraph paragraph3 = new Paragraph(
            "DhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhATOS DE TU POLIZA",
            boldFontTitulo);

    paragraph2.setAlignment(Element.ALIGN_CENTER);

    document.add(paragraph2);
    document.add(paragraph3);

    document.close();

}

From source file:Controlador.PDF.java

public String escribePDF(String nombre) {
    FileOutputStream ficheroPdf = null;

    Random r = new Random();
    r.setSeed(System.currentTimeMillis());

    String f_nombre = "cons" + nombre + r.nextInt(9000) + ".pdf";

    try {//from   w  w w  . ja  v a2  s .  c o m

        Document documento = new Document();

        String basePath = new File("").getAbsolutePath();
        String[] parts = basePath.split("/");

        final String path = "/" + parts[1] + "/" + parts[2] + "/NetBeansProjects/pag_ingles/web/" + f_nombre;
        ficheroPdf = new FileOutputStream(path);

        PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);

        documento.open();

        Image foto = Image.getInstance(
                "/" + parts[1] + "/" + parts[2] + "/NetBeansProjects/pag_ingles/web/img/escuela.png");
        foto.scaleToFit(200, 200);
        foto.setAlignment(Chunk.ALIGN_RIGHT);
        documento.add(foto);
        documento.add(new Paragraph("           "));
        documento.add(new Paragraph("           "));
        documento.add(new Paragraph("           "));

        documento.add(new Paragraph("Darktech Anglo Institute",
                FontFactory.getFont("Courier-Bold", 30, Font.UNDERLINE, BaseColor.BLUE)));

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

        documento.add(new Paragraph("        OTORGA LA PRESENTEaaa",
                FontFactory.getFont("ARIAL", 30, Font.NORMAL, BaseColor.BLACK)));

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

        documento.add(new Paragraph("            CONSTANCIA",
                FontFactory.getFont("ARIAL", 30, Font.NORMAL, BaseColor.BLACK)));

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

        documento.add(new Paragraph("  A :       " + nombre,
                FontFactory.getFont("ARIAL", 20, Font.BOLD, BaseColor.BLACK)));

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

        documento.add(new Paragraph("POR HABER CONCLUIDO CON EXITO EL CURSO DE INGLES.",
                FontFactory.getFont("ARIAL", 14, Font.NORMAL, BaseColor.BLACK)));

        documento.close();
        ficheroPdf.close();

        Thread.sleep(3000);

    } catch (DocumentException | FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();

    } catch (InterruptedException ex) {
        Logger.getLogger(PDF.class.getName()).log(Level.SEVERE, null, ex);
    } finally {

        try {
            ficheroPdf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return f_nombre;
}

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 w  w  w .  j av a  2s. c  o m*/

    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.// w  ww . jav  a 2s.c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    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>

        }
    }

}

From source file:Controller.ControllerVenta.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  ww .ja va  2 s . c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    if (request.getParameter("action") != null) {
        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 documentoCliente = null;
            String nombreCliente = null;
            int numeroVenta = 0;
            if (Validador.validarDocumento(request.getParameter("documentoCliente"))
                    & Validador.validarNombresCompletos(request.getParameter("txtNombreCliente"))
                    & Validador.validarNumero(request.getParameter("txtNumeroVenta"))) {
                documentoCliente = (request.getParameter("documentoCliente"));
                nombreCliente = (request.getParameter("txtNombreCliente"));
                numeroVenta = Integer.parseInt(request.getParameter("txtNumeroVenta"));
            } else {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(Mensaje(false, null, "Ha ingresado datos incorrectos"));
                break;
            }

            int lenght = Integer.parseInt(request.getParameter("size"));
            int totalCompra = Integer.parseInt(request.getParameter("txtTotalVenta"));
            listOjbDetalleMovimientos = 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);
                listOjbDetalleMovimientos.add(_objDetalleMovimiento);
            }
            _objUsuario.setDocumentoUsuario(documentoUsuario);
            _objVenta.setIdVenta(numeroVenta);
            _objVenta.setDocumentoCliente(documentoCliente);
            _objVenta.setNombreCliente(nombreCliente);
            _objVenta.setTotalVenta(totalCompra);
            daoModelVenta = new ModelVenta();
            String salida = Mensaje(daoModelVenta.Add(_objVenta, _objUsuario, listOjbDetalleMovimientos),
                    "La venta ha sido registrada", "Ha ocurrido un error");
            daoModelVenta.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(getTableVenta());
            break;
        }
        case "Contador": {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(getContador());
            break;
        }
        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> venta = (Map) material.get("Venta");
                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("Id. de la Venta: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("numeroVenta") + "\n"));
                headerDerecha.add(new Chunk("Nombre del Cliente: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("nombreCliente") + "\n"));
                headerDerecha.add(new Chunk("Documento del Cliente: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("documentoCliente") + "\n"));
                headerDerecha.add(new Chunk("Fecha Venta: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("fechaVenta") + "\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 Venta", 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(venta.get("totalVenta")))));
                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;
        }
        }
    }
}

From source file:Controller.CrearPDF.java

/**
 * We create a PDF document with iText using different elements to learn 
 * to use this library./*  w  ww.jav a 2  s .  com*/
 * Creamos un documento PDF con iText usando diferentes elementos para aprender 
 * a usar esta librera.
 * @param pdfNewFile  <code>String</code> 
 *      pdf File we are going to write. 
 *      Fichero pdf en el que vamos a escribir. 
 */
//    public void createPDF(File pdfNewFile, ReparacionEntity reparacion) throws Exception {
public void createPDF(File pdfNewFile) throws Exception {
    // We create the document and set the file name.        
    // Creamos el documento e indicamos el nombre del fichero.
    try {
        //            ClienteController cc = new ClienteController();
        //            Cliente cliente = cc.buscarPorId(reparacion.getCliente());
        Document document = new Document();
        try {

            PdfWriter.getInstance(document, new FileOutputStream(pdfNewFile));

        } catch (FileNotFoundException fileNotFoundException) {
            System.out.println("No such file was found to generate the PDF "
                    + "(No se encontr el fichero para generar el pdf)" + fileNotFoundException);
        }
        document.open();
        // We add metadata to PDF
        // Aadimos los metadatos del PDF
        document.addTitle("Table export to PDF (Exportamos la tabla a PDF)");
        document.addSubject("Using iText (usando iText)");
        document.addKeywords("Java, PDF, iText");
        document.addAuthor("Cdigo Xules");
        document.addCreator("Cdigo Xules");

        // First page
        // Primera pgina 
        Chunk chunk = new Chunk("RDEN DE TRABAJO", categoryFont);
        Chunk c2 = new Chunk("\n\n\nCentro de Formacin SATCAR6\n" + "Calle Artes Grficas n1 Nave 12 A\n"
                + "Pinto (28320), Madrid", smallFont);

        Chunk c3 = new Chunk("Datos del Cliente", smallBold);
        //            Chunk c4 = new Chunk("Nombre: "+cliente.getRazonSocial(),smallBold);
        //            Chunk c5 = new Chunk("Poblacin: "+cliente.getPoblacion(),smallBold);
        //            Chunk c6 = new Chunk("Provincia: "+cliente.getProvincia(),smallBold);
        //            Chunk c7 = new Chunk("Cdigo Postal: "+cliente.getCp(),smallBold);
        //            Chunk c8 = new Chunk("Num Telfono: Pepito"+cliente.getTlf1(),smallBold);
        Chunk c4 = new Chunk("Nombre: Jesus Eduardo Garcia Toril", smallBold);
        Chunk c5 = new Chunk("Poblacin: Pinto", smallBold);
        Chunk c6 = new Chunk("Provincia: Madrid", smallBold);
        Chunk c7 = new Chunk("Cdigo Postal: 28320", smallBold);
        Chunk c8 = new Chunk("Num Telfono: 659408182", smallBold);

        Paragraph parrafo = new Paragraph(chunk);
        Paragraph p2 = new Paragraph(c2);
        Paragraph p3 = new Paragraph(c3);
        Phrase ph1 = new Phrase(c4);
        Phrase ph2 = new Phrase(c5);
        Phrase ph3 = new Phrase(c6);
        Phrase ph4 = new Phrase(c7);
        Phrase ph5 = new Phrase(c8);

        // Let's create de first Chapter (Creemos el primer captulo)

        // We add an image (Aadimos una imagen)
        Image image;
        try {
            parrafo.setAlignment(Element.ALIGN_CENTER);
            image = Image.getInstance(iTextExampleImage);
            image.setAbsolutePosition(0, 750);
            p2.setAlignment(Element.ALIGN_LEFT);
            document.add(parrafo);
            document.add(image);
            document.add(p2);
            document.add(p3);
            document.add(ph1);
            document.add(ph2);
            document.add(ph3);
            document.add(ph4);
            document.add(ph5);

        } catch (BadElementException ex) {
            System.out.println("Image BadElementException" + ex);
        }

        // Second page - some elements
        // Segunda pgina - Algunos elementos

        // List by iText (listas por iText)
        String text = "test 1 2 3 ";
        for (int i = 0; i < 5; i++) {
            text = text + text;
        }
        List list = new List(List.UNORDERED);
        ListItem item = new ListItem(text);
        item.setAlignment(Element.ALIGN_JUSTIFIED);
        list.add(item);
        text = "a b c align ";
        for (int i = 0; i < 5; i++) {
            text = text + text;
        }
        item = new ListItem(text);
        item.setAlignment(Element.ALIGN_JUSTIFIED);
        list.add(item);
        text = "supercalifragilisticexpialidocious ";
        for (int i = 0; i < 3; i++) {
            text = text + text;
        }
        item = new ListItem(text);
        item.setAlignment(Element.ALIGN_JUSTIFIED);
        list.add(item);

        // How to use PdfPTable
        // Utilizacin de PdfPTable

        // We use various elements to add title and subtitle
        // Usamos varios elementos para aadir ttulo y subttulo
        Anchor anchor = new Anchor("Table export to PDF (Exportamos la tabla a PDF)", categoryFont);
        anchor.setName("Table export to PDF (Exportamos la tabla a PDF)");
        Chapter chapTitle = new Chapter(new Paragraph(anchor), 1);
        Paragraph paragraph = new Paragraph("Do it by Xules (Realizado por Xules)", subcategoryFont);
        Section paragraphMore = chapTitle.addSection(paragraph);
        paragraphMore.add(new Paragraph("This is a simple example (Este es un ejemplo sencillo)"));
        Integer numColumns = 6;
        Integer numRows = 120;
        // We create the table (Creamos la tabla).
        PdfPTable table = new PdfPTable(numColumns);
        // Now we fill the PDF table 
        // Ahora llenamos la tabla del PDF
        PdfPCell columnHeader;
        // Fill table rows (rellenamos las filas de la tabla).                
        for (int column = 0; column < numColumns; column++) {
            columnHeader = new PdfPCell(new Phrase("COL " + column));
            columnHeader.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(columnHeader);
        }
        table.setHeaderRows(1);
        // Fill table rows (rellenamos las filas de la tabla).                
        for (int row = 0; row < numRows; row++) {
            for (int column = 0; column < numColumns; column++) {
                table.addCell("Row " + row + " - Col" + column);
            }
        }
        // We add the table (Aadimos la tabla)
        paragraphMore.add(table);
        // We add the paragraph with the table (Aadimos el elemento con la tabla).
        document.add(chapTitle);
        document.close();
        System.out.println("Your PDF file has been generated!(Se ha generado tu hoja PDF!");
    } catch (DocumentException documentException) {
        System.out.println(
                "The file not exists (Se ha producido un error al generar un documento): " + documentException);
    }
}