Chapter 4: Organizing content in tables

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

10th October 2015
admin-marketing

Switch code for this example

MyFirstTable.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.chapter04;
  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.Phrase;
  16. import com.itextpdf.text.pdf.PdfPCell;
  17. import com.itextpdf.text.pdf.PdfPTable;
  18. import com.itextpdf.text.pdf.PdfWriter;
  19.  
  20. public class MyFirstTable {
  21.  
  22.     /** The resulting PDF file. */
  23.     public static final String RESULT
  24.         = "results/part1/chapter04/first_table.pdf";
  25.  
  26.     /**
  27.      * Main method.
  28.      * @param    args    no arguments needed
  29.      * @throws DocumentException
  30.      * @throws IOException
  31.      */
  32.     public static void main(String[] args)
  33.         throws IOException, DocumentException {
  34.         new MyFirstTable().createPdf(RESULT);
  35.     }
  36.    
  37.     /**
  38.      * Creates a PDF with information about the movies
  39.      * @param    filename the name of the PDF file that will be created.
  40.      * @throws    DocumentException
  41.      * @throws    IOException
  42.      */
  43.     public void createPdf(String filename)
  44.         throws IOException, DocumentException {
  45.         // step 1
  46.         Document document = new Document();
  47.         // step 2
  48.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  49.         // step 3
  50.         document.open();
  51.         // step 4
  52.         document.add(createFirstTable());
  53.         // step 5
  54.         document.close();
  55.     }
  56.    
  57.     /**
  58.      * Creates our first table
  59.      * @return our first table
  60.      */
  61.     public static PdfPTable createFirstTable() {
  62.         // a table with three columns
  63.         PdfPTable table = new PdfPTable(3);
  64.         // the cell object
  65.         PdfPCell cell;
  66.         // we add a cell with colspan 3
  67.         cell = new PdfPCell(new Phrase("Cell with colspan 3"));
  68.         cell.setColspan(3);
  69.         table.addCell(cell);
  70.         // now we add a cell with rowspan 2
  71.         cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
  72.         cell.setRowspan(2);
  73.         table.addCell(cell);
  74.         // we add the four remaining cells with addCell()
  75.         table.addCell("row 1; cell 1");
  76.         table.addCell("row 1; cell 2");
  77.         table.addCell("row 2; cell 1");
  78.         table.addCell("row 2; cell 2");
  79.         return table;
  80.     }
  81. }
ColumnWidths.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.chapter04;
  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.Phrase;
  16. import com.itextpdf.text.Rectangle;
  17. import com.itextpdf.text.pdf.PdfPCell;
  18. import com.itextpdf.text.pdf.PdfPTable;
  19. import com.itextpdf.text.pdf.PdfWriter;
  20.  
  21. public class ColumnWidths {
  22.  
  23.     /** The resulting PDF file. */
  24.     public static final String RESULT = "results/part1/chapter04/column_widths.pdf";
  25.    
  26.     /**
  27.      * Creates a PDF with five tables.
  28.      * @param    filename the name of the PDF file that will be created.
  29.      * @throws    DocumentException
  30.      * @throws    IOException
  31.      */
  32.     public void createPdf(String filename)
  33.         throws IOException, DocumentException {
  34.         // step 1
  35.         Document document = new Document();
  36.         // step 2
  37.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  38.         // step 3
  39.         document.open();
  40.         // step 4
  41.         PdfPTable table = createTable1();
  42.         document.add(table);
  43.         table = createTable2();
  44.         table.setSpacingBefore(5);
  45.         table.setSpacingAfter(5);
  46.         document.add(table);
  47.         table = createTable3();
  48.         document.add(table);
  49.         table = createTable4();
  50.         table.setSpacingBefore(5);
  51.         table.setSpacingAfter(5);
  52.         document.add(table);
  53.         table = createTable5();
  54.         document.add(table);
  55.         // step 5
  56.         document.close();
  57.     }
  58.    
  59.     /**
  60.      * Creates a table; widths are set with setWidths().
  61.      * @return a PdfPTable
  62.      * @throws DocumentException
  63.      */
  64.     public static PdfPTable createTable1() throws DocumentException {
  65.         PdfPTable table = new PdfPTable(3);
  66.         table.setWidthPercentage(288 / 5.23f);
  67.         table.setWidths(new int[]{2, 1, 1});
  68.         PdfPCell cell;
  69.         cell = new PdfPCell(new Phrase("Table 1"));
  70.         cell.setColspan(3);
  71.         table.addCell(cell);
  72.         cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
  73.         cell.setRowspan(2);
  74.         table.addCell(cell);
  75.         table.addCell("row 1; cell 1");
  76.         table.addCell("row 1; cell 2");
  77.         table.addCell("row 2; cell 1");
  78.         table.addCell("row 2; cell 2");
  79.         return table;
  80.     }
  81.    
  82.     /**
  83.      * Creates a table; widths are set with setWidths().
  84.      * @return a PdfPTable
  85.      * @throws DocumentException
  86.      */
  87.     public static PdfPTable createTable2() throws DocumentException {
  88.         PdfPTable table = new PdfPTable(3);
  89.         table.setTotalWidth(288);
  90.         table.setLockedWidth(true);
  91.         table.setWidths(new float[]{2, 1, 1});
  92.         PdfPCell cell;
  93.         cell = new PdfPCell(new Phrase("Table 2"));
  94.         cell.setColspan(3);
  95.         table.addCell(cell);
  96.         cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
  97.         cell.setRowspan(2);
  98.         table.addCell(cell);
  99.         table.addCell("row 1; cell 1");
  100.         table.addCell("row 1; cell 2");
  101.         table.addCell("row 2; cell 1");
  102.         table.addCell("row 2; cell 2");
  103.         return table;
  104.     }
  105.    
  106.     /**
  107.      * Creates a table; widths are set in the constructor.
  108.      * @return a PdfPTable
  109.      * @throws DocumentException
  110.      */
  111.     public static PdfPTable createTable3() throws DocumentException {
  112.         PdfPTable table = new PdfPTable(new float[]{ 2, 1, 1 });
  113.         table.setWidthPercentage(55.067f);
  114.         PdfPCell cell;
  115.         cell = new PdfPCell(new Phrase("Table 3"));
  116.         cell.setColspan(3);
  117.         table.addCell(cell);
  118.         cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
  119.         cell.setRowspan(2);
  120.         table.addCell(cell);
  121.         table.addCell("row 1; cell 1");
  122.         table.addCell("row 1; cell 2");
  123.         table.addCell("row 2; cell 1");
  124.         table.addCell("row 2; cell 2");
  125.         return table;
  126.     }
  127.    
  128.     /**
  129.      * Creates a table; widths are set with special setWidthPercentage() method.
  130.      * @return a PdfPTable
  131.      * @throws DocumentException
  132.      */
  133.     public static PdfPTable createTable4() throws DocumentException {
  134.         PdfPTable table = new PdfPTable(3);
  135.         Rectangle rect = new Rectangle(523, 770);
  136.         table.setWidthPercentage(new float[]{ 144, 72, 72 }, rect);
  137.         PdfPCell cell;
  138.         cell = new PdfPCell(new Phrase("Table 4"));
  139.         cell.setColspan(3);
  140.         table.addCell(cell);
  141.         cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
  142.         cell.setRowspan(2);
  143.         table.addCell(cell);
  144.         table.addCell("row 1; cell 1");
  145.         table.addCell("row 1; cell 2");
  146.         table.addCell("row 2; cell 1");
  147.         table.addCell("row 2; cell 2");
  148.         return table;
  149.     }
  150.    
  151.     /**
  152.      * Creates a table; widths are set with setTotalWidth().
  153.      * @return a PdfPTable
  154.      * @throws DocumentException
  155.      */
  156.     public static PdfPTable createTable5() throws DocumentException {
  157.         PdfPTable table = new PdfPTable(3);
  158.         table.setTotalWidth(new float[]{ 144, 72, 72 });
  159.         table.setLockedWidth(true);
  160.         PdfPCell cell;
  161.         cell = new PdfPCell(new Phrase("Table 5"));
  162.         cell.setColspan(3);
  163.         table.addCell(cell);
  164.         cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
  165.         cell.setRowspan(2);
  166.         table.addCell(cell);
  167.         table.addCell("row 1; cell 1");
  168.         table.addCell("row 1; cell 2");
  169.         table.addCell("row 2; cell 1");
  170.         table.addCell("row 2; cell 2");
  171.         return table;
  172.     }
  173.  
  174.     /**
  175.      * Main method.
  176.      * @param args no arguments needed
  177.      * @throws DocumentException
  178.      * @throws IOException
  179.      */
  180.     public static void main(String[] args) throws IOException, DocumentException {
  181.         new ColumnWidths().createPdf(RESULT);
  182.     }
  183. }
TableAlignment.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.chapter04;
  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.Element;
  16. import com.itextpdf.text.pdf.PdfPTable;
  17. import com.itextpdf.text.pdf.PdfWriter;
  18.  
  19. public class TableAlignment extends MyFirstTable {
  20.  
  21.     /** The resulting PDF file. */
  22.     public static final String RESULT
  23.         = "results/part1/chapter04/table_alignment.pdf";
  24.    
  25.     /**
  26.      * Creates a PDF with information about the movies
  27.      * @param    filename the name of the PDF file that will be created.
  28.      * @throws    DocumentException
  29.      * @throws    IOException
  30.      */
  31.     public void createPdf(String filename)
  32.         throws IOException, DocumentException {
  33.         // step 1
  34.         Document document = new Document();
  35.         // step 2
  36.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  37.         // step 3
  38.         document.open();
  39.         // step 4
  40.         PdfPTable table = createFirstTable();
  41.         table.setWidthPercentage(50);
  42.         table.setHorizontalAlignment(Element.ALIGN_LEFT);
  43.         document.add(table);
  44.         table.setHorizontalAlignment(Element.ALIGN_CENTER);
  45.         document.add(table);
  46.         table.setHorizontalAlignment(Element.ALIGN_RIGHT);
  47.         document.add(table);
  48.         // step 5
  49.         document.close();
  50.     }
  51.  
  52.     /**
  53.      * Main method.
  54.      * @param    args    no arguments needed
  55.      * @throws DocumentException
  56.      * @throws IOException
  57.      */
  58.     public static void main(String[] args)
  59.         throws IOException, DocumentException {
  60.         new TableAlignment().createPdf(RESULT);
  61.     }
  62. }
MovieTextMode.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.chapter04;
  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.Country;
  18. import com.lowagie.filmfestival.Director;
  19. import com.lowagie.filmfestival.FilmFonts;
  20. import com.lowagie.filmfestival.PojoFactory;
  21. import com.lowagie.filmfestival.Movie;
  22. import com.lowagie.filmfestival.PojoToElementFactory;
  23. import com.itextpdf.text.Document;
  24. import com.itextpdf.text.DocumentException;
  25. import com.itextpdf.text.Element;
  26. import com.itextpdf.text.Paragraph;
  27. import com.itextpdf.text.Phrase;
  28. import com.itextpdf.text.pdf.PdfPCell;
  29. import com.itextpdf.text.pdf.PdfPTable;
  30. import com.itextpdf.text.pdf.PdfWriter;
  31.  
  32. public class MovieTextMode {
  33.  
  34.     /** The resulting PDF file. */
  35.     public static final String RESULT
  36.         = "results/part1/chapter04/movie_text_mode.pdf";
  37.    
  38.     /**
  39.      * Creates a PDF with information about the movies
  40.      * @param    filename the name of the PDF file that will be created.
  41.      * @throws    DocumentException
  42.      * @throws    IOException
  43.      * @throws    SQLException
  44.      */
  45.     public void createPdf(String filename)
  46.         throws IOException, DocumentException, SQLException {
  47.         // Create a database connection
  48.         DatabaseConnection connection = new HsqldbConnection("filmfestival");    
  49.         // step 1
  50.         Document document = new Document();
  51.         // step 2
  52.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  53.         // step 3
  54.         document.open();
  55.         // step 4
  56.         document.add(new Paragraph("Movies:"));
  57.         List movies = PojoFactory.getMovies(connection);
  58.         for (Movie movie : movies) {
  59.             PdfPTable table = new PdfPTable(2);
  60.             table.setWidths(new int[]{1, 4});
  61.             PdfPCell cell;
  62.             cell = new PdfPCell(new Phrase(movie.getTitle(), FilmFonts.BOLD));
  63.             cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  64.             cell.setColspan(2);
  65.             table.addCell(cell);
  66.             if (movie.getOriginalTitle() != null) {
  67.                 cell = new PdfPCell(PojoToElementFactory.getOriginalTitlePhrase(movie));
  68.                 cell.setColspan(2);
  69.                 cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
  70.                 table.addCell(cell);
  71.             }
  72.             List directors = movie.getDirectors();
  73.             cell = new PdfPCell(new Phrase("Directors:"));
  74.             cell.setRowspan(directors.size());
  75.             cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
  76.             table.addCell(cell);
  77.             int count = 0;
  78.             for (Director pojo : directors) {
  79.                 cell = new PdfPCell(PojoToElementFactory.getDirectorPhrase(pojo));
  80.                 cell.setIndent(10 * count++);
  81.                 table.addCell(cell);
  82.             }
  83.             table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
  84.             table.addCell("Year:");
  85.             table.addCell(String.valueOf(movie.getYear()));
  86.             table.addCell("Run length:");
  87.             table.addCell(String.valueOf(movie.getDuration()));
  88.             List countries = movie.getCountries();
  89.             cell = new PdfPCell(new Phrase("Countries:"));
  90.             cell.setRowspan(countries.size());
  91.             cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
  92.             table.addCell(cell);
  93.             table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
  94.             for (Country country : countries) {
  95.                 table.addCell(country.getCountry());
  96.             }
  97.             document.add(table);
  98.         }
  99.         // step 5
  100.         document.close();
  101.         // Close the database connection
  102.         connection.close();
  103.     }
  104.    
  105.     /**
  106.      * Main method.
  107.      *
  108.      * @param    args    no arguments needed
  109.      * @throws DocumentException
  110.      * @throws IOException
  111.      * @throws SQLException
  112.      */
  113.     public static void main(String[] args)
  114.         throws IOException, DocumentException, SQLException {
  115.         new MovieTextMode().createPdf(RESULT);
  116.     }
  117. }
Spacing.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.chapter04;
  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.Phrase;
  16. import com.itextpdf.text.pdf.PdfPCell;
  17. import com.itextpdf.text.pdf.PdfPTable;
  18. import com.itextpdf.text.pdf.PdfWriter;
  19.  
  20. public class Spacing {
  21.  
  22.     /** The resulting PDF file. */
  23.     public static final String RESULT = "results/part1/chapter04/spacing.pdf";
  24.  
  25.     /**
  26.      * Main method.
  27.      * @param    args    no arguments needed
  28.      * @throws DocumentException
  29.      * @throws IOException
  30.      */
  31.     public static void main(String[] args)
  32.         throws DocumentException, IOException {
  33.         // step 1
  34.         Document document = new Document();
  35.         // step 2
  36.         PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  37.         // step 3
  38.         document.open();
  39.         // step 4
  40.         PdfPTable table = new PdfPTable(2);
  41.         table.setWidthPercentage(100);
  42.         Phrase p = new Phrase(
  43.             "Dr. iText or: How I Learned to Stop Worrying " +
  44.             "and Love the Portable Document Format.");
  45.         PdfPCell cell = new PdfPCell(p);
  46.         table.addCell("default leading / spacing");
  47.         table.addCell(cell);
  48.         table.addCell("absolute leading: 20");
  49.         cell.setLeading(20f, 0f);
  50.         table.addCell(cell);
  51.         table.addCell("absolute leading: 3; relative leading: 1.2");
  52.         cell.setLeading(3f, 1.2f);
  53.         table.addCell(cell);
  54.         table.addCell("absolute leading: 0; relative leading: 1.2");
  55.         cell.setLeading(0f, 1.2f);
  56.         table.addCell(cell);
  57.         table.addCell("no leading at all");
  58.         cell.setLeading(0f, 0f);
  59.         table.addCell(cell);
  60.         cell = new PdfPCell(new Phrase(
  61.             "Dr. iText or: How I Learned to Stop Worrying and Love PDF"));
  62.         table.addCell("padding 10");
  63.         cell.setPadding(10);
  64.         table.addCell(cell);
  65.         table.addCell("padding 0");
  66.         cell.setPadding(0);
  67.         table.addCell(cell);
  68.         table.addCell("different padding for left, right, top and bottom");
  69.         cell.setPaddingLeft(20);
  70.         cell.setPaddingRight(50);
  71.         cell.setPaddingTop(0);
  72.         cell.setPaddingBottom(5);
  73.         table.addCell(cell);
  74.         p = new Phrase("iText in Action Second Edition");
  75.         table.getDefaultCell().setPadding(2);
  76.         table.getDefaultCell().setUseAscender(false);
  77.         table.getDefaultCell().setUseDescender(false);
  78.         table.addCell("padding 2; no ascender, no descender");
  79.         table.addCell(p);
  80.         table.getDefaultCell().setUseAscender(true);
  81.         table.getDefaultCell().setUseDescender(false);
  82.         table.addCell("padding 2; ascender, no descender");
  83.         table.addCell(p);
  84.         table.getDefaultCell().setUseAscender(false);
  85.         table.getDefaultCell().setUseDescender(true);
  86.         table.addCell("padding 2; descender, no ascender");
  87.         table.addCell(p);
  88.         table.getDefaultCell().setUseAscender(true);
  89.         table.getDefaultCell().setUseDescender(true);
  90.         table.addCell("padding 2; ascender and descender");
  91.         cell.setPadding(2);
  92.         cell.setUseAscender(true);
  93.         cell.setUseDescender(true);
  94.         table.addCell(p);
  95.         document.add(table);
  96.         // step 5
  97.         document.close();
  98.     }
  99. }
