Example usage for com.lowagie.text.pdf PdfWriter setPageEvent

List of usage examples for com.lowagie.text.pdf PdfWriter setPageEvent

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter setPageEvent.

Prototype


public void setPageEvent(PdfPageEvent event) 

Source Link

Document

Sets the PdfPageEvent for this document.

Usage

From source file:br.org.acessobrasil.silvinha.util.GeraRelatorioPDF.java

License:Open Source License

public static boolean geraRelatorio(File file) {
    TradGeraRelatorioPDF.carregaTexto(TokenLang.LANG);
    Document document = new Document(PageSize.A4);
    try {// ww w. j a  va 2  s.co  m
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setPageEvent(new HeaderAndFooter());
        document.open();
        int linha = 0, j, tot_pg = ResumoDoRelatorio.getTotPage();
        //calcula o total de htmls
        float tot_link = 0.0f;
        for (j = 1; j <= tot_pg; j++) {
            String conteudo = ResumoDoRelatorio.getPage(j);
            String arr[] = conteudo.split("\n");
            tot_link += arr.length;
        }
        PainelStatusBar.showProgTarReq();
        //loop por todas as pginas da paginacao
        for (j = 1; j <= tot_pg; j++) {
            String conteudo = ResumoDoRelatorio.getPage(j);
            String arr[] = conteudo.split("\n");
            int tot = arr.length;
            int i;
            //loop por todos os links
            for (i = 0; i < tot; i++) {
                progresso = (linha++ / tot_link) * 100.0f;
                PainelStatusBar.setValueProgress((int) progresso);
                String arr2[] = arr[i].split("\t");

                if (arr2.length == 8) {

                    String strUrl = arr2[7];// URL
                    /*
                    int ap1 = Integer.parseInt(arr2[4]);// Aviso1
                    int ep1 = Integer.parseInt(arr2[1]);// Erro1
                    int ap2 = Integer.parseInt(arr2[5]);// Aviso2
                    int ep2 = Integer.parseInt(arr2[2]);// Erro2
                    int ap3 = Integer.parseInt(arr2[6]);// Aviso3
                    int ep3 = Integer.parseInt(arr2[3]);// Erro3
                    */
                    String myHash = arr2[0];

                    RelatorioDaUrl relatorio = new RelatorioDaUrl();
                    relatorio.recarregaArquivoRelatorioEmXml2(myHash);

                    document.add(new Phrase("\n"));
                    Font font = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.BOLD);

                    Chunk url = new Chunk(strUrl, font);
                    Paragraph p1 = new Paragraph(TradGeraRelatorioPDF.RELATORIO_URL);
                    p1.add(url);
                    p1.setAlignment(Paragraph.ALIGN_LEFT);
                    document.add(p1);
                    document.add(new Phrase("\n\n"));

                    if (relatorio.getErrosPrioridade1() <= 0 && relatorio.getErrosPrioridade2() <= 0
                            && relatorio.getErrosPrioridade3() <= 0) {
                        Paragraph p2 = new Paragraph(TradGeraRelatorioPDF.PAGINAS_SEM_ERROS);
                        p2.setAlignment(Paragraph.ALIGN_CENTER);
                        document.add(p2);

                    } else {

                        if (relatorio.getErrosPrioridade1() > 0) {
                            Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P1, font);
                            p1.setAlignment(Paragraph.ALIGN_LEFT);
                            document.add(p);
                            document.add(new Chunk("\n"));
                            PdfPTable table = geraLista(relatorio.getListaErrosP1());
                            if (table != null) {
                                document.add(table);
                            }
                            document.add(new Phrase("\n\n"));
                        }

                        if (relatorio.getErrosPrioridade2() > 0) {
                            Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P2, font);
                            p1.setAlignment(Paragraph.ALIGN_LEFT);
                            document.add(p);
                            document.add(new Chunk("\n"));
                            PdfPTable table = geraLista(relatorio.getListaErrosP2());
                            if (table != null) {
                                document.add(table);
                            }
                            document.add(new Phrase("\n\n"));
                        }

                        if (relatorio.getErrosPrioridade3() > 0) {
                            Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P3, font);
                            p1.setAlignment(Paragraph.ALIGN_LEFT);
                            document.add(p);
                            document.add(new Chunk("\n"));
                            PdfPTable table = geraLista(relatorio.getListaErrosP3());
                            if (table != null) {
                                document.add(table);
                            }
                            document.add(new Phrase("\n\n"));
                        }
                        document.newPage();
                    }
                }
            }
        }
        writer.flush();
        document.close();
    } catch (DocumentException de) {
        log.error(de.getMessage(), de);
        PainelStatusBar.hideProgTarReq();
        return false;
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        PainelStatusBar.hideProgTarReq();
        return false;
    }
    PainelStatusBar.hideProgTarReq();
    return true;
}

