Example usage for com.itextpdf.text Image setAlignment

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

Introduction

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

Prototype


public void setAlignment(final int alignment) 

Source Link

Document

Sets the alignment for the image.

Usage

From source file:com.sapito.pdf.PDFView.PDFGeneratorDireccion.java

public void reporteRH(Map<String, Object> model, HttpServletResponse hsr1, int detalle) throws Exception {
    Document document = new Document();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);

    document.open();/*from   w w  w  . j a  va 2 s .co  m*/
    document.addTitle("Sapito PDFs");
    document.addSubject("Pdf de sapito");
    Font font1 = FontFactory.getFont(FontFactory.TIMES_ROMAN, 30);
    font1.setColor(BaseColor.BLACK);
    Font font2 = FontFactory.getFont(FontFactory.TIMES_ROMAN, 24);
    font2.setColor(BaseColor.BLACK);
    document.add(new Paragraph("TAILS 2015", font1));
    document.add(new Paragraph("Reportes Direccin\n", font2));

    //------------------------ TAIS  ______________________________
    Image tais = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/tais-banner.jpg"));
    document.add(tais);

    //---------------------  BODY    ---------------------------------------------------------
    Image body = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/body.png"));
    body.setAlignment(Image.UNDERLYING);
    body.setTransparency(new int[] { 0x00, 0x10 });
    body.setAbsolutePosition(50, 250);
    document.add(body);
    //-------------------------------------------------------------------------------------------
    Image footer = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/footer.jpg"));
    footer.setAbsolutePosition(50, 20);
    document.add(footer);
    //----------------------  TITLE ---------------------------
    String titulo = "Reporte de Recursos Humanos"; //Cambiar el titulo del PDF aqui
    Font f = new Font(FontFamily.HELVETICA, 25.0f, Font.BOLD, BaseColor.BLACK);
    Chunk c = new Chunk(titulo + " \n ", f);
    c.setBackground(BaseColor.WHITE);
    Paragraph title = new Paragraph(c);
    title.setAlignment(Element.ALIGN_CENTER);
    //-------------------------  CONTENIDO -------------------------------------------------------
    document.add(title); //Titulo del PDF

    TextoPdf x = (TextoPdf) model.get("todoTexto");
    document.add(new Paragraph(x.getTodoTexto()));

    PdfPTable table = new PdfPTable(1);
    table.setWidthPercentage(100.0f);
    table.setWidths(new float[] { 2.0f });
    table.setSpacingBefore(10);

    // define font for table header row
    Font font = FontFactory.getFont(FontFactory.COURIER_BOLD);
    font.setColor(BaseColor.WHITE);

    // define table header cell
    PdfPCell cell = new PdfPCell();
    cell.setBackgroundColor(BaseColor.BLUE);
    cell.setPadding(5);

    // write table header 
    cell.setPhrase(new Phrase("Total de de Empleados en Vacaciones", font));
    table.addCell(cell);

    String bla = detalle + " ";
    table.addCell(bla);

    document.add(table);

    //-------------------------- FIN CONTENIDO -----------------
    document.close();

    byte[] bytes = baos.toByteArray();

    hsr1.setContentType("application/pdf");
    hsr1.setContentLength(bytes.length);
    hsr1.getOutputStream().write(bytes);
}

From source file:com.sapito.pdf.PDFView.PDFGeneratorDireccion.java