TableHeight.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.chapter04;
  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.PdfPTable;
  17. import com.itextpdf.text.pdf.PdfWriter;
  18.  
  19. public class TableHeight extends MyFirstTable {
  20.  
  21.     /** The resulting PDF file. */
  22.     public static final String RESULT = "results/part1/chapter04/table_height.pdf";
  23.    
  24.     /**
  25.      * Creates a PDF with information about the movies
  26.      * @param    filename the name of the PDF file that will be created.
  27.      * @throws    DocumentException
  28.      * @throws    IOException
  29.      */
  30.     public void createPdf(String filename)
  31.         throws IOException, DocumentException {
  32.         // step 1
  33.         Document document = new Document();
  34.         // step 2
  35.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  36.         // step 3
  37.         document.open();
  38.         // step 4
  39.         PdfPTable table = createFirstTable();
  40.         document.add(new Paragraph(
  41.             String.format("Table height before document.add(): %f",
  42.                 table.getTotalHeight())));
  43.         document.add(new Paragraph(
  44.             String.format("Height of the first row: %f",
  45.                 table.getRowHeight(0))));
  46.         document.add(table);
  47.         document.add(new Paragraph(
  48.             String.format("Table height after document.add(): %f",
  49.                 table.getTotalHeight())));
  50.         document.add(new Paragraph(
  51.             String.format("Height of the first row: %f",
  52.                 table.getRowHeight(0))));
  53.         table = createFirstTable();
  54.         document.add(new Paragraph(
  55.             String.format("Table height before setTotalWidth(): %f",
  56.                 table.getTotalHeight())));
  57.         document.add(
  58.             new Paragraph(String.format("Height of the first row: %f",
  59.                 table.getRowHeight(0))));
  60.         table.setTotalWidth(50);
  61.         table.setLockedWidth(true);
  62.         document.add(
  63.             new Paragraph(String.format("Table height after setTotalWidth(): %f",
  64.                 table.getTotalHeight())));
  65.         document.add(new Paragraph(String.format("Height of the first row: %f",
  66.             table.getRowHeight(0))));
  67.         document.add(table);
  68.         // step 5
  69.         document.close();
  70.     }
  71.  
  72.     /**
  73.      * Main method.
  74.      * @param    args    no arguments needed
  75.      * @throws DocumentException
  76.      * @throws IOException
  77.      */  
  78.     public static void main(String[] args) throws IOException, DocumentException {
  79.         new TableHeight().createPdf(RESULT);
  80.     }
  81. }
CellHeights.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.chapter04;
  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.Phrase;
  17. import com.itextpdf.text.pdf.PdfPCell;
  18. import com.itextpdf.text.pdf.PdfPTable;
  19. import com.itextpdf.text.pdf.PdfWriter;
  20.  
  21. public class CellHeights {
  22.     /** The resulting PDF file. */
  23.     public static final String RESULT = "results/part1/chapter04/cell_heights.pdf";
  24.  
  25.     /**
  26.      * Main method.
  27.      * @param    args    no arguments needed
  28.      * @throws DocumentException
  29.      * @throws IOException
  30.      */
  31.     public static void main(String[] args) throws DocumentException, IOException {
  32.         // step 1
  33.         Document document = new Document(PageSize.A5.rotate());
  34.         // step 2
  35.         PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  36.         // step 3
  37.         document.open();
  38.         // step 4
  39.         PdfPTable table = new PdfPTable(2);
  40.         // a long phrase
  41.         Phrase p = new Phrase(
  42.             "Dr. iText or: How I Learned to Stop Worrying and Love PDF.");
  43.         PdfPCell cell = new PdfPCell(p);
  44.         // the prhase is wrapped
  45.         table.addCell("wrap");
  46.         cell.setNoWrap(false);
  47.         table.addCell(cell);
  48.         // the phrase isn't wrapped
  49.         table.addCell("no wrap");
  50.         cell.setNoWrap(true);
  51.         table.addCell(cell);
  52.         // a long phrase with newlines
  53.         p = new Phrase(
  54.             "Dr. iText or:\nHow I Learned to Stop Worrying\nand Love PDF.");
  55.         cell = new PdfPCell(p);
  56.         // the phrase fits the fixed height
  57.         table.addCell("fixed height (more than sufficient)");
  58.         cell.setFixedHeight(72f);
  59.         table.addCell(cell);
  60.         // the phrase doesn't fit the fixed height
  61.         table.addCell("fixed height (not sufficient)");
  62.         cell.setFixedHeight(36f);
  63.         table.addCell(cell);
  64.         // The minimum height is exceeded
  65.         table.addCell("minimum height");
  66.         cell = new PdfPCell(new Phrase("Dr. iText"));
  67.         cell.setMinimumHeight(36f);
  68.         table.addCell(cell);
  69.         // The last row is extended
  70.         table.setExtendLastRow(true);
  71.         table.addCell("extend last row");
  72.         table.addCell(cell);
  73.         document.add(table);
  74.         // step 5
  75.         document.close();
  76.     }
  77. }
RotationAndColors.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.chapter04;
  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.Element;
  16. import com.itextpdf.text.PageSize;
  17. import com.itextpdf.text.Phrase;
  18. import com.itextpdf.text.Rectangle;
  19. import com.itextpdf.text.pdf.PdfPCell;
  20. import com.itextpdf.text.pdf.PdfPTable;
  21. import com.itextpdf.text.pdf.PdfWriter;
  22. import com.itextpdf.text.BaseColor;
  23.  
  24. public class RotationAndColors {
  25.     /** The resulting PDF file. */
  26.     public static final String RESULT
  27.         = "results/part1/chapter04/rotation_colors.pdf";
  28.  
  29.     /**
  30.      * Main method.
  31.      * @param    args    no arguments needed
  32.      * @throws DocumentException
  33.      * @throws IOException
  34.      */
  35.     public static void main(String[] args)
  36.         throws DocumentException, IOException {
  37.         // step 1
  38.         Document document = new Document(PageSize.A4.rotate());
  39.         // step 2
  40.         PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  41.         // step 3
  42.         document.open();
  43.         // step 4
  44.         PdfPTable table = new PdfPTable(4);
  45.         table.setWidths(new int[]{ 1, 3, 3, 3 });
  46.         table.setWidthPercentage(100);
  47.         PdfPCell cell;
  48.         // row 1, cell 1
  49.         cell = new PdfPCell(new Phrase("COLOR"));
  50.         cell.setRotation(90);
  51.         cell.setVerticalAlignment(Element.ALIGN_TOP);
  52.         table.addCell(cell);
  53.         // row 1, cell 2
  54.         cell = new PdfPCell(new Phrase("red / no borders"));
  55.         cell.setBorder(Rectangle.NO_BORDER);
  56.         cell.setBackgroundColor(BaseColor.RED);
  57.         table.addCell(cell);
  58.         // row 1, cell 3
  59.         cell = new PdfPCell(new Phrase("green / black bottom border"));
  60.         cell.setBorder(Rectangle.BOTTOM);
  61.         cell.setBorderColorBottom(BaseColor.BLACK);
  62.         cell.setBorderWidthBottom(10f);
  63.         cell.setBackgroundColor(BaseColor.GREEN);
  64.         table.addCell(cell);
  65.         // row 1, cell 4
  66.         cell = new PdfPCell(new Phrase(
  67.                 "cyan / blue top border + padding"));
  68.         cell.setBorder(Rectangle.TOP);
  69.         cell.setUseBorderPadding(true);
  70.         cell.setBorderWidthTop(5f);
  71.         cell.setBorderColorTop(BaseColor.BLUE);
  72.         cell.setBackgroundColor(BaseColor.CYAN);
  73.         table.addCell(cell);
  74.         // row 2, cell 1
  75.         cell = new PdfPCell(new Phrase("GRAY"));
  76.         cell.setRotation(90);
  77.         cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
  78.         table.addCell(cell);
  79.         // row 2, cell 2
  80.         cell = new PdfPCell(new Phrase("0.6"));
  81.         cell.setBorder(Rectangle.NO_BORDER);
  82.         cell.setGrayFill(0.6f);
  83.         table.addCell(cell);
  84.         // row 2, cell 3
  85.         cell = new PdfPCell(new Phrase("0.75"));
  86.         cell.setBorder(Rectangle.NO_BORDER);
  87.         cell.setGrayFill(0.75f);
  88.         table.addCell(cell);
  89.         // row 2, cell 4
  90.         cell = new PdfPCell(new Phrase("0.9"));
  91.         cell.setBorder(Rectangle.NO_BORDER);
  92.         cell.setGrayFill(0.9f);
  93.         table.addCell(cell);
  94.         // row 3, cell 1
  95.         cell = new PdfPCell(new Phrase("BORDERS"));
  96.         cell.setRotation(90);
  97.         cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
  98.         table.addCell(cell);
  99.         // row 3, cell 2
  100.         cell = new PdfPCell(new Phrase("different borders"));
  101.         cell.setBorderWidthLeft(16f);
  102.         cell.setBorderWidthBottom(12f);
  103.         cell.setBorderWidthRight(8f);
  104.         cell.setBorderWidthTop(4f);
  105.         cell.setBorderColorLeft(BaseColor.RED);
  106.         cell.setBorderColorBottom(BaseColor.ORANGE);
  107.         cell.setBorderColorRight(BaseColor.YELLOW);
  108.         cell.setBorderColorTop(BaseColor.GREEN);
  109.         table.addCell(cell);
  110.         // row 3, cell 3
  111.         cell = new PdfPCell(new Phrase("with correct padding"));
  112.         cell.setUseBorderPadding(true);
  113.         cell.setBorderWidthLeft(16f);
  114.         cell.setBorderWidthBottom(12f);
  115.         cell.setBorderWidthRight(8f);
  116.         cell.setBorderWidthTop(4f);
  117.         cell.setBorderColorLeft(BaseColor.RED);
  118.         cell.setBorderColorBottom(BaseColor.ORANGE);
  119.         cell.setBorderColorRight(BaseColor.YELLOW);
  120.         cell.setBorderColorTop(BaseColor.GREEN);
  121.         table.addCell(cell);
  122.         // row 3, cell 4
  123.         cell = new PdfPCell(new Phrase("red border"));
  124.         cell.setBorderWidth(8f);
  125.         cell.setBorderColor(BaseColor.RED);
  126.         table.addCell(cell);
  127.         document.add(table);
  128.         // step 5
  129.         document.close();
  130.     }
  131. }
MovieCompositeMode.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.chapter04;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13.  
  14. import com.lowagie.database.DatabaseConnection;
  15. import com.lowagie.database.HsqldbConnection;
  16. import com.lowagie.filmfestival.FilmFonts;
  17. import com.lowagie.filmfestival.PojoFactory;
  18. import com.lowagie.filmfestival.Movie;
  19. import com.lowagie.filmfestival.PojoToElementFactory;
  20. import com.itextpdf.text.Document;
  21. import com.itextpdf.text.DocumentException;
  22. import com.itextpdf.text.Element;
  23. import com.itextpdf.text.Image;
  24. import com.itextpdf.text.List;
  25. import com.itextpdf.text.Paragraph;
  26. import com.itextpdf.text.pdf.PdfPCell;
  27. import com.itextpdf.text.pdf.PdfPTable;
  28. import com.itextpdf.text.pdf.PdfWriter;
  29.  
  30. public class MovieCompositeMode {
  31.  
  32.     /** The resulting PDF file. */
  33.     public static final String RESULT
  34.         = "results/part1/chapter04/movie_composite_mode.pdf";
  35.     /** Path to the resources. */
  36.     public static final String RESOURCE
  37.         = "resources/posters/%s.jpg";
  38.    
  39.     /**
  40.      * Main method.
  41.      *
  42.      * @param    args    no arguments needed
  43.      * @throws DocumentException
  44.      * @throws IOException
  45.      * @throws SQLException
  46.      */
  47.     public static void main(String[] args)
  48.         throws IOException, DocumentException, SQLException {
  49.         new MovieCompositeMode().createPdf(RESULT);
  50.     }
  51.    
  52.     /**
  53.      * Creates a PDF with information about the movies
  54.      * @param    filename the name of the PDF file that will be created.
  55.      * @throws    DocumentException
  56.      * @throws    IOException
  57.      * @throws    SQLException
  58.      */
  59.     public void createPdf(String filename)
  60.         throws IOException, DocumentException, SQLException {
  61.         // Create a database connection
  62.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  63.         // step 1
  64.         Document document = new Document();
  65.         // step 2
  66.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  67.         // step 3
  68.         document.open();
  69.         // step 4
  70.         document.add(new Paragraph("Movies:"));
  71.         java.util.List movies = PojoFactory.getMovies(connection);
  72.         List list;
  73.         PdfPCell cell;
  74.         for (Movie movie : movies) {
  75.             // a table with two columns
  76.             PdfPTable table = new PdfPTable(new float[]{1, 7});
  77.             table.setWidthPercentage(100);
  78.             table.setSpacingBefore(5);
  79.             // a cell with an image
  80.             cell = new PdfPCell(
  81.                 Image.getInstance(String.format(RESOURCE, movie.getImdb())), true);
  82.             cell.setBorder(PdfPCell.NO_BORDER);
  83.             table.addCell(cell);
  84.             cell = new PdfPCell();
  85.             // a cell with paragraphs and lists
  86.             Paragraph p = new Paragraph(movie.getTitle(), FilmFonts.BOLD);
  87.             p.setAlignment(Element.ALIGN_CENTER);
  88.             p.setSpacingBefore(5);
  89.             p.setSpacingAfter(5);
  90.             cell.addElement(p);
  91.             cell.setBorder(PdfPCell.NO_BORDER);
  92.             if (movie.getOriginalTitle() != null) {
  93.                 p = new Paragraph(movie.getOriginalTitle(), FilmFonts.ITALIC);
  94.                 p.setAlignment(Element.ALIGN_RIGHT);
  95.                 cell.addElement(p);
  96.             }
  97.             list = PojoToElementFactory.getDirectorList(movie);
  98.             list.setIndentationLeft(30);
  99.             cell.addElement(list);
  100.             p = new Paragraph(
  101.                 String.format("Year: %d", movie.getYear()), FilmFonts.NORMAL);
  102.             p.setIndentationLeft(15);
  103.             p.setLeading(24);
  104.             cell.addElement(p);
  105.             p = new Paragraph(
  106.                 String.format("Run length: %d", movie.getDuration()), FilmFonts.NORMAL);
  107.             p.setLeading(14);
  108.             p.setIndentationLeft(30);
  109.             cell.addElement(p);
  110.             list = PojoToElementFactory.getCountryList(movie);
  111.             list.setIndentationLeft(40);
  112.             cell.addElement(list);
  113.             table.addCell(cell);
  114.             // every movie corresponds with one table
  115.             document.add(table);
  116.             // but the result looks like one big table
  117.         }
  118.         // step 4
  119.         document.close();
  120.         // Close the database connection
  121.         connection.close();
  122.     }
  123. }