From source file:br.org.acessobrasil.silvinha.util.GeraRelatorioPDF.java

License:Open Source License

public static boolean geraRelatorio_bkp(File file, ResumoDoRelatorio resumo) {

    Document document = new Document(PageSize.A4);
    try {//ww  w .j av  a 2 s.  c  o m
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setPageEvent(new HeaderAndFooter());
        document.open();

        ArrayList<RelatorioDaUrl> relatorios = resumo.getRelatorios();
        loop: for (RelatorioDaUrl relatorio : relatorios) {
            document.add(new Phrase("\n"));
            Font font = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.BOLD);

            Chunk url = new Chunk(relatorio.getUrl(), font);
            Paragraph p1 = new Paragraph(TradGeraRelatorioPDF.RELATORIO_URL);
            p1.add(url);
            p1.setAlignment(Paragraph.ALIGN_LEFT);
            document.add(p1);
            document.add(new Phrase("\n\n"));

            if (relatorio.getErrosPrioridade1() <= 0 && relatorio.getErrosPrioridade2() <= 0
                    && relatorio.getErrosPrioridade3() <= 0) {
                Paragraph p2 = new Paragraph(TradGeraRelatorioPDF.PAGINAS_SEM_ERROS);
                p2.setAlignment(Paragraph.ALIGN_CENTER);
                document.add(p2);
                continue loop;
            }

            if (relatorio.getErrosPrioridade1() > 0) {
                Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P1_SEM_TAB, font);
                p1.setAlignment(Paragraph.ALIGN_LEFT);
                document.add(p);
                document.add(new Chunk("\n"));
                PdfPTable table = geraLista(relatorio.getListaErrosP1());
                if (table != null) {
                    document.add(table);
                }
                document.add(new Phrase("\n\n"));
            }

            if (relatorio.getErrosPrioridade2() > 0) {
                Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P2_SEM_TAB, font);
                p1.setAlignment(Paragraph.ALIGN_LEFT);
                document.add(p);
                document.add(new Chunk("\n"));
                PdfPTable table = geraLista(relatorio.getListaErrosP2());
                if (table != null) {
                    document.add(table);
                }
                document.add(new Phrase("\n\n"));
            }

            if (relatorio.getErrosPrioridade3() > 0) {
                Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P3_SEM_TAB, font);
                p1.setAlignment(Paragraph.ALIGN_LEFT);
                document.add(p);
                document.add(new Chunk("\n"));
                PdfPTable table = geraLista(relatorio.getListaErrosP3());
                if (table != null) {
                    document.add(table);
                }
                document.add(new Phrase("\n\n"));
            }
            document.newPage();
        }

        writer.flush();
        document.close();
    } catch (DocumentException de) {
        log.error(de.getMessage(), de);
        return false;
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        return false;
    }
    return true;
}

From source file:ca.sqlpower.architect.profile.output.ProfilePDFFormat.java

License:Open Source License