public void reportefinanzas(Map<String, Object> model, HttpServletResponse hsr1, List<CuentaBancaria> cuenta)
        throws Exception {
    Document document = new Document();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);

    document.open();//from   w  ww . jav  a2  s .  co m
    document.addTitle("Sapito PDFs");
    document.addSubject("Pdf de sapito");
    Font font1 = FontFactory.getFont(FontFactory.TIMES_ROMAN, 30);
    font1.setColor(BaseColor.BLACK);
    Font font2 = FontFactory.getFont(FontFactory.TIMES_ROMAN, 24);
    font2.setColor(BaseColor.BLACK);
    document.add(new Paragraph("TAILS 2015", font1));
    document.add(new Paragraph("Reportes Direccin\n", font2));

    //------------------------ TAIS  ______________________________
    Image tais = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/tais-banner.jpg"));
    document.add(tais);

    //---------------------  BODY    ---------------------------------------------------------
    Image body = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/body.png"));
    body.setAlignment(Image.UNDERLYING);
    body.setTransparency(new int[] { 0x00, 0x10 });
    body.setAbsolutePosition(50, 250);
    document.add(body);
    //-------------------------------------------------------------------------------------------
    Image footer = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/footer.jpg"));
    footer.setAbsolutePosition(50, 20);
    document.add(footer);
    //----------------------  TITLE ---------------------------
    String titulo = "Reporte de Finanzas"; //Cambiar el titulo del PDF aqui
    Font f = new Font(FontFamily.HELVETICA, 25.0f, Font.BOLD, BaseColor.BLACK);
    Chunk c = new Chunk(titulo + " \n ", f);
    c.setBackground(BaseColor.WHITE);
    Paragraph title = new Paragraph(c);
    title.setAlignment(Element.ALIGN_CENTER);
    //-------------------------  CONTENIDO -------------------------------------------------------
    document.add(title); //Titulo del PDF

    TextoPdf x = (TextoPdf) model.get("todoTexto");
    document.add(new Paragraph(x.getTodoTexto()));

    PdfPTable table = new PdfPTable(1);
    table.setWidthPercentage(100.0f);
    table.setWidths(new float[] { 2.0f });
    table.setSpacingBefore(10);

    // define font for table header row
    Font font = FontFactory.getFont(FontFactory.COURIER_BOLD);
    font.setColor(BaseColor.WHITE);

    // define table header cell
    PdfPCell cell = new PdfPCell();
    cell.setBackgroundColor(BaseColor.BLUE);
    cell.setPadding(5);

    // write table header 
    cell.setPhrase(new Phrase("Total de dinero que se tiene en CUENTAS BANCARIAS", font));
    table.addCell(cell);

    for (int i = 0; i < cuenta.size(); i++) {
        a = cuenta.get(i).getHaber();
        b = b + a;
    }
    String bla = b + " ";
    table.addCell(bla);

    document.add(table);

    //-------------------------- FIN CONTENIDO -----------------
    document.close();

    byte[] bytes = baos.toByteArray();

    hsr1.setContentType("application/pdf");
    hsr1.setContentLength(bytes.length);
    hsr1.getOutputStream().write(bytes);
}

From source file:com.sapito.pdf.PDFView.PDFGeneratorVentas.java

public void crearPDFFactura(HttpServletResponse hsr1) throws Exception {
    Document document = new Document();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);

    document.open();//from   ww w .j  a va 2 s.  c o m
    document.addTitle("Sapito PDFs");
    document.addSubject("Pdf de sapito");

    //------------------------ TAIS  ______________________________
    Image tais = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/tais-banner.jpg"));
    document.add(tais);

    //---------------------  BODY    ---------------------------------------------------------
    Image body = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/body.png"));
    body.setAlignment(Image.UNDERLYING);
    body.setTransparency(new int[] { 0x00, 0x10 });
    body.setAbsolutePosition(50, 250);
    document.add(body);
    //-------------------------------------------------------------------------------------------
    Image footer = Image.getInstance(new URL("http://localhost:8080/SAPITO/resources/img/footer.jpg"));
    footer.setAbsolutePosition(50, 20);
    document.add(footer);
    //----------------------  TITLE ---------------------------
    String titulo = "Facturas"; //Cambiar el titulo del PDF aqui
    Font f = new Font(FontFamily.HELVETICA, 25.0f, Font.BOLD, BaseColor.BLACK);
    Chunk c = new Chunk(titulo + " \n ", f);
    c.setBackground(BaseColor.WHITE);
    Paragraph title = new Paragraph(c);
    title.setAlignment(Element.ALIGN_CENTER);
    //-------------------------  CONTENIDO -------------------------------------------------------
    document.add(title); //Titulo del PDF
    PdfPTable table = new PdfPTable(1);

    table.addCell("Hola");
    table.addCell("Soy");
    table.addCell("el");
    table.addCell("pdf");
    table.addCell("del");
    table.addCell("sapito");
    document.add(table);

    document.close();

    byte[] bytes = baos.toByteArray();

    hsr1.setContentType("application/pdf");
    hsr1.setContentLength(bytes.length);
    hsr1.getOutputStream().write(bytes);
}