XMen.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.chapter04;
  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.Element;
  16. import com.itextpdf.text.Image;
  17. import com.itextpdf.text.PageSize;
  18. import com.itextpdf.text.pdf.PdfPCell;
  19. import com.itextpdf.text.pdf.PdfPTable;
  20. import com.itextpdf.text.pdf.PdfWriter;
  21.  
  22. public class XMen {
  23.  
  24.     /** The resulting PDF file. */
  25.     public static final String RESULT = "results/part1/chapter04/x_men.pdf";
  26.     /** Path to the resources. */
  27.     public static final String RESOURCE = "resources/posters/%s.jpg";
  28.    
  29.     /**
  30.      * Creates a PDF with information about the movies
  31.      * @param    filename the name of the PDF file that will be created.
  32.      * @throws    DocumentException
  33.      * @throws    IOException
  34.      */
  35.     public void createPdf(String filename)
  36.         throws IOException, DocumentException {
  37.         // step 1
  38.         Document document = new Document(PageSize.A4.rotate());
  39.         // step 2
  40.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  41.         // step 3
  42.         document.open();
  43.         // step 4
  44.         // we'll use 4 images in this example
  45.         Image[] img = {
  46.                 Image.getInstance(String.format(RESOURCE, "0120903")),
  47.                 Image.getInstance(String.format(RESOURCE, "0290334")),
  48.                 Image.getInstance(String.format(RESOURCE, "0376994")),
  49.                 Image.getInstance(String.format(RESOURCE, "0348150"))
  50.         };
  51.         // Creates a table with 6 columns
  52.         PdfPTable table = new PdfPTable(6);
  53.         table.setWidthPercentage(100);
  54.         // first movie
  55.         table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
  56.         table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
  57.         table.addCell("X-Men");
  58.         // we wrap he image in a PdfPCell
  59.         PdfPCell cell = new PdfPCell(img[0]);
  60.         table.addCell(cell);
  61.         // second movie
  62.         table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
  63.         table.addCell("X2");
  64.         // we wrap the image in a PdfPCell and let iText scale it
  65.         cell = new PdfPCell(img[1], true);
  66.         table.addCell(cell);
  67.         // third movie
  68.         table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
  69.         table.addCell("X-Men: The Last Stand");
  70.         // we add the image with addCell()
  71.         table.addCell(img[2]);
  72.         // fourth movie
  73.         table.addCell("Superman Returns");
  74.         cell = new PdfPCell();
  75.         // we add it with addElement(); it can only take 50% of the width.
  76.         img[3].setWidthPercentage(50);
  77.         cell.addElement(img[3]);
  78.         table.addCell(cell);
  79.         // we complete the table (otherwise the last row won't be rendered)
  80.         table.completeRow();
  81.         document.add(table);
  82.         document.close();
  83.     }
  84.  
  85.     /**
  86.      * Main method.
  87.      * @param    args    no arguments needed
  88.      * @throws DocumentException
  89.      * @throws IOException
  90.      */
  91.     public static void main(String[] args) throws IOException, DocumentException {
  92.         new XMen().createPdf(RESULT);
  93.     }
  94. }
NestedTable.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.chapter04;
  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.pdf.PdfPCell;
  16. import com.itextpdf.text.pdf.PdfPTable;
  17. import com.itextpdf.text.pdf.PdfWriter;
  18.  
  19. public class NestedTable {
  20.  
  21.     /** The resulting PDF file. */
  22.     public static final String RESULT
  23.         = "results/part1/chapter04/nested_table.pdf";
  24.  
  25.     /**
  26.      * Main method.
  27.      * @param args no arguments needed
  28.      * @throws DocumentException
  29.      * @throws IOException
  30.      */
  31.     public static void main(String[] args)
  32.         throws DocumentException, IOException {
  33.         // step 1
  34.         Document document = new Document();
  35.         // step 2
  36.         PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  37.         // step 3
  38.         document.open();
  39.         // step 4
  40.         PdfPTable table = new PdfPTable(4);
  41.         PdfPTable nested1 = new PdfPTable(2);
  42.         nested1.addCell("1.1");
  43.         nested1.addCell("1.2");
  44.         PdfPTable nested2 = new PdfPTable(1);
  45.         nested2.addCell("12.1");
  46.         nested2.addCell("12.2");
  47.         for (int k = 0; k < 16; ++k) {
  48.             if (k == 1) {
  49.                 table.addCell(nested1);
  50.             } else if (k == 12) {
  51.                 table.addCell(new PdfPCell(nested2));
  52.             } else {
  53.                 table.addCell("cell " + k);
  54.             }
  55.         }
  56.         document.add(table);
  57.         // step 5
  58.         document.close();
  59.     }
  60. }
NestedTables.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.chapter04;
  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.HashMap;
  15. import java.util.List;
  16.  
  17. import com.lowagie.database.DatabaseConnection;
  18. import com.lowagie.database.HsqldbConnection;
  19. import com.lowagie.filmfestival.FilmFonts;
  20. import com.lowagie.filmfestival.Movie;
  21. import com.lowagie.filmfestival.PojoFactory;
  22. import com.lowagie.filmfestival.PojoToElementFactory;
  23. import com.lowagie.filmfestival.Screening;
  24. import com.itextpdf.text.Document;
  25. import com.itextpdf.text.DocumentException;
  26. import com.itextpdf.text.Element;
  27. import com.itextpdf.text.Font;
  28. import com.itextpdf.text.Image;
  29. import com.itextpdf.text.Paragraph;
  30. import com.itextpdf.text.Phrase;
  31. import com.itextpdf.text.html.WebColors;
  32. import com.itextpdf.text.pdf.PdfPCell;
  33. import com.itextpdf.text.pdf.PdfPTable;
  34. import com.itextpdf.text.pdf.PdfWriter;
  35. import com.itextpdf.text.BaseColor;
  36.  
  37. public class NestedTables {
  38.  
  39.     /** The resulting PDF file. */
  40.     public static final String RESULT = "results/part1/chapter04/nested_tables.pdf";
  41.     /** Path to the resources. */
  42.     public static final String RESOURCE = "resources/posters/%s.jpg";
  43.     /** Collection containing all the Images */
  44.     public HashMap images = new HashMap();
  45.  
  46.     /**
  47.      * Creates a PDF document.
  48.      * @param filename the path to the new PDF document
  49.      * @throws    DocumentException
  50.      * @throws    IOException
  51.      * @throws    SQLException
  52.      */
  53.     public void createPdf(String filename)
  54.         throws SQLException, DocumentException, IOException {
  55.         // create the database connection
  56.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  57.         // step 1
  58.         Document document = new Document();
  59.         // step 2
  60.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  61.         // step 3
  62.         document.open();
  63.         // step 4
  64.         List days = PojoFactory.getDays(connection);
  65.         for (Date day : days) {
  66.             document.add(getTable(connection, day));
  67.             document.newPage();
  68.         }
  69.         // step 5
  70.         document.close();
  71.         // close the database connection
  72.         connection.close();
  73.  
  74.     }
  75.  
  76.     /**
  77.      * Creates a table with all the screenings of a specific day.
  78.      * The table is composed of nested tables.
  79.      * @param connection a database connection
  80.      * @param day a film festival day
  81.      * @return a table
  82.      * @throws SQLException
  83.      * @throws DocumentException
  84.      * @throws IOException
  85.      */
  86.     public PdfPTable getTable(DatabaseConnection connection, Date day)
  87.         throws SQLException, DocumentException, IOException {
  88.         // Create a table with only one column
  89.         PdfPTable table = new PdfPTable(1);
  90.         table.setWidthPercentage(100f);
  91.         // add the cell with the date
  92.         Font f = new Font();
  93.         f.setColor(BaseColor.WHITE);
  94.         PdfPCell cell = new PdfPCell(new Phrase(day.toString(), f));
  95.         cell.setBackgroundColor(BaseColor.BLACK);
  96.         cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  97.         table.addCell(cell);
  98.         // add the movies as nested tables
  99.         List screenings = PojoFactory.getScreenings(connection, day);
  100.         for (Screening screening : screenings) {
  101.             table.addCell(getTable(connection, screening));
  102.         }
  103.         return table;
  104.     }
  105.  
  106.     /**
  107.      * Create a table with information about a movie.
  108.      * @param connection a database connection
  109.      * @param screening a Screening
  110.      * @return a table
  111.      * @throws DocumentException
  112.      * @throws IOException
  113.      */
  114.     private PdfPTable getTable(DatabaseConnection connection, Screening screening)
  115.         throws DocumentException, IOException {
  116.         // Create a table with 4 columns
  117.         PdfPTable table = new PdfPTable(4);
  118.         table.setWidths(new int[]{1, 5, 10, 10});
  119.         // Get the movie
  120.         Movie movie = screening.getMovie();
  121.         // A cell with the title as a nested table spanning the complete row
  122.         PdfPCell cell = new PdfPCell();
  123.         // nesting is done with addElement() in this example
  124.         cell.addElement(fullTitle(screening));
  125.         cell.setColspan(4);
  126.         cell.setBorder(PdfPCell.NO_BORDER);
  127.         BaseColor color
  128.             = WebColors.getRGBColor("#" + movie.getEntry().getCategory().getColor());
  129.         cell.setBackgroundColor(color);
  130.         table.addCell(cell);
  131.         // empty cell
  132.         cell = new PdfPCell();
  133.         cell.setBorder(PdfPCell.NO_BORDER);
  134.         cell.setUseAscender(true);
  135.         cell.setUseDescender(true);
  136.         table.addCell(cell);
  137.         // cell with the movie poster
  138.         cell = new PdfPCell(getImage(movie.getImdb()));
  139.         cell.setBorder(PdfPCell.NO_BORDER);
  140.         table.addCell(cell);
  141.         // cell with the list of directors
  142.         cell = new PdfPCell();
  143.         cell.addElement(PojoToElementFactory.getDirectorList(movie));
  144.         cell.setBorder(PdfPCell.NO_BORDER);
  145.         cell.setUseAscender(true);
  146.         cell.setUseDescender(true);
  147.         table.addCell(cell);
  148.         // cell with the list of countries
  149.         cell = new PdfPCell();
  150.         cell.addElement(PojoToElementFactory.getCountryList(movie));
  151.         cell.setBorder(PdfPCell.NO_BORDER);
  152.         cell.setUseAscender(true);
  153.         cell.setUseDescender(true);
  154.         table.addCell(cell);
  155.  
  156.         return table;
  157.     }
  158.    
  159.     /**
  160.      * Create a table with the full movie title
  161.      * @param screening a Screening object
  162.      * @return a table
  163.      * @throws DocumentException
  164.      */
  165.     private static PdfPTable fullTitle(Screening screening)
  166.         throws DocumentException {
  167.         PdfPTable table = new PdfPTable(3);
  168.         table.setWidths(new int[]{3, 15, 2});
  169.         table.setWidthPercentage(100);
  170.         // cell 1: location and time
  171.         PdfPCell cell = new PdfPCell();
  172.         cell.setBorder(PdfPCell.NO_BORDER);
  173.         cell.setBackgroundColor(BaseColor.WHITE);
  174.         cell.setUseAscender(true);
  175.         cell.setUseDescender(true);
  176.         String s = String.format("%s \u2013 %2$tH:%2$tM",
  177.             screening.getLocation(), screening.getTime().getTime());
  178.         cell.addElement(new Paragraph(s));
  179.         table.addCell(cell);
  180.         // cell 2: English and original title
  181.         Movie movie = screening.getMovie();
  182.         Paragraph p = new Paragraph();
  183.         p.add(new Phrase(movie.getMovieTitle(), FilmFonts.BOLD));
  184.         p.setLeading(16);
  185.         if (movie.getOriginalTitle() != null) {
  186.             p.add(new Phrase(" (" + movie.getOriginalTitle() + ")"));
  187.         }
  188.         cell = new PdfPCell();
  189.         cell.addElement(p);
  190.         cell.setBorder(PdfPCell.NO_BORDER);
  191.         cell.setUseAscender(true);
  192.         cell.setUseDescender(true);
  193.         table.addCell(cell);
  194.         // cell 3 duration
  195.         cell = new PdfPCell();
  196.         cell.setBorder(PdfPCell.NO_BORDER);
  197.         cell.setBackgroundColor(BaseColor.WHITE);
  198.         cell.setUseAscender(true);
  199.         cell.setUseDescender(true);
  200.         p = new Paragraph(String.format("%d'", movie.getDuration()));
  201.         p.setAlignment(Element.ALIGN_CENTER);
  202.         cell.addElement(p);
  203.         table.addCell(cell);
  204.         return table;
  205.     }
  206.    
  207.     /**
  208.      * Create an image with a movie poster.
  209.      * @param imdb an Internet Movie Database id
  210.      * @return an Image
  211.      * @throws DocumentException
  212.      * @throws IOException
  213.      */
  214.     public Image getImage(String imdb) throws DocumentException, IOException {
  215.         Image img = images.get(imdb);
  216.         if (img == null) {
  217.             img = Image.getInstance(String.format(RESOURCE, imdb));
  218.             img.scaleToFit(80, 72);
  219.             images.put(imdb, img);
  220.         }
  221.         return img;
  222.     }
  223.  
  224.     /**
  225.      * Main method.
  226.      * @param args no arguments needed
  227.      * @throws DocumentException
  228.      * @throws IOException
  229.      * @throws SQLException
  230.      */
  231.     public static void main(String[] args)
  232.         throws SQLException, DocumentException, IOException {
  233.         new NestedTables().createPdf(RESULT);
  234.     }
  235. }
HeaderFooter1.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.chapter04;
  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.PojoToElementFactory;
  21. import com.lowagie.filmfestival.Screening;
  22. import com.itextpdf.text.Document;
  23. import com.itextpdf.text.DocumentException;
  24. import com.itextpdf.text.Element;
  25. import com.itextpdf.text.Font;
  26. import com.itextpdf.text.PageSize;
  27. import com.itextpdf.text.Phrase;
  28. import com.itextpdf.text.pdf.PdfPCell;
  29. import com.itextpdf.text.pdf.PdfPTable;
  30. import com.itextpdf.text.pdf.PdfWriter;
  31. import com.itextpdf.text.BaseColor;
  32.  
  33. public class HeaderFooter1 {
  34.  
  35.     /** The resulting PDF file. */
  36.     public static final String RESULT = "results/part1/chapter04/header_footer_1.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)
  46.         throws SQLException, DocumentException, IOException {
  47.         // create a database connection
  48.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  49.         // step 1
  50.         Document document = new Document(PageSize.A4.rotate());
  51.         // step 2
  52.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  53.         // step 3
  54.         document.open();
  55.         // step 4
  56.         List days = PojoFactory.getDays(connection);
  57.         for (Date day : days) {
  58.             document.add(getTable(connection, day));
  59.             document.newPage();
  60.         }
  61.         // step 5
  62.         document.close();
  63.         // close the database connection
  64.         connection.close();
  65.  
  66.     }
  67.  
  68.     /**
  69.      * Creates a table with screenings.
  70.      * @param connection the database connection
  71.      * @param day a film festival day
  72.      * @return a table with screenings
  73.      * @throws SQLException
  74.      * @throws DocumentException
  75.      * @throws IOException
  76.      */
  77.     public PdfPTable getTable(DatabaseConnection connection, Date day)
  78.         throws SQLException, DocumentException, IOException {
  79.         // Create a table with 7 columns
  80.         PdfPTable table = new PdfPTable(new float[] { 2, 1, 2, 5, 1, 3, 2 });
  81.         table.setWidthPercentage(100f);
  82.         table.getDefaultCell().setUseAscender(true);
  83.         table.getDefaultCell().setUseDescender(true);
  84.         // Add the first header row
  85.         Font f = new Font();
  86.         f.setColor(BaseColor.WHITE);
  87.         PdfPCell cell = new PdfPCell(new Phrase(day.toString(), f));
  88.         cell.setBackgroundColor(BaseColor.BLACK);
  89.         cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  90.         cell.setColspan(7);
  91.         table.addCell(cell);
  92.         // Add the second header row twice
  93.         table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
  94.         for (int i = 0; i < 2; i++) {
  95.             table.addCell("Location");
  96.             table.addCell("Time");
  97.             table.addCell("Run Length");
  98.             table.addCell("Title");
  99.             table.addCell("Year");
  100.             table.addCell("Directors");
  101.             table.addCell("Countries");
  102.         }
  103.         table.getDefaultCell().setBackgroundColor(null);
  104.         // There are three special rows
  105.         table.setHeaderRows(3);
  106.         // One of them is a footer
  107.         table.setFooterRows(1);
  108.         // Now let's loop over the screenings
  109.         List screenings = PojoFactory.getScreenings(connection, day);
  110.         Movie movie;
  111.         for (Screening screening : screenings) {
  112.             movie = screening.getMovie();
  113.             table.addCell(screening.getLocation());
  114.             table.addCell(String.format("%1$tH:%1$tM", screening.getTime()));
  115.             table.addCell(String.format("%d '", movie.getDuration()));
  116.             table.addCell(movie.getMovieTitle());
  117.             table.addCell(String.valueOf(movie.getYear()));
  118.             cell = new PdfPCell();
  119.             cell.setUseAscender(true);
  120.             cell.setUseDescender(true);
  121.             cell.addElement(PojoToElementFactory.getDirectorList(movie));
  122.             table.addCell(cell);
  123.             cell = new PdfPCell();
  124.             cell.setUseAscender(true);
  125.             cell.setUseDescender(true);
  126.             cell.addElement(PojoToElementFactory.getCountryList(movie));
  127.             table.addCell(cell);
  128.         }
  129.         return table;
  130.     }
  131.  
  132.     /**
  133.      * Main method.
  134.      * @param args no arguments needed
  135.      * @throws DocumentException
  136.      * @throws IOException
  137.      * @throws SQLException
  138.      */
  139.     public static void main(String[] args)
  140.         throws SQLException, DocumentException, IOException {
  141.         new HeaderFooter1().createPdf(RESULT);
  142.     }
  143. }