/**
 * Outputs a PDF file report of the data in drs to the given
 * output stream./*from w w  w .  j a va2 s.c  o m*/
 * @throws SQLObjectException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public void format(OutputStream out, List<ProfileResult> profileResults)
        throws DocumentException, IOException, SQLException, SQLObjectException, InstantiationException,
        IllegalAccessException, ClassNotFoundException {

    final int minRowsTogether = 1; // counts smaller than this are considered orphan/widow
    final int mtop = 50; // margin at top of page (in points)
    final int mbot = 50; // margin at bottom of page (page numbers are below this)
    //        final int pbot = 20;  // padding between bottom margin and bottom of body text
    final int mlft = 50; // margin at left side of page
    final int mrgt = 50; // margin at right side of page
    final Rectangle pagesize = PageSize.LETTER.rotate();
    final Document document = new Document(pagesize, mlft, mrgt, mtop, mbot);
    final PdfWriter writer = PdfWriter.getInstance(document, out);

    final float fsize = 6f; // the font size to use in the table body
    final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    document.addTitle("Table Profiling Report");
    document.addSubject("Tables: " + profileResults);
    document.addAuthor(System.getProperty("user.name"));
    document.addCreator("Power*Architect version " + ArchitectVersion.APP_FULL_VERSION);

    document.open();

    // vertical position where next element should start
    //   (bottom is 0; top is pagesize.height())
    float pos = pagesize.height() - mtop;

    final PdfContentByte cb = writer.getDirectContent();
    final PdfTemplate nptemplate = cb.createTemplate(50, 50);
    writer.setPageEvent(new PdfPageEventHelper() {
        // prints the "page N of <template>" footer
        public void onEndPage(PdfWriter writer, Document document) {
            int pageN = writer.getPageNumber();
            String text = "Page " + pageN + " of ";
            float len = bf.getWidthPoint(text, fsize - 2);
            cb.beginText();
            cb.setFontAndSize(bf, fsize - 2);
            cb.setTextMatrix(pagesize.width() / 2 - len / 2, mbot / 2);
            cb.showText(text);
            cb.endText();
            cb.addTemplate(nptemplate, pagesize.width() / 2 - len / 2 + len, mbot / 2);
        }

        public void onCloseDocument(PdfWriter writer, Document document) {
            nptemplate.beginText();
            nptemplate.setFontAndSize(bf, fsize - 2);
            nptemplate.showText(String.valueOf(writer.getPageNumber() - 1));
            nptemplate.endText();
        }
    });

    document.add(new Paragraph("SQL Power Architect Profiling Report"));
    document.add(new Paragraph("Generated " + new java.util.Date() + " by " + System.getProperty("user.name")));

    float[] widths = new float[totalColumn]; // widths of widest cells per row in pdf table
    LinkedList<ProfileTableStructure> profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result

    Font f = new Font(bf, fsize);

    // This ddl generator is set to the appropriate ddl generator for the source database
    // every time we encounter a table profile result in the list.
    DDLGenerator ddlg = null;

    PdfPTable pdfTable = null;
    for (ProfileResult result : profileResults) {
        if (result instanceof TableProfileResult) {
            TableProfileResult tableResult = (TableProfileResult) result;
            pdfTable = new PdfPTable(widths.length);
            pdfTable.setWidthPercentage(100f);
            ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths);
            profiles.add(oneProfile);
            ddlg = tableResult.getDDLGenerator();
        } else if (result instanceof ColumnProfileResult) {
            final ColumnProfileResult columnResult = (ColumnProfileResult) result;
            TableProfileResult tResult = columnResult.getParent();
            addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths);
        }
    }

    double allowedTableSize = pagesize.width() - mrgt - mlft;
    double totalWidths = 0;
    for (int i = 0; i < headings.length; i++) {
        if (!columnsToTruncate.contains(headings[i])) {
            widths[i] += PIXELS_PER_BORDER;
            totalWidths += widths[i];
        }
    }
    truncateLength = (allowedTableSize - totalWidths - (PIXELS_PER_BORDER * (columnsToTruncate.size())))
            / columnsToTruncate.size();
    logger.debug("Truncate length is " + truncateLength);
    widths = new float[totalColumn];

    profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result
    for (ProfileResult result : profileResults) {
        if (result instanceof TableProfileResult) {
            TableProfileResult tableResult = (TableProfileResult) result;
            pdfTable = new PdfPTable(widths.length);
            pdfTable.setWidthPercentage(100f);
            ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths);
            profiles.add(oneProfile);
            ddlg = tableResult.getDDLGenerator();
        } else if (result instanceof ColumnProfileResult) {
            final ColumnProfileResult columnResult = (ColumnProfileResult) result;
            TableProfileResult tResult = columnResult.getParent();
            addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths);
        }
    }

    for (int i = 0; i < headings.length; i++) {
        widths[i] += PIXELS_PER_BORDER;
    }

    // add the PdfPTables to the document; try to avoid orphan and widow rows
    pos = writer.getVerticalPosition(true) - fsize;
    logger.debug("Starting at pos=" + pos);
    boolean newPageInd = true;

    for (ProfileTableStructure profile : profiles) {

        pdfTable = profile.getMainTable();
        pdfTable.setTotalWidth(pagesize.width() - mrgt - mlft);
        pdfTable.setWidths(widths);
        resetHeaderWidths(profile, widths);

        int startrow = pdfTable.getHeaderRows();
        int endrow = startrow; // current page will contain header+startrow..endrow

        /* no other rows in the table, just the header, and the header may
         * contain error message
         */
        if (endrow == pdfTable.size()) {
            pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb);
            continue;
        }

        while (endrow < pdfTable.size()) {

            // figure out how many body rows fit nicely on the page
            float endpos = pos - calcHeaderHeight(pdfTable);

            // y position of page number# = (mbot/2+fsize)
            while ((endpos - pdfTable.getRowHeight(endrow)) >= (mbot / 2 + fsize + 2)
                    && endrow < pdfTable.size()) {
                endpos -= pdfTable.getRowHeight(endrow);
                endrow++;
            }

            // adjust for orphan rows. Might create widows or make
            // endrow < startrow, which is handled later by deferring the table
            if (endrow < pdfTable.size() && endrow + minRowsTogether >= pdfTable.size()) {

                // page # maybe fall into table area, but usually that's column of
                // min value, usually that's enough space for both, or we should
                // disable page # on this page
                if (endrow + 1 == pdfTable.size() && endpos - pdfTable.getRowHeight(endrow) > 10) {

                    // short by 1 row.. just squeeze it in
                    endrow = pdfTable.size();
                } else {
                    // more than 1 row remains: shorten this page so orphans aren't lonely
                    endrow = pdfTable.size() - minRowsTogether;
                }
            }

            if (endrow == pdfTable.size() || endrow - startrow >= minRowsTogether) {
                // this is the end of the table, or we have enough rows to bother printing
                pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb);
                pos = pdfTable.writeSelectedRows(startrow, endrow, mlft, pos, cb);
                startrow = endrow;
                newPageInd = false;
            } else {
                // not the end of the table and not enough rows to print out
                if (newPageInd)
                    throw new IllegalStateException(
                            "PDF Page is not large engouh to display " + minRowsTogether + " row(s)");
                endrow = startrow;
            }

            // new page if necessary (that is, when we aren't finished the table yet)
            if (endrow != pdfTable.size()) {
                document.newPage();
                pos = pagesize.height() - mtop;
                newPageInd = true;
            }
        }
    }
    document.close();
}