From source file:com.skatettoo.reportes.Generador.java

public String generarPDF() throws Exception {
    try {//from  ww w  .  j  a  v a  2s .c o m
        String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("img");
        path = path.substring(0, path.indexOf("\\build"));
        path = path + "\\web\\img\\";
        Document doc = new Document(PageSize.A4, 36, 36, 10, 10);
        PdfPTable tabla = new PdfPTable(4);
        PdfWriter.getInstance(doc, new FileOutputStream(path + "\\archivo\\reporte.pdf\\"));
        doc.open();
        Image img = Image.getInstance(path + "Skatetoo4.png");
        img.scaleAbsolute(40, 40);
        img.setAlignment(Element.ALIGN_LEFT);
        doc.add(img);
        doc.addTitle(this.titulo);
        doc.addAuthor("\n ");
        doc.addAuthor("\n ");
        doc.addAuthor("\n ");
        doc.addAuthor("\n ");
        tabla.setWidthPercentage(100);
        tabla.setWidths(new float[] { 1.4f, 0.8f, 0.8f, 0.8f });
        Object font = new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.WHITE);
        PdfPCell cell = new PdfPCell(new Phrase("Reporte de tatuadores", (Font) font));
        cell.setColspan(4);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPaddingTop(0f);
        cell.setPaddingBottom(7f);
        cell.setBackgroundColor(new BaseColor(0, 0, 0));
        cell.setBorder(0);
        cell.setBorderWidthBottom(2f);
        tabla.addCell(cell);
        tabla.addCell("Tatuador");
        tabla.addCell("Cantidad de diseos");
        tabla.addCell("Citas realizadas");
        tabla.addCell("Noticias publicadas");
        for (Usuario u : this.getUsu()) {
            tabla.addCell(u.getNombre() + " " + u.getApellido());
            tabla.addCell(String.valueOf(u.getDisenioList().size()));
            tabla.addCell(String.valueOf(u.getCitaList1().size()));
            tabla.addCell(String.valueOf(u.getNoticiaList().size()));
        }
        doc.add(tabla);
        doc.bottomMargin();
        /* doc.add(new Paragraph("Tatuador mas solicitado"));
         for(Usuario u : this.getUs()){
        doc.add(new Paragraph(u.getNombre() + " " + u.getApellido()));
         }*/
        doc.close();
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext externalContext = context.getExternalContext();

        externalContext.responseReset();
        externalContext.setResponseContentType("application/pdf");
        externalContext.setResponseHeader("Content-Disposition", "attachment;filename=\"reporte.pdf\"");

        FileInputStream inputStream = new FileInputStream(new File(path + "\\archivo\\reporte.pdf\\"));
        OutputStream outputStream = externalContext.getResponseOutputStream();

        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }

        inputStream.close();
        context.responseComplete();
    } catch (Exception e) {
        throw e;
    }
    return "";
}

From source file:com.wabacusdemo.PdfInterceptor_dataexportpdfpage1_vp7.java

License:Open Source License

/**
 * ?PDF??PDF?// ww w  .  ja va  2  s . c o  m
 * ???
 */