HeaderFooter2.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.chapter04;
  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.PojoFactory;
  19. import com.itextpdf.text.Document;
  20. import com.itextpdf.text.DocumentException;
  21. import com.itextpdf.text.PageSize;
  22. import com.itextpdf.text.pdf.PdfPTable;
  23. import com.itextpdf.text.pdf.PdfWriter;
  24.  
  25. public class HeaderFooter2 extends HeaderFooter1 {
  26.  
  27.     /** The resulting PDF file. */
  28.     public static final String RESULT
  29.         = "results/part1/chapter04/header_footer_2.pdf";
  30.  
  31.     /**
  32.      * Creates a PDF document.
  33.      * @param filename the path to the new PDF document
  34.      * @throws    DocumentException
  35.      * @throws    IOException
  36.      * @throws    SQLException
  37.      */
  38.     public void createPdf(String filename)
  39.         throws SQLException, DocumentException, IOException {
  40.         // create a database connection
  41.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  42.         // step 1
  43.         Document document = new Document(PageSize.A4.rotate());
  44.         // step 2
  45.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  46.         // step 3
  47.         document.open();
  48.         // step 4
  49.         List days = PojoFactory.getDays(connection);
  50.         for (Date day : days) {
  51.             PdfPTable table = getTable(connection, day);
  52.             table.setSplitLate(false);
  53.             document.add(table);
  54.             document.newPage();
  55.         }
  56.         // step 5
  57.         document.close();
  58.         // close the database connection
  59.         connection.close();
  60.     }
  61.  
  62.     /**
  63.      * Main method.
  64.      * @param args no arguments needed
  65.      * @throws DocumentException
  66.      * @throws IOException
  67.      * @throws SQLException
  68.      */
  69.     public static void main(String[] args)
  70.         throws SQLException, DocumentException, IOException {
  71.         new HeaderFooter2().createPdf(RESULT);
  72.     }
  73. }