From source file:ch.gpb.elexis.kgexporter.pdf.PdfHandler.java

License:Open Source License

public static void createLaborwertTable(Patient patient, String filename, LinkedList<String[]> laborBlatt,
        String footerText) throws IOException, DocumentException {

    // step 1//from w  ww. ja  v  a 2s  .  c om
    Document document = new Document(PageSize.A4);

    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    writer.setBoxSize("art", rect);

    HeaderFooterPageEvent event = new HeaderFooterPageEvent();
    event.setHeaderText(
            patient.getVorname() + " " + patient.getName() + " (" + patient.getGeburtsdatum() + ")");
    event.setFooterText(footerText);
    writer.setPageEvent(event);

    document.setMargins(56, 72, 60, 60);

    // step 3
    document.open();

    if (laborBlatt.size() == 0) {
        Paragraph p = new Paragraph(new Chunk("Keine Laborwerte vorhanden", fontTimesTitle));
        p.setSpacingBefore(20f);
        document.add(p);
    } else {

        document.add(createTable2(laborBlatt));
    }

    // step 5
    document.close();

}

From source file:ch.gpb.elexis.kgexporter.pdf.PdfHandler.java

License:Open Source License

public static void createDiagnosenSheet(Patient patient, String filename, String footerText)
        throws DocumentException, IOException {

    StringBuffer sb = new StringBuffer("Diagnosen:\n");
    sb.append(patient.getDiagnosen());/*from   w  w w  .j a  v a2 s  . c  om*/
    sb.append("\n");
    sb.append("Persnliche Anamnese:\n");
    sb.append(patient.getPersAnamnese());
    sb.append("\n");

    // step 1
    Document document = new Document(PageSize.A4);

    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    //Rectangle rect = new Rectangle(30, 30, 559, 800);
    writer.setBoxSize("art", rect);

    HeaderFooterPageEvent event = new HeaderFooterPageEvent();
    event.setHeaderText(
            patient.getVorname() + " " + patient.getName() + " (" + patient.getGeburtsdatum() + ")");
    event.setFooterText(footerText);
    writer.setPageEvent(event);

    document.setMargins(36, 72, 60, 60);

    // step 3
    document.open();

    document.add(new Chunk("")); // << this will do the trick. 

    if (patient.getDiagnosen().length() > 0) {
        Paragraph p = new Paragraph("Diagnosen:", fontTimesTitle);
        p.setSpacingAfter(10f);
        document.add(p);

        String[] chunksDiag = patient.getDiagnosen().toString().split("(?m)^\\s*$");
        for (String chunk : chunksDiag) {
            document.add(new Paragraph(chunk, fontTimes));
        }
    } else {
        document.add(new Paragraph("Keine Diagnosen vorhanden", fontTimes));

    }

    if (patient.getPersAnamnese().length() > 0) {
        Paragraph p = new Paragraph("Persnliche Anamnese:", fontTimesTitle);
        p.setSpacingBefore(10f);
        p.setSpacingAfter(10f);

        document.add(p);

        String[] chunksAnam = patient.getPersAnamnese().toString().split("(?m)^\\s*$");
        for (String chunk : chunksAnam) {
            document.add(new Paragraph(chunk, fontTimes));
        }
    } else {
        document.add(new Paragraph("Keine Persnliche Anamnese vorhanden", fontTimes));

    }

    // step 5
    document.close();

}