public void afterDisplayPdfPageWithoutTemplate(Document document, AbsReportType reportTypeObj) {
    super.afterDisplayPdfPageWithoutTemplate(document, reportTypeObj);
    ReportRequest rrequest = reportTypeObj.getReportRequest();
    String serverName = rrequest.getRequest().getServerName();
    String serverPort = String.valueOf(rrequest.getRequest().getServerPort());
    String imgurl = "http://" + serverName + ":" + serverPort + Config.webroot
            + "wabacusdemo/pdftemplate/logo.gif";//?URL
    try {
        Image img = Image.getInstance(imgurl);
        float width = document.getPageSize().getWidth();
        float height = document.getPageSize().getHeight();
        //width = width - img.getWidth();
        img.setAbsolutePosition(width / 2, height / 2 + 300f);
        img.setAlignment(Image.ALIGN_CENTER);
        document.add(img);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:comedor.actions.OperacionesComedorAction.java

private void crearPDF() throws IOException, DocumentException {
    Restaurante restaurante = godr.obtenerDatosRestaurante();

    //Creamos el directorio donde almacenar los pdf sino existe
    File file = new File(RUTA_CUENTAS); //Especificamos la ruta
    if (!file.exists()) { //Si el directorio no existe
        if (file.mkdir()) { //Creamos el directorio
            //Le asignamos los permisos 777
            file.setExecutable(true);//from  ww w .  j a  va  2s  .  c o m
            file.setReadable(true);
            file.setExecutable(true);
        } else {
            System.err.println("Error al crear el directorio especificado");
            throw new IOException(); //Lanzamos una excepcion
        }
    }

    if (file.exists()) { //Si el directorio existe
        //Creamos el documento
        Document documento = new Document();
        //Creamos el OutputStream para el fichero pdf   
        FileOutputStream destino = new FileOutputStream(RUTA_CUENTAS + nombreDocumento);

        //Asociamos el FileOutputStream al Document
        PdfWriter.getInstance(documento, destino);
        //Abrimos el documento
        documento.open();

        //Aadimos el nombre del restaurante
        Font titulo = FontFactory.getFont(FontFactory.TIMES, 16, Font.BOLDITALIC);
        Chunk chunk = new Chunk(restaurante.getNombre(), titulo);
        Paragraph parrafo = new Paragraph(chunk);
        parrafo.setAlignment(Element.ALIGN_CENTER);
        documento.add(parrafo);
        //Aadimos la imagen
        String path = request.getServletContext().getRealPath("/img/elvis.png");
        Image foto = Image.getInstance(path);
        foto.scaleToFit(100, 100);
        foto.setAlignment(Chunk.ALIGN_MIDDLE);
        documento.add(foto);
        //Aadimos los datos del restaurante
        Font datos = FontFactory.getFont(FontFactory.TIMES, 12, Font.NORMAL);
        chunk = new Chunk(getText("cuenta.cif") + ": " + restaurante.getCif(), datos);
        documento.add(new Paragraph(chunk));
        chunk = new Chunk(getText("cuenta.direccion") + ": " + restaurante.getDireccion(), datos);
        documento.add(new Paragraph(chunk));
        chunk = new Chunk(getText("cuenta.telefono") + ": " + restaurante.getTelefono(), datos);
        documento.add(new Paragraph(chunk));
        //Aadimos los datos de la cuenta
        chunk = new Chunk(getText("cuenta.cuentaId") + ": " + cuenta.getId(), datos);
        documento.add(new Paragraph(chunk));
        SimpleDateFormat formatoFecha = new SimpleDateFormat("dd-MM-yyyy");
        chunk = new Chunk(getText("cuenta.fecha") + ": " + formatoFecha.format(cuenta.getFecha()), datos);
        documento.add(new Paragraph(chunk));
        SimpleDateFormat formtoHora = new SimpleDateFormat("HH:mm:ss");
        chunk = new Chunk(getText("cuenta.hora") + ": " + formtoHora.format(cuenta.getFecha()), datos);
        documento.add(new Paragraph(chunk));
        //Aadimos los datos del pedido
        //Obtenemos el usuario, es decir, del camarero con el nombre que tenemos registrado en la session 
        chunk = new Chunk(getText("cuenta.camarero") + ": " + session.get("usuario").toString(), datos);
        documento.add(new Paragraph(chunk));
        documento.add(new Chunk(Chunk.NEWLINE)); //Salto de linea        
        //Aadimos la tabla con los datos del pedido
        //Creamos una tabla
        PdfPTable tabla = new PdfPTable(4); //Especificamos el numero de columnas
        //Aadimos la cabecera de la tabla
        tabla.addCell(getText("cuenta.producto"));
        tabla.addCell(getText("cuenta.unidades"));
        tabla.addCell(getText("cuenta.pvp"));
        tabla.addCell(getText("cuenta.total"));
        for (Producto producto : pedido.getListaProductos()) {
            tabla.addCell(producto.getNombre());
            tabla.addCell(String.valueOf(producto.getUnidades()));
            tabla.addCell(String.valueOf(producto.getPrecio()));
            tabla.addCell(String.valueOf(producto.getPrecio() * producto.getUnidades()));

            if (producto instanceof Hamburguesa) {
                Hamburguesa h = (Hamburguesa) producto;
                for (Producto extra : h.getListaProductosExtra()) {
                    tabla.addCell("(E) " + extra.getNombre());
                    tabla.addCell(String.valueOf(extra.getUnidades()));
                    tabla.addCell(String.valueOf(extra.getPrecio()));
                    tabla.addCell(String.valueOf(extra.getPrecio() * extra.getUnidades()));
                }
            }
        }
        //Aadimos la tabla al documento
        documento.add(tabla);
        documento.add(new Chunk(Chunk.NEWLINE)); //Salto de linea
        //Aadimos una tabla con los impuestos y el total a pagar
        tabla = new PdfPTable(3); //Especificamos el numero de columnas    
        tabla.addCell(getText("cuenta.baseImponible") + ": " + pedido.getImporte() + "");
        tabla.addCell("");
        tabla.addCell("");
        DecimalFormat formato = new DecimalFormat("#.##");
        for (Impuesto dato : listaImpuestos) {
            tabla.addCell("");
            tabla.addCell(dato.getNombre() + ": " + dato.getValor());
            double impuesto = (pedido.getImporte() * dato.getValor()) / 100;
            tabla.addCell(
                    getText("cuenta.impuesto") + " " + dato.getNombre() + ": " + formato.format(impuesto));
        }
        tabla.addCell(getText("cuenta.total") + ": " + cuenta.getCantidad() + "");
        tabla.addCell("");
        tabla.addCell("");
        //Aadimos la tabla al documento
        documento.add(tabla);

        //Cerramos el documento
        documento.close();

    } else { //Si el directoiro no existe
        System.err.println("OperacionesComedorAction. Error no existe el directorio especificado");
        throw new IOException(); //Lanzamos una excepcion
    }
}

From source file:Control.PdfBiglietto.java

/**
 * Funzione che costruisce il file PDF//from   w  w  w  .  ja v a 2s  . c  om
 * @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.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 ww . j  ava2s  .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.app.ConsultaController.java

private File createPDF(TblServicioFactura factura) throws IOException {
    String data = factura.getTesPagoResponse();
    JSONObject obj = new JSONObject(data);
    JSONArray content = obj.getJSONArray("lineaFactura");
    String temp = "";
    File _file = null;/*  w w w  . java2  s .com*/
    Document doc = null;
    OutputStream file = null;
    int page = 0;
    try {
        _file = File.createTempFile("temp_file", ".pdf");
        TblServicioServicio servicio = servicios.search(factura.getTesCodigoSintesisBi().toString());
        file = new FileOutputStream(_file);
        doc = new Document(PageSize.LETTER);
        doc.setMargins(servicio.getMarginLeft().floatValue(), servicio.getMarginRight().floatValue(),
                servicio.getMarginTop().floatValue(), servicio.getMarginBottom().floatValue());
        PdfWriter.getInstance(doc, file);
        doc.open();
        //            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        ClassLoader classloader = getClass().getClassLoader();
        URL url = classloader.getResource("cour.ttf");
        BaseFont base = null;
        if (url == null) {
            base = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } else {
            String path = url.getPath();
            if ("/".equals(path.substring(0, 1))) {
                path = path.substring(1);
            }
            Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, path);
            base = BaseFont.createFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        }
        Font f = new Font(base, servicio.getFontSize(), Font.NORMAL, BaseColor.BLACK);
        String qr = "";
        float line = 0;
        for (Object item : content) {
            Paragraph paragraph = new Paragraph(item.toString(), f);
            if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL")) {
                if (item.toString().contains("P X#X&$#&K##")) {
                    paragraph = new Paragraph(" ", f);
                    doc.add(paragraph);
                    doc.add(paragraph);
                    paragraph = new Paragraph(item.toString(), f);
                }
            }
            if (item.toString().contains("<b>")) {
                Font bold = new Font(base, 7.0f, Font.BOLD, BaseColor.BLACK);
                paragraph = new Paragraph(item.toString().replace("<b>", ""), bold);
            }
            if (item.toString().contains("<QR>") || item.toString().contains("<QR_ENT_G>")) {
                qr = item.toString().replaceAll("<QR>", "");
                qr = item.toString().replaceAll("<QR_ENT_G>", "");
                Image image = QR.create(qr);
                image.scaleAbsolute(servicio.getQrScale().floatValue(), servicio.getQrScale().floatValue());
                if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL")
                        || servicio.getTesDetalleVc().trim().equals("PAGO TELECEL")
                        || servicio.getTesDetalleVc().trim().equals("PAGO NUEVATEL")
                        || servicio.getTesDetalleVc().trim().equals("PAGO TIGOSTAR (MULTIVISION)")) {
                    float y = (doc.getPageSize().getHeight() - (paragraph.getLeading() * (line + 1)));
                    float x = 0;
                    if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL")) {
                        image.setAlignment(Image.ALIGN_RIGHT);
                        x = doc.getPageSize().getWidth() - (110 - servicio.getMarginLeft().floatValue());
                    }
                    if (servicio.getTesDetalleVc().trim().equals("PAGO TELECEL")) {
                        image.setAlignment(Image.ALIGN_LEFT);
                        x = 30;
                        y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading() * 2));
                    }
                    if (servicio.getTesDetalleVc().trim().equals("PAGO NUEVATEL")) {
                        image.setAlignment(Image.ALIGN_LEFT);
                        x = doc.getPageSize().getWidth() - (120 - servicio.getMarginLeft().floatValue());
                        y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading()));
                    }
                    if (servicio.getTesDetalleVc().trim().equals("PAGO TIGOSTAR (MULTIVISION)")) {
                        image.setAlignment(Image.ALIGN_LEFT);
                        x = doc.getPageSize().getWidth() - (120 - servicio.getMarginLeft().floatValue());
                        y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading()));
                    }
                    image.setAbsolutePosition(x, y);
                }
                doc.add(image);
            }
            if (servicio.getDelimitador().equals(item.toString().trim())) {
                line = 0;
                page++;
                doc.newPage();
            } else {
                line += 1f;
                if (!(item.toString().contains("<QR>") || item.toString().contains("<QR_ENT_G>"))) {
                    doc.add(paragraph);
                }
            }
            temp += item.toString();
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, null, ex);
    } catch (DocumentException | IOException ex) {
        Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, null, ex);
    }
    doc.close();
    file.close();
    return _file;
}