MemoryTests.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.chapter04;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.PrintWriter;
  13. import java.io.Writer;
  14. import java.sql.SQLException;
  15.  
  16. import com.lowagie.database.DatabaseConnection;
  17. import com.lowagie.database.HsqldbConnection;
  18. import com.lowagie.filmfestival.FilmFonts;
  19. import com.lowagie.filmfestival.Movie;
  20. import com.lowagie.filmfestival.PojoFactory;
  21. import com.lowagie.filmfestival.PojoToElementFactory;
  22. import com.itextpdf.text.Document;
  23. import com.itextpdf.text.DocumentException;
  24. import com.itextpdf.text.Element;
  25. import com.itextpdf.text.Font;
  26. import com.itextpdf.text.Image;
  27. import com.itextpdf.text.List;
  28. import com.itextpdf.text.Paragraph;
  29. import com.itextpdf.text.Font.FontFamily;
  30. import com.itextpdf.text.pdf.PdfPCell;
  31. import com.itextpdf.text.pdf.PdfPTable;
  32. import com.itextpdf.text.pdf.PdfWriter;
  33.  
  34. public class MemoryTests {
  35.  
  36.     /** The resulting report. */
  37.     public static final String RESULT0
  38.        = "results/part1/chapter04/test_results.txt";
  39.     /** A resulting PDF file. */
  40.     public static final String RESULT1
  41.         = "results/part1/chapter04/pdfptable_without_memory_management.pdf";
  42.     /** A resulting PDF file. */
  43.     public static final String RESULT2
  44.         = "results/part1/chapter04/pdfptable_with_memory_management.pdf";
  45.    
  46.     private boolean test;
  47.     private long memory_use;
  48.     private long initial_memory_use = 0l;
  49.     private long maximum_memory_use = 0l;
  50.    
  51.     /** Path to the resources. */
  52.     public static final String RESOURCE = "resources/posters/%s.jpg";
  53.     /** The different epochs. */
  54.     public static final String[] EPOCH =
  55.         { "Forties", "Fifties", "Sixties", "Seventies", "Eighties", "Nineties", "Twenty-first Century" };
  56.    
  57.     /** The fonts for the title. */
  58.     public static final Font[] FONT = new Font[4];
  59.     static {
  60.         FONT[0] = new Font(FontFamily.HELVETICA, 24);
  61.         FONT[1] = new Font(FontFamily.HELVETICA, 18);
  62.         FONT[2] = new Font(FontFamily.HELVETICA, 14);
  63.         FONT[3] = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
  64.     }
  65.    
  66.     /**
  67.      * Create two PDFs, one without memory management, one with.
  68.      * Write a report file to show the memory usage
  69.      */
  70.     public void createPdfs() {
  71.         try {
  72.             // the report file
  73.             PrintWriter writer = new PrintWriter(new FileOutputStream(RESULT0));
  74.             resetMaximum(writer);
  75.             test = false;
  76.             println(writer, RESULT1);
  77.             // PDF without memory management
  78.             createPdfWithPdfPTable(writer, RESULT1);
  79.             resetMaximum(writer);
  80.             test = true;
  81.             println(writer, RESULT2);
  82.             // PDF with memory management
  83.             createPdfWithPdfPTable(writer, RESULT2);
  84.             resetMaximum(writer);
  85.             writer.flush();
  86.             writer.close();
  87.         }
  88.         catch(Exception e) {
  89.             e.printStackTrace();
  90.         }
  91.     }
  92.  
  93.     /**
  94.      * Creates a PDF with a table
  95.      * @param writer the writer to our report file
  96.      * @param filename the PDF that will be created
  97.      * @throws IOException
  98.      * @throws DocumentException
  99.      * @throws SQLException
  100.      */
  101.     private void createPdfWithPdfPTable(Writer writer, String filename) throws IOException, DocumentException, SQLException {
  102.         // Create a connection to the database
  103.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  104.         // step 1
  105.         Document document = new Document();
  106.         // step 2
  107.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  108.         // step 3
  109.         document.open();
  110.         // step 4
  111.         // Create a table with 2 columns
  112.         PdfPTable table = new PdfPTable(new float[]{1, 7});
  113.         // Mark the table as not complete
  114.         if (test) table.setComplete(false);
  115.         table.setWidthPercentage(100);
  116.         java.util.List movies = PojoFactory.getMovies(connection);
  117.         List list;
  118.         PdfPCell cell;
  119.         int count = 0;
  120.         // add information about a movie
  121.         for (Movie movie : movies) {
  122.             table.setSpacingBefore(5);
  123.             // add a movie poster
  124.             cell = new PdfPCell(Image.getInstance(String.format(RESOURCE, movie.getImdb())), true);
  125.             cell.setBorder(PdfPCell.NO_BORDER);
  126.             table.addCell(cell);
  127.             // add movie information
  128.             cell = new PdfPCell();
  129.             Paragraph p = new Paragraph(movie.getTitle(), FilmFonts.BOLD);
  130.             p.setAlignment(Element.ALIGN_CENTER);
  131.             p.setSpacingBefore(5);
  132.             p.setSpacingAfter(5);
  133.             cell.addElement(p);
  134.             cell.setBorder(PdfPCell.NO_BORDER);
  135.             if (movie.getOriginalTitle() != null) {
  136.                 p = new Paragraph(movie.getOriginalTitle(), FilmFonts.ITALIC);
  137.                 p.setAlignment(Element.ALIGN_RIGHT);
  138.                 cell.addElement(p);
  139.             }
  140.             list = PojoToElementFactory.getDirectorList(movie);
  141.             list.setIndentationLeft(30);
  142.             cell.addElement(list);
  143.             p = new Paragraph(String.format("Year: %d", movie.getYear()), FilmFonts.NORMAL);
  144.             p.setIndentationLeft(15);
  145.             p.setLeading(24);
  146.             cell.addElement(p);
  147.             p = new Paragraph(String.format("Run length: %d", movie.getDuration()), FilmFonts.NORMAL);
  148.             p.setLeading(14);
  149.             p.setIndentationLeft(30);
  150.             cell.addElement(p);
  151.             list = PojoToElementFactory.getCountryList(movie);
  152.             list.setIndentationLeft(40);
  153.             cell.addElement(list);
  154.             table.addCell(cell);
  155.             // insert a checkpoint every 10 movies
  156.             if (count++ % 10 == 0) {
  157.                 // add the incomplete table to the document
  158.                 if (test)
  159.                     document.add(table);
  160.                 checkpoint(writer);
  161.             }
  162.         }
  163.         // Mark the table as complete
  164.         if (test) table.setComplete(true);
  165.         // add the table to the document
  166.         document.add(table);
  167.         // insert a last checkpoint
  168.         checkpoint(writer);
  169.         // step 5
  170.         document.close();
  171.     }
  172.    
  173.     /**
  174.      * Writes a checkpoint to the report file.
  175.      * @param writer the writer to our report file
  176.      */
  177.     private void checkpoint(Writer writer) {
  178.         memory_use = getMemoryUse();
  179.         maximum_memory_use = Math.max(maximum_memory_use, memory_use);
  180.         println(writer, "memory use: ", memory_use);
  181.     }
  182.    
  183.     /**
  184.      * Resets the maximum memory that is in use
  185.      * @param writer the writer to our report file
  186.      */
  187.     private void resetMaximum(Writer writer) {
  188.         println(writer, "maximum: ", maximum_memory_use);
  189.         println(writer, "total used: ", maximum_memory_use - initial_memory_use);
  190.         maximum_memory_use = 0l;
  191.         initial_memory_use = getMemoryUse();
  192.         println(writer, "initial memory use: ", initial_memory_use);
  193.     }
  194.  
  195.     /**
  196.      * Writes a line to our report file
  197.      * @param writer the writer to our report file
  198.      * @param message the message to write
  199.      */
  200.     private void println(Writer writer, String message) {
  201.         try {
  202.             writer.write(message);
  203.             writer.write("\n");
  204.             writer.flush();
  205.         } catch (IOException e) {
  206.             e.printStackTrace();
  207.         }
  208.     }
  209.    
  210.     /**
  211.      * Writes a line to our report file
  212.      * @param writer the writer to our report file
  213.      * @param message the message to write
  214.      * @param l a memory value
  215.      */
  216.     private void println(Writer writer, String message, long l) {
  217.         try {
  218.             writer.write(message + l);
  219.             writer.write("\n");
  220.             writer.flush();
  221.         } catch (IOException e) {
  222.             e.printStackTrace();
  223.         }
  224.     }
  225.    
  226.     /**
  227.      * Returns the current memory use.
  228.      *
  229.      * @return the current memory use
  230.      */
  231.     private static long getMemoryUse() {
  232.         garbageCollect();
  233.         garbageCollect();
  234.         long totalMemory = Runtime.getRuntime().totalMemory();
  235.         garbageCollect();
  236.         garbageCollect();
  237.         long freeMemory = Runtime.getRuntime().freeMemory();
  238.         return (totalMemory - freeMemory);
  239.     }
  240.    
  241.     /**
  242.      * Makes sure all garbage is cleared from the memory.
  243.      */
  244.     private static void garbageCollect() {
  245.         try {
  246.             System.gc();
  247.             Thread.sleep(100);
  248.             System.runFinalization();
  249.             Thread.sleep(100);
  250.             System.gc();
  251.             Thread.sleep(100);
  252.             System.runFinalization();
  253.             Thread.sleep(100);
  254.         } catch (InterruptedException ex) {
  255.             ex.printStackTrace();
  256.         }
  257.     }
  258.  
  259.     /**
  260.      * Main method.
  261.      * @param args no arguments needed
  262.      * @throws DocumentException
  263.      * @throws IOException
  264.      * @throws SQLException
  265.      */
  266.     public static void main(String[] args) {
  267.         MemoryTests tests = new MemoryTests();
  268.         tests.createPdfs();
  269.     }
  270. }
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.chapter04;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.util.Calendar;
  14. import java.util.GregorianCalendar;
  15. import java.util.Locale;
  16. import java.util.Properties;
  17.  
  18. import com.itextpdf.text.Chunk;
  19. import com.itextpdf.text.Document;
  20. import com.itextpdf.text.DocumentException;
  21. import com.itextpdf.text.Element;
  22. import com.itextpdf.text.Font;
  23. import com.itextpdf.text.Image;
  24. import com.itextpdf.text.PageSize;
  25. import com.itextpdf.text.Paragraph;
  26. import com.itextpdf.text.Phrase;
  27. import com.itextpdf.text.pdf.BaseFont;
  28. import com.itextpdf.text.pdf.ColumnText;
  29. import com.itextpdf.text.pdf.PdfContentByte;
  30. import com.itextpdf.text.pdf.PdfPCell;
  31. import com.itextpdf.text.pdf.PdfPTable;
  32. import com.itextpdf.text.pdf.PdfWriter;
  33. import com.itextpdf.text.BaseColor;
  34. import com.itextpdf.text.pdf.draw.VerticalPositionMark;
  35.  
  36. public class PdfCalendar {
  37.  
  38.     /** The resulting PDF file. */
  39.     public static final String RESULT = "results/part1/chapter04/calendar.pdf";
  40.     /** The year for which we want to create a calendar */
  41.     public static final int YEAR = 2011;
  42.     /** The language code for the calendar */
  43.     public static final String LANGUAGE = "en";
  44.     /** Path to the resources. */
  45.     public static final String RESOURCE = "resources/calendar/%tm.jpg";
  46.     /** Path to the resources. */
  47.     public static final String SPECIAL = "resources/calendar/%d.txt";
  48.     /** Path to the resources. */
  49.     public static final String CONTENT = "resources/calendar/content.txt";
  50.  
  51.     /** Collection with special days */
  52.     public static Properties specialDays = new Properties();
  53.     /** Collection with the description of the images */
  54.     public static Properties content = new Properties();
  55.  
  56.     /** A font that is used in the calendar */
  57.     protected Font normal;
  58.     /** A font that is used in the calendar */
  59.     protected Font small;
  60.     /** A font that is used in the calendar */
  61.     protected Font bold;
  62.  
  63.     /**
  64.      * Main method.
  65.      * @param    args    no arguments needed
  66.      * @throws DocumentException
  67.      * @throws IOException
  68.      */
  69.     public static void main(String[] args)
  70.         throws IOException, DocumentException {
  71.         Locale locale = new Locale(LANGUAGE);
  72.         new PdfCalendar().createPdf(RESULT, locale, YEAR);
  73.     }
  74.    
  75.     /**
  76.      * Initializes the fonts and collections.
  77.      * @throws DocumentException
  78.      * @throws IOException
  79.      */
  80.     public PdfCalendar() throws DocumentException, IOException {
  81.         // fonts
  82.         BaseFont bf_normal
  83.             = BaseFont.createFont("c://windows/fonts/arial.ttf",
  84.                 BaseFont.WINANSI, BaseFont.EMBEDDED);
  85.         normal = new Font(bf_normal, 16);
  86.         small = new Font(bf_normal, 8);
  87.         BaseFont bf_bold
  88.             = BaseFont.createFont("c://windows/fonts/arialbd.ttf",
  89.                 BaseFont.WINANSI,BaseFont.EMBEDDED);
  90.         bold = new Font(bf_bold, 14);
  91.         // collections
  92.         specialDays.load(new FileInputStream(String.format(SPECIAL, YEAR)));
  93.         content.load(new FileInputStream(CONTENT));
  94.     }
  95.  
  96.     /**
  97.      * Creates a PDF document.
  98.      * @param filename the path to the new PDF document
  99.      * @param locale Locale in case you want to create
  100.      * a Calendar in another language
  101.      * @param year the year for which you want to make a calendar
  102.      * @throws    DocumentException
  103.      * @throws    IOException
  104.      */
  105.     public void createPdf(String filename, Locale locale, int year) throws IOException, DocumentException {
  106.         // step 1
  107.         Document document = new Document(PageSize.A4.rotate());
  108.         // step 2
  109.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  110.         // step 3
  111.         document.open();
  112.         // step 4
  113.         PdfPTable table;
  114.         Calendar calendar;
  115.         PdfContentByte canvas = writer.getDirectContent();
  116.         // Loop over the months
  117.         for (int month = 0; month < 12; month++) {
  118.             calendar = new GregorianCalendar(year, month, 1);
  119.             // draw the background
  120.             drawImageAndText(canvas, calendar);
  121.             // create a table with 7 columns
  122.             table = new PdfPTable(7);
  123.             table.setTotalWidth(504);
  124.             // add the name of the month
  125.             table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
  126.             table.addCell(getMonthCell(calendar, locale));
  127.             int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
  128.             int day = 1;
  129.             int position = 2;
  130.             // add empty cells
  131.             while (position != calendar.get(Calendar.DAY_OF_WEEK)) {
  132.                 position = (position % 7) + 1;
  133.                 table.addCell("");
  134.             }
  135.             // add cells for each day
  136.             while (day
Zhang.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.chapter04;
  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.pdf.PdfContentByte;
  22. import com.itextpdf.text.pdf.PdfPTable;
  23. import com.itextpdf.text.pdf.PdfWriter;
  24.  
  25. public class Zhang {
  26.  
  27.     /** The resulting PDF file. */
  28.     public static final String RESULT = "results/part1/chapter04/zhang.pdf";
  29.  
  30.     /**
  31.      * Creates a PDF document.
  32.      * @param filename the path to the new PDF document
  33.      * @throws    DocumentException
  34.      * @throws    IOException
  35.      * @throws    SQLException
  36.      */
  37.     public void createPdf(String filename)
  38.         throws IOException, DocumentException, SQLException {
  39.         // Create a database connection
  40.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  41.         // step 1
  42.         Document document = new Document();
  43.         // step 2
  44.         PdfWriter writer
  45.             = PdfWriter.getInstance(document, new FileOutputStream(filename));
  46.         // step 3
  47.         document.open();
  48.         // step 4
  49.         // Create a table and fill it with movies
  50.         List movies = PojoFactory.getMovies(connection, 3);
  51.         PdfPTable table = new PdfPTable(new float[] { 1, 5, 5, 1});
  52.         for (Movie movie : movies) {
  53.             table.addCell(String.valueOf(movie.getYear()));
  54.             table.addCell(movie.getMovieTitle());
  55.             table.addCell(movie.getOriginalTitle());
  56.             table.addCell(String.valueOf(movie.getDuration()));
  57.         }
  58.         // set the total width of the table
  59.         table.setTotalWidth(600);
  60.         PdfContentByte canvas = writer.getDirectContent();
  61.         // draw the first two columns on one page
  62.         table.writeSelectedRows(0, 2, 0, -1, 236, 806, canvas);
  63.         document.newPage();
  64.         // draw the remaining two columns on the next page
  65.         table.writeSelectedRows(2, -1, 0, -1, 36, 806, canvas);
  66.         // step 5
  67.         document.close();
  68.         // close the database connection
  69.         connection.close();
  70.     }
  71.  
  72.     /**
  73.      * Main method.
  74.      * @param args no arguments needed
  75.      * @throws DocumentException
  76.      * @throws IOException
  77.      * @throws SQLException
  78.      */
  79.     public static void main(String[] args) throws IOException, DocumentException, SQLException {
  80.         new Zhang().createPdf(RESULT);
  81.     }
  82. }
ColumnTable.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.chapter04;
  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.Font;
  25. import com.itextpdf.text.PageSize;
  26. import com.itextpdf.text.Phrase;
  27. import com.itextpdf.text.Font.FontFamily;
  28. import com.itextpdf.text.pdf.ColumnText;
  29. import com.itextpdf.text.pdf.PdfPTable;
  30. import com.itextpdf.text.pdf.PdfWriter;
  31. import com.itextpdf.text.BaseColor;
  32.  
  33. public class ColumnTable {
  34.  
  35.     public static final String RESULT = "results/part1/chapter04/column_table.pdf";
  36.  
  37.     /**
  38.      * Creates a PDF document.
  39.      * @param filename the path to the new PDF document
  40.      * @throws    DocumentException
  41.      * @throws    IOException
  42.      * @throws    SQLException
  43.      */
  44.     public void createPdf(String filename)
  45.         throws SQLException, DocumentException, IOException {
  46.         // Create the database connection
  47.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  48.         // step 1
  49.         Document document = new Document(PageSize.A4.rotate());
  50.         // step 2
  51.         PdfWriter writer
  52.             = PdfWriter.getInstance(document, new FileOutputStream(filename));
  53.         // step 3
  54.         document.open();
  55.         // step 4
  56.         ColumnText column = new ColumnText(writer.getDirectContent());
  57.         List days = PojoFactory.getDays(connection);
  58.         // COlumn definition
  59.         float[][] x = {
  60.                 { document.left(), document.left() + 380 },
  61.                 { document.right() - 380, document.right() }
  62.             };
  63.         // Loop over the festival days
  64.         for (Date day : days) {
  65.             // add content to the column
  66.             column.addElement(getTable(connection, day));
  67.             int count = 0;
  68.             float height = 0;
  69.             int status = ColumnText.START_COLUMN;
  70.             // render the column as long as it has content
  71.             while (ColumnText.hasMoreText(status)) {
  72.                 // add the top-level header to each new page
  73.                 if (count == 0) {
  74.                     height = addHeaderTable(
  75.                         document, day, writer.getPageNumber());
  76.                 }
  77.                 // set the dimensions of the current column
  78.                 column.setSimpleColumn(
  79.                     x[count][0], document.bottom(),
  80.                     x[count][1], document.top() - height - 10);
  81.                 // render as much content as possible
  82.                 status = column.go();
  83.                 // go to a new page if you've reached the last column
  84.                 if (++count > 1) {
  85.                     count = 0;
  86.                     document.newPage();
  87.                 }
  88.             }
  89.             document.newPage();
  90.         }
  91.         // step 5
  92.         document.close();
  93.         // Close the database connection
  94.         connection.close();
  95.     }
  96.    
  97.     /**
  98.      * Add a header table to the document
  99.      * @param document The document to which you want to add a header table
  100.      * @param day The day that needs to be shown in the header table
  101.      * @param page The page number that has to be shown in the header
  102.      * @return the height of the resulting header table
  103.      * @throws DocumentException
  104.      */
  105.     public float addHeaderTable(Document document, Date day, int page)
  106.         throws DocumentException {
  107.         PdfPTable header = new PdfPTable(3);
  108.         header.setWidthPercentage(100);
  109.         header.getDefaultCell().setBackgroundColor(BaseColor.BLACK);
  110.         Font font = new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.WHITE);
  111.         Phrase p = new Phrase("Foobar Film Festival", font);
  112.         header.addCell(p);
  113.         header.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
  114.         p = new Phrase(day.toString(), font);
  115.         header.addCell(p);
  116.         header.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
  117.         p = new Phrase(String.format("page %d", page), font);
  118.         header.addCell(p);
  119.         document.add(header);
  120.         return header.getTotalHeight();
  121.     }
  122.  
  123.     /**
  124.      * Creates a table with movie screenings for a specific day
  125.      * @param connection a connection to the database
  126.      * @param day a day
  127.      * @return a table with screenings
  128.      * @throws SQLException
  129.      * @throws DocumentException
  130.      * @throws IOException
  131.      */
  132.     public PdfPTable getTable(DatabaseConnection connection, Date day)
  133.         throws SQLException, DocumentException, IOException {
  134.         PdfPTable table = new PdfPTable(new float[] { 2, 1, 2, 5, 1 });
  135.         table.setWidthPercentage(100f);
  136.         table.getDefaultCell().setUseAscender(true);
  137.         table.getDefaultCell().setUseDescender(true);
  138.         table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
  139.         for (int i = 0; i < 2; i++) {
  140.             table.addCell("Location");
  141.             table.addCell("Time");
  142.             table.addCell("Run Length");
  143.             table.addCell("Title");
  144.             table.addCell("Year");
  145.         }
  146.         table.getDefaultCell().setBackgroundColor(null);
  147.         table.setHeaderRows(2);
  148.         table.setFooterRows(1);
  149.         List screenings = PojoFactory.getScreenings(connection, day);
  150.         Movie movie;
  151.         for (Screening screening : screenings) {
  152.             movie = screening.getMovie();
  153.             table.addCell(screening.getLocation());
  154.             table.addCell(String.format("%1$tH:%1$tM", screening.getTime()));
  155.             table.addCell(String.format("%d '", movie.getDuration()));
  156.             table.addCell(movie.getMovieTitle());
  157.             table.addCell(String.valueOf(movie.getYear()));
  158.         }
  159.         return table;
  160.     }
  161.  
  162.     /**
  163.      * Main method.
  164.      * @param args no arguments needed
  165.      * @throws DocumentException
  166.      * @throws IOException
  167.      * @throws SQLException
  168.      */
  169.     public static void main(String[] args)
  170.         throws SQLException, DocumentException, IOException {
  171.         new ColumnTable().createPdf(RESULT);
  172.     }
  173. }
MyFirstTable.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.Chapter04 {
  13.   public class MyFirstTable : IWriter {
  14. // ===========================================================================
  15.     public virtual void Write(Stream stream) {
  16.       // step 1
  17.       using (Document document = new Document()) {
  18.         // step 2
  19.         PdfWriter.GetInstance(document, stream);
  20.         // step 3
  21.         document.Open();
  22.         // step 4
  23.         document.Add(CreateFirstTable());
  24.       }
  25.     }
  26. // ---------------------------------------------------------------------------    
  27.     /**
  28.      * Creates our first table
  29.      * @return our first table
  30.      */
  31.     public static PdfPTable CreateFirstTable() {
  32.     // a table with three columns
  33.       PdfPTable table = new PdfPTable(3);
  34.       // the cell object
  35.       PdfPCell cell;
  36.       // we add a cell with colspan 3
  37.       cell = new PdfPCell(new Phrase("Cell with colspan 3"));
  38.       cell.Colspan = 3;
  39.       table.AddCell(cell);
  40.       // now we add a cell with rowspan 2
  41.       cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
  42.       cell.Rowspan = 2;
  43.       table.AddCell(cell);
  44.       // we add the four remaining cells with addCell()
  45.       table.AddCell("row 1; cell 1");
  46.       table.AddCell("row 1; cell 2");
  47.       table.AddCell("row 2; cell 1");
  48.       table.AddCell("row 2; cell 2");
  49.       return table;
  50.     }
  51. // ===========================================================================
  52.   }
  53. }
ColumnWidths.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.Chapter04 {
  13.   public class ColumnWidths : IWriter {
  14. // ===========================================================================
  15.     public void Write(Stream stream) {
  16.       // step 1
  17.       using (Document document = new Document()) {
  18.         // step 2
  19.         PdfWriter.GetInstance(document, stream);
  20.         // step 3
  21.         document.Open();
  22.         // step 4
  23.         PdfPTable table = CreateTable1();
  24.         document.Add(table);
  25.         table = CreateTable2();
  26.         table.SpacingBefore = 5;
  27.         table.SpacingAfter = 5;
  28.         document.Add(table);
  29.         table = CreateTable3();
  30.         document.Add(table);
  31.         table = CreateTable4();
  32.         table.SpacingBefore = 5;
  33.         table.SpacingAfter = 5;
  34.         document.Add(table);
  35.         table = CreateTable5();
  36.         document.Add(table);
  37.       }
  38.     }
  39. // ---------------------------------------------------------------------------    
  40.     /**
  41.      * Creates a table; widths are set with setWidths().
  42.      * @return a PdfPTable
  43.      * @throws DocumentException
  44.      */
  45.     public static PdfPTable CreateTable1() {
  46.       PdfPTable table = new PdfPTable(3);
  47.       table.WidthPercentage  =288 / 5.23f;
  48.       table.SetWidths(new int[]{2, 1, 1});
  49.       PdfPCell cell;
  50.       cell = new PdfPCell(new Phrase("Table 1"));
  51.       cell.Colspan = 3;
  52.       table.AddCell(cell);
  53.       cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
  54.       cell.Rowspan = 2;
  55.       table.AddCell(cell);
  56.       table.AddCell("row 1; cell 1");
  57.       table.AddCell("row 1; cell 2");
  58.       table.AddCell("row 2; cell 1");
  59.       table.AddCell("row 2; cell 2");
  60.       return table;
  61.     }
  62. // ---------------------------------------------------------------------------    
  63.     /**
  64.      * Creates a table; widths are set with setWidths().
  65.      * @return a PdfPTable
  66.      * @throws DocumentException
  67.      */
  68.     public static PdfPTable CreateTable2() {
  69.       PdfPTable table = new PdfPTable(3);
  70.       table.TotalWidth = 288;
  71.       table.LockedWidth = true;
  72.       table.SetWidths(new float[]{2, 1, 1});
  73.       PdfPCell cell;
  74.       cell = new PdfPCell(new Phrase("Table 2"));
  75.       cell.Colspan = 3;
  76.       table.AddCell(cell);
  77.       cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
  78.       cell.Rowspan = 2;
  79.       table.AddCell(cell);
  80.       table.AddCell("row 1; cell 1");
  81.       table.AddCell("row 1; cell 2");
  82.       table.AddCell("row 2; cell 1");
  83.       table.AddCell("row 2; cell 2");
  84.       return table;
  85.     }
  86. // ---------------------------------------------------------------------------    
  87.     /**
  88.      * Creates a table; widths are set in the constructor.
  89.      * @return a PdfPTable
  90.      * @throws DocumentException
  91.      */
  92.     public static PdfPTable CreateTable3() {
  93.       PdfPTable table = new PdfPTable(new float[]{ 2, 1, 1 });
  94.       table.WidthPercentage = 55.067f;
  95.       PdfPCell cell;
  96.       cell = new PdfPCell(new Phrase("Table 3"));
  97.       cell.Colspan = 3;
  98.       table.AddCell(cell);
  99.       cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
  100.       cell.Rowspan = 2;
  101.       table.AddCell(cell);
  102.       table.AddCell("row 1; cell 1");
  103.       table.AddCell("row 1; cell 2");
  104.       table.AddCell("row 2; cell 1");
  105.       table.AddCell("row 2; cell 2");
  106.       return table;
  107.     }
  108. // ---------------------------------------------------------------------------    
  109.     /**
  110.      * Creates a table; widths are set with special setWidthPercentage() method.
  111.      * @return a PdfPTable
  112.      */
  113.     public static PdfPTable CreateTable4() {
  114.       PdfPTable table = new PdfPTable(3);
  115.       Rectangle rect = new Rectangle(523, 770);
  116.       table.SetWidthPercentage(new float[]{ 144, 72, 72 }, rect);
  117.       PdfPCell cell;
  118.       cell = new PdfPCell(new Phrase("Table 4"));
  119.       cell.Colspan =3;
  120.       table.AddCell(cell);
  121.       cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
  122.       cell.Rowspan = 2;
  123.       table.AddCell(cell);
  124.       table.AddCell("row 1; cell 1");
  125.       table.AddCell("row 1; cell 2");
  126.       table.AddCell("row 2; cell 1");
  127.       table.AddCell("row 2; cell 2");
  128.       return table;
  129.     }
  130. // ---------------------------------------------------------------------------    
  131.     /**
  132.      * Creates a table; widths are set with setTotalWidth().
  133.      * @return a PdfPTable
  134.      */
  135.     public static PdfPTable CreateTable5() {
  136.       PdfPTable table = new PdfPTable(3);
  137.       table.SetTotalWidth(new float[]{ 144, 72, 72 });
  138.       table.LockedWidth = true;
  139.       PdfPCell cell;
  140.       cell = new PdfPCell(new Phrase("Table 5"));
  141.       cell.Colspan = 3 ;
  142.       table.AddCell(cell);
  143.       cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
  144.       cell.Rowspan = 2;
  145.       table.AddCell(cell);
  146.       table.AddCell("row 1; cell 1");
  147.       table.AddCell("row 1; cell 2");
  148.       table.AddCell("row 2; cell 1");
  149.       table.AddCell("row 2; cell 2");
  150.       return table;
  151.     }    
  152. // ===========================================================================
  153.   }
  154. }
TableAlignment.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.Chapter04 {
  13.   public class TableAlignment : MyFirstTable {
  14. // ===========================================================================
  15.     public override void Write(Stream stream) {
  16.       // step 1
  17.       using (Document document = new Document()) {
  18.         // step 2
  19.         PdfWriter.GetInstance(document, stream);
  20.         // step 3
  21.         document.Open();
  22.         // step 4
  23.         PdfPTable table = CreateFirstTable();
  24.         table.WidthPercentage = 50;
  25.         table.HorizontalAlignment = Element.ALIGN_LEFT;
  26.         document.Add(table);
  27.         table.HorizontalAlignment = Element.ALIGN_CENTER;
  28.         document.Add(table);
  29.         table.HorizontalAlignment = Element.ALIGN_RIGHT;
  30.         document.Add(table);
  31.       }
  32.     }
  33. // ===========================================================================
  34.   }
  35. }
MovieTextMode.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.Chapter04 {
  16.   public class MovieTextMode : IWriter {
  17. // ===========================================================================
  18.     public void Write(Stream stream) {
  19.       // step 1
  20.       using (Document document = new Document()) {
  21.         // step 2
  22.         PdfWriter.GetInstance(document, stream);
  23.         // step 3
  24.         document.Open();
  25.         // step 4
  26.         document.Add(new Paragraph("Movies:"));
  27.         IEnumerable movies = PojoFactory.GetMovies();
  28.         foreach (Movie movie in movies) {
  29.           PdfPTable table = new PdfPTable(2);
  30.           table.SetWidths(new int[]{1, 4});
  31.           PdfPCell cell;
  32.           cell = new PdfPCell(new Phrase(movie.Title, FilmFonts.BOLD));
  33.           cell.HorizontalAlignment = Element.ALIGN_CENTER;
  34.           cell.Colspan = 2;
  35.           table.AddCell(cell);
  36.           if (!string.IsNullOrEmpty(movie.OriginalTitle)) {
  37.             cell = new PdfPCell(PojoToElementFactory.GetOriginalTitlePhrase(movie));
  38.             cell.Colspan = 2;
  39.             cell.HorizontalAlignment = Element.ALIGN_RIGHT;
  40.             table.AddCell(cell);
  41.           }
  42.           List directors = movie.Directors;
  43.           cell = new PdfPCell(new Phrase("Directors:"));
  44.           cell.Rowspan = directors.Count;
  45.           cell.VerticalAlignment = Element.ALIGN_MIDDLE;
  46.           table.AddCell(cell);
  47.           int count = 0;
  48.           foreach (Director pojo in directors) {
  49.             cell = new PdfPCell(PojoToElementFactory.GetDirectorPhrase(pojo));
  50.             cell.Indent = (10 * count++);
  51.             table.AddCell(cell);
  52.           }
  53.           table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
  54.           table.AddCell("Year:");
  55.           table.AddCell(movie.Year.ToString());
  56.           table.AddCell("Run length:");
  57.           table.AddCell(movie.Duration.ToString());
  58.           List countries = movie.Countries;
  59.           cell = new PdfPCell(new Phrase("Countries:"));
  60.           cell.Rowspan = countries.Count;
  61.           cell.VerticalAlignment = Element.ALIGN_BOTTOM;
  62.           table.AddCell(cell);
  63.           table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
  64.           foreach (Country country in countries) {
  65.             table.AddCell(country.Name);
  66.           }
  67.           document.Add(table);
  68.         }        
  69.       }
  70.     }
  71. // ===========================================================================
  72.   }
  73. }
Spacing.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.Chapter04 {
  13.   public class Spacing : IWriter {
  14. // ===========================================================================
  15.     public void Write(Stream stream) {
  16.       // step 1
  17.       using (Document document = new Document()) {
  18.         // step 2
  19.         PdfWriter.GetInstance(document, stream);
  20.         // step 3
  21.         document.Open();
  22.         // step 4
  23.         PdfPTable table = new PdfPTable(2);
  24.         table.WidthPercentage = 100;
  25.         Phrase p = new Phrase(
  26.           "Dr. iText or: How I Learned to Stop Worrying " +
  27.           "and Love the Portable Document Format."
  28.         );
  29.         PdfPCell cell = new PdfPCell(p);
  30.         table.AddCell("default leading / spacing");
  31.         table.AddCell(cell);
  32.         table.AddCell("absolute leading: 20");
  33.         cell.SetLeading(20f, 0f);
  34.         table.AddCell(cell);
  35.         table.AddCell("absolute leading: 3; relative leading: 1.2");
  36.         cell.SetLeading(3f, 1.2f);
  37.         table.AddCell(cell);
  38.         table.AddCell("absolute leading: 0; relative leading: 1.2");
  39.         cell.SetLeading(0f, 1.2f);
  40.         table.AddCell(cell);
  41.         table.AddCell("no leading at all");
  42.         cell.SetLeading(0f, 0f);
  43.         table.AddCell(cell);
  44.         cell = new PdfPCell(new Phrase(
  45.             "Dr. iText or: How I Learned to Stop Worrying and Love PDF"));
  46.         table.AddCell("padding 10");
  47.         cell.Padding = 10;
  48.         table.AddCell(cell);
  49.         table.AddCell("padding 0");
  50.         cell.Padding = 0;
  51.         table.AddCell(cell);
  52.         table.AddCell("different padding for left, right, top and bottom");
  53.         cell.PaddingLeft = 20;
  54.         cell.PaddingRight = 50;
  55.         cell.PaddingTop = 0;
  56.         cell.PaddingBottom = 5;
  57.         table.AddCell(cell);
  58.         p = new Phrase("iText in Action Second Edition");
  59.         table.DefaultCell.Padding = 2;
  60.         table.DefaultCell.UseAscender = false;
  61.         table.DefaultCell.UseDescender = false;
  62.         table.AddCell("padding 2; no ascender, no descender");
  63.         table.AddCell(p);
  64.         table.DefaultCell.UseAscender = true;
  65.         table.DefaultCell.UseDescender = false;
  66.         table.AddCell("padding 2; ascender, no descender");
  67.         table.AddCell(p);
  68.         table.DefaultCell.UseAscender = false;
  69.         table.DefaultCell.UseDescender = true;
  70.         table.AddCell("padding 2; descender, no ascender");
  71.         table.AddCell(p);
  72.         table.DefaultCell.UseAscender = true;
  73.         table.DefaultCell.UseDescender = true;
  74.         table.AddCell("padding 2; ascender and descender");
  75.         cell.Padding = 2;
  76.         cell.UseAscender = true;
  77.         cell.UseDescender = true;
  78.         table.AddCell(p);
  79.         document.Add(table);
  80.       }
  81.     }
  82. // ===========================================================================
  83.   }
  84. }
TableHeight.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.Chapter04 {
  13.   public class TableHeight : MyFirstTable {
  14. // ===========================================================================
  15.     public override void Write(Stream stream) {
  16.       // step 1
  17.       using (Document document = new Document()) {
  18.         // step 2
  19.         PdfWriter.GetInstance(document, stream);
  20.         // step 3
  21.         document.Open();
  22.         // step 4
  23.         PdfPTable table = CreateFirstTable();
  24.         document.Add(new Paragraph(string.Format(
  25.           "Table height before document.Add(): {0}",
  26.           table.TotalHeight)
  27.         ));
  28.         document.Add(new Paragraph(
  29.             string.Format("Height of the first row: {0}",
  30.                 table.GetRowHeight(0))
  31.          ));
  32.         document.Add(table);
  33.         document.Add(new Paragraph(string.Format(
  34.           "Table height after document.Add(): {0}",
  35.           table.TotalHeight
  36.         )));
  37.         document.Add(new Paragraph(string.Format(
  38.           "Height of the first row: {0}",
  39.           table.GetRowHeight(0)
  40.         )));
  41.         table = CreateFirstTable();
  42.         document.Add(new Paragraph( string.Format(
  43.           "Table height before setTotalWidth(): {0}",
  44.           table.TotalHeight
  45.         )));
  46.         document.Add(new Paragraph(string.Format(
  47.           "Height of the first row: {0}",
  48.           table.GetRowHeight(0)
  49.         )));
  50.         table.TotalWidth = 50;
  51.         table.LockedWidth = true;
  52.         document.Add( new Paragraph(string.Format(
  53.           "Table height after setTotalWidth(): {0}",
  54.           table.TotalHeight
  55.         )));
  56.         document.Add(new Paragraph(string.Format(
  57.           "Height of the first row: {0}",
  58.           table.GetRowHeight(0)
  59.         )));
  60.         document.Add(table);
  61.       }
  62.     }
  63. // ===========================================================================
  64.   }
  65. }
CellHeights.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.Chapter04 {
  13.   public class CellHeights : IWriter {
  14. // ===========================================================================
  15.     public void Write(Stream stream) {
  16.       // step 1
  17.       using (Document document = new Document()) {
  18.         // step 2
  19.         PdfWriter.GetInstance(document, stream);
  20.         // step 3
  21.         document.Open();
  22.         // step 4
  23.         PdfPTable table = new PdfPTable(2);
  24.         // a long phrase
  25.         Phrase p = new Phrase(
  26.           "Dr. iText or: How I Learned to Stop Worrying and Love PDF."
  27.         );
  28.         PdfPCell cell = new PdfPCell(p);
  29.         // the prhase is wrapped
  30.         table.AddCell("wrap");
  31.         cell.NoWrap = false;
  32.         table.AddCell(cell);
  33.         // the phrase isn't wrapped
  34.         table.AddCell("no wrap");
  35.         cell.NoWrap = true;
  36.         table.AddCell(cell);
  37.         // a long phrase with newlines
  38.         p = new Phrase(
  39.             "Dr. iText or:\nHow I Learned to Stop Worrying\nand Love PDF.");
  40.         cell = new PdfPCell(p);
  41.         // the phrase fits the fixed height
  42.         table.AddCell("fixed height (more than sufficient)");
  43.         cell.FixedHeight = 72f;
  44.         table.AddCell(cell);
  45.         // the phrase doesn't fit the fixed height
  46.         table.AddCell("fixed height (not sufficient)");
  47.         cell.FixedHeight = 36f;
  48.         table.AddCell(cell);
  49.         // The minimum height is exceeded
  50.         table.AddCell("minimum height");
  51.         cell = new PdfPCell(new Phrase("Dr. iText"));
  52.         cell.MinimumHeight = 36f;
  53.         table.AddCell(cell);
  54.         // The last row is extended
  55.         table.ExtendLastRow = true;
  56.         table.AddCell("extend last row");
  57.         table.AddCell(cell);
  58.         document.Add(table);
  59.       }
  60.     }
  61. // ===========================================================================
  62.   }
  63. }
RotationAndColors.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.Chapter04 {
  13.   public class RotationAndColors : IWriter {
  14. // ===========================================================================
  15.     public void Write(Stream stream) {
  16.       // step 1
  17.       using (Document document = new Document()) {
  18.         // step 2
  19.         PdfWriter.GetInstance(document, stream);
  20.         // step 3
  21.         document.Open();
  22.         // step 4
  23.         PdfPTable table = new PdfPTable(4);
  24.         table.SetWidths(new int[]{ 1, 3, 3, 3 });
  25.         table.WidthPercentage = 100;
  26.         PdfPCell cell;
  27.         // row 1, cell 1
  28.         cell = new PdfPCell(new Phrase("COLOR"));
  29.         cell.Rotation = 90;
  30.         cell.VerticalAlignment = Element.ALIGN_TOP;
  31.         table.AddCell(cell);
  32.         // row 1, cell 2
  33.         cell = new PdfPCell(new Phrase("red / no borders"));
  34.         cell.Border = Rectangle.NO_BORDER;
  35.         cell.BackgroundColor = BaseColor.RED;
  36.         table.AddCell(cell);
  37.         // row 1, cell 3
  38.         cell = new PdfPCell(new Phrase("green / black bottom border"));
  39.         cell.Border = Rectangle.BOTTOM_BORDER;
  40.         cell.BorderColorBottom = BaseColor.BLACK;
  41.         cell.BorderWidthBottom = 10f;
  42.         cell.BackgroundColor = BaseColor.GREEN;
  43.         table.AddCell(cell);
  44.         // row 1, cell 4
  45.         cell = new PdfPCell(new Phrase(
  46.           "cyan / blue top border + padding"
  47.         ));
  48.         cell.Border  = Rectangle.TOP_BORDER;
  49.         cell.UseBorderPadding = true;
  50.         cell.BorderWidthTop = 5f;
  51.         cell.BorderColorTop = BaseColor.BLUE;
  52.         cell.BackgroundColor = BaseColor.CYAN;
  53.         table.AddCell(cell);
  54.         // row 2, cell 1
  55.         cell = new PdfPCell(new Phrase("GRAY"));
  56.         cell.Rotation = 90;
  57.         cell.VerticalAlignment = Element.ALIGN_MIDDLE;
  58.         table.AddCell(cell);
  59.         // row 2, cell 2
  60.         cell = new PdfPCell(new Phrase("0.6"));
  61.         cell.Border = Rectangle.NO_BORDER;
  62.         cell.GrayFill = 0.6f;
  63.         table.AddCell(cell);
  64.         // row 2, cell 3
  65.         cell = new PdfPCell(new Phrase("0.75"));
  66.         cell.Border = Rectangle.NO_BORDER;
  67.         cell.GrayFill = 0.75f;
  68.         table.AddCell(cell);
  69.         // row 2, cell 4
  70.         cell = new PdfPCell(new Phrase("0.9"));
  71.         cell.Border = Rectangle.NO_BORDER;
  72.         cell.GrayFill = 0.9f;
  73.         table.AddCell(cell);
  74.         // row 3, cell 1
  75.         cell = new PdfPCell(new Phrase("BORDERS"));
  76.         cell.Rotation = 90;
  77.         cell.VerticalAlignment = Element.ALIGN_BOTTOM;
  78.         table.AddCell(cell);
  79.         // row 3, cell 2
  80.         cell = new PdfPCell(new Phrase("different borders"));
  81.         cell.BorderWidthLeft = 16f;
  82.         cell.BorderWidthBottom = 12f;
  83.         cell.BorderWidthRight = 8f;
  84.         cell.BorderWidthTop = 4f;
  85.         cell.BorderColorLeft = BaseColor.RED;
  86.         cell.BorderColorBottom = BaseColor.ORANGE;
  87.         cell.BorderColorRight = BaseColor.YELLOW;
  88.         cell.BorderColorTop = BaseColor.GREEN;
  89.         table.AddCell(cell);
  90.         // row 3, cell 3
  91.         cell = new PdfPCell(new Phrase("with correct padding"));
  92.         cell.UseBorderPadding = true;
  93.         cell.BorderWidthLeft = 16f;
  94.         cell.BorderWidthBottom = 12f;
  95.         cell.BorderWidthRight = 8f;
  96.         cell.BorderWidthTop = 4f;
  97.         cell.BorderColorLeft = BaseColor.RED;
  98.         cell.BorderColorBottom = BaseColor.ORANGE;
  99.         cell.BorderColorRight = BaseColor.YELLOW;
  100.         cell.BorderColorTop = BaseColor.GREEN;
  101.         table.AddCell(cell);
  102.         // row 3, cell 4
  103.         cell = new PdfPCell(new Phrase("red border"));
  104.         cell.BorderWidth = 8f;
  105.         cell.BorderColor = BaseColor.RED;
  106.         table.AddCell(cell);
  107.         document.Add(table);
  108.       }
  109.     }
  110. // ===========================================================================
  111.   }
  112. }
MovieCompositeMode.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.Chapter04 {
  16.   public class MovieCompositeMode : IWriter {
  17. // ===========================================================================
  18.     public void Write(Stream stream) {
  19.       // step 1
  20.       using (Document document = new Document()) {
  21.         // step 2
  22.         PdfWriter.GetInstance(document, stream);
  23.         // step 3
  24.         document.Open();
  25.         // step 4
  26.         document.Add(new Paragraph("Movies:"));
  27.         IEnumerable movies = PojoFactory.GetMovies();
  28.         List list;
  29.         PdfPCell cell;
  30.         string RESOURCE = Utility.ResourcePosters;
  31.         foreach (Movie movie in movies) {
  32.       // a table with two columns
  33.           PdfPTable table = new PdfPTable(new float[]{1, 7});
  34.           table.WidthPercentage = 100;
  35.           table.SpacingBefore = 5;
  36.           // a cell with an image
  37.           cell = new PdfPCell(
  38.             Image.GetInstance(Path.Combine(RESOURCE, movie.Imdb + ".jpg")),
  39.             true
  40.           );
  41.           cell.Border = PdfPCell.NO_BORDER;
  42.           table.AddCell(cell);
  43.           cell = new PdfPCell();
  44.           // a cell with paragraphs and lists
  45.           Paragraph p = new Paragraph(movie.Title, FilmFonts.BOLD);
  46.           p.Alignment = Element.ALIGN_CENTER;
  47.           p.SpacingBefore = 5;
  48.           p.SpacingAfter = 5;
  49.           cell.AddElement(p);
  50.           cell.Border = PdfPCell.NO_BORDER;
  51.           if (!string.IsNullOrEmpty(movie.OriginalTitle)) {
  52.             p = new Paragraph(movie.OriginalTitle, FilmFonts.ITALIC);
  53.             p.Alignment = Element.ALIGN_RIGHT;
  54.             cell.AddElement(p);
  55.           }
  56.           list = PojoToElementFactory.GetDirectorList(movie);
  57.           list.IndentationLeft = 30;
  58.           cell.AddElement(list);
  59.           p = new Paragraph(
  60.             string.Format("Year: {0}", movie.Year),
  61.             FilmFonts.NORMAL
  62.           );
  63.           p.IndentationLeft = 15;
  64.           p.Leading = 24;
  65.           cell.AddElement(p);
  66.           p = new Paragraph(
  67.             string.Format("Run length: {0}", movie.Duration),
  68.             FilmFonts.NORMAL
  69.           );
  70.           p.Leading = 14;
  71.           p.IndentationLeft = 30;
  72.           cell.AddElement(p);
  73.           list = PojoToElementFactory.GetCountryList(movie);
  74.           list.IndentationLeft = 40;
  75.           cell.AddElement(list);
  76.           table.AddCell(cell);
  77.           // every movie corresponds with one table
  78.           document.Add(table);
  79.           // but the result looks like one big table
  80.         }
  81.       }
  82.     }
  83. // ===========================================================================
  84.   }
  85. }
XMen.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.Chapter04 {
  13.   public class XMen : IWriter {
  14. // ===========================================================================
  15.     public void Write(Stream stream) {
  16.       // step 1
  17.       using (Document document = new Document()) {
  18.         // step 2
  19.         PdfWriter.GetInstance(document, stream);
  20.         // step 3
  21.         document.Open();
  22.         // step 4
  23.         string RESOURCE = Utility.ResourcePosters;
  24.         // we'll use 4 images in this example
  25.         Image[] img = {
  26.           Image.GetInstance(Path.Combine(RESOURCE, "0120903.jpg")),
  27.           Image.GetInstance(Path.Combine(RESOURCE, "0290334.jpg")),
  28.           Image.GetInstance(Path.Combine(RESOURCE, "0376994.jpg")),
  29.           Image.GetInstance(Path.Combine(RESOURCE, "0348150.jpg"))
  30.         };
  31.         // Creates a table with 6 columns
  32.         PdfPTable table = new PdfPTable(6);
  33.         table.WidthPercentage = 100;
  34.         // first movie
  35.         table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
  36.         table.DefaultCell.VerticalAlignment = Element.ALIGN_TOP;
  37.         table.AddCell("X-Men");
  38.         // we wrap he image in a PdfPCell
  39.         PdfPCell cell = new PdfPCell(img[0]);
  40.         table.AddCell(cell);
  41.         // second movie
  42.         table.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
  43.         table.AddCell("X2");
  44.         // we wrap the image in a PdfPCell and let iText scale it
  45.         cell = new PdfPCell(img[1], true);
  46.         table.AddCell(cell);
  47.         // third movie
  48.         table.DefaultCell.VerticalAlignment = Element.ALIGN_BOTTOM;
  49.         table.AddCell("X-Men: The Last Stand");
  50.         // we add the image with addCell()
  51.         table.AddCell(img[2]);
  52.         // fourth movie
  53.         table.AddCell("Superman Returns");
  54.         cell = new PdfPCell();
  55.         // we add it with addElement(); it can only take 50% of the width.
  56.         img[3].WidthPercentage = 50;
  57.         cell.AddElement(img[3]);
  58.         table.AddCell(cell);
  59.         // we complete the table (otherwise the last row won't be rendered)
  60.         table.CompleteRow();
  61.         document.Add(table);
  62.       }
  63.     }
  64. // ===========================================================================
  65.   }
  66. }
NestedTable.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.Chapter04 {
  13.   public class NestedTable : IWriter {
  14. // ===========================================================================
  15.     public void Write(Stream stream) {
  16.       // step 1
  17.       using (Document document = new Document()) {
  18.         // step 2
  19.         PdfWriter.GetInstance(document, stream);
  20.         // step 3
  21.         document.Open();
  22.         // step 4
  23.         PdfPTable table = new PdfPTable(4);
  24.         PdfPTable nested1 = new PdfPTable(2);
  25.         nested1.AddCell("1.1");
  26.         nested1.AddCell("1.2");
  27.         PdfPTable nested2 = new PdfPTable(1);
  28.         nested2.AddCell("12.1");
  29.         nested2.AddCell("12.2");
  30.         for (int k = 0; k < 16; ++k) {
  31.           if (k == 1) {
  32.             table.AddCell(nested1);
  33.           } else if (k == 12) {
  34.             table.AddCell(new PdfPCell(nested2));
  35.           } else {
  36.             table.AddCell("cell " + k);
  37.           }
  38.         }
  39.         document.Add(table);
  40.       }
  41.     }
  42. // ===========================================================================
  43.   }
  44. }
NestedTables.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.Text.RegularExpressions;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using iTextSharp.text.html;
  14. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter04 {
  17.   public class NestedTables : IWriter {
  18. // ===========================================================================
  19.     /** Collection containing all the Images */
  20.     public Dictionary images = new Dictionary();
  21.     /** Path to the resources. */
  22.     public readonly string RESOURCE = Utility.ResourcePosters;
  23. // ---------------------------------------------------------------------------
  24.     public void Write(Stream stream) {
  25.       // step 1
  26.       using (Document document = new Document()) {
  27.         // step 2
  28.         PdfWriter.GetInstance(document, stream);
  29.         // step 3
  30.         document.Open();
  31.         // step 4
  32.         List days = PojoFactory.GetDays();
  33.         foreach (string day in days) {
  34.           document.Add(GetTable(day));
  35.           document.NewPage();
  36.         }
  37.       }
  38.     }
  39. // ---------------------------------------------------------------------------  
  40.     /**
  41.      * Creates a table with all the screenings of a specific day.
  42.      * The table is composed of nested tables.
  43.      * @param day a film festival day
  44.      * @return a table
  45.      */
  46.     public PdfPTable GetTable(string day) {
  47.       // Create a table with only one column
  48.       PdfPTable table = new PdfPTable(1);
  49.       table.WidthPercentage = 100f;
  50.       // add the cell with the date
  51.       Font f = new Font();
  52.       f.Color = BaseColor.WHITE;
  53.       PdfPCell cell = new PdfPCell(new Phrase(day, f));
  54.       cell.BackgroundColor = BaseColor.BLACK;
  55.       cell.HorizontalAlignment = Element.ALIGN_CENTER;
  56.       table.AddCell(cell);
  57.       // add the movies as nested tables
  58.       List screenings = PojoFactory.GetScreenings(day);
  59.       foreach (Screening screening in screenings) {
  60.         table.AddCell(GetTable(screening));
  61.       }
  62.       return table;
  63.     }
  64. // ---------------------------------------------------------------------------  
  65.     /**
  66.      * Create a table with information about a movie.
  67.      * @param screening a Screening
  68.      * @return a table
  69.      */
  70.     private PdfPTable GetTable(Screening screening) {
  71.       // Create a table with 4 columns
  72.       PdfPTable table = new PdfPTable(4);
  73.       table.SetWidths(new int[]{1, 5, 10, 10});
  74.       // Get the movie
  75.       Movie movie = screening.movie;
  76.       // A cell with the title as a nested table spanning the complete row
  77.       PdfPCell cell = new PdfPCell();
  78.       // nesting is done with addElement() in this example
  79.       cell.AddElement(FullTitle(screening));
  80.       cell.Colspan = 4;
  81.       cell.Border = PdfPCell.NO_BORDER;
  82.       BaseColor color = WebColors.GetRGBColor(
  83.         "#" + movie.entry.category.color
  84.       );
  85.       cell.BackgroundColor = color;
  86.       table.AddCell(cell);
  87.       // empty cell
  88.       cell = new PdfPCell();
  89.       cell.Border = PdfPCell.NO_BORDER;
  90.       cell.UseAscender = true;
  91.       cell.UseDescender = true;
  92.       table.AddCell(cell);
  93.       // cell with the movie poster
  94.       cell = new PdfPCell(GetImage(movie.Imdb));
  95.       cell.Border = PdfPCell.NO_BORDER;
  96.       table.AddCell(cell);
  97.       // cell with the list of directors
  98.       cell = new PdfPCell();
  99.       cell.AddElement(PojoToElementFactory.GetDirectorList(movie));
  100.       cell.Border = PdfPCell.NO_BORDER;
  101.       cell.UseAscender = true;
  102.       cell.UseDescender = true;
  103.       table.AddCell(cell);
  104.       // cell with the list of countries
  105.       cell = new PdfPCell();
  106.       cell.AddElement(PojoToElementFactory.GetCountryList(movie));
  107.       cell.Border = PdfPCell.NO_BORDER;
  108.       cell.UseAscender =  true;
  109.       cell.UseDescender = true;
  110.       table.AddCell(cell);
  111.       return table;
  112.     }
  113. // ---------------------------------------------------------------------------      
  114.     /**
  115.      * Create a table with the full movie title
  116.      * @param screening a Screening object
  117.      * @return a table
  118.      */
  119.     private static PdfPTable FullTitle(Screening screening) {
  120.       PdfPTable table = new PdfPTable(3);
  121.       table.SetWidths(new int[]{3, 15, 2});
  122.       table.WidthPercentage = 100;
  123.       // cell 1: location and time
  124.       PdfPCell cell = new PdfPCell();
  125.       cell.Border = PdfPCell.NO_BORDER;
  126.       cell.BackgroundColor = BaseColor.WHITE;
  127.       cell.UseAscender = true;
  128.       cell.UseDescender = true;
  129.       String s = string.Format(
  130.         // "{0} \u2013 %2$tH:%2$tM",
  131.         "{0} \u2013 {1}",
  132.         screening.Location,
  133.         screening.Time.Substring(0, 5)
  134.         // screening.Time().getTime()
  135.       );
  136.       cell.AddElement(new Paragraph(s));
  137.       table.AddCell(cell);
  138.       // cell 2: English and original title
  139.       Movie movie = screening.movie;
  140.       Paragraph p = new Paragraph();
  141.       p.Add(new Phrase(movie.MovieTitle, FilmFonts.BOLD));
  142.       p.Leading = 16;
  143.       if (!string.IsNullOrEmpty(movie.OriginalTitle)) {
  144.         p.Add(new Phrase(" (" + movie.OriginalTitle + ")"));
  145.       }
  146.       cell = new PdfPCell();
  147.       cell.AddElement(p);
  148.       cell.Border = PdfPCell.NO_BORDER;
  149.       cell.UseAscender = true;
  150.       cell.UseDescender = true;
  151.       table.AddCell(cell);
  152.       // cell 3 duration
  153.       cell = new PdfPCell();
  154.       cell.Border = PdfPCell.NO_BORDER;
  155.       cell.BackgroundColor = BaseColor.WHITE;
  156.       cell.UseAscender = true;
  157.       cell.UseDescender = true;
  158.       // p = new Paragraph(String.format("%d'", movie.getDuration()));
  159.       p = new Paragraph(movie.Duration.ToString() + "'");
  160.       p.Alignment = Element.ALIGN_CENTER;
  161.       cell.AddElement(p);
  162.       table.AddCell(cell);
  163.       return table;
  164.     }
  165. // ---------------------------------------------------------------------------      
  166.     /**
  167.      * Create an image with a movie poster.
  168.      * @param imdb an Internet Movie Database id
  169.      * @return an Image
  170.      * @throws DocumentException
  171.      * @throws IOException
  172.      */
  173.     public Image GetImage(String imdb) {
  174.       if ( images.ContainsKey(imdb) ) {
  175.         return images[imdb];
  176.       }
  177.       else {
  178.         Image img = Image.GetInstance(Path.Combine(RESOURCE, imdb + ".jpg"));
  179.         img.ScaleToFit(80, 72);
  180.         images.Add(imdb, img);
  181.         return img;
  182.       }
  183.     }
  184. // ===========================================================================
  185.   }
  186. }
HeaderFooter1.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.Chapter04 {
  15.   public class HeaderFooter1 : IWriter {
  16. // ===========================================================================
  17.     public virtual 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.         foreach (string day in days) {
  27.           document.Add(GetTable(day));
  28.           document.NewPage();
  29.         }
  30.       }
  31.     }
  32. // ---------------------------------------------------------------------------    
  33.     /**
  34.      * Creates a table with screenings.
  35.      * @param day a film festival day
  36.      * @return a table with screenings
  37.      */
  38.     public PdfPTable GetTable(string day) {
  39.     // Create a table with 7 columns
  40.       PdfPTable table = new PdfPTable(new float[] { 2, 1, 2, 5, 1, 3, 2 });
  41.       table.WidthPercentage = 100f;
  42.       table.DefaultCell.UseAscender = true;
  43.       table.DefaultCell.UseDescender = true;
  44.       // Add the first header row
  45.       Font f = new Font();
  46.       f.Color = BaseColor.WHITE;
  47.       PdfPCell cell = new PdfPCell(new Phrase(day, f));
  48.       cell.BackgroundColor = BaseColor.BLACK;
  49.       cell.HorizontalAlignment = Element.ALIGN_CENTER;
  50.       cell.Colspan = 7;
  51.       table.AddCell(cell);
  52.       // Add the second header row twice
  53.       table.DefaultCell.BackgroundColor = BaseColor.LIGHT_GRAY;
  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.         table.AddCell("Directors");
  61.         table.AddCell("Countries");
  62.       }
  63.       table.DefaultCell.BackgroundColor = null;
  64.       // There are three special rows
  65.       table.HeaderRows = 3;
  66.       // One of them is a footer
  67.       table.FooterRows = 1;
  68.       // Now let's loop over the screenings
  69.       List screenings = PojoFactory.GetScreenings(day);
  70.       Movie movie;
  71.       foreach (Screening screening in screenings) {
  72.         movie = screening.movie;
  73.         table.AddCell(screening.Location);
  74.         table.AddCell(screening.Time.Substring(0, 5));
  75.         table.AddCell(movie.Duration.ToString() + " '");
  76.         table.AddCell(movie.MovieTitle);
  77.         table.AddCell(movie.Year.ToString());
  78.         cell = new PdfPCell();
  79.         cell.UseAscender = true;
  80.         cell.UseDescender = true;
  81.         cell.AddElement(PojoToElementFactory.GetDirectorList(movie));
  82.         table.AddCell(cell);
  83.         cell = new PdfPCell();
  84.         cell.UseAscender = true;
  85.         cell.UseDescender = true;
  86.         cell.AddElement(PojoToElementFactory.GetCountryList(movie));
  87.         table.AddCell(cell);
  88.       }
  89.       return table;
  90.     }    
  91. // ===========================================================================
  92.   }
  93. }
