Example usage for com.itextpdf.text Document newPage

List of usage examples for com.itextpdf.text Document newPage

Introduction

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

Prototype


public boolean newPage() 

Source Link

Document

Signals that an new page has to be started.

Usage

From source file:com.util.Imprimir.java

public static void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);/*from   ww  w. j  a  va 2 s  . c om*/
    // Lets write a big header
    preface.add(new Paragraph("Titulo do documento", catFont));

    addEmptyLine(preface, 1);
    // Will create: Report generated by: _name, _date
    preface.add(new Paragraph("Relatrio criado por: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("This document describes something which is very important ", smallBold));

    addEmptyLine(preface, 8);

    preface.add(new Paragraph(
            "This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
            redFont));

    document.add(preface);
    // Start a new page
    document.newPage();
}

From source file:com.vectorprint.report.itext.debug.DebugHelper.java

License:Open Source License

/**
 * This method will append to the pdf a legend explaining the visual feedback in the pdf, an overview of the styles
 * used and an overview of the properties used.
 *
 * @throws DocumentException/*w w  w . j a  va2 s  .c o  m*/
 */
public static void appendDebugInfo(PdfWriter writer, Document document, EnhancedMap settings,
        StylerFactory stylerFactory) throws DocumentException, VectorPrintException {

    PdfContentByte canvas = writer.getDirectContent();
    canvas.setFontAndSize(FontFactory.getFont(FontFactory.COURIER).getBaseFont(), 8);
    canvas.setColorFill(
            itextHelper.fromColor(settings.getColorProperty(Color.MAGENTA, ReportConstants.DEBUGCOLOR)));
    canvas.setColorStroke(
            itextHelper.fromColor(settings.getColorProperty(Color.MAGENTA, ReportConstants.DEBUGCOLOR)));

    Font f = FontFactory.getFont(FontFactory.COURIER, 8);

    f.setColor(itextHelper.fromColor(settings.getColorProperty(Color.MAGENTA, ReportConstants.DEBUGCOLOR)));

    float top = document.getPageSize().getTop();

    document.add(new Phrase(new Chunk("table: ", f).setLocalDestination(DEBUGPAGE)));
    document.add(Chunk.NEWLINE);
    document.add(new Phrase("cell: ", f));
    document.add(Chunk.NEWLINE);
    document.add(new Phrase("image: ", f));
    document.add(Chunk.NEWLINE);
    document.add(new Phrase("text: ", f));
    document.add(Chunk.NEWLINE);
    document.add(new Phrase("background color is shown in a small rectangle", f));
    document.add(Chunk.NEWLINE);
    canvas.setLineWidth(2);
    canvas.setLineDash(new float[] { 0.3f, 5 }, 0);
    float left = document.leftMargin();
    canvas.rectangle(left + 80, top - 25, left + 80, 8);
    canvas.closePathStroke();
    canvas.setLineWidth(0.3f);
    canvas.setLineDash(new float[] { 2, 2 }, 0);
    canvas.rectangle(left + 80, top - 37, left + 80, 8);
    canvas.closePathStroke();
    canvas.setLineDash(new float[] { 1, 0 }, 0);
    canvas.rectangle(left + 80, top - 50, left + 80, 8);
    canvas.closePathStroke();
    canvas.setLineDash(new float[] { 0.3f, 5 }, 0);
    canvas.rectangle(left + 80, top - 63, left + 80, 8);
    canvas.closePathStroke();
    document.add(Chunk.NEWLINE);

    document.add(new Phrase("fonts available: " + FontFactory.getRegisteredFonts(), f));

    document.add(Chunk.NEWLINE);

    if (settings.getBooleanProperty(false, DEBUG)) {
        document.add(new Phrase("OVERVIEW OF STYLES FOR THIS REPORT", f));
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
    }

    Font b = new Font(f);
    b.setStyle("bold");
    Set<Map.Entry<String, String>> entrySet = stylerFactory.getStylerSetup().entrySet();
    for (Map.Entry<String, String> styleInfo : entrySet) {
        String key = styleInfo.getKey();
        document.add(new Chunk(key, b).setLocalDestination(key));
        document.add(new Chunk(": " + styleInfo.getValue(), f));
        document.add(Chunk.NEWLINE);
        document.add(new Phrase("   styling configured by " + key + ": ", f));
        for (BaseStyler st : (Collection<BaseStyler>) stylerFactory.getBaseStylersFromCache((key))) {
            document.add(Chunk.NEWLINE);
            document.add(new Chunk("      ", f));
            document.add(new Chunk(st.getClass().getSimpleName(), DebugHelper.debugFontLink(canvas, settings))
                    .setLocalGoto(st.getClass().getSimpleName()));
            document.add(new Chunk(":", f));
            document.add(Chunk.NEWLINE);
            document.add(new Phrase("         non default parameters for " + st.getClass().getSimpleName()
                    + ": " + getParamInfo(st), f));
            document.add(Chunk.NEWLINE);
            if (!st.getConditions().isEmpty()) {
                document.add(new Phrase("      conditions for this styler: ", f));
            }
            for (StylingCondition sc : (Collection<StylingCondition>) st.getConditions()) {
                document.add(Chunk.NEWLINE);
                document.add(new Chunk("         ", f));
                document.add(
                        new Chunk(sc.getClass().getSimpleName(), DebugHelper.debugFontLink(canvas, settings))
                                .setLocalGoto(sc.getClass().getSimpleName()));
                document.add(Chunk.NEWLINE);
                document.add(new Phrase("            non default parameters for "
                        + sc.getClass().getSimpleName() + ": " + getParamInfo(sc), f));
            }
        }
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
    }

    document.newPage();

    document.add(new Phrase("Properties used for the report", f));
    document.add(Chunk.NEWLINE);

    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(bo);

    settings.listProperties(ps);
    ps.close();
    document.add(new Paragraph(bo.toString(), f));

    document.newPage();

    try {
        bo = new ByteArrayOutputStream();
        ps = new PrintStream(bo);
        Help.printHelpHeader(ps);
        ps.close();
        document.add(new Paragraph(bo.toString(), f));

        Help.printStylerHelp(document, f);

        Help.printConditionrHelp(document, f);

    } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException
            | NoSuchMethodException | InvocationTargetException ex) {
        log.log(Level.SEVERE, null, ex);
    }
}