From source file:Controller.Movimientos.generatePDF.java

public void generateAgendaClientes() {
    mm = new Model_Movimientos();
    try {/* ww w .  ja v  a 2 s .  co  m*/

        Calendar calendar = Calendar.getInstance();
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        int monthOfYear = calendar.get(Calendar.MONTH);
        int year = calendar.get(Calendar.YEAR);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int min = calendar.get(Calendar.MINUTE);
        int sec = calendar.get(Calendar.SECOND);

        Document documento = new Document();//Creamos el documento
        FileOutputStream ficheroPdf = new FileOutputStream("agendaClientes" + dayOfMonth + "--" + monthOfYear
                + "--" + year + " " + hour + ";" + min + ";" + sec + ".pdf");//Abrimos el flujo y le asignamos nombre al pdf y su direccion
        PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);//Instanciamos el documento con el fichero

        documento.open();//Abrimos el documento

        documento.add(new Paragraph("Agenda Clientes",
                FontFactory.getFont("Calibri", 30, Font.BOLD, BaseColor.BLACK)));//Le indicamos el tipo de letra, el tamanio, el estilo y el color de la letra
        documento.add(new Paragraph("___________________________"));//Realiza un salto de linea
        Iterator it;
        it = mm.getUserss().iterator();
        while (it.hasNext()) {
            User u = (User) it.next();
            System.out.println("" + u.getEmail().toString());
            documento.add(new Paragraph(""));
            try {
                Image foto = Image.getInstance("src/IMG/userBig.png");
                foto.scaleToFit(48, 48);
                foto.setAlignment(Chunk.ALIGN_LEFT);
                documento.add(foto);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //Le decimos que nos imprima el Dni, Nombre y Apellidos del cliente, contenidos en el objeto Cliente y le indicamos el tipo de letra, tamanio, estilo y color de la letra
            documento.add(new Paragraph(
                    "Nombre: " + u.getName() + "  Apellidos: " + u.getSurname() + "  Email: " + u.getEmail()
                            + "  Nickname: " + u.getNickname() + "  Contrasea: " + u.getPassword(),
                    FontFactory.getFont("Calibri", 8, Font.BOLD, BaseColor.BLACK)));

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

        documento.close();//Cerramos el flujo con el documento
        JOptionPane.showMessageDialog(null, "Se ha creado la agenda Clientes.");

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