Chapter 5: Table, cell, and page events

This is a code example of iText PDF, discover more.

10th October 2015
admin-marketing

Switch code for this example

AlternatingBackground.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part1.chapter05;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.Date;
  13. import java.sql.SQLException;
  14. import java.util.List;
  15.  
  16. import com.lowagie.database.DatabaseConnection;
  17. import com.lowagie.database.HsqldbConnection;
  18. import com.lowagie.filmfestival.Movie;
  19. import com.lowagie.filmfestival.PojoFactory;
  20. import com.lowagie.filmfestival.Screening;
  21. import com.itextpdf.text.Document;
  22. import com.itextpdf.text.DocumentException;
  23. import com.itextpdf.text.Element;
  24. import com.itextpdf.text.PageSize;
  25. import com.itextpdf.text.Rectangle;
  26. import com.itextpdf.text.pdf.PdfContentByte;
  27. import com.itextpdf.text.pdf.PdfPTable;
  28. import com.itextpdf.text.pdf.PdfPTableEvent;
  29. import com.itextpdf.text.pdf.PdfWriter;
  30. import com.itextpdf.text.BaseColor;
  31.  
  32. public class AlternatingBackground implements PdfPTableEvent {
  33.  
  34.     /** The resulting PDF file. */
  35.     public static final String RESULT
  36.         = "results/part1/chapter05/alternating.pdf";
  37.  
  38.     /**
  39.      * Creates a PDF document.
  40.      * @param filename the path to the new PDF document
  41.      * @throws    DocumentException
  42.      * @throws    IOException
  43.      * @throws    SQLException
  44.      */
  45.     public void createPdf(String filename) throws SQLException, DocumentException, IOException {
  46.         // Create a database connection
  47.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  48.         // step 1
  49.         Document document = new Document(PageSize.A4.rotate());
  50.         // step 2
  51.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  52.         // step 3
  53.         document.open();
  54.         // step 4
  55.         List days = PojoFactory.getDays(connection);
  56.         PdfPTableEvent event = new AlternatingBackground();
  57.         for (Date day : days) {
  58.             PdfPTable table = getTable(connection, day);
  59.             table.setTableEvent(event);
  60.             document.add(table);
  61.             document.newPage();
  62.         }
  63.         // step 5
  64.         document.close();
  65.         // Close the database connection
  66.         connection.close();
  67.     }
  68.    
  69.     /**
  70.      * Creates a table with film festival screenings.
  71.      * @param connection a database connection
  72.      * @param day a film festival day
  73.      * @return a table with screenings.
  74.      * @throws SQLException
  75.      * @throws DocumentException
  76.      * @throws IOException
  77.      */
  78.     public PdfPTable getTable(DatabaseConnection connection, Date day)
  79.         throws SQLException, DocumentException, IOException {
  80.         PdfPTable table = new PdfPTable(new float[] { 2, 1, 2, 5, 1 });
  81.         table.setWidthPercentage(100f);
  82.         table.getDefaultCell().setPadding(3);
  83.         table.getDefaultCell().setUseAscender(true);
  84.         table.getDefaultCell().setUseDescender(true);
  85.         table.getDefaultCell().setColspan(5);
  86.         table.getDefaultCell().setBackgroundColor(BaseColor.RED);
  87.         table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
  88.         table.addCell(day.toString());
  89.         table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
  90.         table.getDefaultCell().setColspan(1);
  91.         table.getDefaultCell().setBackgroundColor(BaseColor.ORANGE);
  92.         for (int i = 0; i < 2; i++) {
  93.             table.addCell("Location");
  94.             table.addCell("Time");
  95.             table.addCell("Run Length");
  96.             table.addCell("Title");
  97.             table.addCell("Year");
  98.         }
  99.         table.getDefaultCell().setBackgroundColor(null);
  100.         table.setHeaderRows(3);
  101.         table.setFooterRows(1);
  102.         List screenings = PojoFactory.getScreenings(connection, day);
  103.         Movie movie;
  104.         for (Screening screening : screenings) {
  105.             movie = screening.getMovie();
  106.             table.addCell(screening.getLocation());
  107.             table.addCell(String.format("%1$tH:%1$tM", screening.getTime()));
  108.             table.addCell(String.format("%d '", movie.getDuration()));
  109.             table.addCell(movie.getMovieTitle());
  110.             table.addCell(String.valueOf(movie.getYear()));
  111.         }
  112.         return table;
  113.     }
  114.    
  115.     /**
  116.      * Draws a background for every other row.
  117.      * @see com.itextpdf.text.pdf.PdfPTableEvent#tableLayout(
  118.      *      com.itextpdf.text.pdf.PdfPTable, float[][], float[], int, int,
  119.      *      com.itextpdf.text.pdf.PdfContentByte[])
  120.      */
  121.     public void tableLayout(PdfPTable table, float[][] widths, float[] heights,
  122.         int headerRows, int rowStart, PdfContentByte[] canvases) {
  123.         int columns;
  124.         Rectangle rect;
  125.         int footer = widths.length - table.getFooterRows();
  126.         int header = table.getHeaderRows() - table.getFooterRows() + 1;
  127.         for (int row = header; row < footer; row += 2) {
  128.             columns = widths[row].length - 1;
  129.             rect = new Rectangle(widths[row][0], heights[row],
  130.                         widths[row][columns], heights[row + 1]);
  131.             rect.setBackgroundColor(BaseColor.YELLOW);
  132.             rect.setBorder(Rectangle.NO_BORDER);
  133.             canvases[PdfPTable.BASECANVAS].rectangle(rect);
  134.         }
  135.     }
  136.  
  137.     /**
  138.      * Main method.
  139.      * @param    args    no arguments needed
  140.      * @throws DocumentException
  141.      * @throws IOException
  142.      * @throws SQLException
  143.      */
  144.     public static void main(String[] args) throws SQLException, DocumentException, IOException {
  145.         new AlternatingBackground().createPdf(RESULT);
  146.     }
  147. }
RunLengthEvent.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part1.chapter05;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.Date;
  13. import java.sql.SQLException;
  14. import java.util.List;
  15.  
  16. import com.lowagie.database.DatabaseConnection;
  17. import com.lowagie.database.HsqldbConnection;
  18. import com.lowagie.filmfestival.Movie;
  19. import com.lowagie.filmfestival.PojoFactory;
  20. import com.lowagie.filmfestival.Screening;
  21. import com.itextpdf.text.Document;
  22. import com.itextpdf.text.DocumentException;
  23. import com.itextpdf.text.Element;
  24. import com.itextpdf.text.PageSize;
  25. import com.itextpdf.text.Phrase;
  26. import com.itextpdf.text.Rectangle;
  27. import com.itextpdf.text.pdf.BaseFont;
  28. import com.itextpdf.text.pdf.PdfContentByte;
  29. import com.itextpdf.text.pdf.PdfPCell;
  30. import com.itextpdf.text.pdf.PdfPCellEvent;
  31. import com.itextpdf.text.pdf.PdfPTable;
  32. import com.itextpdf.text.pdf.PdfWriter;
  33. import com.itextpdf.text.BaseColor;
  34.  
  35. public class RunLengthEvent {
  36.  
  37.     /** The resulting PDF. */
  38.     public static final String RESULT
  39.         = "results/part1/chapter05/run_length.pdf";
  40.  
  41.     /** Inner class to draw a bar inside a cell. */
  42.     class RunLength implements PdfPCellEvent {
  43.        
  44.         public int duration;
  45.        
  46.         public RunLength(int duration) {
  47.             this.duration = duration;
  48.         }
  49.        
  50.         /**
  51.          * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(
  52.          *      com.lowagie.text.pdf.PdfPCell, com.lowagie.text.Rectangle,
  53.          *      com.lowagie.text.pdf.PdfContentByte[])
  54.          */
  55.         public void cellLayout(PdfPCell cell, Rectangle rect,
  56.                 PdfContentByte[] canvas) {
  57.             PdfContentByte cb = canvas[PdfPTable.BACKGROUNDCANVAS];
  58.             cb.saveState();
  59.             if (duration < 90) {
  60.                 cb.setRGBColorFill(0x7C, 0xFC, 0x00);
  61.             }
  62.             else if (duration > 120) {
  63.                 cb.setRGBColorFill(0x8B, 0x00, 0x00);
  64.             }
  65.             else {
  66.                 cb.setRGBColorFill(0xFF, 0xA5, 0x00);
  67.             }
  68.             cb.rectangle(rect.getLeft(), rect.getBottom(),
  69.                 rect.getWidth() * duration / 240, rect.getHeight());
  70.             cb.fill();
  71.             cb.restoreState();
  72.         }
  73.     }
  74.  
  75.     /** Inner class to add the words PRESS PREVIEW to a cell. */
  76.     class PressPreview implements PdfPCellEvent {
  77.        
  78.         public BaseFont bf;
  79.        
  80.         public PressPreview() throws DocumentException, IOException {
  81.             bf = BaseFont.createFont();
  82.         }
  83.        
  84.         /**
  85.          * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(com.lowagie.text.pdf.PdfPCell,
  86.          *      com.lowagie.text.Rectangle,
  87.          *      com.lowagie.text.pdf.PdfContentByte[])
  88.          */
  89.         public void cellLayout(PdfPCell cell, Rectangle rect,
  90.                 PdfContentByte[] canvas) {
  91.             PdfContentByte cb = canvas[PdfPTable.TEXTCANVAS];
  92.             cb.beginText();
  93.             cb.setFontAndSize(bf, 12);
  94.             cb.showTextAligned(Element.ALIGN_RIGHT, "PRESS PREVIEW",
  95.                 rect.getRight() - 3, rect.getBottom() + 4.5f, 0);
  96.             cb.endText();
  97.         }
  98.     }
  99.    
  100.     /** The press cell event. */
  101.     public PdfPCellEvent press;
  102.  
  103.     /**
  104.      * Creates a PDF document.
  105.      * @param filename the path to the new PDF document
  106.      * @throws    DocumentException
  107.      * @throws    IOException
  108.      * @throws    SQLException
  109.      */
  110.     public void createPdf(String filename)
  111.         throws SQLException, DocumentException, IOException {
  112.         press = new PressPreview();
  113.         // Create a database connection
  114.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  115.         // step 1
  116.         Document document = new Document(PageSize.A4.rotate());
  117.         // step 2
  118.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  119.         // step 3
  120.         document.open();
  121.         // step 4
  122.         List days = PojoFactory.getDays(connection);
  123.         for (Date day : days) {
  124.             document.add(getTable(connection, day));
  125.             document.newPage();
  126.         }
  127.         // step 5
  128.         document.close();
  129.         // Close the database connection
  130.         connection.close();
  131.     }
  132.    
  133.     /**
  134.      * @param connection
  135.      * @param day
  136.      * @return
  137.      * @throws SQLException
  138.      * @throws DocumentException
  139.      * @throws IOException
  140.      */
  141.     public PdfPTable getTable(DatabaseConnection connection, Date day)
  142.         throws SQLException, DocumentException, IOException {
  143.         PdfPTable table = new PdfPTable(new float[] { 2, 1, 2, 5, 1 });
  144.         table.setWidthPercentage(100f);
  145.         table.getDefaultCell().setPadding(3);
  146.         table.getDefaultCell().setUseAscender(true);
  147.         table.getDefaultCell().setUseDescender(true);
  148.         table.getDefaultCell().setColspan(5);
  149.         table.getDefaultCell().setBackgroundColor(BaseColor.RED);
  150.         table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
  151.         table.addCell(day.toString());
  152.         table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
  153.         table.getDefaultCell().setColspan(1);
  154.         table.getDefaultCell().setBackgroundColor(BaseColor.YELLOW);
  155.         for (int i = 0; i < 2; i++) {
  156.             table.addCell("Location");
  157.             table.addCell("Time");
  158.             table.addCell("Run Length");
  159.             table.addCell("Title");
  160.             table.addCell("Year");
  161.         }
  162.         table.getDefaultCell().setBackgroundColor(null);
  163.         table.setHeaderRows(3);
  164.         table.setFooterRows(1);
  165.         List screenings = PojoFactory.getScreenings(connection, day);
  166.         Movie movie;
  167.         PdfPCell runLength;
  168.         for (Screening screening : screenings) {
  169.             movie = screening.getMovie();
  170.             table.addCell(screening.getLocation());
  171.             table.addCell(String.format("%1$tH:%1$tM", screening.getTime()));
  172.             runLength = new PdfPCell(table.getDefaultCell());
  173.             runLength.setPhrase(new Phrase(String.format("%d '", movie.getDuration())));
  174.             runLength.setCellEvent(new RunLength(movie.getDuration()));
  175.             if (screening.isPress()) {
  176.                 runLength.setCellEvent(press);
  177.             }
  178.             table.addCell(runLength);
  179.             table.addCell(movie.getMovieTitle());
  180.             table.addCell(String.valueOf(movie.getYear()));
  181.         }
  182.         return table;
  183.     }
  184.  
  185.     /**
  186.      * Main method.
  187.      * @param    args    no arguments needed
  188.      * @throws DocumentException
  189.      * @throws IOException
  190.      * @throws SQLException
  191.      */
  192.     public static void main(String[] args) throws SQLException, DocumentException, IOException {
  193.         new RunLengthEvent().createPdf(RESULT);
  194.     }
  195. }