From source file:ch.gpb.elexis.kgexporter.pdf.PdfHandler.java

License:Open Source License

public static void createFixMediSheet(Patient patient, String filename, String footerText)
        throws DocumentException, IOException {
    Prescription[] prescriptions = patient.getFixmedikation();
    StringBuffer sb = new StringBuffer();
    for (Prescription prescription : prescriptions) {
        //System.out.println("Prescription: " + prescription.getLabel() + "/" + prescription.getDosis());
        sb.append(prescription.getLabel());
        sb.append("\r\n");
    }/*from  ww w  .j  a va  2 s .  c  o  m*/

    // step 1
    Document document = new Document(PageSize.A4);

    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    //Rectangle rect = new Rectangle(30, 30, 559, 800);
    writer.setBoxSize("art", rect);

    HeaderFooterPageEvent event = new HeaderFooterPageEvent();
    event.setHeaderText(
            patient.getVorname() + " " + patient.getName() + " (" + patient.getGeburtsdatum() + ")");
    event.setFooterText(footerText);
    writer.setPageEvent(event);

    document.setMargins(36, 72, 60, 60);

    // step 3
    document.open();

    document.add(new Chunk("")); // << this will do the trick. 

    if (sb.length() > 0) {
        Paragraph p = new Paragraph("Fixmedikation:", fontTimesTitle);
        p.setSpacingAfter(10f);
        document.add(p);

        String[] chunksDiag = sb.toString().split("(?m)^\\s*$");
        for (String chunk : chunksDiag) {
            document.add(new Paragraph(chunk, fontTimes));
        }
    } else {

        //document.add(new Paragraph("Keine Medikationen vorhanden", fontTimes));
        Paragraph p = new Paragraph(new Chunk("Keine Medikationen vorhanden", fontTimesTitle));
        p.setSpacingBefore(20f);
        document.add(p);

    }

    // step 5
    document.close();

}