HeaderFooter2.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.Chapter04 {
  15.   public class HeaderFooter2 : HeaderFooter1 {
  16. // ===========================================================================
  17.     public override 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.         foreach (string day in days) {
  27.           PdfPTable table = GetTable(day);
  28.           table.SplitLate = false;
  29.           document.Add(table);
  30.           document.NewPage();
  31.         }
  32.       }
  33.     }
  34. // ===========================================================================
  35.   }
  36. }
MemoryTests.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.Collections.Generic;
  9. using System.Diagnostics;
  10. using System.IO;
  11. using System.Threading;
  12. using Ionic.Zip;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter04 {
  18.   public class MemoryTests : IWriter {
  19.  
  20.     /** The resulting report. */
  21.     public readonly String RESULT0 = "test_results.txt";
  22.  
  23.     /** A resulting PDF file. */
  24.     public readonly String RESULT1
  25.         = "pdfptable_without_memory_management.pdf";
  26.     /** A resulting PDF file. */
  27.     public readonly String RESULT2
  28.         = "pdfptable_with_memory_management.pdf";
  29.    
  30.     private bool test;
  31.     private long memory_use;
  32.     private long initial_memory_use = 0l;
  33.     private long maximum_memory_use = 0l;
  34.    
  35.     /** Path to the resources. */
  36.     public readonly String RESOURCE = Utility.ResourceDirectory+"/posters/{0}.jpg";
  37.     /** The different epochs. */
  38.     public readonly String[] EPOCH = new [] { "Forties", "Fifties", "Sixties", "Seventies", "Eighties", "Nineties", "Twenty-first Century" };
  39.    
  40.     /** The fonts for the title. */
  41.     public readonly Font[] FONT  = new []
  42.     {
  43.         new Font(Font.FontFamily.HELVETICA, 24),
  44.         new Font(Font.FontFamily.HELVETICA, 18),
  45.         new Font(Font.FontFamily.HELVETICA, 14),
  46.         new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD)
  47.     };
  48.    
  49.    
  50.     /**
  51.      * Creates a PDF with a table
  52.      * @param writer the writer to our report file
  53.      * @param filename the PDF that will be created
  54.      * @throws IOException
  55.      * @throws DocumentException
  56.      * @throws SQLException
  57.      */
  58.     private void CreatePdfWithPdfPTable(StreamWriter writer, Stream doc) {
  59.         // Create a connection to the database
  60.         //DatabaseConnection connection = new HsqldbConnection("filmfestival");
  61.         // step 1
  62.         Document document = new Document();
  63.         // step 2
  64.         PdfWriter.GetInstance(document, doc);
  65.         // step 3
  66.         document.Open();
  67.         // step 4
  68.         // Create a table with 2 columns
  69.         PdfPTable table = new PdfPTable(new float[]{1, 7});
  70.         // Mark the table as not complete
  71.         if (test) table.Complete = false;
  72.         table.WidthPercentage = 100;
  73.         IEnumerable movies = PojoFactory.GetMovies();
  74.         List list;
  75.         PdfPCell cell;
  76.         int count = 0;
  77.         // add information about a movie
  78.         foreach (Movie movie in movies) {
  79.             table.SpacingBefore = 5;
  80.             // add a movie poster
  81.             cell = new PdfPCell(Image.GetInstance(String.Format(RESOURCE, movie.Imdb)), true);
  82.             cell.Border = PdfPCell.NO_BORDER;
  83.             table.AddCell(cell);
  84.             // add movie information
  85.             cell = new PdfPCell();
  86.             Paragraph p = new Paragraph(movie.Title, FilmFonts.BOLD);
  87.             p.Alignment = Element.ALIGN_CENTER;
  88.             p.SpacingBefore = 5;
  89.             p.SpacingAfter = 5;
  90.             cell.AddElement(p);
  91.             cell.Border = PdfPCell.NO_BORDER;
  92.             if (movie.OriginalTitle != null) {
  93.                 p = new Paragraph(movie.OriginalTitle, FilmFonts.ITALIC);
  94.                 p.Alignment = Element.ALIGN_RIGHT;
  95.                 cell.AddElement(p);
  96.             }
  97.             list = PojoToElementFactory.GetDirectorList(movie);
  98.             list.IndentationLeft = 30;
  99.             cell.AddElement(list);
  100.             p = new Paragraph(String.Format("Year: %d", movie.Year), FilmFonts.NORMAL);
  101.             p.IndentationLeft = 15;
  102.             p.Leading = 24;
  103.             cell.AddElement(p);
  104.             p = new Paragraph(String.Format("Run length: %d", movie.Duration), FilmFonts.NORMAL);
  105.             p.Leading = 14;
  106.             p.IndentationLeft = 30;
  107.             cell.AddElement(p);
  108.             list = PojoToElementFactory.GetCountryList(movie);
  109.             list.IndentationLeft = 40;
  110.             cell.AddElement(list);
  111.             table.AddCell(cell);
  112.             // insert a checkpoint every 10 movies
  113.             if (count++ % 10 == 0) {
  114.                 // add the incomplete table to the document
  115.                 if (test)
  116.                     document.Add(table);
  117.                 Checkpoint(writer);
  118.             }
  119.         }
  120.         // Mark the table as complete
  121.         if (test) table.Complete = true;
  122.         // add the table to the document
  123.         document.Add(table);
  124.         // insert a last checkpoint
  125.         Checkpoint(writer);
  126.         // step 5
  127.         document.Close();
  128.     }
  129.    
  130.     /**
  131.      * Writes a checkpoint to the report file.
  132.      * @param writer the writer to our report file
  133.      */
  134.     private void Checkpoint(StreamWriter writer) {
  135.         memory_use = GetMemoryUse();
  136.         maximum_memory_use = Math.Max(maximum_memory_use, memory_use);
  137.         Println(writer, "memory use: ", memory_use);
  138.     }
  139.    
  140.     /**
  141.      * Resets the maximum memory that is in use
  142.      * @param writer the writer to our report file
  143.      */
  144.     private void ResetMaximum(StreamWriter writer) {
  145.         Println(writer, "maximum: ", maximum_memory_use);
  146.         Println(writer, "total used: ", maximum_memory_use - initial_memory_use);
  147.         maximum_memory_use = 0l;
  148.         GarbageCollect();
  149.         initial_memory_use = GetMemoryUse();
  150.         Println(writer, "initial memory use: ", initial_memory_use);
  151.     }
  152.  
  153.     /**
  154.      * Writes a line to our report file
  155.      * @param writer the writer to our report file
  156.      * @param message the message to write
  157.      */
  158.     private void Println(StreamWriter writer, String message) {
  159.         try {
  160.             writer.WriteLine(message);
  161.             writer.WriteLine("\n");
  162.             writer.Flush();
  163.         } catch (IOException e) {
  164.             Console.WriteLine(e.StackTrace);
  165.         }
  166.     }
  167.    
  168.     /**
  169.      * Writes a line to our report file
  170.      * @param writer the writer to our report file
  171.      * @param message the message to write
  172.      * @param l a memory value
  173.      */
  174.     private void Println(StreamWriter writer, String message, long l) {
  175.         try {
  176.             writer.WriteLine(message + l);
  177.             writer.WriteLine("\n");
  178.             writer.Flush();
  179.         } catch (IOException e) {
  180.             Console.WriteLine(e.StackTrace);
  181.         }
  182.     }
  183.    
  184.     /**
  185.      * Returns the current memory use.
  186.      *
  187.      * @return the current memory use
  188.      */
  189.     private static long GetMemoryUse() {
  190.         return (GC.GetTotalMemory(true));
  191.     }
  192.    
  193.     /**
  194.      * Makes sure all garbage is cleared from the memory.
  195.      */
  196.     private static void GarbageCollect() {
  197.         try {
  198.             GC.Collect();
  199.             Thread.Sleep(200);
  200.             GC.WaitForPendingFinalizers();
  201.             Thread.Sleep(200);
  202.             GC.Collect();
  203.             Thread.Sleep(200);
  204.             GC.WaitForPendingFinalizers();
  205.             Thread.Sleep(200);
  206.         } catch (Exception ex) {
  207.             Console.WriteLine(ex.StackTrace);
  208.         }
  209.     }
  210.  
  211.     /**
  212.      * Main method.
  213.      * @param args no arguments needed
  214.      * @throws DocumentException
  215.      * @throws IOException
  216.      * @throws SQLException
  217.      */
  218.     public static void Main(String[] args) {
  219.        
  220.     }
  221. // ===========================================================================
  222.     public void Write(Stream stream) {
  223.         try
  224.         {
  225.             using (ZipFile zip = new ZipFile())
  226.             {
  227.                 using (MemoryStream resultStream = new MemoryStream())
  228.                 {
  229.                     using (StreamWriter sw = new StreamWriter(resultStream))
  230.                     {
  231.                         ResetMaximum(sw);
  232.                         using (MemoryStream ms = new MemoryStream())
  233.                         {
  234.                             // step 1
  235.                             test = false;
  236.                             Println(sw, RESULT1);
  237.                             // PDF without memory management
  238.                             CreatePdfWithPdfPTable(sw, ms);
  239.                             ResetMaximum(sw);
  240.                             zip.AddEntry(RESULT1, ms.ToArray());
  241.                         }
  242.                         using (MemoryStream ms = new MemoryStream())
  243.                         {
  244.                             // step 2
  245.                             test = true;
  246.                             Println(sw, RESULT2);
  247.                             // PDF with memory management
  248.                             CreatePdfWithPdfPTable(sw, ms);
  249.                             ResetMaximum(sw);
  250.                             zip.AddEntry(RESULT2, ms.ToArray());
  251.                         }
  252.                         // step 3
  253.                         zip.AddEntry(RESULT0, resultStream.ToArray());
  254.                     }
  255.                 }
  256.                 zip.Save(stream);
  257.             }
  258.         }
  259.         catch(Exception ex)
  260.         {
  261.             Console.WriteLine(ex.StackTrace);
  262.         }
  263.     }
  264. // ===========================================================================
  265.   }
  266. }
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 System.util;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using iTextSharp.text.pdf.draw;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter04 {
  16.   public class PdfCalendar : IWriter {
  17. // ===========================================================================
  18.     /** The year for which we want to create a calendar */
  19.     public const int YEAR = 2011;
  20.     /** The language code for the calendar
  21.      * change this to set culture-specific info
  22.     */
  23.     public const string LANGUAGE = "en";
  24.     /** Path to the resources. */
  25.     public readonly string RESOURCE = Utility.ResourceCalendar;
  26.     /** resources file. */
  27.     public const string CONTENT = "content.txt";
  28.  
  29.     public Properties specialDays = new Properties();
  30.     /** Collection with the description of the images */
  31.     public Properties content = new Properties();
  32.  
  33.     /** A font that is used in the calendar */
  34.     protected Font normal;
  35.     /** A font that is used in the calendar */
  36.     protected Font small;
  37.     /** A font that is used in the calendar */
  38.     protected Font bold;
  39. // ---------------------------------------------------------------------------
  40.     /**
  41.      * Initializes the fonts and collections.
  42.      */
  43.     public PdfCalendar() {
  44.       // fonts
  45.     BaseFont bf_normal = BaseFont.CreateFont(
  46.       "c://windows/fonts/arial.ttf",
  47.         BaseFont.WINANSI,
  48.         BaseFont.EMBEDDED
  49.       );
  50.       normal = new Font(bf_normal, 16);
  51.       small = new Font(bf_normal, 8);
  52.       BaseFont bf_bold = BaseFont.CreateFont(
  53.         "c://windows/fonts/arialbd.ttf",
  54.         BaseFont.WINANSI,
  55.         BaseFont.EMBEDDED
  56.       );
  57.       bold = new Font(bf_bold, 14);
  58.       // collections
  59.       string year_file = Path.Combine(
  60.         Utility.ResourceCalendar, string.Format("{0}.txt", YEAR)
  61.       );
  62.       if (!File.Exists(year_file)) {
  63.         throw new ArgumentException(year_file + " NOT FOUND!");
  64.       }
  65.       string content_file = Path.Combine(Utility.ResourceCalendar, CONTENT);
  66.       if (!File.Exists(content_file)) {
  67.         throw new ArgumentException(year_file + " NOT FOUND!");
  68.       }
  69.       using (FileStream fs = new FileStream(
  70.         year_file, FileMode.Open, FileAccess.Read
  71.       ) ) {
  72.         specialDays.Load(fs);
  73.       }
  74.       using (FileStream fs = new FileStream(
  75.         content_file, FileMode.Open, FileAccess.Read
  76.       ) ) {
  77.         content.Load(fs);
  78.       }      
  79.     }
  80. // ---------------------------------------------------------------------------
  81.     /**
  82.      * Creates a PDF document.
  83.      */
  84.     public virtual void Write(Stream stream) {
  85.       // step 1
  86.       using (Document document = new Document(PageSize.A4.Rotate())) {
  87.         // step 2
  88.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  89.         // step 3
  90.         document.Open();
  91.         // step 4
  92.         // "en" => System.Globalization.GregorianCalendar
  93.         Calendar calendar = new CultureInfo(LANGUAGE, false).Calendar;
  94.         PdfContentByte canvas = writer.DirectContent;
  95.         // Loop over the months
  96.         for (int month = 0; month < 12; month++) {
  97.           int current_month = month + 1;
  98.           DateTime dt = new DateTime(YEAR, current_month, 1, calendar);
  99.           // draw the background
  100.           DrawImageAndText(canvas, dt);
  101.           // create a table with 7 columns
  102.           PdfPTable table = new PdfPTable(7);
  103.           table.TotalWidth = 504;
  104.           // add the name of the month
  105.           table.DefaultCell.BackgroundColor = BaseColor.WHITE;
  106.           table.AddCell(GetMonthCell(dt));
  107.           int daysInMonth = DateTime.DaysInMonth(YEAR, dt.Month);
  108.           int day = 1;
  109.           // add empty cells
  110.           // SUNDAY; Java => 1, .NET => 0
  111.           int position = 0;
  112.           while (position++ != (int) dt.DayOfWeek) {
  113.             table.AddCell("");
  114.           }
  115.           // add cells for each day
  116.           while (day
Zhang.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.Chapter04 {
  16.   public class Zhang : IWriter {
  17. // ===========================================================================
  18.     public void Write(Stream stream) {
  19.       // step 1
  20.       using (Document document = new Document()) {
  21.         // step 2
  22.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  23.         // step 3
  24.         document.Open();
  25.         // step 4
  26.         // Create a table and fill it with movies
  27.         IEnumerable movies = PojoFactory.GetMovies(3);
  28.         PdfPTable table = new PdfPTable(new float[] { 1, 5, 5, 1});
  29.         foreach (Movie movie in movies) {
  30.           table.AddCell(movie.Year.ToString());
  31.           table.AddCell(movie.MovieTitle);
  32.           table.AddCell(movie.OriginalTitle);
  33.           table.AddCell(movie.Duration.ToString());
  34.         }
  35.         // set the total width of the table
  36.         table.TotalWidth = 600;
  37.         PdfContentByte canvas = writer.DirectContent;
  38.         // draw the first three columns on one page
  39.         table.WriteSelectedRows(0, 2, 0, -1, 236, 806, canvas);
  40.         document.NewPage();
  41.         // draw the next three columns on the next page
  42.         table.WriteSelectedRows(2, -1, 0, -1, 36, 806, canvas);
  43.       }
  44.     }
  45. // ===========================================================================
  46.   }
  47. }
ColumnTable.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.Chapter04 {
  15.   public class ColumnTable : IWriter {
  16. // ===========================================================================
  17.     public void Write(Stream stream) {
  18.       // step 1
  19.       using (Document document = new Document(PageSize.A4.Rotate())) {
  20.         // step 2
  21.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  22.         // step 3
  23.         document.Open();
  24.         // step 4
  25.         ColumnText column = new ColumnText(writer.DirectContent);
  26.         List days = PojoFactory.GetDays();
  27.         // COlumn definition
  28.         float[][] x = {
  29.           new float[] { document.Left, document.Left + 380 },
  30.           new float[] { document.Right - 380, document.Right }
  31.         };
  32.         // Loop over the festival days
  33.         foreach (string day in days) {
  34.         // add content to the column
  35.           column.AddElement(GetTable(day));
  36.           int count = 0;
  37.           float height = 0;
  38.           // iText-ONLY, 'Initial value of the status' => 0
  39.           // iTextSharp **DOES NOT** include this member variable
  40.           // int status = ColumnText.START_COLUMN;
  41.           int status = 0;
  42.           // render the column as long as it has content
  43.           while (ColumnText.HasMoreText(status)) {
  44.           // add the top-level header to each new page
  45.             if (count == 0) {
  46.               height = AddHeaderTable(document, day, writer.PageNumber);
  47.             }
  48.             // set the dimensions of the current column
  49.             column.SetSimpleColumn(
  50.               x[count][0], document.Bottom,
  51.               x[count][1], document.Top - height - 10
  52.             );
  53.             // render as much content as possible
  54.             status = column.Go();
  55.             // go to a new page if you've reached the last column
  56.             if (++count > 1) {
  57.               count = 0;
  58.               document.NewPage();
  59.             }
  60.           }
  61.           document.NewPage();
  62.         }
  63.       }
  64.     }
  65. // ---------------------------------------------------------------------------    
  66.     /**
  67.      * Add a header table to the document
  68.      * @param document The document to which you want to add a header table
  69.      * @param day The day that needs to be shown in the header table
  70.      * @param page The page number that has to be shown in the header
  71.      * @return the height of the resulting header table
  72.      */
  73.     public float AddHeaderTable(Document document, string day, int page) {
  74.       PdfPTable header = new PdfPTable(3);
  75.       header.WidthPercentage = 100;
  76.       header.DefaultCell.BackgroundColor = BaseColor.BLACK;
  77.       Font font = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.WHITE);
  78.       Phrase p = new Phrase("Foobar Film Festival", font);
  79.       header.AddCell(p);
  80.       header.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
  81.       p = new Phrase(day, font);
  82.       header.AddCell(p);
  83.       header.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
  84.       p = new Phrase(string.Format("page {0}", page), font);
  85.       header.AddCell(p);
  86.       document.Add(header);
  87.       return header.TotalHeight;
  88.     }
  89. // ---------------------------------------------------------------------------
  90.     /**
  91.      * Creates a table with movie screenings for a specific day
  92.      * @param connection a connection to the database
  93.      * @param day a day
  94.      * @return a table with screenings
  95.      */
  96.     public PdfPTable GetTable(string day) {
  97.       PdfPTable table = new PdfPTable(new float[] { 2, 1, 2, 5, 1 });
  98.       table.WidthPercentage = 100f;
  99.       table.DefaultCell.UseAscender = true;
  100.       table.DefaultCell.UseDescender = true;
  101.       table.DefaultCell.BackgroundColor = BaseColor.LIGHT_GRAY;
  102.       for (int i = 0; i < 2; i++) {
  103.         table.AddCell("Location");
  104.         table.AddCell("Time");
  105.         table.AddCell("Run Length");
  106.         table.AddCell("Title");
  107.         table.AddCell("Year");
  108.       }
  109.       table.DefaultCell.BackgroundColor = null;
  110.       table.HeaderRows = 2;
  111.       table.FooterRows = 1;
  112.       List screenings = PojoFactory.GetScreenings(day);
  113.       Movie movie;
  114.       foreach (Screening screening in screenings) {
  115.         movie = screening.movie;
  116.         table.AddCell(screening.Location);
  117.         table.AddCell(screening.Time.Substring(0, 5));
  118.         table.AddCell(movie.Duration.ToString());
  119.         table.AddCell(movie.MovieTitle);
  120.         table.AddCell(movie.Year.ToString());
  121.       }
  122.       return table;
  123.     }    
  124. // ===========================================================================
  125.   }
  126. }
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