PressPreviews.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part1.chapter05;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13. import java.util.List;
  14.  
  15. import com.lowagie.database.DatabaseConnection;
  16. import com.lowagie.database.HsqldbConnection;
  17. import com.lowagie.filmfestival.Movie;
  18. import com.lowagie.filmfestival.PojoFactory;
  19. import com.lowagie.filmfestival.Screening;
  20. import com.itextpdf.text.Document;
  21. import com.itextpdf.text.DocumentException;
  22. import com.itextpdf.text.PageSize;
  23. import com.itextpdf.text.Rectangle;
  24. import com.itextpdf.text.pdf.PdfContentByte;
  25. import com.itextpdf.text.pdf.PdfPCell;
  26. import com.itextpdf.text.pdf.PdfPCellEvent;
  27. import com.itextpdf.text.pdf.PdfPTable;
  28. import com.itextpdf.text.pdf.PdfPTableEvent;
  29. import com.itextpdf.text.pdf.PdfWriter;
  30.  
  31. public class PressPreviews implements PdfPCellEvent, PdfPTableEvent {
  32.  
  33.     /** The resulting PDF. */
  34.     public static final String RESULT = "results/part1/chapter05/press_previews.pdf";
  35.  
  36.     /**
  37.      * @see com.itextpdf.text.pdf.PdfPTableEvent#tableLayout(com.itextpdf.text.pdf.PdfPTable,
  38.      *      float[][], float[], int, int, com.itextpdf.text.pdf.PdfContentByte[])
  39.      */
  40.     public void tableLayout(PdfPTable table, float[][] width, float[] height,
  41.             int headerRows, int rowStart, PdfContentByte[] canvas) {
  42.         float widths[] = width[0];
  43.         float x1 = widths[0];
  44.         float x2 = widths[widths.length - 1];
  45.         float y1 = height[0];
  46.         float y2 = height[height.length - 1];
  47.         PdfContentByte cb = canvas[PdfPTable.LINECANVAS];
  48.         cb.rectangle(x1, y1, x2 - x1, y2 - y1);
  49.         cb.stroke();
  50.         cb.resetRGBColorStroke();
  51.     }
  52.  
  53.     /**
  54.      * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(com.lowagie.text.pdf.PdfPCell,
  55.      *      com.lowagie.text.Rectangle, com.lowagie.text.pdf.PdfContentByte[])
  56.      */
  57.     public void cellLayout(PdfPCell cell, Rectangle position,
  58.             PdfContentByte[] canvases) {
  59.         float x1 = position.getLeft() + 2;
  60.         float x2 = position.getRight() - 2;
  61.         float y1 = position.getTop() - 2;
  62.         float y2 = position.getBottom() + 2;
  63.         PdfContentByte canvas = canvases[PdfPTable.LINECANVAS];
  64.         canvas.rectangle(x1, y1, x2 - x1, y2 - y1);
  65.         canvas.stroke();
  66.     }
  67.  
  68.     /**
  69.      * Creates a PDF document.
  70.      * @param filename the path to the new PDF document
  71.      * @throws    DocumentException
  72.      * @throws    IOException
  73.      * @throws    SQLException
  74.      */
  75.     public void createPdf(String filename)
  76.         throws SQLException, DocumentException, IOException {
  77.         // Create a database connection
  78.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  79.         // step 1
  80.         Document document = new Document(PageSize.A4.rotate());
  81.         // step 2
  82.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  83.         // step 3
  84.         document.open();
  85.         // step 4
  86.         document.add(getTable(connection));
  87.         // step 5
  88.         document.close();
  89.         // close the database connection
  90.         connection.close();
  91.     }
  92.    
  93.     /**
  94.      * Creates a table that mimics cellspacing using table and cell events.
  95.      * @param connection
  96.      * @return a table
  97.      * @throws SQLException
  98.      * @throws DocumentException
  99.      * @throws IOException
  100.      */
  101.     public PdfPTable getTable(DatabaseConnection connection)
  102.         throws SQLException, DocumentException, IOException {
  103.         PdfPTable table = new PdfPTable(new float[] { 1, 2, 2, 5, 1 });
  104.         table.setTableEvent(new PressPreviews());
  105.         table.setWidthPercentage(100f);
  106.         table.getDefaultCell().setPadding(5);
  107.         table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
  108.         table.getDefaultCell().setCellEvent(new PressPreviews());
  109.         for (int i = 0; i < 2; i++) {
  110.             table.addCell("Location");
  111.             table.addCell("Date/Time");
  112.             table.addCell("Run Length");
  113.             table.addCell("Title");
  114.             table.addCell("Year");
  115.         }
  116.         table.getDefaultCell().setBackgroundColor(null);
  117.         table.setHeaderRows(2);
  118.         table.setFooterRows(1);
  119.         List screenings = PojoFactory.getPressPreviews(connection);
  120.         Movie movie;
  121.         for (Screening screening : screenings) {
  122.             movie = screening.getMovie();
  123.             table.addCell(screening.getLocation());
  124.             table.addCell(String.format("%s   %2$tH:%2$tM",
  125.                 screening.getDate().toString(), screening.getTime()));
  126.             table.addCell(String.format("%d '", movie.getDuration()));
  127.             table.addCell(movie.getMovieTitle());
  128.             table.addCell(String.valueOf(movie.getYear()));
  129.         }
  130.         return table;
  131.     }
  132.    
  133.     /**
  134.      * Main method.
  135.      * @param    args    no arguments needed
  136.      * @throws DocumentException
  137.      * @throws IOException
  138.      * @throws SQLException
  139.      */
  140.     public static void main(String[] args) throws SQLException, DocumentException, IOException {
  141.         new PressPreviews().createPdf(RESULT);
  142.     }
  143. }