From source file:classroom.filmfestival_a.Movies05.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    // step 1//from  w  w w . j  a  va2  s . c o  m
    Document document = new Document();
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter writer = PdfWriter.getInstance(document, os);
        writer.setPageEvent(new Movies05().new Ellipse());
        // step 3
        document.open();
        // step 4
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();
        Paragraph p;
        Chunk c;
        Font bold = new Font(Font.HELVETICA, 12, Font.BOLD);
        Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC);
        Font white = new Font(Font.HELVETICA, 12, Font.BOLD | Font.ITALIC, Color.WHITE);
        for (FilmTitle movie : results) {
            p = new Paragraph(20);
            c = new Chunk(movie.getTitle(), bold);
            c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId());
            p.add(c);
            c = new Chunk(" (" + movie.getYear() + ") ", italic);
            p.add(c);
            c = new Chunk("IMDB", white);
            c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
            c.setGenericTag("ellipse");
            p.add(c);
            document.add(p);
            Set<DirectorName> directors = movie.getDirectorNames();
            List list = new List();
            for (DirectorName director : directors) {
                list.add(director.getName());
            }
            document.add(list);
        }
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:classroom.filmfestival_b.Movies11.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    // step 1//w w  w  .j a  v  a  2  s.  c  o  m
    Document document = new Document();
    document.setMargins(36, 36, 48, 48);
    float middle = (document.right() + document.left()) / 2;
    float columns[][] = { { document.left(), document.bottom(), middle - 12, document.top() },
            { middle + 12, document.bottom(), document.right(), document.top() } };
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter writer = PdfWriter.getInstance(document, os);
        writer.setPageEvent(new Movies11().new MoviePageEvents(middle, document.top(), document.bottom()));
        // step 3
        document.open();
        // step 4
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();

        ColumnText column = new ColumnText(writer.getDirectContent());
        column.setSimpleColumn(columns[0][0], columns[0][1], columns[0][2], columns[0][3]);

        float pos;
        int status;
        int ccount = 0;
        File f;
        Image img;
        Paragraph p;
        Chunk c;
        Font bold = new Font(Font.HELVETICA, 12, Font.BOLD);
        Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC);
        for (FilmTitle movie : results) {
            f = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg");
            if (f.exists()) {
                img = Image.getInstance(f.getPath());
                img.setWidthPercentage(0);
                img.scaleToFit(72, 144);
            } else {
                img = null;
            }
            p = new Paragraph(20);
            c = new Chunk(movie.getTitle(), bold);
            c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId());
            p.add(c);
            c = new Chunk(" (" + movie.getYear() + ") ", italic);
            p.add(c);
            c = new Chunk("IMDB");
            c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
            p.add(c);
            Set<DirectorName> directors = movie.getDirectorNames();
            List list = new List();
            for (DirectorName director : directors) {
                list.add(director.getName());
            }

            if (img != null)
                column.addElement(img);
            column.addElement(p);
            column.addElement(list);
            pos = column.getYLine();
            status = column.go(true);
            if (ColumnText.hasMoreText(status)) {
                column.setText(null);
                ccount++;
                if (ccount > 1) {
                    ccount = 0;
                    document.newPage();
                    column.setSimpleColumn(columns[0][0], columns[0][1], columns[0][2], columns[0][3]);
                } else {
                    column.setSimpleColumn(columns[1][0], columns[1][1], columns[1][2], columns[1][3]);
                }
            } else {
                column.setYLine(pos);
            }
            if (img != null)
                column.addElement(img);
            column.addElement(p);
            column.addElement(list);
            column.addElement(Chunk.NEWLINE);
            column.go();
        }
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:com.actelion.research.spiritapp.ui.util.PDFUtils.java