From source file:com.vectorprint.report.itext.TocOutputStream.java

License:Open Source License

@Override
public void secondPass(InputStream firstPass, OutputStream orig) throws IOException {
    PdfReader reader = null;/*from w  w  w .jav a2 s. com*/
    VectorPrintDocument vpd = (VectorPrintDocument) outer.getDocument();
    try {
        reader = new PdfReader(firstPass);
        prepareToc();
        // init fresh components for second pass styling
        StylerFactory _stylerFactory = outer.getStylerFactory().getClass().newInstance();
        StylerFactoryHelper.SETTINGS_ANNOTATION_PROCESSOR.initSettings(_stylerFactory, outer.getSettings());
        _stylerFactory.setLayerManager(outer.getElementProducer());
        _stylerFactory.setImageLoader(outer.getElementProducer());
        outer.getStyleHelper().setStylerFactory(_stylerFactory);
        EventHelper event = outer.getEventHelper().getClass().newInstance();
        event.setItextStylerFactory(_stylerFactory);
        event.setElementProvider(outer.getElementProducer());
        ((DefaultElementProducer) outer.getElementProducer()).setPh(event);
        Document d = new VectorPrintDocument(event, _stylerFactory, outer.getStyleHelper());
        PdfWriter w = PdfWriter.getInstance(d, orig);
        w.setPageEvent(event);
        outer.getStyleHelper().setVpd((VectorPrintDocument) d);
        _stylerFactory.setDocument(d, w);
        DocumentStyler ds = _stylerFactory.getDocumentStyler();
        outer.getStyleHelper().style(d, null, StyleHelper.toCollection(ds));
        d.open();
        ds.styleAfterOpen(d, null);
        List outline = SimpleBookmark.getBookmark(reader);
        if (!ds.getValue(DocumentSettings.TOCAPPEND, Boolean.class)) {
            printToc(d, w, vpd);
            if (outline != null) {
                int cur = w.getCurrentPageNumber();
                SimpleBookmark.shiftPageNumbers(outline, cur, null);
            }
            d.newPage();
        }
        outer.getSettings().put(ReportConstants.DEBUG, Boolean.FALSE.toString());
        for (int p = 1; p <= reader.getNumberOfPages(); p++) {
            Image page = Image.getInstance(w.getImportedPage(reader, p));
            page.setAbsolutePosition(0, 0);
            d.setPageSize(page);
            d.newPage();
            Chunk i = new Chunk(" ");
            if (vpd.getToc().containsKey(p)) {
                Section s = null;
                for (Map.Entry<Integer, List<Section>> e : vpd.getToc().entrySet()) {
                    if (e.getKey() == p) {
                        s = e.getValue().get(0);
                        break;
                    }
                }
                i.setLocalDestination(s.getTitle().getContent());
            }
            d.add(i);
            w.getDirectContent().addImage(page);
            w.freeReader(reader);
        }
        if (_stylerFactory.getDocumentStyler().getValue(DocumentSettings.TOCAPPEND, Boolean.class)) {
            printToc(d, w, vpd);
        }
        w.setOutlines(outline);
        if (outer.isWasDebug()) {
            event.setLastPage(outer.getWriter().getCurrentPageNumber());
            d.setPageSize(new Rectangle(ItextHelper.mmToPts(297), ItextHelper.mmToPts(210)));
            d.setMargins(5, 5, 5, 5);
            d.newPage();
            outer.getSettings().put(ReportConstants.DEBUG, Boolean.TRUE.toString());
            event.setDebugHereAfter(true);
            DebugHelper.appendDebugInfo(w, d, outer.getSettings(), _stylerFactory);
        }
        d.close();
    } catch (VectorPrintException | DocumentException | InstantiationException | IllegalAccessException ex) {
        throw new VectorPrintRuntimeException(ex);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:com.wipro.srs.service.PrintTicket.java

private void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);//from w  w w. ja  v a2s  . c  om
    // Lets write a big header
    preface.add(new Paragraph("Title of the document", catFont));

    addEmptyLine(preface, 1);
    // Will create: Report generated by: _name, _date
    preface.add(new Paragraph("Ticket generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("This is an autogenerated document", smallBold));

    addEmptyLine(preface, 8);

    preface.add(new Paragraph(
            "This document is a preliminary version and not subject to your license agreement or any other agreement with MaverickShipServices.com ;-).",
            redFont));

    document.add(preface);
    // Start a new page
    document.newPage();
}

From source file:com.workhub.utils.PDFUtils.java

private static void addTitlePage(Document document, String title, List<ElementModel> models, String creator)
        throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);/*from ww w  . java2  s  . co  m*/
    // Lets write a big header
    Paragraph titleParag = new Paragraph(title, catFont);
    titleParag.setAlignment(Element.ALIGN_CENTER);
    preface.add(titleParag);

    addEmptyLine(preface, 1);
    // Will create: Report generated by: _name, _date
    // 1. Choix de la langue
    Locale locale = Locale.getDefault();

    /** 2. Construction du DateFormat en choisiant un format :
     * SHORT = 01/01/2002
     * FULL = lundi 1 janvier 2002
     */
    DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, locale);
    preface.add(new Paragraph("Rapport gnr par: " + creator + ", " + dateFormat.format(new Date()), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("Ce document reprend les contenus suivants: ", subFont));

    addEmptyLine(preface, 1);
    Paragraph sommaire = new Paragraph("", smallBold);
    preface.add(sommaire);
    createList(sommaire, models);
    /*preface.add(new Paragraph("This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
    redFont));
     */

    document.add(preface);
    // Start a new page
    document.newPage();
}