PdfCalendar.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part1.chapter05;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.util.Calendar;
  13. import java.util.GregorianCalendar;
  14. import java.util.Locale;
  15.  
  16. import com.itextpdf.text.Chunk;
  17. import com.itextpdf.text.Document;
  18. import com.itextpdf.text.DocumentException;
  19. import com.itextpdf.text.Element;
  20. import com.itextpdf.text.PageSize;
  21. import com.itextpdf.text.Paragraph;
  22. import com.itextpdf.text.Rectangle;
  23. import com.itextpdf.text.pdf.PdfContentByte;
  24. import com.itextpdf.text.pdf.PdfPCell;
  25. import com.itextpdf.text.pdf.PdfPCellEvent;
  26. import com.itextpdf.text.pdf.PdfPTable;
  27. import com.itextpdf.text.pdf.PdfPTableEvent;
  28. import com.itextpdf.text.pdf.PdfWriter;
  29. import com.itextpdf.text.pdf.draw.VerticalPositionMark;
  30.  
  31. public class PdfCalendar extends part1.chapter04.PdfCalendar {
  32.  
  33.     /** The resulting PDF. */
  34.     public static final String RESULT = "results/part1/chapter05/calendar.pdf";
  35.  
  36.     /** A table event. */
  37.     public PdfPTableEvent tableBackground;
  38.     /** A cell event. */
  39.     public PdfPCellEvent cellBackground;
  40.     /** A cell event. */
  41.     public PdfPCellEvent roundRectangle;
  42.     /** A cell event. */
  43.     public PdfPCellEvent whiteRectangle;
  44.    
  45.     /**
  46.      * Inner class with a table event that draws a background with rounded corners.
  47.      */
  48.     class TableBackground implements PdfPTableEvent {
  49.        
  50.         public void tableLayout(PdfPTable table, float[][] width, float[] height,
  51.                 int headerRows, int rowStart, PdfContentByte[] canvas) {
  52.             PdfContentByte background = canvas[PdfPTable.BASECANVAS];
  53.             background.saveState();
  54.             background.setCMYKColorFill(0x00, 0x00, 0xFF, 0x0F);
  55.             background.roundRectangle(
  56.                 width[0][0], height[height.length - 1] - 2,
  57.                 width[0][1] - width[0][0] + 6, height[0] - height[height.length - 1] - 4, 4);
  58.             background.fill();
  59.             background.restoreState();
  60.         }
  61.  
  62.     }
  63.    
  64.     /**
  65.      * Inner class with a cell event that draws a background with rounded corners.
  66.      */
  67.     class CellBackground implements PdfPCellEvent {
  68.        
  69.         public void cellLayout(PdfPCell cell, Rectangle rect,
  70.                 PdfContentByte[] canvas) {
  71.             PdfContentByte cb = canvas[PdfPTable.BACKGROUNDCANVAS];
  72.             cb.roundRectangle(
  73.                 rect.getLeft() + 1.5f, rect.getBottom() + 1.5f, rect.getWidth() - 3,
  74.                 rect.getHeight() - 3, 4);
  75.             cb.setCMYKColorFill(0x00, 0x00, 0x00, 0x00);
  76.             cb.fill();
  77.         }
  78.     }
  79.  
  80.     /**
  81.      * Inner class with a cell event that draws a border with rounded corners.
  82.      */
  83.     class RoundRectangle implements PdfPCellEvent {
  84.         /** the border color described as CMYK values. */
  85.         protected int[] color;
  86.         /** Constructs the event using a certain color. */
  87.         public RoundRectangle(int[] color) {
  88.             this.color = color;
  89.         }
  90.        
  91.         public void cellLayout(PdfPCell cell, Rectangle rect,
  92.                 PdfContentByte[] canvas) {
  93.             PdfContentByte cb = canvas[PdfPTable.LINECANVAS];
  94.             cb.roundRectangle(
  95.                 rect.getLeft() + 1.5f, rect.getBottom() + 1.5f, rect.getWidth() - 3,
  96.                 rect.getHeight() - 3, 4);
  97.             cb.setLineWidth(1.5f);
  98.             cb.setCMYKColorStrokeF(color[0], color[1], color[2], color[3]);
  99.             cb.stroke();
  100.         }
  101.     }
  102.    
  103.     /**
  104.      * Main method creating the PDF.
  105.      * @param    args    no arguments needed
  106.      * @throws IOException
  107.      * @throws DocumentException
  108.      */
  109.     public static void main(String[] args) throws IOException, DocumentException {
  110.         Locale locale = new Locale(LANGUAGE);
  111.         new PdfCalendar().createPdf(RESULT, locale, YEAR);
  112.     }
  113.  
  114.     /**
  115.      * Initializes the fonts and collections.
  116.      * @throws DocumentException
  117.      * @throws IOException
  118.      */
  119.     public PdfCalendar() throws DocumentException, IOException {
  120.         super();
  121.         tableBackground = new TableBackground();
  122.         cellBackground = new CellBackground();
  123.         roundRectangle = new RoundRectangle(new int[]{ 0xFF, 0x00, 0xFF, 0x00 });
  124.         whiteRectangle = new RoundRectangle(new int[]{ 0x00, 0x00, 0x00, 0x00 });
  125.     }
  126.  
  127.     /**
  128.      * Creates a PDF document.
  129.      * @param filename the path to the new PDF document
  130.      * @param locale Locale in case you want to create
  131.      * a Calendar in another language
  132.      * @param year the year for which you want to make a calendar
  133.      * @throws    DocumentException
  134.      * @throws    IOException
  135.      */
  136.     public void createPdf(String filename, Locale locale, int year) throws IOException, DocumentException {
  137.         // step 1
  138.         Document document = new Document(PageSize.A4.rotate());
  139.         // step 2
  140.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  141.         // step 3
  142.         document.open();
  143.         // step 4
  144.         PdfPTable table;
  145.         Calendar calendar;
  146.         PdfContentByte canvas = writer.getDirectContent();
  147.         // Loop over the months
  148.         for (int month = 0; month < 12; month++) {
  149.             calendar = new GregorianCalendar(year, month, 1);
  150.             // draw the background
  151.             drawImageAndText(canvas, calendar);
  152.             // create a table with 7 columns
  153.             table = new PdfPTable(7);
  154.             table.setTableEvent(tableBackground);
  155.             table.setTotalWidth(504);
  156.             // add the name of the month
  157.             table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
  158.             table.getDefaultCell().setCellEvent(whiteRectangle);
  159.             table.addCell(getMonthCell(calendar, locale));
  160.             int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
  161.             int day = 1;
  162.             int position = 2;
  163.             // add empty cells
  164.             while (position != calendar.get(Calendar.DAY_OF_WEEK)) {
  165.                 position = (position % 7) + 1;
  166.                 table.addCell("");
  167.             }
  168.             // add cells for each day
  169.             while (day
MovieYears.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part1.chapter05;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13. import java.util.Map;
  14. import java.util.Set;
  15. import java.util.TreeMap;
  16. import java.util.TreeSet;
  17.  
  18. import com.lowagie.database.DatabaseConnection;
  19. import com.lowagie.database.HsqldbConnection;
  20. import com.lowagie.filmfestival.Movie;
  21. import com.lowagie.filmfestival.MovieComparator;
  22. import com.lowagie.filmfestival.PojoFactory;
  23. import com.itextpdf.text.Chunk;
  24. import com.itextpdf.text.Document;
  25. import com.itextpdf.text.DocumentException;
  26. import com.itextpdf.text.Font;
  27. import com.itextpdf.text.Paragraph;
  28. import com.itextpdf.text.Rectangle;
  29. import com.itextpdf.text.Font.FontFamily;
  30. import com.itextpdf.text.pdf.PdfContentByte;
  31. import com.itextpdf.text.pdf.PdfPageEventHelper;
  32. import com.itextpdf.text.pdf.PdfWriter;
  33. import com.itextpdf.text.BaseColor;
  34.  
  35. public class MovieYears {
  36.    
  37.     /** The resulting PDF file. */
  38.     public static final String RESULT = "results/part1/chapter05/movie_years.pdf";
  39.  
  40.     /**
  41.      * Inner class to add functionality to a Chunk in a generic way.
  42.      */
  43.     class GenericTags extends PdfPageEventHelper {
  44.          
  45.         public void onGenericTag(PdfWriter writer, Document pdfDocument,
  46.                 Rectangle rect, String text) {
  47.             if ("strip".equals(text))
  48.                 strip(writer.getDirectContent(), rect);
  49.             else if ("ellipse".equals(text))
  50.                 ellipse(writer.getDirectContentUnder(), rect);
  51.             else
  52.                 countYear(text);
  53.         }
  54.  
  55.         public void strip(PdfContentByte content, Rectangle rect) {
  56.             content.rectangle(rect.getLeft() - 1, rect.getBottom() - 5f,
  57.                     rect.getWidth(), rect.getHeight() + 8);
  58.             content.rectangle(rect.getLeft(), rect.getBottom() - 2,
  59.                     rect.getWidth() - 2, rect.getHeight() + 2);
  60.             float y1 = rect.getTop() + 0.5f;
  61.             float y2 = rect.getBottom() - 4;
  62.             for (float f = rect.getLeft(); f < rect.getRight() - 4; f += 5) {
  63.                 content.rectangle(f, y1, 4f, 1.5f);
  64.                 content.rectangle(f, y2, 4f, 1.5f);
  65.             }
  66.             content.eoFill();
  67.         }
  68.        
  69.         public void ellipse(PdfContentByte content, Rectangle rect) {
  70.             content.saveState();
  71.             content.setRGBColorFill(0x00, 0x00, 0xFF);
  72.             content.ellipse(rect.getLeft() - 3f, rect.getBottom() - 5f,
  73.                     rect.getRight() + 3f, rect.getTop() + 3f);
  74.             content.fill();
  75.             content.restoreState();
  76.         }
  77.  
  78.         TreeMap years = new TreeMap();
  79.        
  80.         public void countYear(String text) {
  81.             Integer count = years.get(text);
  82.             if (count == null) {
  83.                 years.put(text, 1);
  84.             }
  85.             else {
  86.                 years.put(text, count + 1);
  87.             }
  88.         }
  89.     }
  90.    
  91.     /**
  92.      * Inner class to add lines when a paragraph begins and ends.
  93.      */
  94.     class ParagraphPositions extends PdfPageEventHelper {
  95.         public void onParagraph(PdfWriter writer, Document pdfDocument,
  96.                 float paragraphPosition) {
  97.             drawLine(writer.getDirectContent(),
  98.                     pdfDocument.left(), pdfDocument.right(), paragraphPosition - 8);
  99.         }
  100.  
  101.         public void onParagraphEnd(PdfWriter writer, Document pdfDocument,
  102.                 float paragraphPosition) {
  103.             drawLine(writer.getDirectContent(),
  104.                     pdfDocument.left(), pdfDocument.right(), paragraphPosition - 5);
  105.         }
  106.        
  107.         public void drawLine(PdfContentByte cb, float x1, float x2, float y) {
  108.             cb.moveTo(x1, y);
  109.             cb.lineTo(x2, y);
  110.             cb.stroke();
  111.         }
  112.     }
  113.  
  114.     /**
  115.      * Creates a PDF document.
  116.      * @param filename the path to the new PDF document
  117.      * @throws    DocumentException
  118.      * @throws    IOException
  119.      */
  120.     public void createPdf(String filename) throws IOException, DocumentException, SQLException {
  121.         // Create a database connection
  122.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  123.         // step 1
  124.         Document document = new Document();
  125.         // step 2
  126.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  127.         GenericTags event = new GenericTags();
  128.         writer.setPageEvent(event);
  129.         writer.setPageEvent(new ParagraphPositions());
  130.         // step 3
  131.         document.open();
  132.         // step 4
  133.         Font bold = new Font(FontFamily.HELVETICA, 11, Font.BOLD);
  134.         Font italic = new Font(FontFamily.HELVETICA, 11, Font.ITALIC);
  135.         Font white = new Font(FontFamily.HELVETICA, 12, Font.BOLD | Font.ITALIC, BaseColor.WHITE);
  136.         Paragraph p;
  137.         Chunk c;
  138.        
  139.         Set movies =
  140.             new TreeSet(new MovieComparator(MovieComparator.BY_YEAR));
  141.         movies.addAll(PojoFactory.getMovies(connection));
  142.         for (Movie movie : movies) {
  143.             p = new Paragraph(22);
  144.             c = new Chunk(String.format("%d ", movie.getYear()), bold);
  145.             c.setGenericTag("strip");
  146.             p.add(c);
  147.             c = new Chunk(movie.getMovieTitle());
  148.             c.setGenericTag(String.valueOf(movie.getYear()));
  149.             p.add(c);
  150.             c = new Chunk(String.format(" (%d minutes)  ", movie.getDuration()), italic);
  151.             p.add(c);
  152.             c = new Chunk("IMDB", white);
  153.             c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
  154.             c.setGenericTag("ellipse");
  155.             p.add(c);
  156.             document.add(p);
  157.         }
  158.         document.newPage();
  159.         writer.setPageEvent(null);
  160.         for (Map.Entry entry : event.years.entrySet()) {
  161.             p = new Paragraph(String.format("%s: %d movie(s)", entry.getKey(), entry.getValue()));
  162.             document.add(p);
  163.         }
  164.         // step 5
  165.         document.close();
  166.         // Close the database connection
  167.         connection.close();
  168.     }
  169.    
  170.     /**
  171.      * Main method.
  172.      * @param    args    no arguments needed
  173.      * @throws DocumentException
  174.      * @throws IOException
  175.      * @throws SQLException
  176.      */
  177.     public static void main(String[] args)
  178.         throws IOException, DocumentException, SQLException {
  179.         new MovieYears().createPdf(RESULT);
  180.     }
  181. }
MovieHistory1.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part1.chapter05;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13. import java.util.ArrayList;
  14. import java.util.List;
  15. import java.util.Set;
  16. import java.util.TreeSet;
  17.  
  18. import com.lowagie.database.DatabaseConnection;
  19. import com.lowagie.database.HsqldbConnection;
  20. import com.lowagie.filmfestival.Movie;
  21. import com.lowagie.filmfestival.MovieComparator;
  22. import com.lowagie.filmfestival.PojoFactory;
  23. import com.lowagie.filmfestival.PojoToElementFactory;
  24. import com.itextpdf.text.Chapter;
  25. import com.itextpdf.text.Document;
  26. import com.itextpdf.text.DocumentException;
  27. import com.itextpdf.text.Font;
  28. import com.itextpdf.text.Paragraph;
  29. import com.itextpdf.text.Section;
  30. import com.itextpdf.text.Font.FontFamily;
  31. import com.itextpdf.text.pdf.PdfContentByte;
  32. import com.itextpdf.text.pdf.PdfPageEventHelper;
  33. import com.itextpdf.text.pdf.PdfWriter;
  34.  
  35. public class MovieHistory1 {
  36.    
  37.     /** The resulting PDF file. */
  38.     public static final String RESULT
  39.         = "results/part1/chapter05/movie_history1.pdf";
  40.  
  41.     /**
  42.      * Inner class to keep track of the TOC
  43.      * and to draw lines under ever chapter and section.
  44.      */
  45.     class ChapterSectionTOC extends PdfPageEventHelper {
  46.         /** List with the titles. */
  47.         List titles = new ArrayList();
  48.        
  49.         public void onChapter(PdfWriter writer, Document document,
  50.                 float position, Paragraph title) {
  51.             titles.add(new Paragraph(title.getContent(), FONT[4]));
  52.         }
  53.  
  54.         public void onChapterEnd(PdfWriter writer, Document document,
  55.                 float position) {
  56.             drawLine(writer.getDirectContent(),
  57.                     document.left(), document.right(), position - 5);
  58.         }
  59.  
  60.         public void onSection(PdfWriter writer, Document document,
  61.                 float position, int depth, Paragraph title) {
  62.             title = new Paragraph(title.getContent(), FONT[4]);
  63.             title.setIndentationLeft(18 * depth);
  64.             titles.add(title);
  65.         }
  66.  
  67.         public void onSectionEnd(PdfWriter writer, Document document,
  68.                 float position) {
  69.             drawLine(writer.getDirectContent(),
  70.                     document.left(), document.right(), position - 3);
  71.         }
  72.        
  73.         public void drawLine(PdfContentByte cb, float x1, float x2, float y) {
  74.             cb.moveTo(x1, y);
  75.             cb.lineTo(x2, y);
  76.             cb.stroke();
  77.         }
  78.     }
  79.    
  80.     /** The different epochs. */
  81.     public static final String[] EPOCH =
  82.         { "Forties", "Fifties", "Sixties", "Seventies", "Eighties",
  83.           "Nineties", "Twenty-first Century" };
  84.     /** The fonts for the title. */
  85.     public static final Font[] FONT = new Font[5];
  86.     static {
  87.         FONT[0] = new Font(FontFamily.HELVETICA, 24);
  88.         FONT[1] = new Font(FontFamily.HELVETICA, 18);
  89.         FONT[2] = new Font(FontFamily.HELVETICA, 14);
  90.         FONT[3] = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
  91.         FONT[4] = new Font(FontFamily.HELVETICA, 10);
  92.     }
  93.  
  94.     /**
  95.      * Creates a PDF document.
  96.      * @param filename the path to the new PDF document
  97.      * @throws    DocumentException
  98.      * @throws    IOException
  99.      * @throws    SQLException
  100.      */
  101.     public void createPdf(String filename)
  102.         throws IOException, DocumentException, SQLException {
  103.         // Create a database connection
  104.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  105.         // step 1
  106.         Document document = new Document();
  107.         // step 2
  108.         PdfWriter writer
  109.             = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  110.         // IMPORTANT: set linear page mode!
  111.         writer.setLinearPageMode();
  112.         ChapterSectionTOC event = new ChapterSectionTOC();
  113.         writer.setPageEvent(event);
  114.         // step 3
  115.         document.open();
  116.         // step 4
  117.         // add the chapters
  118.         Set movies =
  119.             new TreeSet(new MovieComparator(MovieComparator.BY_YEAR));
  120.         movies.addAll(PojoFactory.getMovies(connection));
  121.         int epoch = -1;
  122.         int currentYear = 0;
  123.         Paragraph title = null;
  124.         Chapter chapter = null;
  125.         Section section = null;
  126.         Section subsection = null;
  127.         for (Movie movie : movies) {
  128.             if (epoch < (movie.getYear() - 1940) / 10) {
  129.                 epoch = (movie.getYear() - 1940) / 10;
  130.                 if (chapter != null) {
  131.                     document.add(chapter);
  132.                 }
  133.                 title = new Paragraph(EPOCH[epoch], FONT[0]);
  134.                 chapter = new Chapter(title, epoch + 1);
  135.             }
  136.             if (currentYear < movie.getYear()) {
  137.                 currentYear = movie.getYear();
  138.                 title = new Paragraph(
  139.                     String.format("The year %d", movie.getYear()), FONT[1]);
  140.                 section = chapter.addSection(title);
  141.                 section.setBookmarkTitle(String.valueOf(movie.getYear()));
  142.                 section.setIndentation(30);
  143.                 section.setBookmarkOpen(false);
  144.                 section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
  145.                 section.add(new Paragraph(
  146.                     String.format("Movies from the year %d:", movie.getYear())));
  147.             }
  148.             title = new Paragraph(movie.getMovieTitle(), FONT[2]);
  149.             subsection = section.addSection(title);
  150.             subsection.setIndentationLeft(20);
  151.             subsection.setNumberDepth(1);
  152.             subsection.add(new Paragraph("Duration: " + movie.getDuration(), FONT[3]));
  153.             subsection.add(new Paragraph("Director(s):", FONT[3]));
  154.             subsection.add(PojoToElementFactory.getDirectorList(movie));
  155.             subsection.add(new Paragraph("Countries:", FONT[3]));
  156.             subsection.add(PojoToElementFactory.getCountryList(movie));
  157.         }
  158.         document.add(chapter);
  159.         // add the TOC starting on the next page
  160.         document.newPage();
  161.         int toc = writer.getPageNumber();
  162.         for (Paragraph p : event.titles) {
  163.             document.add(p);
  164.         }
  165.         // always go to a new page before reordering pages.
  166.         document.newPage();
  167.         // get the total number of pages that needs to be reordered
  168.         int total = writer.reorderPages(null);
  169.         // change the order
  170.         int[] order = new int[total];
  171.         for (int i = 0; i < total; i++) {
  172.             order[i] = i + toc;
  173.             if (order[i] > total)
  174.                 order[i] -= total;
  175.         }
  176.         // apply the new order
  177.         writer.reorderPages(order);
  178.         // step 5
  179.         document.close();
  180.         // Close the database connection
  181.         connection.close();
  182.     }
  183.    
  184.     /**
  185.      * Main method.
  186.      *
  187.      * @param    args    no arguments needed
  188.      * @throws DocumentException
  189.      * @throws IOException
  190.      * @throws SQLException
  191.      */
  192.     public static void main(String[] args)
  193.         throws IOException, DocumentException, SQLException {
  194.         new MovieHistory1().createPdf(RESULT);
  195.     }
  196. }
NewPage.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part1.chapter05;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.Document;
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.Paragraph;
  16. import com.itextpdf.text.pdf.PdfWriter;
  17.  
  18. public class NewPage {
  19.    
  20.     /** Path to the resulting PDF file. */
  21.     public static final String RESULT
  22.         = "results/part1/chapter05/new_page.pdf";
  23.    
  24.     /**
  25.      * Main method creating the PDF.
  26.      * @param    args    no arguments needed
  27.      * @throws IOException
  28.      * @throws DocumentException
  29.      */
  30.     public static void main(String[] args) throws IOException, DocumentException {
  31.         // step 1
  32.         Document document = new Document();
  33.         // step 2
  34.         PdfWriter writer
  35.             = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  36.         // step 3
  37.         document.open();
  38.         // step 4
  39.         document.add(new Paragraph("This page will NOT be followed by a blank page!"));
  40.         document.newPage();
  41.         // we don't add anything to this page: newPage() will be ignored
  42.         document.newPage();
  43.         document.add(new Paragraph("This page will be followed by a blank page!"));
  44.         document.newPage();
  45.         writer.setPageEmpty(false);
  46.         document.newPage();
  47.         document.add(new Paragraph("The previous page was a blank page!"));
  48.         // step 5
  49.         document.close();
  50.        
  51.     }
  52. }
Hero1.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part1.chapter05;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.FileReader;
  12. import java.io.IOException;
  13.  
  14. import com.itextpdf.text.Document;
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.Rectangle;
  17. import com.itextpdf.text.pdf.PdfContentByte;
  18. import com.itextpdf.text.pdf.PdfTemplate;
  19. import com.itextpdf.text.pdf.PdfWriter;
  20.  
  21. public class Hero1 {
  22.  
  23.     /** The resulting PDF file. */
  24.     public static final String RESULT = "results/part1/chapter05/hero1.pdf";
  25.     /** Path to the resources. */
  26.     public static final String RESOURCE = "resources/txt/hero.txt";
  27.  
  28.     /**
  29.      * Creates a PDF document.
  30.      * @param filename the path to the new PDF document
  31.      * @throws    DocumentException
  32.      * @throws    IOException
  33.      */
  34.     public void createPdf(String filename)
  35.         throws IOException, DocumentException {
  36.         // step 1
  37.         Rectangle rect = new Rectangle(-1192, -1685, 1192, 1685);
  38.         Document document = new Document(rect);
  39.         // step 2
  40.         PdfWriter writer =
  41.             PdfWriter.getInstance(document, new FileOutputStream(filename));
  42.         // step 3
  43.         document.open();
  44.         // step 4
  45.         PdfContentByte content = writer.getDirectContent();
  46.         PdfTemplate template = createTemplate(content, rect, 4);
  47.         content.addTemplate(template, -1192, -1685);
  48.         content.moveTo(-595, 0);
  49.         content.lineTo(595, 0);
  50.         content.moveTo(0, -842);
  51.         content.lineTo(0, 842);
  52.         content.stroke();
  53.         // step 5
  54.         document.close();
  55.     }
  56.    
  57.     /**
  58.      * Creates a template based on a stream of PDF syntax.
  59.      * @param content The direct content
  60.      * @param rect The dimension of the templare
  61.      * @param factor A magnification factor
  62.      * @return A PdfTemplate
  63.      * @throws IOException
  64.      */
  65.     public PdfTemplate createTemplate(PdfContentByte content, Rectangle rect, int factor)
  66.         throws IOException {
  67.         PdfTemplate template = content.createTemplate(rect.getWidth(), rect.getHeight());
  68.         template.concatCTM(factor, 0, 0, factor, 0, 0);
  69.         FileReader reader = new FileReader(RESOURCE);
  70.         int c;
  71.         while ((c = reader.read()) > -1) {
  72.             template.setLiteral((char)c);
  73.         }
  74.         return template;
  75.     }
  76.  
  77.     /**
  78.      * Main method.
  79.      * @param    args    no arguments needed
  80.      * @throws DocumentException
  81.      * @throws IOException
  82.      */
  83.     public static void main(String[] args)
  84.         throws IOException, DocumentException {
  85.         new Hero1().createPdf(RESULT);
  86.     }
  87. }
Hero2.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part1.chapter05;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.Document;
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.PageSize;
  16. import com.itextpdf.text.Rectangle;
  17. import com.itextpdf.text.pdf.PdfContentByte;
  18. import com.itextpdf.text.pdf.PdfTemplate;
  19. import com.itextpdf.text.pdf.PdfWriter;
  20.  
  21. public class Hero2 extends Hero1 {
  22.  
  23.     /** The resulting PDF file. */
  24.     public static final String RESULT = "results/part1/chapter05/hero2.pdf";
  25.  
  26.     /**
  27.      * Creates a PDF document.
  28.      * @param filename the path to the new PDF document
  29.      * @throws    DocumentException
  30.      * @throws    IOException
  31.      */
  32.     public void createPdf(String filename) throws IOException, DocumentException {
  33.         float w = PageSize.A4.getWidth();
  34.         float h = PageSize.A4.getHeight();
  35.         Rectangle rect = new Rectangle(-2*w, -2*h, 2*w, 2*h);
  36.         Rectangle crop = new Rectangle(-2 * w, h, -w, 2 * h);
  37.         // step 1
  38.         Document document = new Document(rect);
  39.         // step 2
  40.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  41.         writer.setCropBoxSize(crop);
  42.         // step 3
  43.         document.open();
  44.         // step 4
  45.         PdfContentByte content = writer.getDirectContent();
  46.         PdfTemplate template = createTemplate(content, rect, 4);
  47.         float adjust;
  48.         while(true) {
  49.             content.addTemplate(template, -2*w, -2*h);
  50.             adjust = crop.getRight() + w;
  51.             if (adjust > 2 * w) {
  52.                 adjust = crop.getBottom() - h;
  53.                 if (adjust < - 2 * h)
  54.                     break;
  55.                 crop = new Rectangle(-2*w, adjust, -w, crop.getBottom());
  56.             }
  57.             else {
  58.                 crop = new Rectangle(crop.getRight(), crop.getBottom(), adjust, crop.getTop());
  59.             }
  60.             writer.setCropBoxSize(crop);
  61.             document.newPage();
  62.         }
  63.         // step 5
  64.         document.close();
  65.     }
  66.  
  67.     /**
  68.      * Main method.
  69.      * @param    args    no arguments needed
  70.      * @throws DocumentException
  71.      * @throws IOException
  72.      */
  73.     public static void main(String[] args)
  74.         throws IOException, DocumentException {
  75.         new Hero2().createPdf(RESULT);
  76.     }
  77. }
Hero3.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part1.chapter05;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.Document;
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.PageSize;
  16. import com.itextpdf.text.Rectangle;
  17. import com.itextpdf.text.pdf.PdfContentByte;
  18. import com.itextpdf.text.pdf.PdfTemplate;
  19. import com.itextpdf.text.pdf.PdfWriter;
  20.  
  21. public class Hero3 extends Hero1 {
  22.  
  23.     /** The resulting PDF file. */
  24.     public static final String RESULT = "results/part1/chapter05/hero3.pdf";
  25.  
  26.     /**
  27.      * Creates a PDF document.
  28.      * @param filename the path to the new PDF document
  29.      * @throws    DocumentException
  30.      * @throws    IOException
  31.      */
  32.     public void createPdf(String filename) throws IOException, DocumentException {
  33.         // step 1
  34.         Document document = new Document(PageSize.A4);
  35.         // step 2
  36.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  37.         Rectangle art = new Rectangle(50, 50, 545, 792);
  38.         writer.setBoxSize("art", art);
  39.         // step 3
  40.         document.open();
  41.         // step 4
  42.         PdfContentByte content = writer.getDirectContent();
  43.         PdfTemplate template = createTemplate(content, PageSize.A4, 1);
  44.         content.addTemplate(template, 0, 0);
  45.         // step 5
  46.         document.close();
  47.     }
  48.  
  49.     /**
  50.      * Main method.
  51.      * @param    args    no arguments needed
  52.      * @throws DocumentException
  53.      * @throws IOException
  54.      */
  55.     public static void main(String[] args)
  56.         throws IOException, DocumentException {
  57.         new Hero3().createPdf(RESULT);
  58.     }
  59. }
MovieHistory2.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part1.chapter05;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13. import java.util.Set;
  14. import java.util.TreeSet;
  15.  
  16. import com.lowagie.database.DatabaseConnection;
  17. import com.lowagie.database.HsqldbConnection;
  18. import com.lowagie.filmfestival.Movie;
  19. import com.lowagie.filmfestival.MovieComparator;
  20. import com.lowagie.filmfestival.PojoFactory;
  21. import com.lowagie.filmfestival.PojoToElementFactory;
  22. import com.itextpdf.text.Chapter;
  23. import com.itextpdf.text.Document;
  24. import com.itextpdf.text.DocumentException;
  25. import com.itextpdf.text.Element;
  26. import com.itextpdf.text.Font;
  27. import com.itextpdf.text.PageSize;
  28. import com.itextpdf.text.Paragraph;
  29. import com.itextpdf.text.Phrase;
  30. import com.itextpdf.text.Rectangle;
  31. import com.itextpdf.text.Section;
  32. import com.itextpdf.text.Font.FontFamily;
  33. import com.itextpdf.text.pdf.ColumnText;
  34. import com.itextpdf.text.pdf.PdfPageEventHelper;
  35. import com.itextpdf.text.pdf.PdfWriter;
  36.  
  37. public class MovieHistory2 {
  38.    
  39.     /** The resulting PDF file. */
  40.     public static final String RESULT
  41.         = "results/part1/chapter05/movie_history2.pdf";
  42.    
  43.     /** Inner class to add a header and a footer. */
  44.     class HeaderFooter extends PdfPageEventHelper {
  45.         /** Alternating phrase for the header. */
  46.         Phrase[] header = new Phrase[2];
  47.         /** Current page number (will be reset for every chapter). */
  48.         int pagenumber;
  49.        
  50.         /**
  51.          * Initialize one of the headers.
  52.          * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(
  53.          *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  54.          */
  55.         public void onOpenDocument(PdfWriter writer, Document document) {
  56.             header[0] = new Phrase("Movie history");
  57.         }
  58.        
  59.         /**
  60.          * Initialize one of the headers, based on the chapter title;
  61.          * reset the page number.
  62.          * @see com.itextpdf.text.pdf.PdfPageEventHelper#onChapter(
  63.          *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document, float,
  64.          *      com.itextpdf.text.Paragraph)
  65.          */
  66.         public void onChapter(PdfWriter writer, Document document,
  67.                 float paragraphPosition, Paragraph title) {
  68.             header[1] = new Phrase(title.getContent());
  69.             pagenumber = 1;
  70.         }
  71.  
  72.         /**
  73.          * Increase the page number.
  74.          * @see com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage(
  75.          *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  76.          */
  77.         public void onStartPage(PdfWriter writer, Document document) {
  78.             pagenumber++;
  79.         }
  80.        
  81.         /**
  82.          * Adds the header and the footer.
  83.          * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
  84.          *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  85.          */
  86.         public void onEndPage(PdfWriter writer, Document document) {
  87.             Rectangle rect = writer.getBoxSize("art");
  88.             switch(writer.getPageNumber() % 2) {
  89.             case 0:
  90.                 ColumnText.showTextAligned(writer.getDirectContent(),
  91.                         Element.ALIGN_RIGHT, header[0],
  92.                         rect.getRight(), rect.getTop(), 0);
  93.                 break;
  94.             case 1:
  95.                 ColumnText.showTextAligned(writer.getDirectContent(),
  96.                         Element.ALIGN_LEFT, header[1],
  97.                         rect.getLeft(), rect.getTop(), 0);
  98.                 break;
  99.             }
  100.             ColumnText.showTextAligned(writer.getDirectContent(),
  101.                     Element.ALIGN_CENTER, new Phrase(String.format("page %d", pagenumber)),
  102.                     (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
  103.         }
  104.     }
  105.    
  106.     /** The different epochs. */
  107.     public static final String[] EPOCH =
  108.         { "Forties", "Fifties", "Sixties", "Seventies", "Eighties",
  109.           "Nineties", "Twenty-first Century" };
  110.     /** The fonts for the title. */
  111.     public static final Font[] FONT = new Font[4];
  112.     static {
  113.         FONT[0] = new Font(FontFamily.HELVETICA, 24);
  114.         FONT[1] = new Font(FontFamily.HELVETICA, 18);
  115.         FONT[2] = new Font(FontFamily.HELVETICA, 14);
  116.         FONT[3] = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
  117.     }
  118.  
  119.     /**
  120.      * Creates a PDF document.
  121.      * @param filename the path to the new PDF document
  122.      * @throws    DocumentException
  123.      * @throws    IOException
  124.      * @throws    SQLException
  125.      */
  126.     public void createPdf(String filename)
  127.         throws IOException, DocumentException, SQLException {
  128.         // Create a database connection
  129.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  130.         // step 1
  131.         Document document = new Document(PageSize.A4, 36, 36, 54, 54);
  132.         // step 2
  133.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  134.         HeaderFooter event = new HeaderFooter();
  135.         writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
  136.         writer.setPageEvent(event);
  137.         // step 3
  138.         document.open();
  139.         // step 4
  140.         Set movies =
  141.             new TreeSet(new MovieComparator(MovieComparator.BY_YEAR));
  142.         movies.addAll(PojoFactory.getMovies(connection));
  143.         int epoch = -1;
  144.         int currentYear = 0;
  145.         Paragraph title = null;
  146.         Chapter chapter = null;
  147.         Section section = null;
  148.         Section subsection = null;
  149.         for (Movie movie : movies) {
  150.             if (epoch < (movie.getYear() - 1940) / 10) {
  151.                 epoch = (movie.getYear() - 1940) / 10;
  152.                 if (chapter != null) {
  153.                     document.add(chapter);
  154.                 }
  155.                 title = new Paragraph(EPOCH[epoch], FONT[0]);
  156.                 chapter = new Chapter(title, epoch + 1);
  157.             }
  158.             if (currentYear < movie.getYear()) {
  159.                 currentYear = movie.getYear();
  160.                 title = new Paragraph(String.format("The year %d", movie.getYear()), FONT[1]);
  161.                 section = chapter.addSection(title);
  162.                 section.setBookmarkTitle(String.valueOf(movie.getYear()));
  163.                 section.setIndentation(30);
  164.                 section.setBookmarkOpen(false);
  165.                 section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
  166.                 section.add(new Paragraph(String.format("Movies from the year %d:", movie.getYear())));
  167.             }
  168.             title = new Paragraph(movie.getMovieTitle(), FONT[2]);
  169.             subsection = section.addSection(title);
  170.             subsection.setIndentationLeft(20);
  171.             subsection.setNumberDepth(1);
  172.             subsection.add(new Paragraph("Duration: " + movie.getDuration(), FONT[3]));
  173.             subsection.add(new Paragraph("Director(s):", FONT[3]));
  174.             subsection.add(PojoToElementFactory.getDirectorList(movie));
  175.             subsection.add(new Paragraph("Countries:", FONT[3]));
  176.             subsection.add(PojoToElementFactory.getCountryList(movie));
  177.         }
  178.         document.add(chapter);
  179.         // step 5
  180.         document.close();
  181.         // close the database connection
  182.         connection.close();
  183.     }
  184.    
  185.     /**
  186.      * Main method.
  187.      *
  188.      * @param    args    no arguments needed
  189.      * @throws DocumentException
  190.      * @throws IOException
  191.      * @throws SQLException
  192.      */
  193.     public static void main(String[] args)
  194.         throws IOException, DocumentException, SQLException {
  195.         new MovieHistory2().createPdf(RESULT);
  196.     }
  197. }
MovieCountries1.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part1.chapter05;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15. import java.util.Set;
  16. import java.util.TreeSet;
  17.  
  18. import com.lowagie.database.DatabaseConnection;
  19. import com.lowagie.database.HsqldbConnection;
  20. import com.lowagie.filmfestival.FilmFonts;
  21. import com.lowagie.filmfestival.Movie;
  22. import com.lowagie.filmfestival.MovieComparator;
  23. import com.lowagie.filmfestival.PojoFactory;
  24. import com.lowagie.filmfestival.PojoToElementFactory;
  25. import com.itextpdf.text.Document;
  26. import com.itextpdf.text.DocumentException;
  27. import com.itextpdf.text.Element;
  28. import com.itextpdf.text.ExceptionConverter;
  29. import com.itextpdf.text.Image;
  30. import com.itextpdf.text.PageSize;
  31. import com.itextpdf.text.Paragraph;
  32. import com.itextpdf.text.Phrase;
  33. import com.itextpdf.text.Rectangle;
  34. import com.itextpdf.text.pdf.ColumnText;
  35. import com.itextpdf.text.pdf.PdfPCell;
  36. import com.itextpdf.text.pdf.PdfPTable;
  37. import com.itextpdf.text.pdf.PdfPageEventHelper;
  38. import com.itextpdf.text.pdf.PdfTemplate;
  39. import com.itextpdf.text.pdf.PdfWriter;
  40.  
  41. public class MovieCountries1 {
  42.    
  43.     /** The resulting PDF file. */
  44.     public static final String RESULT
  45.         = "results/part1/chapter05/movie_countries1.pdf";
  46.  
  47.     /**
  48.      * Inner class to add a table as header.
  49.      */
  50.     class TableHeader extends PdfPageEventHelper {
  51.         /** The header text. */
  52.         String header;
  53.         /** The template with the total number of pages. */
  54.         PdfTemplate total;
  55.        
  56.         /**
  57.          * Allows us to change the content of the header.
  58.          * @param header The new header String
  59.          */
  60.         public void setHeader(String header) {
  61.             this.header = header;
  62.         }
  63.  
  64.         /**
  65.          * Creates the PdfTemplate that will hold the total number of pages.
  66.          * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(
  67.          *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  68.          */
  69.         public void onOpenDocument(PdfWriter writer, Document document) {
  70.             total = writer.getDirectContent().createTemplate(30, 16);
  71.         }
  72.        
  73.         /**
  74.          * Adds a header to every page
  75.          * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
  76.          *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  77.          */
  78.         public void onEndPage(PdfWriter writer, Document document) {
  79.             PdfPTable table = new PdfPTable(3);
  80.             try {
  81.                 table.setWidths(new int[]{24, 24, 2});
  82.                 table.setTotalWidth(527);
  83.                 table.setLockedWidth(true);
  84.                 table.getDefaultCell().setFixedHeight(20);
  85.                 table.getDefaultCell().setBorder(Rectangle.BOTTOM);
  86.                 table.addCell(header);
  87.                 table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
  88.                 table.addCell(String.format("Page %d of", writer.getPageNumber()));
  89.                 PdfPCell cell = new PdfPCell(Image.getInstance(total));
  90.                 cell.setBorder(Rectangle.BOTTOM);
  91.                 table.addCell(cell);
  92.                 table.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());
  93.             }
  94.             catch(DocumentException de) {
  95.                 throw new ExceptionConverter(de);
  96.             }
  97.         }
  98.        
  99.         /**
  100.          * Fills out the total number of pages before the document is closed.
  101.          * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(
  102.          *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  103.          */
  104.         public void onCloseDocument(PdfWriter writer, Document document) {
  105.             ColumnText.showTextAligned(total, Element.ALIGN_LEFT,
  106.                     new Phrase(String.valueOf(writer.getPageNumber() - 1)),
  107.                     2, 2, 0);
  108.         }
  109.     }
  110.  
  111.     /**
  112.      * Creates a PDF document.
  113.      * @param filename the path to the new PDF document
  114.      * @throws    DocumentException
  115.      * @throws    IOException
  116.      * @throws    SQLException
  117.      */
  118.     public void createPdf(String filename)
  119.         throws IOException, DocumentException, SQLException {
  120.         // Create a database connection
  121.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  122.         // step 1
  123.         Document document = new Document(PageSize.A4, 36, 36, 54, 36);
  124.         // step 2
  125.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  126.         TableHeader event = new TableHeader();
  127.         writer.setPageEvent(event);
  128.         // step 3
  129.         document.open();
  130.         // step 4
  131.         Statement stm = connection.createStatement();
  132.         ResultSet rs = stm.executeQuery(
  133.             "SELECT country, id FROM film_country ORDER BY country");
  134.         while (rs.next()) {
  135.             event.setHeader(rs.getString("country"));
  136.             Set movies =
  137.                 new TreeSet(new MovieComparator(MovieComparator.BY_YEAR));
  138.             movies.addAll(PojoFactory.getMovies(connection, rs.getString("id")));
  139.             for(Movie movie : movies) {
  140.                 document.add(new Paragraph(movie.getMovieTitle(), FilmFonts.BOLD));
  141.                 if (movie.getOriginalTitle() != null)
  142.                     document.add(new Paragraph(movie.getOriginalTitle(), FilmFonts.ITALIC));
  143.                 document.add(new Paragraph(
  144.                     String.format("Year: %d; run length: %d minutes",
  145.                         movie.getYear(), movie.getDuration()), FilmFonts.NORMAL));
  146.                 document.add(PojoToElementFactory.getDirectorList(movie));
  147.             }
  148.             document.newPage();
  149.         }
  150.         // step 4
  151.         document.close();
  152.         // close the database connection
  153.         connection.close();
  154.     }
  155.    
  156.     /**
  157.      * Main method.
  158.      *
  159.      * @param    args    no arguments needed
  160.      * @throws DocumentException
  161.      * @throws IOException
  162.      * @throws SQLException
  163.      */
  164.     public static void main(String[] args)
  165.         throws IOException, DocumentException, SQLException {
  166.         new MovieCountries1().createPdf(RESULT);
  167.     }
  168. }
MovieCountries2.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part1.chapter05;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15. import java.util.Set;
  16. import java.util.TreeSet;
  17.  
  18. import com.lowagie.database.DatabaseConnection;
  19. import com.lowagie.database.HsqldbConnection;
  20. import com.lowagie.filmfestival.FilmFonts;
  21. import com.lowagie.filmfestival.Movie;
  22. import com.lowagie.filmfestival.MovieComparator;
  23. import com.lowagie.filmfestival.PojoFactory;
  24. import com.lowagie.filmfestival.PojoToElementFactory;
  25. import com.itextpdf.text.Document;
  26. import com.itextpdf.text.DocumentException;
  27. import com.itextpdf.text.Element;
  28. import com.itextpdf.text.Font;
  29. import com.itextpdf.text.PageSize;
  30. import com.itextpdf.text.Paragraph;
  31. import com.itextpdf.text.Phrase;
  32. import com.itextpdf.text.Font.FontFamily;
  33. import com.itextpdf.text.pdf.ColumnText;
  34. import com.itextpdf.text.pdf.GrayColor;
  35. import com.itextpdf.text.pdf.PdfPageEventHelper;
  36. import com.itextpdf.text.pdf.PdfWriter;
  37.  
  38. public class MovieCountries2 extends MovieCountries1 {
  39.    
  40.     /** The resulting PDF file. */
  41.     public static final String RESULT
  42.         = "results/part1/chapter05/movie_countries2.pdf";
  43.  
  44.     /**
  45.      * Inner class to add a watermark to every page.
  46.      */
  47.     class Watermark extends PdfPageEventHelper {
  48.        
  49.         Font FONT = new Font(FontFamily.HELVETICA, 52, Font.BOLD, new GrayColor(0.75f));
  50.        
  51.         public void onEndPage(PdfWriter writer, Document document) {
  52.             ColumnText.showTextAligned(writer.getDirectContentUnder(),
  53.                     Element.ALIGN_CENTER, new Phrase("FOOBAR FILM FESTIVAL", FONT),
  54.                     297.5f, 421, writer.getPageNumber() % 2 == 1 ? 45 : -45);
  55.         }
  56.     }
  57.  
  58.     /**
  59.      * Creates a PDF document.
  60.      * @param filename the path to the new PDF document
  61.      * @throws    DocumentException
  62.      * @throws    IOException
  63.      * @throws    SQLException
  64.      */
  65.     public void createPdf(String filename)
  66.         throws IOException, DocumentException, SQLException {
  67.         // Create a database connection
  68.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  69.         // step 1
  70.         Document document = new Document(PageSize.A4, 36, 36, 54, 36);
  71.         // step 2
  72.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  73.         TableHeader event = new TableHeader();
  74.         writer.setPageEvent(event);
  75.         writer.setPageEvent(new Watermark());
  76.         // step 3
  77.         document.open();
  78.         // step 4
  79.         Statement stm = connection.createStatement();
  80.         ResultSet rs = stm.executeQuery(
  81.             "SELECT country, id FROM film_country ORDER BY country");
  82.         while (rs.next()) {
  83.             event.setHeader(rs.getString("country"));
  84.             Set movies =
  85.                 new TreeSet(new MovieComparator(MovieComparator.BY_YEAR));
  86.             movies.addAll(PojoFactory.getMovies(connection, rs.getString("id")));
  87.             for(Movie movie : movies) {
  88.                 document.add(new Paragraph(movie.getMovieTitle(), FilmFonts.BOLD));
  89.                 if (movie.getOriginalTitle() != null)
  90.                     document.add(new Paragraph(movie.getOriginalTitle(), FilmFonts.ITALIC));
  91.                 document.add(new Paragraph(String.format("Year: %d; run length: %d minutes",
  92.                     movie.getYear(), movie.getDuration()), FilmFonts.NORMAL));
  93.                 document.add(PojoToElementFactory.getDirectorList(movie));
  94.             }
  95.             document.newPage();
  96.         }
  97.         // step 5
  98.         document.close();
  99.         // close the database connection
  100.         connection.close();
  101.     }
  102.    
  103.     /**
  104.      * Main method.
  105.      *
  106.      * @param    args    no arguments needed
  107.      * @throws DocumentException
  108.      * @throws IOException
  109.      * @throws SQLException
  110.      */
  111.     public static void main(String[] args)
  112.         throws IOException, DocumentException, SQLException {
  113.         new MovieCountries2().createPdf(RESULT);
  114.     }
  115. }
MovieSlideShow.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part1.chapter05;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13. import java.util.List;
  14.  
  15. import com.lowagie.database.DatabaseConnection;
  16. import com.lowagie.database.HsqldbConnection;
  17. import com.lowagie.filmfestival.Movie;
  18. import com.lowagie.filmfestival.PojoFactory;
  19. import com.itextpdf.text.Document;
  20. import com.itextpdf.text.DocumentException;
  21. import com.itextpdf.text.Image;
  22. import com.itextpdf.text.PageSize;
  23. import com.itextpdf.text.pdf.PdfPCell;
  24. import com.itextpdf.text.pdf.PdfPTable;
  25. import com.itextpdf.text.pdf.PdfPageEventHelper;
  26. import com.itextpdf.text.pdf.PdfTransition;
  27. import com.itextpdf.text.pdf.PdfWriter;
  28.  
  29. public class MovieSlideShow {
  30.     /** The resulting PDF file. */
  31.     public static final String RESULT = "results/part1/chapter05/movie_slides.pdf";
  32.     /** Path to the resources. */
  33.     public static final String RESOURCE = "resources/posters/%s.jpg";
  34.    
  35.    
  36.     /**
  37.      * Page event to set the transition and duration for every page.
  38.      */
  39.     class TransitionDuration extends PdfPageEventHelper {
  40.  
  41.         public void onStartPage(PdfWriter writer, Document document) {
  42.             writer.setTransition(new PdfTransition(PdfTransition.DISSOLVE, 3));
  43.             writer.setDuration(5);
  44.         }
  45.        
  46.     }
  47.        
  48.     /**
  49.      * Creates a PDF with information about the movies
  50.      * @param    filename the name of the PDF file that will be created.
  51.      * @throws    DocumentException
  52.      * @throws    IOException
  53.      * @throws    SQLException
  54.      */
  55.     public void createPdf(String filename)
  56.         throws IOException, DocumentException, SQLException {
  57.         // Create a database connection
  58.         DatabaseConnection connection = new HsqldbConnection("filmfestival");    
  59.         // step 1
  60.         Document document = new Document(PageSize.A5.rotate());
  61.         // step 2
  62.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  63.         writer.setPdfVersion(PdfWriter.VERSION_1_5);
  64.         writer.setViewerPreferences(PdfWriter.PageModeFullScreen);
  65.         writer.setPageEvent(new TransitionDuration());
  66.         // step 3
  67.         document.open();
  68.         // step 4
  69.         List movies = PojoFactory.getMovies(connection);
  70.         Image img;
  71.         PdfPCell cell;
  72.         PdfPTable table = new PdfPTable(6);
  73.         for (Movie movie : movies) {
  74.             img = Image.getInstance(String.format(RESOURCE, movie.getImdb()));
  75.             cell = new PdfPCell(img, true);
  76.             cell.setBorder(PdfPCell.NO_BORDER);
  77.             table.addCell(cell);
  78.         }
  79.         document.add(table);
  80.         // step 5
  81.         document.close();
  82.         // Close the database connection
  83.         connection.close();
  84.     }
  85.    
  86.     /**
  87.      * Main method creating the PDF.
  88.      * @param    args    no arguments needed
  89.      * @throws IOException
  90.      * @throws DocumentException
  91.      * @throws SQLException
  92.      */
  93.     public static void main(String[] args)
  94.         throws IOException, SQLException, DocumentException {
  95.         new MovieSlideShow().createPdf(RESULT);
  96.     }
  97. }
AlternatingBackground.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter05 {
  15.   public class AlternatingBackground : IWriter, IPdfPTableEvent {
  16. // ===========================================================================
  17.     public void Write(Stream stream) {
  18.       // step 1
  19.       using (Document document = new Document(PageSize.A4.Rotate())) {
  20.         // step 2
  21.         PdfWriter.GetInstance(document, stream);
  22.         // step 3
  23.         document.Open();
  24.         // step 4
  25.         List days = PojoFactory.GetDays();
  26.         IPdfPTableEvent Pevent = new AlternatingBackground();
  27.         foreach (string day in days) {
  28.           PdfPTable table = GetTable(day);
  29.           table.TableEvent = Pevent;
  30.           document.Add(table);
  31.           document.NewPage();
  32.         }
  33.       }
  34.     }
  35. // ---------------------------------------------------------------------------
  36.     /**
  37.      * Creates a table with film festival screenings.
  38.      * @param day a film festival day
  39.      * @return a table with screenings.
  40.      */
  41.     public PdfPTable GetTable(string day) {
  42.       PdfPTable table = new PdfPTable(new float[] { 2, 1, 2, 5, 1 });
  43.       table.WidthPercentage = 100f;
  44.       table.DefaultCell.Padding = 3;
  45.       table.DefaultCell.UseAscender = true;
  46.       table.DefaultCell.UseDescender = true;
  47.       table.DefaultCell.Colspan = 5;
  48.       table.DefaultCell.BackgroundColor = BaseColor.RED;
  49.       table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
  50.       table.AddCell(day);
  51.       table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
  52.       table.DefaultCell.Colspan = 1;
  53.       table.DefaultCell.BackgroundColor = BaseColor.ORANGE;
  54.       for (int i = 0; i < 2; i++) {
  55.         table.AddCell("Location");
  56.         table.AddCell("Time");
  57.         table.AddCell("Run Length");
  58.         table.AddCell("Title");
  59.         table.AddCell("Year");
  60.       }
  61.       table.DefaultCell.BackgroundColor = null;
  62.       table.HeaderRows = 3;
  63.       table.FooterRows = 1;
  64.       List screenings = PojoFactory.GetScreenings(day);
  65.       Movie movie;
  66.       foreach (Screening screening in screenings) {
  67.         movie = screening.movie;
  68.         table.AddCell(screening.Location);
  69.         table.AddCell(screening.Time.Substring(0, 5));
  70.         table.AddCell(movie.Duration.ToString() + " '");
  71.         table.AddCell(movie.MovieTitle);
  72.         table.AddCell(movie.Year.ToString());
  73.       }
  74.       return table;
  75.     }
  76. // ---------------------------------------------------------------------------
  77.     /**
  78.      * Draws a background for every other row.
  79.      * @see com.itextpdf.text.pdf.PdfPTableEvent#tableLayout(
  80.      *      com.itextpdf.text.pdf.PdfPTable, float[][], float[], int, int,
  81.      *      com.itextpdf.text.pdf.PdfContentByte[])
  82.      */
  83.     public void TableLayout(
  84.       PdfPTable table, float[][] widths, float[] heights,
  85.       int headerRows, int rowStart, PdfContentByte[] canvases
  86.     ) {
  87.       int columns;
  88.       Rectangle rect;
  89.       int footer = widths.Length - table.FooterRows;
  90.       int header = table.HeaderRows - table.FooterRows + 1;
  91.       for (int row = header; row < footer; row += 2) {
  92.         columns = widths[row].Length - 1;
  93.         rect = new Rectangle(
  94.           widths[row][0], heights[row],
  95.           widths[row][columns], heights[row + 1]
  96.         );
  97.         rect.BackgroundColor = BaseColor.YELLOW;
  98.         rect.Border = Rectangle.NO_BORDER;
  99.         canvases[PdfPTable.BASECANVAS].Rectangle(rect);
  100.       }
  101.     }    
  102. // ===========================================================================
  103.   }
  104. }
RunLengthEvent.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter05 {
  16.   public class RunLengthEvent : IWriter {
  17. // ===========================================================================
  18.     /** Inner class to draw a bar inside a cell. */
  19.     class RunLength : IPdfPCellEvent {
  20.       public int duration;
  21.      
  22.       public RunLength(int duration) {
  23.         this.duration = duration;
  24.       }
  25.      
  26.       /**
  27.        * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(
  28.        *      com.lowagie.text.pdf.PdfPCell, com.lowagie.text.Rectangle,
  29.        *      com.lowagie.text.pdf.PdfContentByte[])
  30.        */
  31.       public void CellLayout(
  32.         PdfPCell cell, Rectangle rect, PdfContentByte[] canvas
  33.       ) {
  34.         PdfContentByte cb = canvas[PdfPTable.BACKGROUNDCANVAS];
  35.         cb.SaveState();
  36.         if (duration < 90) {
  37.           cb.SetRGBColorFill(0x7C, 0xFC, 0x00);
  38.         }
  39.         else if (duration > 120) {
  40.           cb.SetRGBColorFill(0x8B, 0x00, 0x00);
  41.         }
  42.         else {
  43.           cb.SetRGBColorFill(0xFF, 0xA5, 0x00);
  44.         }
  45.         cb.Rectangle(
  46.           rect.Left, rect.Bottom,
  47.           rect.Width * duration / 240, rect.Height
  48.         );
  49.         cb.Fill();
  50.         cb.RestoreState();
  51.       }
  52.     }
  53. /*
  54.  * end inner class
  55. */
  56.     /** Inner class to add the words PRESS PREVIEW to a cell. */
  57.     class PressPreview : IPdfPCellEvent {
  58.       public BaseFont bf;
  59.       public PressPreview() {
  60.         bf = BaseFont.CreateFont();
  61.       }
  62.      
  63.       /**
  64.        * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(com.lowagie.text.pdf.PdfPCell,
  65.        *      com.lowagie.text.Rectangle,
  66.        *      com.lowagie.text.pdf.PdfContentByte[])
  67.        */
  68.       public void CellLayout(
  69.         PdfPCell cell, Rectangle rect, PdfContentByte[] canvas
  70.       ) {
  71.         PdfContentByte cb = canvas[PdfPTable.TEXTCANVAS];
  72.         cb.BeginText();
  73.         cb.SetFontAndSize(bf, 12);
  74.         cb.ShowTextAligned(
  75.           Element.ALIGN_RIGHT, "PRESS PREVIEW",
  76.           rect.Right - 3,
  77.           rect.Bottom + 4.5f, 0
  78.         );
  79.         cb.EndText();
  80.       }
  81.     }
  82. /*
  83.  * end inner class
  84. */  
  85. // ---------------------------------------------------------------------------
  86.     /** The press cell event. */
  87.     public IPdfPCellEvent press;
  88.     public void Write(Stream stream) {
  89.       press = new PressPreview();
  90.       // step 1
  91.       using (Document document = new Document(PageSize.A4.Rotate())) {
  92.         // step 2
  93.         PdfWriter.GetInstance(document, stream);      
  94.         // step 3
  95.         document.Open();
  96.         // step 4
  97.         List days = PojoFactory.GetDays();
  98.         foreach (string day in days) {
  99.           document.Add(GetTable(day));
  100.           document.NewPage();
  101.         }        
  102.       }
  103.     }
  104. // ---------------------------------------------------------------------------
  105.     /**
  106.      * @param connection
  107.      * @param day
  108.      * @return
  109.      * @throws SQLException
  110.      * @throws DocumentException
  111.      * @throws IOException
  112.      */
  113.     public PdfPTable GetTable(string day) {
  114.       PdfPTable table = new PdfPTable(new float[] { 2, 1, 2, 5, 1 });
  115.       table.WidthPercentage = 100f;
  116.       table.DefaultCell.Padding = 3;
  117.       table.DefaultCell.UseAscender = true;
  118.       table.DefaultCell.UseDescender = true;
  119.       table.DefaultCell.Colspan = 5;
  120.       table.DefaultCell.BackgroundColor = BaseColor.RED;
  121.       table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
  122.       table.AddCell(day);
  123.       table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
  124.       table.DefaultCell.Colspan = 1;
  125.       table.DefaultCell.BackgroundColor = BaseColor.YELLOW;
  126.       for (int i = 0; i < 2; i++) {
  127.         table.AddCell("Location");
  128.         table.AddCell("Time");
  129.         table.AddCell("Run Length");
  130.         table.AddCell("Title");
  131.         table.AddCell("Year");
  132.       }
  133.       table.DefaultCell.BackgroundColor = null;
  134.       table.HeaderRows = 3;
  135.       table.FooterRows = 1;
  136.       List screenings = PojoFactory.GetScreenings(day);
  137.       Movie movie;
  138.       PdfPCell runLength;
  139.       foreach (Screening screening in screenings) {
  140.         movie = screening.movie;
  141.         table.AddCell(screening.Location);
  142.         table.AddCell(screening.Time.Substring(0, 5));
  143.         runLength = new PdfPCell(table.DefaultCell);
  144.         runLength.Phrase = new Phrase(String.Format(
  145.           "{0} '", movie.Duration
  146.         ));
  147.         runLength.CellEvent = new RunLength(movie.Duration);
  148.         if (screening.Press) {
  149.           runLength.CellEvent = press;
  150.         }
  151.         table.AddCell(runLength);
  152.         table.AddCell(movie.MovieTitle);
  153.         table.AddCell(movie.Year.ToString());
  154.       }
  155.       return table;
  156.     }
  157. // ===========================================================================
  158.   }
  159. }
PressPreviews.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter05 {
  15.   public class PressPreviews : IWriter, IPdfPCellEvent, IPdfPTableEvent {
  16. // ===========================================================================
  17.     /**
  18.      * @see com.itextpdf.text.pdf.PdfPTableEvent#tableLayout(com.itextpdf.text.pdf.PdfPTable,
  19.      *      float[][], float[], int, int, com.itextpdf.text.pdf.PdfContentByte[])
  20.      */
  21.     public void TableLayout(
  22.       PdfPTable table, float[][] width, float[] height,
  23.       int headerRows, int rowStart, PdfContentByte[] canvas
  24.     ) {
  25.       float[] widths = width[0];
  26.       float x1 = widths[0];
  27.       float x2 = widths[widths.Length - 1];
  28.       float y1 = height[0];
  29.       float y2 = height[height.Length - 1];
  30.       PdfContentByte cb = canvas[PdfPTable.LINECANVAS];
  31.       cb.Rectangle(x1, y1, x2 - x1, y2 - y1);
  32.       cb.Stroke();
  33.       cb.ResetRGBColorStroke();
  34.     }
  35.  
  36.     /**
  37.      * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(com.lowagie.text.pdf.PdfPCell,
  38.      *      com.lowagie.text.Rectangle, com.lowagie.text.pdf.PdfContentByte[])
  39.      */
  40.     public void CellLayout(
  41.       PdfPCell cell, Rectangle position, PdfContentByte[] canvases
  42.     ) {
  43.       float x1 = position.Left + 2;
  44.       float x2 = position.Right - 2;
  45.       float y1 = position.Top - 2;
  46.       float y2 = position.Bottom + 2;
  47.       PdfContentByte canvas = canvases[PdfPTable.LINECANVAS];
  48.       canvas.Rectangle(x1, y1, x2 - x1, y2 - y1);
  49.       canvas.Stroke();
  50.       canvas.ResetRGBColorStroke();
  51.     }
  52. // ---------------------------------------------------------------------------
  53.     public void Write(Stream stream) {
  54.       // step 1
  55.       using (Document document = new Document(PageSize.A4.Rotate())) {
  56.         // step 2
  57.         PdfWriter.GetInstance(document, stream);
  58.         // step 3
  59.         document.Open();
  60.         // step 4
  61.         document.Add(GetTable());
  62.       }
  63.     }
  64. // ---------------------------------------------------------------------------
  65.     /**
  66.      * Creates a table that mimics cellspacing using table and cell events.
  67.      * @param connection
  68.      * @return a table
  69.      * @throws SQLException
  70.      * @throws DocumentException
  71.      * @throws IOException
  72.      */
  73.     public PdfPTable GetTable() {
  74.       PdfPTable table = new PdfPTable(new float[] { 1, 2, 2, 5, 1 });
  75.       table.TableEvent = new PressPreviews();
  76.       table.WidthPercentage = 100f;
  77.       table.DefaultCell.Padding = 5;
  78.       table.DefaultCell.Border = PdfPCell.NO_BORDER;
  79.       table.DefaultCell.CellEvent = new PressPreviews();
  80.       for (int i = 0; i < 2; i++) {
  81.         table.AddCell("Location");
  82.         table.AddCell("Date/Time");
  83.         table.AddCell("Run Length");
  84.         table.AddCell("Title");
  85.         table.AddCell("Year");
  86.       }
  87.       table.DefaultCell.BackgroundColor = null;
  88.       table.HeaderRows = 2;
  89.       table.FooterRows = 1;
  90.       List screenings = PojoFactory.GetPressPreviews();
  91.       foreach (Screening screening in screenings) {
  92.         Movie movie = screening.movie;
  93.         table.AddCell(screening.Location);
  94.         table.AddCell(String.Format(
  95.           "{0}   {1}", screening.Date,
  96.           screening.Time.Substring(0, 5)
  97.         ));
  98.         table.AddCell(String.Format("{0} '", movie.Duration));
  99.         table.AddCell(movie.MovieTitle);
  100.         table.AddCell(movie.Year.ToString());
  101.       }
  102.       return table;
  103.     }    
  104. // ===========================================================================
  105.   }
  106. }
PdfCalendar.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Globalization;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using iTextSharp.text.pdf.draw;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter05 {
  15.   public class PdfCalendar : kuujinbo.iTextInAction2Ed.Chapter04.PdfCalendar {
  16. // ===========================================================================
  17.     /** A table event. */
  18.     public IPdfPTableEvent tableBackground;
  19.     /** A cell event. */
  20.     public IPdfPCellEvent cellBackground;
  21.     /** A cell event. */
  22.     public IPdfPCellEvent roundRectangle;
  23.     /** A cell event. */
  24.     public IPdfPCellEvent whiteRectangle;
  25.     /**
  26.      * Inner class with a table event that draws a background with rounded corners.
  27.      */
  28.     class TableBackground : IPdfPTableEvent {
  29.       public void TableLayout(
  30.         PdfPTable table, float[][] width, float[] height,
  31.         int headerRows, int rowStart, PdfContentByte[] canvas
  32.       ) {
  33.         PdfContentByte background = canvas[PdfPTable.BASECANVAS];
  34.         background.SaveState();
  35.         background.SetCMYKColorFill(0x00, 0x00, 0xFF, 0x0F);
  36.         background.RoundRectangle(
  37.           width[0][0], height[height.Length - 1] - 2,
  38.           width[0][1] - width[0][0] + 6,
  39.           height[0] - height[height.Length - 1] - 4, 4
  40.         );
  41.         background.Fill();
  42.         background.RestoreState();
  43.       }
  44.     }
  45. /*
  46.  * end inner class
  47. */    
  48.     /**
  49.      * Inner class with a cell event that draws a background with rounded corners.
  50.      */
  51.     class CellBackground : IPdfPCellEvent {
  52.       public void CellLayout(
  53.         PdfPCell cell, Rectangle rect, PdfContentByte[] canvas
  54.     ) {
  55.         PdfContentByte cb = canvas[PdfPTable.BACKGROUNDCANVAS];
  56.         cb.RoundRectangle(
  57.           rect.Left + 1.5f,
  58.           rect.Bottom + 1.5f,
  59.           rect.Width - 3,
  60.           rect.Height - 3, 4
  61.         );
  62.         cb.SetCMYKColorFill(0x00, 0x00, 0x00, 0x00);
  63.         cb.Fill();
  64.       }
  65.     }
  66. /*
  67.  * end inner class
  68. */
  69.     /**
  70.      * Inner class with a cell event that draws a border with rounded corners.
  71.      */
  72.     class RoundRectangle : IPdfPCellEvent {
  73.       /** the border color described as CMYK values. */
  74.       protected int[] color;
  75.       /** Constructs the event using a certain color. */
  76.       public RoundRectangle(int[] color) {
  77.         this.color = color;
  78.       }
  79.      
  80.       public void CellLayout(
  81.         PdfPCell cell, Rectangle rect, PdfContentByte[] canvas
  82.       ) {
  83.         PdfContentByte cb = canvas[PdfPTable.LINECANVAS];
  84.         cb.RoundRectangle(
  85.           rect.Left + 1.5f,
  86.           rect.Bottom + 1.5f,
  87.           rect.Width - 3,
  88.           rect.Height - 3, 4
  89.         );
  90.         cb.SetLineWidth(1.5f);
  91.         cb.SetCMYKColorStrokeF(color[0], color[1], color[2], color[3]);
  92.         cb.Stroke();
  93.       }
  94.     }
  95. /*
  96.  * end inner class
  97. */
  98. // ---------------------------------------------------------------------------
  99.     /**
  100.      * Initializes the fonts and collections.
  101.      */
  102.     public PdfCalendar() : base() {
  103.       tableBackground = new TableBackground();
  104.       cellBackground = new CellBackground();
  105.       roundRectangle = new RoundRectangle(new int[]{ 0xFF, 0x00, 0xFF, 0x00 });
  106.       whiteRectangle = new RoundRectangle(new int[]{ 0x00, 0x00, 0x00, 0x00 });
  107.     }
  108.  
  109.     public override void Write(Stream stream) {
  110.       // step 1
  111.       using (Document document = new Document(PageSize.A4.Rotate())) {
  112.         // step 2
  113.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  114.         // step 3
  115.         document.Open();
  116.         // step 4
  117.         // "en" => System.Globalization.GregorianCalendar
  118.         Calendar calendar = new CultureInfo(LANGUAGE, false).Calendar;
  119.         PdfPTable table;
  120.         PdfContentByte canvas = writer.DirectContent;
  121.         // Loop over the months
  122.         for (int month = 0; month < 12; month++) {
  123.           int current_month = month + 1;
  124.           DateTime dt = new DateTime(YEAR, current_month, 1, calendar);
  125.           // draw the background
  126.           DrawImageAndText(canvas, dt);
  127.           // create a table with 7 columns
  128.           table = new PdfPTable(7);
  129.           table.TableEvent = tableBackground;
  130.           table.TotalWidth = 504;
  131.           // add the name of the month
  132.           table.DefaultCell.Border  = PdfPCell.NO_BORDER;
  133.           table.DefaultCell.CellEvent = whiteRectangle;
  134.           table.AddCell(GetMonthCell(dt));
  135.           int daysInMonth = DateTime.DaysInMonth(YEAR, dt.Month);
  136.           int day = 1;
  137.           // add empty cells
  138.           // SUNDAY; Java => 1, .NET => 0
  139.           int position = 0;
  140.           while (position++ != (int) dt.DayOfWeek) {
  141.             table.AddCell("");
  142.           }
  143.           // add cells for each day
  144.           while (day
MovieYears.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter05 {
  16.   public class MovieYears : IWriter {
  17. // ===========================================================================
  18.     /**
  19.      * Inner class to add functionality to a Chunk in a generic way.
  20.      */
  21.     class GenericTags : PdfPageEventHelper {
  22.       public override void OnGenericTag(
  23.         PdfWriter writer, Document pdfDocument, Rectangle rect, String text
  24.     ) {
  25.         if ("strip".Equals(text)) {
  26.           Strip(writer.DirectContent, rect);
  27.         }
  28.         else if ("ellipse".Equals(text)) {
  29.           Ellipse(writer.DirectContentUnder, rect);
  30.         }
  31.         else {
  32.           CountYear(text);
  33.         }
  34.       }
  35.  
  36.       public void Strip(PdfContentByte content, Rectangle rect) {
  37.         content.Rectangle(
  38.           rect.Left - 1, rect.Bottom - 5f,
  39.           rect.Width, rect.Height + 8
  40.         );
  41.         content.Rectangle(
  42.           rect.Left, rect.Bottom - 2,
  43.           rect.Width - 2, rect.Height + 2
  44.         );
  45.         float y1 = rect.Top + 0.5f;
  46.         float y2 = rect.Bottom - 4;
  47.         for (float f = rect.Left; f < rect.Right - 4; f += 5) {
  48.           content.Rectangle(f, y1, 4f, 1.5f);
  49.           content.Rectangle(f, y2, 4f, 1.5f);
  50.         }
  51.         content.EoFill();
  52.       }
  53.      
  54.       public void Ellipse(PdfContentByte content, Rectangle rect) {
  55.         content.SaveState();
  56.         content.SetRGBColorFill(0x00, 0x00, 0xFF);
  57.         content.Ellipse(
  58.           rect.Left - 3f, rect.Bottom - 5f,
  59.           rect.Right + 3f, rect.Top + 3f
  60.         );
  61.         content.Fill();
  62.         content.RestoreState();
  63.       }
  64.  
  65.       internal SortedDictionary years = new SortedDictionary();
  66.      
  67.       public void CountYear(String text) {
  68.         if ( years.ContainsKey(text) ) {
  69.           ++years[text];
  70.         }
  71.         else {
  72.           years.Add(text, 1);
  73.         }
  74.       }
  75.     }
  76. /*
  77.  * end inner class
  78. */    
  79.     /**
  80.      * Inner class to add lines when a paragraph begins and ends.
  81.      */
  82.     class ParagraphPositions : PdfPageEventHelper {
  83.       public override void OnParagraph(
  84.           PdfWriter writer, Document pdfDocument, float paragraphPosition
  85.       ) {
  86.         DrawLine(
  87.           writer.DirectContent, pdfDocument.Left,
  88.           pdfDocument.Right, paragraphPosition - 8
  89.         );
  90.       }
  91.  
  92.       public override void OnParagraphEnd(
  93.           PdfWriter writer, Document pdfDocument, float paragraphPosition
  94.       ) {
  95.           DrawLine(
  96.             writer.DirectContent, pdfDocument.Left,
  97.             pdfDocument.Right, paragraphPosition - 5
  98.           );
  99.       }
  100.      
  101.       public void DrawLine(PdfContentByte cb, float x1, float x2, float y) {
  102.         cb.MoveTo(x1, y);
  103.         cb.LineTo(x2, y);
  104.         cb.Stroke();
  105.       }
  106.     }
  107. /*
  108.  * end inner class
  109. */
  110. // ---------------------------------------------------------------------------
  111.     public void Write(Stream stream) {
  112.       // step 1
  113.       using (Document document = new Document()) {
  114.       // step 2
  115.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  116.         GenericTags gevent = new GenericTags();
  117.         writer.PageEvent = gevent;
  118.         writer.PageEvent = new ParagraphPositions();      
  119.         // step 3
  120.         document.Open();
  121.         // step 4
  122.         Font bold = new Font(Font.FontFamily.HELVETICA, 11, Font.BOLD);
  123.         Font italic = new Font(Font.FontFamily.HELVETICA, 11, Font.ITALIC);
  124.         Font white = new Font(
  125.           Font.FontFamily.HELVETICA, 12,
  126.           Font.BOLD | Font.ITALIC,
  127.           BaseColor.WHITE
  128.         );
  129.         Paragraph p;
  130.         Chunk c;        
  131.         foreach (Movie movie in PojoFactory.GetMovies(true)) {
  132.             p = new Paragraph(22);
  133.             c = new Chunk(String.Format("{0} ", movie.Year), bold);
  134.             c.SetGenericTag("strip");
  135.             p.Add(c);
  136.             c = new Chunk(movie.MovieTitle);
  137.             c.SetGenericTag(movie.Year.ToString());
  138.             p.Add(c);
  139.             c = new Chunk(
  140.               String.Format(" ({0} minutes)  ", movie.Duration),
  141.               italic
  142.             );
  143.             p.Add(c);
  144.             c = new Chunk("IMDB", white);
  145.             c.SetAnchor("http://www.imdb.com/title/tt" + movie.Imdb);
  146.             c.SetGenericTag("ellipse");
  147.             p.Add(c);
  148.             document.Add(p);
  149.         }
  150.         document.NewPage();
  151.         writer.PageEvent = null;
  152.         foreach (string entry in gevent.years.Keys) {
  153.           p = new Paragraph(String.Format(
  154.             "{0}: {1} movie(s)", entry, gevent.years[entry]
  155.           ));
  156.           document.Add(p);
  157.         }
  158.       }
  159.     }
  160. // ===========================================================================
  161.   }
  162. }
MovieHistory1.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter05 {
  16.   public class MovieHistory1 : IWriter {
  17. // ===========================================================================
  18.     /**
  19.      * Inner class to keep track of the TOC
  20.      * and to draw lines under ever chapter and section.
  21.      */
  22.     class ChapterSectionTOC : PdfPageEventHelper {
  23.       private MovieHistory1 mh1;
  24.       public ChapterSectionTOC(MovieHistory1 mh1) {
  25.         this.mh1 = mh1;
  26.       }
  27.    
  28.       /** List with the titles. */
  29.       public List titles = new List();
  30.      
  31.       public override void OnChapter(PdfWriter writer, Document document,
  32.               float position, Paragraph title)
  33.       {
  34.         titles.Add(new Paragraph(title.Content, mh1.FONT[4]));
  35.       }
  36.  
  37.       public override void OnChapterEnd(
  38.         PdfWriter writer, Document document,
  39.         float position)
  40.       {
  41.         DrawLine(
  42.           writer.DirectContent, document.Left, document.Right, position - 5
  43.         );
  44.       }
  45.  
  46.       public override void OnSection(
  47.         PdfWriter writer, Document document,
  48.         float position, int depth, Paragraph title)
  49.       {
  50.           title = new Paragraph(title.Content, mh1.FONT[4]);
  51.           title.IndentationLeft = 18 * depth;
  52.           titles.Add(title);
  53.       }
  54.  
  55.       public override void OnSectionEnd(
  56.         PdfWriter writer, Document document, float position
  57.         )
  58.       {
  59.         DrawLine(
  60.           writer.DirectContent, document.Left, document.Right, position - 3
  61.         );
  62.       }
  63.      
  64.       public void DrawLine(
  65.         PdfContentByte cb, float x1, float x2, float y
  66.         )
  67.       {
  68.         cb.MoveTo(x1, y);
  69.         cb.LineTo(x2, y);
  70.         cb.Stroke();
  71.       }
  72.     }
  73.     // end inner class
  74. // ---------------------------------------------------------------------------
  75.    
  76.     /** The different epochs. */
  77.     public readonly string[] EPOCH = {
  78.       "Forties", "Fifties", "Sixties", "Seventies", "Eighties",
  79.     "Nineties", "Twenty-first Century"
  80.     };
  81.     /** The fonts for the title. */
  82.     public Font[] FONT = new Font[5];
  83.    
  84.     public MovieHistory1() {
  85.       FONT[0] = new Font(Font.FontFamily.HELVETICA, 24);
  86.       FONT[1] = new Font(Font.FontFamily.HELVETICA, 18);
  87.       FONT[2] = new Font(Font.FontFamily.HELVETICA, 14);
  88.       FONT[3] = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
  89.       FONT[4] = new Font(Font.FontFamily.HELVETICA, 10);
  90.     }
  91. // ---------------------------------------------------------------------------
  92.     public void Write(Stream stream) {
  93.       // step 1
  94.       using (Document document = new Document()) {
  95.         // step 2
  96.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  97.         // IMPORTANT: set linear page mode!
  98.         writer.SetLinearPageMode();
  99.         ChapterSectionTOC tevent = new ChapterSectionTOC(new MovieHistory1());
  100.         writer.PageEvent = tevent;        
  101.         // step 3
  102.         document.Open();
  103.         // step 4
  104.         int epoch = -1;
  105.         int currentYear = 0;
  106.         Paragraph title = null;
  107.         Chapter chapter = null;
  108.         Section section = null;
  109.         Section subsection = null;
  110.         // add the chapters, sort by year
  111.         foreach (Movie movie in PojoFactory.GetMovies(true)) {
  112.           int year = movie.Year;
  113.           if (epoch < (year - 1940) / 10) {
  114.             epoch = (year - 1940) / 10;
  115.             if (chapter != null) {
  116.               document.Add(chapter);
  117.             }
  118.             title = new Paragraph(EPOCH[epoch], FONT[0]);
  119.             chapter = new Chapter(title, epoch + 1);
  120.           }
  121.           if (currentYear < year) {
  122.             currentYear = year;
  123.             title = new Paragraph(
  124.               String.Format("The year {0}", year), FONT[1]
  125.             );
  126.             section = chapter.AddSection(title);
  127.             section.BookmarkTitle = year.ToString();
  128.             section.Indentation = 30;
  129.             section.BookmarkOpen = false;
  130.             section.NumberStyle = Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT;
  131.             section.Add(new Paragraph(
  132.               String.Format("Movies from the year {0}:", year))
  133.             );
  134.           }
  135.           title = new Paragraph(movie.MovieTitle, FONT[2]);
  136.           subsection = section.AddSection(title);
  137.           subsection.IndentationLeft = 20;
  138.           subsection.NumberDepth = 1;
  139.           subsection.Add(new Paragraph(
  140.             "Duration: " + movie.Duration.ToString(), FONT[3]
  141.           ));
  142.           subsection.Add(new Paragraph("Director(s):", FONT[3]));
  143.           subsection.Add(PojoToElementFactory.GetDirectorList(movie));
  144.           subsection.Add(new Paragraph("Countries:", FONT[3]));
  145.           subsection.Add(PojoToElementFactory.GetCountryList(movie));
  146.         }      
  147.         document.Add(chapter);
  148.         // add the TOC starting on the next page
  149.         document.NewPage();
  150.         int toc = writer.PageNumber;
  151.         foreach (Paragraph p in tevent.titles) {
  152.           document.Add(p);
  153.         }
  154.         // always go to a new page before reordering pages.
  155.         document.NewPage();
  156.         // get the total number of pages that needs to be reordered
  157.         int total = writer.ReorderPages(null);
  158.         // change the order
  159.         int[] order = new int[total];
  160.         for (int i = 0; i < total; i++) {
  161.           order[i] = i + toc;
  162.           if (order[i] > total) {
  163.             order[i] -= total;
  164.           }
  165.         }
  166.         // apply the new order
  167.         writer.ReorderPages(order);        
  168.       }
  169.     }
  170. // ===========================================================================
  171.   }
  172. }
NewPage.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using iTextSharp.text;
  10. using iTextSharp.text.pdf;
  11.  
  12. namespace kuujinbo.iTextInAction2Ed.Chapter05 {
  13.   public class NewPage : IWriter {
  14. // ===========================================================================
  15.     public void Write(Stream stream) {
  16.       // step 1
  17.       using (Document document = new Document()) {
  18.         // step 2
  19.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  20.         // step 3
  21.         document.Open();
  22.         // step 4
  23.         document.Add(new Paragraph("This page will NOT be followed by a blank page!"));
  24.         document.NewPage();
  25.         // we don't add anything to this page: newPage() will be ignored
  26.         document.NewPage();
  27.         document.Add(new Paragraph("This page will be followed by a blank page!"));
  28.         document.NewPage();
  29.         writer.PageEmpty = false;
  30.         document.NewPage();
  31.         document.Add(new Paragraph("The previous page was a blank page!"));
  32.       }
  33.     }
  34. // ===========================================================================
  35.   }
  36. }
Hero1.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using iTextSharp.text;
  10. using iTextSharp.text.pdf;
  11.  
  12. namespace kuujinbo.iTextInAction2Ed.Chapter05 {
  13.   public class Hero1 : IWriter {
  14. // ===========================================================================
  15.     public virtual void Write(Stream stream) {
  16.       // step 1
  17.       Rectangle rect = new Rectangle(-1192, -1685, 1192, 1685);
  18.       using (Document document = new Document(rect)) {
  19.         // step 2
  20.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  21.         // step 3
  22.         document.Open();
  23.         // step 4
  24.         PdfContentByte content = writer.DirectContent;
  25.         PdfTemplate template = CreateTemplate(content, rect, 4);
  26.         content.AddTemplate(template, -1192, -1685);
  27.         content.MoveTo(-595, 0);
  28.         content.LineTo(595, 0);
  29.         content.MoveTo(0, -842);
  30.         content.LineTo(0, 842);
  31.         content.Stroke();
  32.       }
  33.     }
  34. // ---------------------------------------------------------------------------    
  35.     /**
  36.      * Creates a template based on a stream of PDF syntax.
  37.      * @param content The direct content
  38.      * @param rect The dimension of the templare
  39.      * @param factor A magnification factor
  40.      * @return A PdfTemplate
  41.      */
  42.     public virtual PdfTemplate CreateTemplate(
  43.       PdfContentByte content, Rectangle rect, int factor)
  44.     {
  45.       PdfTemplate template = content.CreateTemplate(rect.Width, rect.Height);
  46.       template.ConcatCTM(factor, 0, 0, factor, 0, 0);
  47.       string hero = Path.Combine(Utility.ResourceText, "hero.txt");
  48.       if (!File.Exists(hero)) {
  49.         throw new ArgumentException(hero + " NOT FOUND!");  
  50.       }    
  51.       var fi = new FileInfo(hero);
  52.       using ( var sr = fi.OpenText() ) {
  53.         while (sr.Peek() >= 0) {
  54.           template.SetLiteral((char) sr.Read());
  55.         }
  56.       }
  57.       return template;
  58.     }    
  59. // ===========================================================================
  60.   }
  61. }
Hero2.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using iTextSharp.text;
  10. using iTextSharp.text.pdf;
  11.  
  12. namespace kuujinbo.iTextInAction2Ed.Chapter05 {
  13.   public class Hero2 : Hero1 {
  14. // ===========================================================================
  15.     public override void Write(Stream stream) {
  16.       float w = PageSize.A4.Width;
  17.       float h = PageSize.A4.Height;
  18.       Rectangle rect = new Rectangle(-2*w, -2*h, 2*w, 2*h);
  19.       Rectangle crop = new Rectangle(-2 * w, h, -w, 2 * h);      
  20.       // step 1
  21.       using (Document document = new Document(rect)) {
  22.         // step 2
  23.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  24.         writer.CropBoxSize = crop;
  25.         // step 3
  26.         document.Open();
  27.         // step 4
  28.         PdfContentByte content = writer.DirectContent;
  29.         PdfTemplate template = CreateTemplate(content, rect, 4);
  30.         float adjust;
  31.         while(true) {
  32.           content.AddTemplate(template, -2*w, -2*h);
  33.           adjust = crop.Right + w;
  34.           if (adjust > 2 * w) {
  35.             adjust = crop.Bottom - h;
  36.             if (adjust < - 2 * h)
  37.                 break;
  38.             crop = new Rectangle(-2*w, adjust, -w, crop.Bottom);
  39.           }
  40.           else {
  41.             crop = new Rectangle(crop.Right, crop.Bottom, adjust, crop.Top);
  42.           }
  43.           writer.CropBoxSize = crop;
  44.           document.NewPage();
  45.         }
  46.       }
  47.     }
  48. // ---------------------------------------------------------------------------    
  49.     /**
  50.      * Creates a template based on a stream of PDF syntax.
  51.      * @param content The direct content
  52.      * @param rect The dimension of the templare
  53.      * @param factor A magnification factor
  54.      * @return A PdfTemplate
  55.      */
  56.     public override  PdfTemplate CreateTemplate(
  57.       PdfContentByte content, Rectangle rect, int factor
  58.     )
  59.     {
  60.       PdfTemplate template = content.CreateTemplate(rect.Width, rect.Height);
  61.       template.ConcatCTM(factor, 0, 0, factor, 0, 0);
  62.       string hero = Path.Combine(Utility.ResourceText, "hero.txt");
  63.       if (!File.Exists(hero)) {
  64.         throw new ArgumentException(hero + " NOT FOUND!");
  65.       }  
  66.       var fi = new FileInfo(hero);
  67.       using ( var sr = fi.OpenText() ) {
  68.         while (sr.Peek() >= 0) {
  69.           template.SetLiteral((char) sr.Read());
  70.         }
  71.       }
  72.       return template;
  73.     }    
  74. // ===========================================================================
  75.   }
  76. }
Hero3.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using iTextSharp.text;
  10. using iTextSharp.text.pdf;
  11.  
  12. namespace kuujinbo.iTextInAction2Ed.Chapter05 {
  13.   public class Hero3 : Hero1 {
  14. // ===========================================================================
  15.     public override void Write(Stream stream) {
  16.       // step 1
  17.       using (Document document = new Document(PageSize.A4)) {
  18.         // step 2
  19.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  20.         Rectangle art = new Rectangle(50, 50, 545, 792);
  21.         writer.SetBoxSize("art", art);        
  22.         // step 3
  23.         document.Open();
  24.         // step 4
  25.         PdfContentByte content = writer.DirectContent;
  26.         PdfTemplate template = CreateTemplate(content, PageSize.A4, 1);
  27.         content.AddTemplate(template, 0, 0);
  28.       }
  29.     }
  30. // ---------------------------------------------------------------------------    
  31.     /**
  32.      * Creates a template based on a stream of PDF syntax.
  33.      * @param content The direct content
  34.      * @param rect The dimension of the templare
  35.      * @param factor A magnification factor
  36.      * @return A PdfTemplate
  37.      */
  38.     public override PdfTemplate CreateTemplate(
  39.       PdfContentByte content, Rectangle rect, int factor
  40.     )
  41.     {
  42.       PdfTemplate template = content.CreateTemplate(rect.Width, rect.Height);
  43.       template.ConcatCTM(factor, 0, 0, factor, 0, 0);
  44.       string hero = Path.Combine(Utility.ResourceText, "hero.txt");
  45.       if (!File.Exists(hero)) {
  46.         throw new ArgumentException(hero + " NOT FOUND!");      
  47.       }
  48.       var fi = new FileInfo(hero);
  49.       using ( StreamReader sr = fi.OpenText() ) {
  50.         while (sr.Peek() >= 0) {
  51.           template.SetLiteral((char) sr.Read());
  52.         }
  53.       }
  54.       return template;
  55.     }    
  56. // ===========================================================================
  57.   }
  58. }
MovieHistory2.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter05 {
  16.   public class MovieHistory2 : IWriter {
  17. // ===========================================================================
  18.     /** Inner class to add a header and a footer. */
  19.     class HeaderFooter : PdfPageEventHelper {
  20.       /** Alternating phrase for the header. */
  21.       Phrase[] header = new Phrase[2];
  22.       /** Current page number (will be reset for every chapter). */
  23.       int pagenumber;
  24.      
  25.       /**
  26.        * Initialize one of the headers.
  27.        * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(
  28.        *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  29.        */
  30.       public override void OnOpenDocument(PdfWriter writer, Document document) {
  31.         header[0] = new Phrase("Movie history");
  32.       }
  33.      
  34.       /**
  35.        * Initialize one of the headers, based on the chapter title;
  36.        * reset the page number.
  37.        * @see com.itextpdf.text.pdf.PdfPageEventHelper#onChapter(
  38.        *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document, float,
  39.        *      com.itextpdf.text.Paragraph)
  40.        */
  41.       public override void OnChapter(
  42.         PdfWriter writer, Document document,
  43.         float paragraphPosition, Paragraph title)
  44.       {
  45.         header[1] = new Phrase(title.Content);
  46.         pagenumber = 1;
  47.       }
  48.  
  49.       /**
  50.        * Increase the page number.
  51.        * @see com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage(
  52.        *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  53.        */
  54.       public override void OnStartPage(PdfWriter writer, Document document) {
  55.         pagenumber++;
  56.       }
  57.        
  58.       /**
  59.        * Adds the header and the footer.
  60.        * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
  61.        *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  62.        */
  63.       public override void OnEndPage(PdfWriter writer, Document document) {
  64.         Rectangle rect = writer.GetBoxSize("art");
  65.         switch(writer.PageNumber % 2) {
  66.         case 0:
  67.           ColumnText.ShowTextAligned(writer.DirectContent,
  68.             Element.ALIGN_RIGHT,
  69.             header[0],
  70.             rect.Right, rect.Top, 0
  71.           );
  72.           break;
  73.         case 1:
  74.           ColumnText.ShowTextAligned(
  75.             writer.DirectContent,
  76.             Element.ALIGN_LEFT,
  77.             header[1],
  78.             rect.Left, rect.Top, 0
  79.           );
  80.           break;
  81.         }
  82.         ColumnText.ShowTextAligned(
  83.           writer.DirectContent,
  84.           Element.ALIGN_CENTER,
  85.           new Phrase(String.Format("page {0}", pagenumber)),
  86.           (rect.Left + rect.Right) / 2,
  87.           rect.Bottom - 18, 0
  88.         );
  89.       }
  90.     }
  91.     // end inner class
  92. // ---------------------------------------------------------------------------
  93.     /** The different epochs. */
  94.     public readonly string[] EPOCH = {
  95.       "Forties", "Fifties", "Sixties", "Seventies", "Eighties",
  96.     "Nineties", "Twenty-first Century"
  97.     };
  98.     /** The fonts for the title. */
  99.     public Font[] FONT = new Font[5];
  100.    
  101.     public MovieHistory2() {
  102.       FONT[0] = new Font(Font.FontFamily.HELVETICA, 24);
  103.       FONT[1] = new Font(Font.FontFamily.HELVETICA, 18);
  104.       FONT[2] = new Font(Font.FontFamily.HELVETICA, 14);
  105.       FONT[3] = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
  106.       FONT[4] = new Font(Font.FontFamily.HELVETICA, 10);
  107.     }
  108. // ---------------------------------------------------------------------------
  109.     public void Write(Stream stream) {
  110.       // step 1
  111.       using (Document document = new Document(PageSize.A4, 36, 36, 54, 54)) {
  112.         // step 2
  113.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  114.         HeaderFooter tevent = new HeaderFooter();
  115.         writer.SetBoxSize("art", new Rectangle(36, 54, 559, 788));
  116.         writer.PageEvent = tevent;
  117.         // step 3
  118.         document.Open();
  119.         // step 4
  120.         int epoch = -1;
  121.         int currentYear = 0;
  122.         Paragraph title = null;
  123.         Chapter chapter = null;
  124.         Section section = null;
  125.         Section subsection = null;
  126.         // add the chapters, sort by year
  127.         foreach (Movie movie in PojoFactory.GetMovies(true)) {
  128.           int year = movie.Year;
  129.           if (epoch < (year - 1940) / 10) {
  130.             epoch = (year - 1940) / 10;
  131.             if (chapter != null) {
  132.               document.Add(chapter);
  133.             }
  134.             title = new Paragraph(EPOCH[epoch], FONT[0]);
  135.             chapter = new Chapter(title, epoch + 1);
  136.           }
  137.           if (currentYear < year) {
  138.             currentYear = year;
  139.             title = new Paragraph(
  140.               String.Format("The year {0}", year), FONT[1]
  141.             );
  142.             section = chapter.AddSection(title);
  143.             section.BookmarkTitle = year.ToString();
  144.             section.Indentation = 30;
  145.             section.BookmarkOpen = false;
  146.             section.NumberStyle = Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT;
  147.             section.Add(new Paragraph(
  148.               String.Format("Movies from the year {0}:", year))
  149.             );
  150.           }
  151.           title = new Paragraph(movie.MovieTitle, FONT[2]);
  152.           subsection = section.AddSection(title);
  153.           subsection.IndentationLeft = 20;
  154.           subsection.NumberDepth = 1;
  155.           subsection.Add(new Paragraph(
  156.             "Duration: " + movie.Duration.ToString(), FONT[3]
  157.           ));
  158.           subsection.Add(new Paragraph("Director(s):", FONT[3]));
  159.           subsection.Add(PojoToElementFactory.GetDirectorList(movie));
  160.           subsection.Add(new Paragraph("Countries:", FONT[3]));
  161.           subsection.Add(PojoToElementFactory.GetCountryList(movie));
  162.         }      
  163.         document.Add(chapter);
  164.       }
  165.     }
  166. // ===========================================================================
  167.   }
  168. }
MovieCountries1.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Data;
  11. using System.Data.Common;
  12. using System.Linq;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter05 {
  18.   public class MovieCountries1 : IWriter {
  19. // ===========================================================================
  20.     /**
  21.      * Inner class to add a table as header.
  22.      */
  23.     protected class TableHeader : PdfPageEventHelper {
  24.       /** The template with the total number of pages. */
  25.       PdfTemplate total;
  26.      
  27.       /** The header text. */
  28.       public string Header { get; set; }
  29.  
  30.       /**
  31.        * Creates the PdfTemplate that will hold the total number of pages.
  32.        * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(
  33.        *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  34.        */
  35.       public override void OnOpenDocument(PdfWriter writer, Document document) {
  36.         total = writer.DirectContent.CreateTemplate(30, 16);
  37.       }
  38.      
  39.       /**
  40.        * Adds a header to every page
  41.        * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
  42.        *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  43.        */
  44.       public override void OnEndPage(PdfWriter writer, Document document) {
  45.         PdfPTable table = new PdfPTable(3);
  46.         try {
  47.           table.SetWidths(new int[]{24, 24, 2});
  48.           table.TotalWidth = 527;
  49.           table.LockedWidth = true;
  50.           table.DefaultCell.FixedHeight = 20;
  51.           table.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
  52.           table.AddCell(Header);
  53.           table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
  54.           table.AddCell(string.Format("Page {0} of", writer.PageNumber));
  55.           PdfPCell cell = new PdfPCell(Image.GetInstance(total));
  56.           cell.Border = Rectangle.BOTTOM_BORDER;
  57.           table.AddCell(cell);
  58.           table.WriteSelectedRows(0, -1, 34, 803, writer.DirectContent);
  59.         }
  60.         catch(DocumentException de) {
  61.           throw de;
  62.         }
  63.       }
  64.      
  65.       /**
  66.        * Fills out the total number of pages before the document is closed.
  67.        * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(
  68.        *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  69.        */
  70.       public override void OnCloseDocument(PdfWriter writer, Document document) {
  71.         ColumnText.ShowTextAligned(
  72.           total, Element.ALIGN_LEFT,
  73. /*
  74.  * NewPage() already called when closing the document; subtract 1
  75. */
  76.           new Phrase((writer.PageNumber - 1).ToString()),
  77.           2, 2, 0
  78.         );
  79.       }
  80.     }
  81. // ---------------------------------------------------------------------------
  82.     protected readonly string SQL =
  83. @"SELECT country, id FROM film_country
  84. ORDER BY country
  85. ";
  86.     public virtual void Write(Stream stream) {
  87.       // step 1
  88.       using (Document document = new Document(PageSize.A4, 36, 36, 54, 36)) {
  89.         // step 2
  90.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  91.         TableHeader tevent = new TableHeader();
  92.         writer.PageEvent = tevent;
  93.         // step 3
  94.         document.Open();
  95.         // step 4      
  96.         using (var c =  AdoDB.Provider.CreateConnection()) {
  97.           c.ConnectionString = AdoDB.CS;
  98.           using (DbCommand cmd = c.CreateCommand()) {
  99.             cmd.CommandText = SQL;        
  100.             c.Open();
  101.             using (var r = cmd.ExecuteReader()) {
  102.               while (r.Read()) {
  103.                 tevent.Header = r["country"].ToString();
  104.                 // LINQ allows us to sort on any movie object property inline;
  105.                 // let's sort by Movie.Year, Movie.Title
  106.                 var by_year = from m in PojoFactory.GetMovies(
  107.                   r["id"].ToString()
  108.                 )
  109.                   orderby m.Year, m.Title
  110.                   select m
  111.                 ;                
  112.                 foreach (Movie movie in by_year) {
  113.                   document.Add(new Paragraph(
  114.                     movie.MovieTitle, FilmFonts.BOLD
  115.                   ));
  116.                   if (!string.IsNullOrEmpty(movie.OriginalTitle)) document.Add(
  117.                     new Paragraph(movie.OriginalTitle, FilmFonts.ITALIC)
  118.                   );
  119.                   document.Add(new Paragraph(
  120.                     String.Format("Year: {0}; run length: {1} minutes",
  121.                       movie.Year, movie.Duration
  122.                     ), FilmFonts.NORMAL
  123.                   ));
  124.                   document.Add(PojoToElementFactory.GetDirectorList(movie));
  125.                 }
  126.                 document.NewPage();              
  127.               }      
  128.             }
  129.           }
  130.         }
  131.       }
  132.     }    
  133. // ===========================================================================
  134.   }
  135. }
MovieCountries2.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Data;
  11. using System.Data.Common;
  12. using System.Linq;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter05 {
  18.   public class MovieCountries2 : MovieCountries1 {
  19. // ===========================================================================
  20.     /**
  21.      * Inner class to add a watermark to every page.
  22.      */
  23.     class Watermark : PdfPageEventHelper {
  24.       Font FONT = new Font(Font.FontFamily.HELVETICA, 52, Font.BOLD, new GrayColor(0.75f));
  25.      
  26.       public override void OnEndPage(PdfWriter writer, Document document) {
  27.         ColumnText.ShowTextAligned(
  28.           writer.DirectContentUnder,
  29.           Element.ALIGN_CENTER, new Phrase("FOOBAR FILM FESTIVAL", FONT),
  30.           297.5f, 421, writer.PageNumber % 2 == 1 ? 45 : -45
  31.         );
  32.       }
  33.     }
  34. // ---------------------------------------------------------------------------
  35.     public override void Write(Stream stream) {
  36.       // step 1
  37.       using (Document document = new Document(PageSize.A4, 36, 36, 54, 36)) {
  38.         // step 2
  39.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  40.         TableHeader tevent = new TableHeader();
  41.         writer.PageEvent = tevent;
  42.         writer.PageEvent = new Watermark();
  43.         // step 3
  44.         document.Open();
  45.         // step 4
  46.         using (var c =  AdoDB.Provider.CreateConnection()) {
  47.           c.ConnectionString = AdoDB.CS;
  48.           using (DbCommand cmd = c.CreateCommand()) {
  49.             cmd.CommandText = SQL;        
  50.             c.Open();
  51.             using (var r = cmd.ExecuteReader()) {
  52.               while (r.Read()) {
  53.                 tevent.Header = r["country"].ToString();
  54.                 foreach (Movie movie
  55.                   in PojoFactory.GetMovies(r["id"].ToString(), true))
  56.                 {
  57.                   document.Add(new Paragraph(
  58.                     movie.MovieTitle, FilmFonts.BOLD
  59.                   ));
  60.                   if (!string.IsNullOrEmpty(movie.OriginalTitle)) document.Add(
  61.                     new Paragraph(movie.OriginalTitle, FilmFonts.ITALIC)
  62.                   );
  63.                   document.Add(new Paragraph(
  64.                     String.Format("Year: {0}; run length: {1} minutes",
  65.                       movie.Year, movie.Duration
  66.                     ), FilmFonts.NORMAL
  67.                   ));
  68.                   document.Add(PojoToElementFactory.GetDirectorList(movie));
  69.                 }
  70.                 document.NewPage();              
  71.               }      
  72.             }
  73.           }
  74.         }
  75.       }
  76.     }    
  77. // ===========================================================================
  78.   }
  79. }
MovieSlideShow.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter05 {
  16.   public class MovieSlideShow : IWriter {
  17. // ===========================================================================
  18.     /**
  19.      * Page event to set the transition and duration for every page.
  20.      */
  21.     class TransitionDuration : PdfPageEventHelper {
  22.       public override void OnStartPage(PdfWriter writer, Document document) {
  23.         writer.Transition = new PdfTransition(PdfTransition.DISSOLVE, 3);
  24.         writer.Duration = 5;
  25.       }
  26.     }
  27. // ---------------------------------------------------------------------------
  28.     public void Write(Stream stream) {
  29.       // step 1
  30.       using (Document document = new Document(PageSize.A5.Rotate())) {
  31.         // step 2
  32.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  33.         writer.PdfVersion = PdfWriter.VERSION_1_5;
  34.         writer.ViewerPreferences = PdfWriter.PageModeFullScreen;
  35.         writer.PageEvent = new TransitionDuration();        
  36.         // step 3
  37.         document.Open();
  38.         // step 4
  39.         IEnumerable movies = PojoFactory.GetMovies();
  40.         Image img;
  41.         PdfPCell cell;
  42.         PdfPTable table = new PdfPTable(6);
  43.         string RESOURCE = Utility.ResourcePosters;
  44.         foreach (Movie movie in movies) {
  45.           img = Image.GetInstance(Path.Combine(RESOURCE, movie.Imdb + ".jpg"));
  46.           cell = new PdfPCell(img, true);
  47.           cell.Border = PdfPCell.NO_BORDER;
  48.           table.AddCell(cell);
  49.         }
  50.         document.Add(table);
  51.       }
  52.     }
  53. // ===========================================================================
  54.   }
  55. }
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now