License:Open Source License

public static void addHeader(PdfWriter writer, String header) {
    class MyFooter extends PdfPageEventHelper {
        com.lowagie.text.Font ffont;

        @Override//from w  w  w .ja va2  s  .  c  o  m
        public void onEndPage(PdfWriter writer, Document document) {
            try {
                ffont = new com.lowagie.text.Font(
                        BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED), 6f,
                        com.lowagie.text.Font.ITALIC);
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }

            String date = FormatterUtils.formatDateTime(new Date());
            PdfContentByte cb = writer.getDirectContent();
            ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(header, ffont), document.left(),
                    document.top() + 5, 0);
            ColumnText.showTextAligned(cb, Element.ALIGN_CENTER,
                    new Phrase("Page " + writer.getCurrentPageNumber(), ffont),
                    (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom() - 5, 0);
            ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, new Phrase(date, ffont), document.right(),
                    document.bottom() - 5, 0);
        }
    }
    writer.setPageEvent(new MyFooter());
}

From source file:com.aryjr.nheengatu.pdf.PDFDocument.java

License:Open Source License

public void generateFile(final OutputStream out) throws IOException {
    final Document document;
    if (styleSheet == null || styleSheet.getStyles() == null || !styleSheet.getStyles().containsKey("@page")) {
        document = new Document(PageSize.A4);
        document.setMargins(3.0f * PDFDocument.CM_UNIT, 2.0f * PDFDocument.CM_UNIT, 1.0f * PDFDocument.CM_UNIT,
                2.0f * PDFDocument.CM_UNIT);
        System.out.println("Processamento: terminou setMargins");
    } else {//ww w .  j  av a2 s . co m
        Style style = ((Style) (styleSheet.getStyles().get("@page")));
        if ("landscape".equals(style.getPropertyValue("size"))) {
            document = new Document(PageSize.A4.rotate());
        } else {
            document = new Document(PageSize.A4);
        }
        String s = style.getPropertyValue("margin-left");
        Float f = styleMeasure(s, "3cm");
        document.setMargins(styleMeasure(style.getPropertyValue("margin-left"), "3cm"),
                styleMeasure(style.getPropertyValue("margin-right"), "2cm"),
                styleMeasure(style.getPropertyValue("margin-top"), "1cm"),
                styleMeasure(style.getPropertyValue("margin-bottom"), "2cm"));
        System.out.println("Processamento: terminou setMargins do else");
    }
    try {
        final PdfWriter writer = PdfWriter.getInstance(document, out);
        writer.setPageEvent(new PDFPageBreak(writer, document, headFirstPage, footFirstPage, head, foot));
        document.open();
        final MultiColumnText mct = new MultiColumnText();
        // set up 3 even columns with 10pt space between
        mct.addRegularColumns(document.left(), document.right(), 0f, 1);

        System.out.println("Processamento: prestes a extract visible components");

        // Extracting the document content
        extractVisibleComponents(body, document, mct, null, null);

        document.add(mct);
        document.close();
    } catch (final DocumentException de) {
        System.err.println(de.getMessage());
    }
}