From source file:com.zaptech.pdfdemo.MainActivity.java

private void addTitlePage(Document document) {
    try {// ww  w. j a va2s  . co  m
        Paragraph paragraph = new Paragraph();
        addEmptyLine(paragraph, 1);
        paragraph.add(new Paragraph("Sample Title", catFont));
        addEmptyLine(paragraph, 1);
        paragraph.add(
                new Paragraph("Report generated by:: " + System.getProperty("user.name") + ", ", smallFont));
        addEmptyLine(paragraph, 3);
        paragraph.add(new Paragraph("This document describes something which is very important ", smallFont));
        addEmptyLine(paragraph, 8);
        paragraph.add(new Paragraph(
                "This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
                redFont));
        document.add(paragraph);
        document.newPage();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:comisionesafis.informes.FacturasComisionesAgentes.java

public boolean generar() {

    // Abrimos el fichero de comisiones
    Periodos periodos = new Periodos(pb.getFicheroComisiones());
    String sSQL = "";
    Statement stmt;//from  w  w w.  jav  a  2  s  . c om
    ResultSet rsComisiones;
    String sFactura1;
    String sFactura2;

    // Generamos la sentencia de Seleccin de Datos
    try {

        // Generamos el PDF
        Document documento = new Document(PageSize.A4, 80, 80, 50, 50);
        FileOutputStream salida = new FileOutputStream("FacturasComisionesAgentes.pdf");
        PdfWriter writer = PdfWriter.getInstance(documento, salida);
        writer.setInitialLeading(0);

        //  Obtenemos una instancia de nuestro manejador de eventos
        FacturasComisionesAgentesPie pie = new FacturasComisionesAgentesPie();
        //Asignamos el manejador de eventos al escritor.
        writer.setPageEvent(pie);

        // Abrimos el Documento
        documento.open();

        sSQL = "SELECT * ";
        sSQL += "  FROM ResumenComisiones";
        sSQL += " ORDER BY CodAgente";
        stmt = conexion.createStatement();
        rsComisiones = stmt.executeQuery(sSQL);

        while (rsComisiones.next()) {

            // Generamos los prrafos
            // Datos del agente
            Paragraph pAgente[] = new Paragraph[5];
            pAgente[0] = new Paragraph();
            pAgente[0].add(rsComisiones.getString("Nombre"));
            pAgente[0].setAlignment(Paragraph.ALIGN_LEFT);
            pAgente[1] = new Paragraph();
            pAgente[1].add(rsComisiones.getString("Direccion"));
            pAgente[1].setAlignment(Paragraph.ALIGN_LEFT);
            pAgente[2] = new Paragraph();
            pAgente[2].add(rsComisiones.getString("CodPostal") + "  " + rsComisiones.getString("Poblacion"));
            pAgente[2].setAlignment(Paragraph.ALIGN_LEFT);
            pAgente[3] = new Paragraph();
            pAgente[3].add(rsComisiones.getString("Provincia"));
            pAgente[3].setAlignment(Paragraph.ALIGN_LEFT);
            pAgente[4] = new Paragraph();
            pAgente[4].add(rsComisiones.getString("NIF"));
            pAgente[4].setAlignment(Paragraph.ALIGN_LEFT);

            // creating separators
            LineSeparator separador = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);

            // Datos fijos
            Paragraph pPelayo[] = new Paragraph[5];
            pPelayo[0] = new Paragraph();
            pPelayo[0].add("PELAYO VIDA");
            pPelayo[0].setAlignment(Paragraph.ALIGN_RIGHT);
            pPelayo[1] = new Paragraph();
            pPelayo[1].add("CL SANTA ENGRACIA 69");
            pPelayo[1].setAlignment(Paragraph.ALIGN_RIGHT);
            pPelayo[2] = new Paragraph();
            pPelayo[2].add("28010  MADRID");
            pPelayo[2].setAlignment(Paragraph.ALIGN_RIGHT);
            pPelayo[3] = new Paragraph();
            pPelayo[3].add("MADRID");
            pPelayo[3].setAlignment(Paragraph.ALIGN_RIGHT);
            pPelayo[4] = new Paragraph();
            pPelayo[4].add("06422");
            pPelayo[4].setAlignment(Paragraph.ALIGN_RIGHT);

            // Fecha
            Paragraph pFecha = new Paragraph();
            pFecha = new Paragraph("Madrid, a " + periodos.extraeFechaLarga());
            pFecha.setAlignment(Paragraph.ALIGN_RIGHT);

            // Lnea 1 de FACTURA
            Paragraph pFactura1 = new Paragraph();
            sFactura1 = "FACTURA: n factura ";
            sFactura1 += rsComisiones.getString("CodAgente") + " - ";
            sFactura1 += periodos.extraePeriodoMY("MM-YYYY");
            pFactura1 = new Paragraph(sFactura1);

            // Lnea 2 de FACTURA
            Paragraph pFactura2 = new Paragraph();
            sFactura2 = "Factura por la prestacin de servicios relativos a las operaciones ";
            sFactura2 += "de intermediacin de seguros realizadas para su entidad del mes de ";
            sFactura2 += periodos.extraePeriodoMY("MM YYYY");
            ;
            pFactura2 = new Paragraph(sFactura2);

            // Datos Econmicos
            float[] anchuras = { 5f, 2f };
            PdfPTable table = new PdfPTable(anchuras);
            table.getDefaultCell().setBorder(0);

            // Tipo de letra para la tabla
            Font font = new Font(Font.FontFamily.COURIER, 11, Font.NORMAL);

            PdfPCell celda = new PdfPCell();

            celda = new PdfPCell(new Phrase("Comisiones pagadas", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(celda);

            celda = new PdfPCell(
                    new Phrase(Double.toString(rsComisiones.getDouble("TotalComisiones")) + " ", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase("Otros conceptos", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase(" ", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase(
                    "Retencin (" + Double.toString(rsComisiones.getDouble("RetencionPorcentaje")) + "%)",
                    font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(celda);

            Double dblRetencion = rsComisiones.getDouble("TotalComisiones")
                    * (rsComisiones.getDouble("RetencionPorcentaje") / 100);
            celda = new PdfPCell(new Phrase(Numeros.formateaDosDecimales(dblRetencion) + " ", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase("Conceptos no sujetos", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase(" ", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase("Total a pagar", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(celda);

            Double dblTotalPagar = rsComisiones.getDouble("TotalComisiones") - dblRetencion;
            celda = new PdfPCell(new Phrase(Numeros.formateaDosDecimales(dblTotalPagar) + " ", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(celda);

            // Literal: Operacin exenta de IVA
            Paragraph pColetilla = new Paragraph();
            pColetilla.add("Operacin exenta de IVA");

            // Aadimos los prrafos al Documento
            for (int i = 0; i < 5; i++)
                documento.add(pAgente[i]);

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

            for (int i = 0; i < 5; i++)
                documento.add(pPelayo[i]);

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

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

            documento.add(pFactura1);
            documento.add(separador);
            documento.add(pFactura2);

            // Agregamos la tabla al documento    
            documento.add(new Paragraph(" "));
            documento.add(table);

            documento.add(new Paragraph(" "));
            documento.add(new Paragraph(" "));
            documento.add(pColetilla);
            documento.newPage();
        }
        documento.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:comisionesafis.informes.LiquidacionComisiones.java

public boolean generar() {

    // Abrimos el fichero de comisiones
    String sSQL = "";
    Statement stmt;//from w  w  w  . j  a v a 2 s .  c  om
    ResultSet rsAgentes;
    ResultSet rsRecibos;
    PdfPCell celda;
    boolean cabeceraColumnas;
    int filasPorPagina = 0;
    int fila = 0;
    PdfPTable table;
    Double dblTotal = 0.0;

    // Generamos la sentencia de Seleccin de Datos
    try {

        // Generamos el PDF
        Document documento = new Document(PageSize.A4, 80, 80, 50, 50);
        FileOutputStream salida = new FileOutputStream("LiquidacionComisiones.pdf");
        PdfWriter writer = PdfWriter.getInstance(documento, salida);
        writer.setInitialLeading(0);

        //  Obtenemos una instancia de nuestro manejador de eventos
        LiquidacionComisionesPie pie = new LiquidacionComisionesPie();
        //Asignamos el manejador de eventos al escritor.
        writer.setPageEvent(pie);

        // Abrimos el Documento
        documento.open();

        // SELECT para extraer todos los cdigos de los agentes con Recibos
        sSQL = "SELECT DISTINCT (CodAgente) AS Agente ";
        sSQL += "  FROM ResumenComisiones";
        sSQL += " ORDER BY CodAgente";
        stmt = conexion.createStatement();
        rsAgentes = stmt.executeQuery(sSQL);

        while (rsAgentes.next()) {

            if (sumaComisiones(rsAgentes.getString("Agente")) != 0) {
                paginaNum = 0;
                printCabecera1(documento);
                printCabeceraPelayo(documento);
                printCabecera2(documento, rsAgentes);

                // SELECT para extraer todos los Recibos de un agente
                sSQL = "SELECT * ";
                sSQL += "  FROM Recibos";
                sSQL += " WHERE CodAgente = '" + rsAgentes.getString("Agente") + "'";
                stmt = conexion.createStatement();
                rsRecibos = stmt.executeQuery(sSQL);

                //                if(rsAgentes.getString("Agente").equals("10803")){
                //                    System.out.println("");
                //                }

                // Creamos la tabla formateada
                table = creaTabla();

                cabeceraColumnas = true;
                filasPorPagina = 42;
                dblTotal = 0.0;
                while (rsRecibos.next()) {
                    if (Double.parseDouble(rsRecibos.getString("ImpComision")) != 0) {
                        if (fila >= filasPorPagina) {
                            // Salto de pgina
                            // Imprimimos el contenido de la tabla
                            documento.add(table);
                            documento.newPage();
                            table = creaTabla();
                            saltoDePagina(documento, table, rsAgentes);
                            fila = 1;
                            filasPorPagina = 47;
                        } else if (cabeceraColumnas) {
                            // Primera pgina
                            printCabeceraColumnas(table);
                            cabeceraColumnas = false;
                            fila = 1;
                        }
                        Font font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
                        celda = new PdfPCell(new Phrase(rsRecibos.getString("NPoliza"), font));
                        celda.setBorder(Rectangle.NO_BORDER);
                        celda.setHorizontalAlignment(Element.ALIGN_LEFT);
                        table.addCell(celda);
                        celda = new PdfPCell(
                                new Phrase(Fechas.fechaVencimiento(rsRecibos.getString("Fecha")), font));
                        celda.setBorder(Rectangle.NO_BORDER);
                        celda.setHorizontalAlignment(Element.ALIGN_LEFT);
                        table.addCell(celda);
                        celda = new PdfPCell(new Phrase(fondoRecibo(rsRecibos.getString("Descripcion")), font));
                        celda.setBorder(Rectangle.NO_BORDER);
                        celda.setHorizontalAlignment(Element.ALIGN_LEFT);
                        table.addCell(celda);
                        celda = new PdfPCell(new Phrase(rsRecibos.getString("Importe"), font));
                        celda.setBorder(Rectangle.NO_BORDER);
                        celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
                        table.addCell(celda);
                        celda = new PdfPCell(new Phrase(Numeros.formateaDosDecimales(
                                Double.parseDouble(rsRecibos.getString("ImpComision"))), font));
                        celda.setBorder(Rectangle.NO_BORDER);
                        celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
                        table.addCell(celda);
                        dblTotal += Double.parseDouble(rsRecibos.getString("ImpComision"));
                        fila++;
                    }
                }
                if (fila >= filasPorPagina - 5) {
                    documento.add(table);
                    documento.newPage();
                    table = creaTabla();
                }
                printResumenContable(table, dblTotal, rsAgentes.getString("Agente"));
                documento.add(table);
                documento.newPage();
            }
        }
        documento.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:Control.PdfBiglietto.java

/**
 * Funzione che costruisce il file PDF//from  w  w w .java  2 s .co  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:Control.ProcessaArq.java

public void gravaArquivoConsumoUnidades(ArrayList<Usuario> listaUsuario, String caminho)
        throws IOException, DocumentException {

    Document doc = null;
    OutputStream os = null;// w w  w  .  j ava  2  s  . c o m
    PdfWriter pdf = null;
    Paragraph p = new Paragraph();
    Tratamento tempo = new Tratamento();
    PdfPTable table = new PdfPTable(5);
    DecimalFormat df = new DecimalFormat("#####.##");
    ArrayList<String> listaCidade = new ArrayList<String>();
    String local = new String();
    String informacao, tipo = new String();
    Double soma, valorTotal, diferenca = 0.0;
    Usuario unidade = new Usuario();
    ArrayList<Usuario> listaUnidades = new ArrayList<Usuario>();
    /*    
        if(banco.getConta().get(banco.getConta().size()-1).getDiferenca() > 0){
    diferenca = banco.getConta().get(banco.getConta().size()-1).getDiferenca()/9;
        }
        else{ diferenca = 0.0; }
    */
    for (int a = 0; a <= listaUsuario.size() - 1; a++) {
        if ((!listaCidade.contains(listaUsuario.get(a).getCidade()))) {
            listaCidade.add(listaUsuario.get(a).getCidade());
        }
    }

    float[] headerwidths = { 30, 80, 35, 35, 25 }; // define a largura de cada coluna       
    table.setWidths(headerwidths);

    caminho = localizaArquivo(false) + ".pdf";
    try {//configuraes da pgina          
        float fntSize, lineSpacing;
        fntSize = 8f;
        lineSpacing = 8f;

        doc = new Document(PageSize.A4.rotate(), 10, 10, 30, 40);
        os = new FileOutputStream(caminho);
        pdf.getInstance(doc, os);
        doc.open();

        /*
        local = new String();
        local = caminho +" "+ listaCidade.get(a) + ".pdf";
                
        doc = new Document(PageSize.A4.rotate(), 10, 10, 30, 40); 
        os = new FileOutputStream(local);            
        pdf.getInstance(doc, os);   
        doc.open();
        */
        //cabecalho da tabela
        table.getDefaultCell().setBorder(0);

        table.getDefaultCell().setBorder(0);
        table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        table.getDefaultCell().setColspan(5);

        table.addCell(new Paragraph("CONSUMO POR UNIDADE " + banco.periodoFatura()));

        table.getDefaultCell().setBorder(0);
        table.getDefaultCell().setColspan(0);
        table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        doc.add(table);

        for (int a = 0; a <= listaCidade.size() - 1; a++) {

            table = new PdfPTable(5);
            table.setWidths(headerwidths);
            table.getDefaultCell().setBorder(0);
            table.addCell(new Paragraph(""));
            table.addCell(new Paragraph(""));
            table.addCell(new Paragraph(""));
            table.addCell(new Paragraph(""));
            table.addCell(new Paragraph(""));
            table.getDefaultCell().setBorder(1);

            table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
            table.addCell(new Paragraph("Cidade"));
            table.addCell(new Paragraph("Usurio"));
            table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            table.addCell(new Paragraph("Nmero"));
            table.addCell(new Paragraph("Tipo"));
            table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            table.addCell(new Paragraph("Valor"));
            table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);

            soma = 0.0;
            for (int b = 0; b <= listaUsuario.size() - 1; b++) {

                if (listaCidade.get(a).equals(listaUsuario.get(b).getCidade())) {

                    //cidade
                    informacao = new String();
                    informacao = listaUsuario.get(b).getCidade();
                    table.addCell(new Paragraph(informacao));

                    //Usurio
                    informacao = new String();
                    informacao = listaUsuario.get(b).getNome();
                    table.addCell(new Paragraph(informacao));

                    //Nmero
                    informacao = new String();
                    informacao = String.valueOf(listaUsuario.get(b).getLinha());
                    table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                    table.addCell(new Paragraph(informacao));

                    //Tipo
                    informacao = new String();
                    informacao = listaUsuario.get(b).getTipo();
                    table.addCell(new Paragraph(informacao));

                    //Valor
                    informacao = new String();
                    soma += listaUsuario.get(b).getValor();
                    informacao = "R$" + df.format(listaUsuario.get(b).getValor());
                    table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
                    table.addCell(new Paragraph(informacao));
                }
            }

            // Total
            table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
            informacao = new String();
            informacao = "Total apurado";
            table.addCell(informacao);

            // tempo                        
            table.addCell("");
            table.addCell("");
            table.addCell("");

            // valor
            informacao = new String();
            informacao = "R$" + df.format(soma);
            table.addCell(informacao);
            table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);

            if ((soma - diferenca) > 0) {
                table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
                informacao = new String();
                informacao = "Total a pagar";
                table.addCell(informacao);

                // tempo                        
                table.addCell("");
                table.addCell("");
                table.addCell("");

                // valor
                informacao = new String();
                informacao = "R$" + df.format(soma - diferenca);
                table.addCell(informacao);
                table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
            }

            table.addCell("");
            table.addCell("");
            table.addCell("");
            table.addCell("");
            table.addCell("");

            unidade = new Usuario();
            unidade.setCidade(listaCidade.get(a));
            unidade.setValor(soma);
            listaUnidades.add(unidade);

            doc.add(table);
        }

        doc.newPage();
        table.getDefaultCell().setBorder(0);
        table.addCell(new Paragraph(""));
        table.addCell(new Paragraph(""));
        table.addCell(new Paragraph(""));
        table.addCell(new Paragraph(""));
        table.addCell(new Paragraph(""));
        table.getDefaultCell().setBorder(1);

        table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
        table.addCell(new Paragraph("Cidade"));
        table.addCell(new Paragraph(""));
        table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        table.addCell(new Paragraph(""));
        table.addCell(new Paragraph(""));
        table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        table.addCell(new Paragraph("Valor"));
        table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);

        soma = 0.0;
        for (int a = 0; a <= listaUnidades.size() - 1; a++) {
            //cidade
            informacao = new String();
            informacao = listaUnidades.get(a).getCidade();
            table.addCell(new Paragraph(informacao));

            table.addCell("");
            table.addCell("");
            table.addCell("");

            //Valor
            informacao = new String();
            soma += listaUnidades.get(a).getValor();
            informacao = "R$" + df.format(listaUnidades.get(a).getValor());
            table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            table.addCell(new Paragraph(informacao));
        }

        // Total
        table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
        informacao = new String();
        informacao = "Total apurado";
        table.addCell(informacao);

        // tempo                        
        table.addCell("");
        table.addCell("");
        table.addCell("");

        // valor
        informacao = new String();
        informacao = "R$" + df.format(soma);
        table.addCell(informacao);
        table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);

        table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
        informacao = new String();
        informacao = "Total a pagar";
        table.addCell(informacao);

        // tempo                        
        table.addCell("");
        table.addCell("");
        table.addCell("");

        // valor
        informacao = new String();
        informacao = "R$" + df.format(soma);
        //    informacao = "R$"+ df.format(soma-banco.getConta().get(banco.getConta().size()-1).getDiferenca());
        table.addCell(informacao);
        table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);

        doc.add(table);
        doc.close();
        os.close();

    } finally {
        if (doc != null) {
            //fechamento do documento
            doc.close();
        }
        if (os != null) {
            //fechamento da stream de sada
            os.close();
        }
    }
}