Chapter 2: Using iText's basic building blocks

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

10th October 2015
admin-marketing

Switch code for this example

DatabaseTest.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.chapter02;
  9.  
  10. import java.io.FileNotFoundException;
  11. import java.io.FileOutputStream;
  12. import java.io.PrintStream;
  13. import java.io.UnsupportedEncodingException;
  14. import java.sql.ResultSet;
  15. import java.sql.SQLException;
  16. import java.sql.Statement;
  17.  
  18. import com.lowagie.database.DatabaseConnection;
  19. import com.lowagie.database.HsqldbConnection;
  20.  
  21. /**
  22.  * We'll test our hsqldb database with this example
  23.  */
  24. public class DatabaseTest {
  25.    
  26.     /** The output of this database test: a text file with a list of countries. */
  27.     public static final String RESULT = "results/part1/chapter02/countries.txt";
  28.    
  29.     /**
  30.      * Writes the names of the countries that are in our database
  31.      * @param    args    no arguments needed
  32.      * @throws FileNotFoundException
  33.      */
  34.     public static void main(String[] args)
  35.         throws SQLException, UnsupportedEncodingException, FileNotFoundException {
  36.         // no PDF, just a text file
  37.         PrintStream out = new PrintStream(new FileOutputStream(RESULT));
  38.         // Make the connection to the database
  39.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  40.         // create the statement
  41.         Statement stm = connection.createStatement();
  42.         // execute the query
  43.         ResultSet rs = stm.executeQuery("SELECT country FROM film_country ORDER BY country");
  44.         // loop over the results
  45.         while (rs.next()) {
  46.             // write a country to the text file
  47.             out.println(rs.getString("country"));
  48.         }
  49.         // close the statement
  50.         stm.close();
  51.         // close the database connection
  52.         connection.close();
  53.         // flush and close the print stream
  54.         out.flush();
  55.         out.close();
  56.     }
  57. }
CountryChunks.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.chapter02;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15.  
  16. import com.lowagie.database.DatabaseConnection;
  17. import com.lowagie.database.HsqldbConnection;
  18. import com.itextpdf.text.Chunk;
  19. import com.itextpdf.text.Document;
  20. import com.itextpdf.text.DocumentException;
  21. import com.itextpdf.text.Font;
  22. import com.itextpdf.text.Font.FontFamily;
  23. import com.itextpdf.text.pdf.PdfWriter;
  24. import com.itextpdf.text.BaseColor;
  25.  
  26. /**
  27.  * Writes a list of countries to a PDF file.
  28.  */
  29. public class CountryChunks {
  30.  
  31.     /** The resulting PDF file. */
  32.     public static final String RESULT
  33.         = "results/part1/chapter02/country_chunks.pdf";
  34.  
  35.     /**
  36.      * Main method.
  37.      *
  38.      * @param    args    no arguments needed
  39.      * @throws DocumentException
  40.      * @throws IOException
  41.      * @throws SQLException
  42.      */
  43.     public static void main(String[] args)
  44.         throws IOException, DocumentException, SQLException {
  45.         new CountryChunks().createPdf(RESULT);
  46.     }
  47.  
  48.     /**
  49.      * Creates a PDF document.
  50.      * @param filename the path to the new PDF document
  51.      * @throws    DocumentException
  52.      * @throws    IOException
  53.      * @throws    SQLException
  54.      */
  55.     public void createPdf(String filename)
  56.         throws IOException, DocumentException, SQLException{
  57.         // step 1
  58.         Document document = new Document();
  59.         // step 2
  60.         PdfWriter.getInstance(document, new FileOutputStream(filename))
  61.             .setInitialLeading(16);
  62.         // step 3
  63.         document.open();
  64.         // step 4
  65.         // database connection and statement
  66.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  67.         Statement stm = connection.createStatement();
  68.         ResultSet rs = stm.executeQuery(
  69.             "SELECT country, id FROM film_country ORDER BY country");
  70.         // add the ID in another font
  71.         Font font = new Font(FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
  72.         while (rs.next()) {
  73.             // add a country to the document as a Chunk
  74.             document.add(new Chunk(rs.getString("country")));
  75.             document.add(new Chunk(" "));
  76.             Chunk id = new Chunk(rs.getString("id"), font);
  77.             // with a background color
  78.             id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
  79.             // and a text rise
  80.             id.setTextRise(6);
  81.             document.add(id);
  82.             document.add(Chunk.NEWLINE);
  83.         }
  84.         stm.close();
  85.         connection.close();
  86.         // step 5
  87.         document.close();
  88.     }
  89. }
DirectorPhrases1.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.chapter02;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.UnsupportedEncodingException;
  13. import java.sql.ResultSet;
  14. import java.sql.SQLException;
  15. import java.sql.Statement;
  16.  
  17. import com.lowagie.database.DatabaseConnection;
  18. import com.lowagie.database.HsqldbConnection;
  19. import com.itextpdf.text.Chunk;
  20. import com.itextpdf.text.Document;
  21. import com.itextpdf.text.DocumentException;
  22. import com.itextpdf.text.Font;
  23. import com.itextpdf.text.Phrase;
  24. import com.itextpdf.text.Font.FontFamily;
  25. import com.itextpdf.text.pdf.PdfWriter;
  26.  
  27. /**
  28.  * Writes a list of directors to a PDF file.
  29.  */
  30. public class DirectorPhrases1 {
  31.    
  32.     /** The resulting PDF file. */
  33.     public static final String RESULT = "results/part1/chapter02/director_phrases_1.pdf";
  34.  
  35.     /** A font that will be used in our PDF. */
  36.     public static final Font BOLD_UNDERLINED =
  37.         new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLD | Font.UNDERLINE);
  38.     /** A font that will be used in our PDF. */
  39.     public static final Font NORMAL =
  40.         new Font(FontFamily.TIMES_ROMAN, 12);
  41.    
  42.     /**
  43.      * Creates a Phrase with the name and given name of a director using different fonts.
  44.      * @param    rs    the ResultSet containing director records.
  45.      */
  46.     public Phrase createDirectorPhrase(ResultSet rs)
  47.         throws UnsupportedEncodingException, SQLException {
  48.         Phrase director = new Phrase();
  49.         director.add(
  50.             new Chunk(new String(rs.getBytes("name"), "UTF-8"), BOLD_UNDERLINED));
  51.         director.add(new Chunk(",", BOLD_UNDERLINED));
  52.         director.add(new Chunk(" ", NORMAL));
  53.         director.add(
  54.             new Chunk(new String(rs.getBytes("given_name"), "UTF-8"), NORMAL));
  55.         return director;
  56.     }
  57.    
  58.     /**
  59.      * Creates a PDF file with director names.
  60.      * @param    filename    the name of the PDF file that needs to be created.
  61.      * @throws    DocumentException
  62.      * @throws    IOException
  63.      * @throws    SQLException
  64.      */
  65.     public void createPdf(String filename)
  66.         throws IOException, DocumentException, SQLException {
  67.         // step 1
  68.         Document document = new Document();
  69.         // step 2
  70.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  71.         // step 3
  72.         document.open();
  73.         // step 4
  74.         // create the database connection and statement
  75.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  76.         Statement stm = connection.createStatement();
  77.         ResultSet rs = stm.executeQuery(
  78.             "SELECT name, given_name FROM film_director ORDER BY name, given_name");
  79.         // loop over the results
  80.         while (rs.next()) {
  81.             document.add(createDirectorPhrase(rs));
  82.             document.add(Chunk.NEWLINE);
  83.         }
  84.         // close the statement and database connection
  85.         stm.close();
  86.         connection.close();
  87.         // step 5
  88.         document.close();
  89.     }
  90.    
  91.     /**
  92.      * Main method.
  93.      *
  94.      * @param    args    no arguments needed
  95.      * @throws DocumentException
  96.      * @throws IOException
  97.      * @throws SQLException
  98.      */
  99.     public static void main(String[] args)
  100.         throws IOException, DocumentException, SQLException {
  101.         new DirectorPhrases1().createPdf(RESULT);
  102.     }
  103. }
DirectorPhrases2.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.chapter02;
  9.  
  10. import java.io.IOException;
  11. import java.io.UnsupportedEncodingException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14.  
  15. import com.itextpdf.text.Chunk;
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.Font;
  18. import com.itextpdf.text.Phrase;
  19. import com.itextpdf.text.pdf.BaseFont;
  20.  
  21. /**
  22.  * Writes a list of directors to a PDF file.
  23.  */
  24. public class DirectorPhrases2 extends DirectorPhrases1 {
  25.    
  26.     /** The resulting PDF file. */
  27.     public static final String RESULT = "results/part1/chapter02/director_phrases_2.pdf";
  28.  
  29.     /** A font that will be used in our PDF. */
  30.     public static final Font BOLD;
  31.     /** A font that will be used in our PDF. */
  32.     public static final Font NORMAL;
  33.    
  34.     static {
  35.         BaseFont timesbd = null;
  36.         BaseFont times = null;
  37.         try {
  38.             // create a font that will be embedded
  39.             timesbd = BaseFont.createFont(
  40.                 "c:/windows/fonts/timesbd.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED);
  41.             // create a font that will be embedded
  42.             times = BaseFont.createFont(
  43.                 "c:/windows/fonts/times.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED);
  44.         } catch (DocumentException e) {
  45.             e.printStackTrace();
  46.             System.exit(1);
  47.         } catch (IOException e) {
  48.             e.printStackTrace();
  49.             System.exit(1);
  50.         }
  51.         BOLD = new Font(timesbd, 12);
  52.         NORMAL = new Font(times, 12);
  53.     }
  54.    
  55.     /**
  56.      * Creates a Phrase with the name and given name of a director using different fonts.
  57.      * @param    rs    the ResultSet containing director records.
  58.      */
  59.     public Phrase createDirectorPhrase(ResultSet rs)
  60.         throws UnsupportedEncodingException, SQLException {
  61.         Phrase director = new Phrase();
  62.         Chunk name = new Chunk(new String(rs.getBytes("name"), "UTF-8"), BOLD);
  63.         name.setUnderline(0.2f, -2f);
  64.         director.add(name);
  65.         director.add(new Chunk(",", BOLD));
  66.         director.add(new Chunk(" ", NORMAL));
  67.         director.add(
  68.             new Chunk(new String(rs.getBytes("given_name"), "UTF-8"), NORMAL));
  69.         director.setLeading(24);
  70.         return director;
  71.     }
  72.    
  73.     /**
  74.      * Main method.
  75.      *
  76.      * @param    args    no arguments needed
  77.      * @throws DocumentException
  78.      * @throws IOException
  79.      * @throws SQLException
  80.      */
  81.     public static void main(String[] args)
  82.         throws IOException, DocumentException, SQLException {
  83.         new DirectorPhrases2().createPdf(RESULT);
  84.     }
  85. }
MovieTitles.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.chapter02;
  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.PojoFactory;
  18. import com.lowagie.filmfestival.Movie;
  19. import com.itextpdf.text.Document;
  20. import com.itextpdf.text.DocumentException;
  21. import com.itextpdf.text.Paragraph;
  22. import com.itextpdf.text.pdf.PdfWriter;
  23.  
  24. /**
  25.  * Writes a list of movies titles to a PDF file.
  26.  */
  27. public class MovieTitles {
  28.  
  29.     /** The resulting PDF file. */
  30.     public static final String RESULT = "results/part1/chapter02/movie_titles.pdf";
  31.    
  32.     /**
  33.      * Main method.
  34.      *
  35.      * @param    args    no arguments needed
  36.      * @throws DocumentException
  37.      * @throws IOException
  38.      * @throws SQLException
  39.      */
  40.     public static void main(String[] args) throws IOException, DocumentException, SQLException {
  41.         // Create a database connection
  42.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  43.         // step 1
  44.         Document document = new Document();
  45.         // step 2
  46.         PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  47.         // step 3
  48.         document.open();
  49.         // step 4
  50.         List movies = PojoFactory.getMovies(connection);
  51.         for (Movie movie : movies) {
  52.             document.add(new Paragraph(movie.getTitle()));
  53.         }
  54.         // step 5
  55.         document.close();
  56.         // Close the database connection
  57.         connection.close();
  58.     }
  59. }
MovieParagraphs1.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.chapter02;
  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.PojoToElementFactory;
  21. import com.lowagie.filmfestival.PojoFactory;
  22. import com.lowagie.filmfestival.Movie;
  23. import com.itextpdf.text.Chunk;
  24. import com.itextpdf.text.Document;
  25. import com.itextpdf.text.DocumentException;
  26. import com.itextpdf.text.Element;
  27. import com.itextpdf.text.Paragraph;
  28. import com.itextpdf.text.Phrase;
  29. import com.itextpdf.text.pdf.PdfWriter;
  30.  
  31. /**
  32.  * Writes a list of movies titles to a PDF file.
  33.  */
  34. public class MovieParagraphs1 {
  35.  
  36.     /** The resulting PDF file. */
  37.     public static final String RESULT
  38.         = "results/part1/chapter02/movie_paragraphs_1.pdf";
  39.    
  40.     /**
  41.      * Creates a Paragraph containing information about a movie.
  42.      * @param    movie    the movie for which you want to create a Paragraph
  43.      */
  44.     public Paragraph createMovieInformation(Movie movie) {
  45.         Paragraph p = new Paragraph();
  46.         p.setFont(FilmFonts.NORMAL);
  47.         p.add(new Phrase("Title: ", FilmFonts.BOLDITALIC));
  48.         p.add(PojoToElementFactory.getMovieTitlePhrase(movie));
  49.         p.add(" ");
  50.         if (movie.getOriginalTitle() != null) {
  51.             p.add(new Phrase("Original title: ", FilmFonts.BOLDITALIC));
  52.             p.add(PojoToElementFactory.getOriginalTitlePhrase(movie));
  53.             p.add(" ");
  54.         }
  55.         p.add(new Phrase("Country: ", FilmFonts.BOLDITALIC));
  56.         for (Country country : movie.getCountries()) {
  57.             p.add(PojoToElementFactory.getCountryPhrase(country));
  58.             p.add(" ");
  59.         }
  60.         p.add(new Phrase("Director: ", FilmFonts.BOLDITALIC));
  61.         for (Director director : movie.getDirectors()) {
  62.             p.add(PojoToElementFactory.getDirectorPhrase(director));
  63.             p.add(" ");
  64.         }
  65.         p.add(createYearAndDuration(movie));
  66.         return p;
  67.     }
  68.    
  69.     /**
  70.      * Creates a Paragraph containing information about the year
  71.      * and the duration of a movie.
  72.      * @param    movie    the movie for which you want to create a Paragraph
  73.      */
  74.     public Paragraph createYearAndDuration(Movie movie) {
  75.         Paragraph info = new Paragraph();
  76.         info.setFont(FilmFonts.NORMAL);
  77.         info.add(new Chunk("Year: ", FilmFonts.BOLDITALIC));
  78.         info.add(new Chunk(String.valueOf(movie.getYear()), FilmFonts.NORMAL));
  79.         info.add(new Chunk(" Duration: ", FilmFonts.BOLDITALIC));
  80.         info.add(new Chunk(String.valueOf(movie.getDuration()), FilmFonts.NORMAL));
  81.         info.add(new Chunk(" minutes", FilmFonts.NORMAL));
  82.         return info;
  83.     }
  84.    
  85.     /**
  86.      * Creates a PDF with information about the movies
  87.      * @param    filename the name of the PDF file that will be created.
  88.      * @throws    DocumentException
  89.      * @throws    IOException
  90.      * @throws    SQLException
  91.      */
  92.     public void createPdf(String filename)
  93.         throws IOException, DocumentException, SQLException {
  94.         // Create a database connection
  95.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  96.         // step 1
  97.         Document document = new Document();
  98.         // step 2
  99.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  100.         // step 3
  101.         document.open();
  102.         // step 4
  103.         List movies = PojoFactory.getMovies(connection);
  104.         for (Movie movie : movies) {
  105.             Paragraph p = createMovieInformation(movie);
  106.             p.setAlignment(Element.ALIGN_JUSTIFIED);
  107.             p.setIndentationLeft(18);
  108.             p.setFirstLineIndent(-18);
  109.             document.add(p);
  110.         }
  111.         // step 5
  112.         document.close();
  113.         // Close the database connection
  114.         connection.close();
  115.     }
  116.    
  117.     /**
  118.      * Main method.
  119.      *
  120.      * @param    args    no arguments needed
  121.      * @throws DocumentException
  122.      * @throws IOException
  123.      * @throws SQLException
  124.      */
  125.     public static void main(String[] args)
  126.         throws IOException, DocumentException, SQLException {
  127.         new MovieParagraphs1().createPdf(RESULT);
  128.     }
  129. }
MovieParagraphs2.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.chapter02;
  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.pdf.PdfWriter;
  28.  
  29. public class MovieParagraphs2 extends MovieParagraphs1 {
  30.  
  31.     public static final String RESULT = "results/part1/chapter02/movie_paragraphs_2.pdf";
  32.    
  33.     /**
  34.      * Main method.
  35.      *
  36.      * @param    args    no arguments needed
  37.      * @throws DocumentException
  38.      * @throws IOException
  39.      * @throws SQLException
  40.      */
  41.     public static void main(String[] args)
  42.         throws IOException, DocumentException, SQLException {
  43.         new MovieParagraphs2().createPdf(RESULT);
  44.     }
  45.    
  46.     /**
  47.      * Creates a PDF with information about the movies
  48.      * @param    filename the name of the PDF file that will be created.
  49.      * @throws    DocumentException
  50.      * @throws    IOException
  51.      * @throws    SQLException
  52.      */
  53.     public void createPdf(String filename)
  54.         throws IOException, DocumentException, SQLException {
  55.         // Create a 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 movies = PojoFactory.getMovies(connection);
  65.         for (Movie movie : movies) {
  66.             // Create a paragraph with the title
  67.             Paragraph title = new Paragraph(
  68.                 PojoToElementFactory.getMovieTitlePhrase(movie));
  69.             title.setAlignment(Element.ALIGN_LEFT);
  70.             document.add(title);
  71.             // Add the original title next to it using a dirty hack
  72.             if (movie.getOriginalTitle() != null) {
  73.                 Paragraph dummy = new Paragraph("\u00a0", FilmFonts.NORMAL);
  74.                 dummy.setLeading(-18);
  75.                 document.add(dummy);
  76.                 Paragraph originalTitle = new Paragraph(
  77.                     PojoToElementFactory.getOriginalTitlePhrase(movie));
  78.                 originalTitle.setAlignment(Element.ALIGN_RIGHT);
  79.                 document.add(originalTitle);
  80.             }
  81.             // Info about the director
  82.             Paragraph director;
  83.             float indent = 20;
  84.             // Loop over the directors
  85.             for (Director pojo : movie.getDirectors()) {
  86.                 director = new Paragraph(
  87.                     PojoToElementFactory.getDirectorPhrase(pojo));
  88.                 director.setIndentationLeft(indent);
  89.                 document.add(director);
  90.                 indent += 20;
  91.             }
  92.             // Info about the country
  93.             Paragraph country;
  94.             indent = 20;
  95.             // Loop over the countries
  96.             for (Country pojo : movie.getCountries()) {
  97.                 country = new Paragraph(
  98.                     PojoToElementFactory.getCountryPhrase(pojo));
  99.                 country.setAlignment(Element.ALIGN_RIGHT);
  100.                 country.setIndentationRight(indent);
  101.                 document.add(country);
  102.                 indent += 20;
  103.             }
  104.             // Extra info about the movie
  105.             Paragraph info = createYearAndDuration(movie);
  106.             info.setAlignment(Element.ALIGN_CENTER);
  107.             info.setSpacingAfter(36);
  108.             document.add(info);
  109.         }
  110.         // step 5
  111.         document.close();
  112.         // Close the database connection
  113.         connection.close();
  114.     }
  115. }
PipeSplitCharacter.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.chapter02;
  9.  
  10. import com.itextpdf.text.SplitCharacter;
  11. import com.itextpdf.text.pdf.PdfChunk;
  12.  
  13. /**
  14.  * Implementation of the SplitCharacter interface.
  15.  * Use an instance of this class with Chunk.setSplitCharacter();
  16.  */
  17. public class PipeSplitCharacter implements SplitCharacter {
  18.    
  19.     /**
  20.      * @see com.itextpdf.text.SplitCharacter#isSplitCharacter(int, int, int, char[],
  21.      *      com.itextpdf.text.pdf.PdfChunk[])
  22.      */
  23.     public boolean isSplitCharacter(int start, int current, int end, char[] cc,
  24.             PdfChunk[] ck) {
  25.         char c;
  26.         if (ck == null)
  27.             c = cc[current];
  28.         else
  29.             c = (char)ck[Math.min(current, ck.length - 1)]
  30.                     .getUnicodeEquivalent(cc[current]);
  31.         return (c == '|' || c
MovieChain.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.chapter02;
  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.Chunk;
  20. import com.itextpdf.text.Document;
  21. import com.itextpdf.text.DocumentException;
  22. import com.itextpdf.text.Element;
  23. import com.itextpdf.text.Paragraph;
  24. import com.itextpdf.text.Rectangle;
  25. import com.itextpdf.text.pdf.HyphenationAuto;
  26. import com.itextpdf.text.pdf.PdfWriter;
  27.  
  28. /**
  29.  * Writes a list of directors to a PDF file.
  30.  */
  31. public class MovieChain {
  32.    
  33.     /** The resulting PDF file. */
  34.     public static final String RESULT = "results/part1/chapter02/kubrick.pdf";
  35.    
  36.     /**
  37.      * Creates a PDF file with director names.
  38.      * @param    filename    the name of the PDF file that needs to be created.
  39.      * @throws    DocumentException
  40.      * @throws    IOException
  41.      * @throws    SQLException
  42.      */
  43.     public void createPdf(String filename)
  44.         throws IOException, DocumentException, SQLException {
  45.  
  46.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  47.         List kubrick = PojoFactory.getMovies(connection, 1);
  48.         connection.close();
  49.         // step 1
  50.         Document document = new Document(new Rectangle(240, 240), 10, 10, 10, 10);
  51.         // step 2
  52.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  53.         // step 3
  54.         document.open();
  55.         // step 4
  56.         // create a long Stringbuffer with movie titles
  57.         StringBuffer buf1 = new StringBuffer();
  58.         for (Movie movie : kubrick) {
  59.             // replace spaces with non-breaking spaces
  60.             buf1.append(movie.getMovieTitle().replace(' ', '\u00a0'));
  61.             // use pipe as separator
  62.             buf1.append('|');
  63.         }
  64.         // Create a first chunk
  65.         Chunk chunk1 = new Chunk(buf1.toString());
  66.         // wrap the chunk in a paragraph and add it to the document
  67.         Paragraph paragraph = new Paragraph("A:\u00a0");
  68.         paragraph.add(chunk1);
  69.         paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
  70.         document.add(paragraph);
  71.         document.add(Chunk.NEWLINE);
  72.         // define the pipe character as split character
  73.         chunk1.setSplitCharacter(new PipeSplitCharacter());
  74.         // wrap the chunk in a second paragraph and add it
  75.         paragraph = new Paragraph("B:\u00a0");
  76.         paragraph.add(chunk1);
  77.         paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
  78.         document.add(paragraph);
  79.         document.add(Chunk.NEWLINE);
  80.  
  81.         // create a new StringBuffer with movie titles
  82.         StringBuffer buf2 = new StringBuffer();
  83.         for (Movie movie : kubrick) {
  84.             buf2.append(movie.getMovieTitle());
  85.             buf2.append('|');
  86.         }
  87.         // Create a second chunk
  88.         Chunk chunk2 = new Chunk(buf2.toString());
  89.         // wrap the chunk in a paragraph and add it to the document
  90.         paragraph = new Paragraph("C:\u00a0");
  91.         paragraph.add(chunk2);
  92.         paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
  93.         document.add(paragraph);
  94.         document.newPage();
  95.         // define hyphenation for the chunk
  96.         chunk2.setHyphenation(new HyphenationAuto("en", "US", 2, 2));
  97.         // wrap the second chunk in a second paragraph and add it
  98.         paragraph = new Paragraph("D:\u00a0");
  99.         paragraph.add(chunk2);
  100.         paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
  101.         document.add(paragraph);
  102.        
  103.         // go to a new page
  104.         document.newPage();
  105.         // define a new space/char ratio
  106.         writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
  107.         // wrap the second chunk in a third paragraph and add it
  108.         paragraph = new Paragraph("E:\u00a0");
  109.         paragraph.add(chunk2);
  110.         paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
  111.         document.add(paragraph);
  112.         // step 5
  113.         document.close();
  114.     }
  115.    
  116.     /**
  117.      * Main method.
  118.      *
  119.      * @param    args    no arguments needed
  120.      * @throws DocumentException
  121.      * @throws IOException
  122.      * @throws SQLException
  123.      */
  124.     public static void main(String[] args)
  125.         throws IOException, DocumentException, SQLException {
  126.         new MovieChain().createPdf(RESULT);
  127.     }
  128. }
MovieLists1.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.chapter02;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15.  
  16. import com.lowagie.database.DatabaseConnection;
  17. import com.lowagie.database.HsqldbConnection;
  18. import com.lowagie.filmfestival.Director;
  19. import com.lowagie.filmfestival.FilmFonts;
  20. import com.lowagie.filmfestival.Movie;
  21. import com.lowagie.filmfestival.PojoFactory;
  22. import com.itextpdf.text.Document;
  23. import com.itextpdf.text.DocumentException;
  24. import com.itextpdf.text.List;
  25. import com.itextpdf.text.ListItem;
  26. import com.itextpdf.text.pdf.PdfWriter;
  27.  
  28. public class MovieLists1 {
  29.  
  30.     /** The resulting PDF file. */
  31.     public static final String RESULT = "results/part1/chapter02/movie_lists_1.pdf";
  32.    
  33.     /**
  34.      * Creates a PDF with information about the movies
  35.      * @param    filename the name of the PDF file that will be created.
  36.      * @throws    DocumentException
  37.      * @throws    IOException
  38.      * @throws    SQLException
  39.      */
  40.     public void createPdf(String filename)
  41.         throws IOException, DocumentException, SQLException {
  42.         // step 1
  43.         Document document = new Document();
  44.         // step 2
  45.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  46.         // step 3
  47.         document.open();
  48.         // step 4
  49.         // Create database connection and statement
  50.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  51.         Statement stm = connection.createStatement();
  52.         ResultSet rs = stm.executeQuery(
  53.             "SELECT DISTINCT mc.country_id, c.country, count(*) AS c "
  54.             + "FROM film_country c, film_movie_country mc "
  55.             + "WHERE c.id = mc.country_id "
  56.             + "GROUP BY mc.country_id, country ORDER BY c DESC");
  57.         // Create a new list
  58.         List list = new List(List.ORDERED);
  59.         // loop over the countries
  60.         while (rs.next()) {
  61.             // create a list item for the country
  62.             ListItem item = new ListItem(
  63.                 String.format("%s: %d movies",
  64.                     rs.getString("country"), rs.getInt("c")),
  65.                 FilmFonts.BOLDITALIC);
  66.             // create a movie list for each country
  67.             List movielist = new List(List.ORDERED, List.ALPHABETICAL);
  68.             movielist.setLowercase(List.LOWERCASE);
  69.             for(Movie movie :
  70.                 PojoFactory.getMovies(connection, rs.getString("country_id"))) {
  71.                 ListItem movieitem = new ListItem(movie.getMovieTitle());
  72.                 List directorlist = new List(List.UNORDERED);
  73.                 for (Director director : movie.getDirectors()) {
  74.                     directorlist.add(
  75.                         String.format("%s, %s",
  76.                             director.getName(), director.getGivenName()));
  77.                 }
  78.                 movieitem.add(directorlist);
  79.                 movielist.add(movieitem);
  80.             }
  81.             item.add(movielist);
  82.             list.add(item);
  83.         }
  84.         document.add(list);
  85.         // close the statement and the database connection
  86.         stm.close();
  87.         connection.close();
  88.         // step 4
  89.         document.close();
  90.     }
  91.    
  92.     /**
  93.      * Main method.
  94.      *
  95.      * @param    args    no arguments needed
  96.      * @throws DocumentException
  97.      * @throws IOException
  98.      * @throws SQLException
  99.      */
  100.     public static void main(String[] args) throws IOException, DocumentException, SQLException {
  101.         new MovieLists1().createPdf(RESULT);
  102.     }
  103. }
MovieLists2.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.chapter02;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15.  
  16. import com.lowagie.database.DatabaseConnection;
  17. import com.lowagie.database.HsqldbConnection;
  18. import com.lowagie.filmfestival.Director;
  19. import com.lowagie.filmfestival.Movie;
  20. import com.lowagie.filmfestival.PojoFactory;
  21. import com.itextpdf.text.Chunk;
  22. import com.itextpdf.text.Document;
  23. import com.itextpdf.text.DocumentException;
  24. import com.itextpdf.text.List;
  25. import com.itextpdf.text.ListItem;
  26. import com.itextpdf.text.pdf.PdfWriter;
  27.  
  28. public class MovieLists2 {
  29.  
  30.     /** The resulting PDF file. */
  31.     public static final String RESULT = "results/part1/chapter02/movie_lists_2.pdf";
  32.    
  33.     /**
  34.      * Creates a PDF with information about the movies
  35.      * @param    filename the name of the PDF file that will be created.
  36.      * @throws    DocumentException
  37.      * @throws    IOException
  38.      * @throws    SQLException
  39.      */
  40.     public void createPdf(String filename)
  41.         throws IOException, DocumentException, SQLException {
  42.         // step 1
  43.         Document document = new Document();
  44.         // step 2
  45.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  46.         // step 3
  47.         document.open();
  48.         // step 4
  49.         // Create a database connection and statement
  50.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  51.         Statement stm = connection.createStatement();
  52.         ResultSet rs = stm.executeQuery(
  53.             "SELECT DISTINCT mc.country_id, c.country, count(*) AS c "
  54.             + "FROM film_country c, film_movie_country mc WHERE c.id = mc.country_id "
  55.             + "GROUP BY mc.country_id, country ORDER BY c DESC");
  56.         // Create a list
  57.         List list = new List();
  58.         list.setAutoindent(false);
  59.         list.setSymbolIndent(36);
  60.         // Loop over the countries
  61.         while (rs.next()) {
  62.             // Create a list item for a country
  63.             ListItem item = new ListItem(
  64.                String.format("%s: %d movies", rs.getString("country"), rs.getInt("c")));
  65.             item.setListSymbol(new Chunk(rs.getString("country_id")));
  66.             // Create a list for the movies produced in the current country
  67.             List movielist = new List(List.ORDERED, List.ALPHABETICAL);
  68.             movielist.setAlignindent(false);
  69.             for(Movie movie :
  70.                 PojoFactory.getMovies(connection, rs.getString("country_id"))) {
  71.                 ListItem movieitem = new ListItem(movie.getMovieTitle());
  72.                 List directorlist = new List(List.ORDERED);
  73.                 directorlist.setPreSymbol("Director ");
  74.                 directorlist.setPostSymbol(": ");
  75.                 for (Director director : movie.getDirectors()) {
  76.                     directorlist.add(
  77.                         String.format("%s, %s", director.getName(), director.getGivenName()));
  78.                 }
  79.                 movieitem.add(directorlist);
  80.                 movielist.add(movieitem);
  81.             }
  82.             item.add(movielist);
  83.             list.add(item);
  84.         }
  85.         document.add(list);
  86.         // Close the statement and database connection
  87.         stm.close();
  88.         connection.close();
  89.         // step 5
  90.         document.close();
  91.     }
  92.    
  93.     /**
  94.      * Main method.
  95.      *
  96.      * @param    args    no arguments needed
  97.      * @throws DocumentException
  98.      * @throws IOException
  99.      * @throws SQLException
  100.      */
  101.     public static void main(String[] args) throws IOException, DocumentException, SQLException {
  102.         new MovieLists2().createPdf(RESULT);
  103.     }
  104. }
MovieLists3.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.chapter02;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15.  
  16. import com.lowagie.database.DatabaseConnection;
  17. import com.lowagie.database.HsqldbConnection;
  18. import com.lowagie.filmfestival.Director;
  19. import com.lowagie.filmfestival.Movie;
  20. import com.lowagie.filmfestival.PojoFactory;
  21. import com.itextpdf.text.Document;
  22. import com.itextpdf.text.DocumentException;
  23. import com.itextpdf.text.GreekList;
  24. import com.itextpdf.text.List;
  25. import com.itextpdf.text.ListItem;
  26. import com.itextpdf.text.RomanList;
  27. import com.itextpdf.text.ZapfDingbatsNumberList;
  28. import com.itextpdf.text.pdf.PdfWriter;
  29.  
  30. public class MovieLists3 {
  31.  
  32.     /** The resulting PDF file. */
  33.     public static final String RESULT = "results/part1/chapter02/movie_lists_3.pdf";
  34.    
  35.     /**
  36.      * Creates a PDF with information about the movies
  37.      * @param    filename the name of the PDF file that will be created.
  38.      * @throws    DocumentException
  39.      * @throws    IOException
  40.      * @throws    SQLException
  41.      */
  42.     public void createPdf(String filename)
  43.         throws IOException, DocumentException, SQLException {
  44.         // step 1
  45.         Document document = new Document();
  46.         // step 2
  47.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  48.         // step 3
  49.         document.open();
  50.         // step 4
  51.         // Create database connection and statement
  52.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  53.         Statement stm = connection.createStatement();
  54.         ResultSet rs = stm.executeQuery(
  55.             "SELECT DISTINCT mc.country_id, c.country, count(*) AS c "
  56.             + "FROM film_country c, film_movie_country mc WHERE c.id = mc.country_id "
  57.             + "GROUP BY mc.country_id, country ORDER BY c DESC");
  58.         // Create a list for the countries
  59.         List list = new RomanList();
  60.         // Loop over the countries
  61.         while (rs.next()) {
  62.             // Create a list item for the country
  63.             ListItem item = new ListItem(
  64.                String.format("%s: %d movies", rs.getString("country"), rs.getInt("c")));
  65.             // Create a list for the movies
  66.             List movielist = new GreekList();
  67.             movielist.setLowercase(List.LOWERCASE);
  68.             // Loop over the movies
  69.             for(Movie movie :
  70.                 PojoFactory.getMovies(connection, rs.getString("country_id"))) {
  71.                 ListItem movieitem = new ListItem(movie.getMovieTitle());
  72.                 // Create a list for the directors
  73.                 List directorlist = new ZapfDingbatsNumberList(0);
  74.                 // Loop over the directors
  75.                 for (Director director : movie.getDirectors()) {
  76.                     directorlist.add(String.format("%s, %s",
  77.                        director.getName(), director.getGivenName()));
  78.                 }
  79.                 movieitem.add(directorlist);
  80.                 movielist.add(movieitem);
  81.             }
  82.             item.add(movielist);
  83.             list.add(item);
  84.         }
  85.         document.add(list);
  86.         // Close the statement and the database connection
  87.         stm.close();
  88.         connection.close();
  89.         // step 5
  90.         document.close();
  91.     }
  92.    
  93.     /**
  94.      * Main method.
  95.      *
  96.      * @param    args    no arguments needed
  97.      * @throws DocumentException
  98.      * @throws IOException
  99.      * @throws SQLException
  100.      */
  101.     public static void main(String[] args) throws IOException, DocumentException, SQLException {
  102.         new MovieLists3().createPdf(RESULT);
  103.     }
  104. }
MovieLists4.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.chapter02;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15.  
  16. import com.lowagie.database.DatabaseConnection;
  17. import com.lowagie.database.HsqldbConnection;
  18. import com.lowagie.filmfestival.Director;
  19. import com.lowagie.filmfestival.FilmFonts;
  20. import com.lowagie.filmfestival.Movie;
  21. import com.lowagie.filmfestival.PojoFactory;
  22. import com.itextpdf.text.Chunk;
  23. import com.itextpdf.text.Document;
  24. import com.itextpdf.text.DocumentException;
  25. import com.itextpdf.text.List;
  26. import com.itextpdf.text.ListItem;
  27. import com.itextpdf.text.ZapfDingbatsList;
  28. import com.itextpdf.text.pdf.PdfWriter;
  29.  
  30. public class MovieLists4 {
  31.  
  32.     /** The resulting PDF file. */
  33.     public static final String RESULT = "results/part1/chapter02/movie_lists_4.pdf";
  34.    
  35.     /**
  36.      * Creates a PDF with information about the movies
  37.      * @param    filename the name of the PDF file that will be created.
  38.      * @throws    DocumentException
  39.      * @throws    IOException
  40.      * @throws    SQLException
  41.      */
  42.     public void createPdf(String filename)
  43.         throws IOException, DocumentException, SQLException {
  44.         // step 1
  45.         Document document = new Document();
  46.         // step 2
  47.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  48.         // step 3
  49.         document.open();
  50.         // step 4
  51.         // Create the database connection and statement
  52.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  53.         Statement stm = connection.createStatement();
  54.         ResultSet rs = stm.executeQuery(
  55.             "SELECT DISTINCT mc.country_id, c.country, count(*) AS c "
  56.             + "FROM film_country c, film_movie_country mc "
  57.             + "WHERE c.id = mc.country_id "
  58.             + "GROUP BY mc.country_id, country ORDER BY c DESC");
  59.         // Create a list for the countries
  60.         List list = new List(List.ORDERED);
  61.         list.setFirst(9);
  62.         // Loop over the countries
  63.         while (rs.next()) {
  64.             // Create a list item for a country
  65.             ListItem item = new ListItem(String.format("%s: %d movies",
  66.                 rs.getString("country"), rs.getInt("c")));
  67.             // Create a list for the movies
  68.             List movielist = new List();
  69.             movielist.setListSymbol(new Chunk("Movie: ", FilmFonts.BOLD));
  70.             for(Movie movie :
  71.                 PojoFactory.getMovies(connection, rs.getString("country_id"))) {
  72.                 ListItem movieitem = new ListItem(movie.getMovieTitle());
  73.                 // Create a list for the directors
  74.                 List directorlist = new ZapfDingbatsList(42);
  75.                 for (Director director : movie.getDirectors()) {
  76.                     directorlist.add(String.format("%s, %s",
  77.                         director.getName(), director.getGivenName()));
  78.                 }
  79.                 movieitem.add(directorlist);
  80.                 movielist.add(movieitem);
  81.             }
  82.             item.add(movielist);
  83.             list.add(item);
  84.         }
  85.         document.add(list);
  86.         // Close the statement and database connection
  87.         stm.close();
  88.         connection.close();
  89.         // step 5
  90.         document.close();
  91.     }
  92.    
  93.     /**
  94.      * Main method.
  95.      *
  96.      * @param    args    no arguments needed
  97.      * @throws DocumentException
  98.      * @throws IOException
  99.      * @throws SQLException
  100.      */
  101.     public static void main(String[] args) throws IOException, DocumentException, SQLException {
  102.         new MovieLists4().createPdf(RESULT);
  103.     }
  104. }
PositionedArrow.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.chapter02;
  9.  
  10. import java.io.IOException;
  11.  
  12. import com.itextpdf.text.DocumentException;
  13. import com.itextpdf.text.Element;
  14. import com.itextpdf.text.pdf.BaseFont;
  15. import com.itextpdf.text.pdf.PdfContentByte;
  16. import com.itextpdf.text.pdf.draw.VerticalPositionMark;
  17.  
  18. /**
  19.  * Subclass of VerticalPositionMark that draws an arrow in the left
  20.  * or right margin.
  21.  */
  22. public class PositionedArrow extends VerticalPositionMark {
  23.  
  24.     /** Indicates if the arrow needs to be drawn to the left. */
  25.     protected boolean left;
  26.    
  27.     /** Thee font that will be used to draw the arrow. */
  28.     protected BaseFont zapfdingbats;
  29.    
  30.     /** An arrow pointing to the right will be added on the left. */
  31.     public static final PositionedArrow LEFT = new PositionedArrow(true);
  32.     /** An arrow pointing to the left will be added on the right. */
  33.     public static final PositionedArrow RIGHT = new PositionedArrow(false);
  34.    
  35.     /**
  36.      * Constructs a positioned Arrow mark.
  37.      * @param    left    if true, an arrow will be drawn on the left;
  38.      * otherwise, it will be drawn on the right.
  39.      * @throws IOException
  40.      * @throws DocumentException
  41.      */
  42.     public PositionedArrow(boolean left) {
  43.         this.left = left;
  44.         try {
  45.             zapfdingbats = BaseFont.createFont(
  46.                 BaseFont.ZAPFDINGBATS, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
  47.         }
  48.         catch(DocumentException de) {
  49.             zapfdingbats = null;
  50.         }
  51.         catch(IOException ioe) {
  52.             zapfdingbats = null;
  53.         }
  54.     }
  55.    
  56.     /**
  57.      * Draws a character representing an arrow at the current position.
  58.      * @see com.itextpdf.text.pdf.draw.VerticalPositionMark#draw(
  59.      *      com.itextpdf.text.pdf.PdfContentByte, float, float, float, float, float)
  60.      */
  61.     public void draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) {
  62.         canvas.beginText();
  63.         canvas.setFontAndSize(zapfdingbats, 12);
  64.         if (left) {
  65.             canvas.showTextAligned(Element.ALIGN_CENTER,
  66.                 String.valueOf((char)220), llx - 10, y, 0);
  67.         }
  68.         else {
  69.             canvas.showTextAligned(Element.ALIGN_CENTER,
  70.                 String.valueOf((char)220), urx + 10, y + 8, 180);
  71.         }
  72.         canvas.endText();
  73.     }
  74. }
StarSeparator.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.chapter02;
  9.  
  10. import java.io.IOException;
  11.  
  12. import com.itextpdf.text.DocumentException;
  13. import com.itextpdf.text.Element;
  14. import com.itextpdf.text.pdf.BaseFont;
  15. import com.itextpdf.text.pdf.PdfContentByte;
  16. import com.itextpdf.text.pdf.draw.DrawInterface;
  17.  
  18. public class StarSeparator implements DrawInterface {
  19.    
  20.     /** The font that will be used to draw the arrow. */
  21.     protected BaseFont bf;
  22.    
  23.     public static final StarSeparator LINE = new StarSeparator();
  24.    
  25.     /**
  26.      * Constructs a positioned Arrow mark.
  27.      * @param    left    if true, an arrow will be drawn on the left;
  28.      * otherwise, it will be drawn on the right.
  29.      * @throws IOException
  30.      * @throws DocumentException
  31.      */
  32.     public StarSeparator() {
  33.         try {
  34.             bf = BaseFont.createFont();
  35.         } catch (DocumentException e) {
  36.             bf = null;
  37.         } catch (IOException e) {
  38.             bf = null;
  39.         }
  40.     }
  41.    
  42.     /**
  43.      * Draws three stars to separate two paragraphs.
  44.      * @see com.itextpdf.text.pdf.draw.DrawInterface#draw(
  45.      * com.itextpdf.text.pdf.PdfContentByte, float, float, float, float, float)
  46.      */
  47.     public void draw(PdfContentByte canvas,
  48.         float llx, float lly, float urx, float ury, float y) {
  49.         float middle = (llx + urx) / 2;
  50.         canvas.beginText();
  51.         canvas.setFontAndSize(bf, 10);
  52.         canvas.showTextAligned(Element.ALIGN_CENTER, "*", middle, y, 0);
  53.         canvas.showTextAligned(Element.ALIGN_CENTER, "*  *", middle, y -10, 0);
  54.         canvas.endText();
  55.     }
  56.  
  57. }
DirectorOverview1.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.chapter02;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15. import java.util.TreeSet;
  16.  
  17. import com.lowagie.database.DatabaseConnection;
  18. import com.lowagie.database.HsqldbConnection;
  19. import com.lowagie.filmfestival.Director;
  20. import com.lowagie.filmfestival.Movie;
  21. import com.lowagie.filmfestival.MovieComparator;
  22. import com.lowagie.filmfestival.PojoFactory;
  23. import com.lowagie.filmfestival.PojoToElementFactory;
  24. import com.itextpdf.text.Chunk;
  25. import com.itextpdf.text.Document;
  26. import com.itextpdf.text.DocumentException;
  27. import com.itextpdf.text.Element;
  28. import com.itextpdf.text.Paragraph;
  29. import com.itextpdf.text.pdf.PdfWriter;
  30. import com.itextpdf.text.pdf.draw.LineSeparator;
  31.  
  32. public class DirectorOverview1 {
  33.    
  34.     /** The resulting PDF file. */
  35.     public static final String RESULT
  36.         = "results/part1/chapter02/director_overview_1.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.         // step 1
  48.         Document document = new Document();
  49.         // step 2
  50.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  51.         // step 3
  52.         document.open();
  53.         // step 4
  54.         // database connection and statement
  55.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  56.         Statement stm = connection.createStatement();
  57.         ResultSet rs = stm.executeQuery(
  58.             "SELECT DISTINCT d.id, d.name, d.given_name, count(*) AS c "
  59.             + "FROM film_director d, film_movie_director md "
  60.             + "WHERE d.id = md.director_id "
  61.             + "GROUP BY d.id, d.name, d.given_name ORDER BY name");
  62.         Director director;
  63.         // creating separators
  64.         LineSeparator line
  65.             = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);
  66.         Paragraph stars = new Paragraph(20);
  67.         stars.add(new Chunk(StarSeparator.LINE));
  68.         stars.setSpacingAfter(30);
  69.         // looping over the directors
  70.         while (rs.next()) {
  71.             // get the director object and use it in a Paragraph
  72.             director = PojoFactory.getDirector(rs);
  73.             Paragraph p = new Paragraph(
  74.                 PojoToElementFactory.getDirectorPhrase(director));
  75.             // if there are more than 2 movies for this director
  76.             // an arrow is added to the left
  77.             if (rs.getInt("c") > 2)
  78.                 p.add(PositionedArrow.LEFT);
  79.             p.add(line);
  80.             // add the paragraph with the arrow to the document
  81.             document.add(p);
  82.            
  83.             // Get the movies of the directory, ordered by year
  84.             TreeSet movies = new TreeSet(
  85.                 new MovieComparator(MovieComparator.BY_YEAR));
  86.             movies.addAll(PojoFactory.getMovies(connection, rs.getInt("id")));
  87.             // loop over the movies
  88.             for (Movie movie : movies) {
  89.                 p = new Paragraph(movie.getMovieTitle());
  90.                 p.add(": ");
  91.                 p.add(new Chunk(String.valueOf(movie.getYear())));
  92.                 if (movie.getYear() > 1999)
  93.                     p.add(PositionedArrow.RIGHT);
  94.                 document.add(p);
  95.             }
  96.             // add a star separator after the director info is added
  97.             document.add(stars);
  98.         }
  99.         // step 5
  100.         document.close();
  101.         connection.close();
  102.     }
  103.    
  104.     /**
  105.      * Main method.
  106.      *
  107.      * @param    args    no arguments needed
  108.      * @throws DocumentException
  109.      * @throws IOException
  110.      * @throws SQLException
  111.      */
  112.     public static void main(String[] args)
  113.         throws IOException, DocumentException, SQLException {
  114.         new DirectorOverview1().createPdf(RESULT);
  115.     }
  116. }
DirectorOverview2.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.chapter02;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15. import java.util.TreeSet;
  16.  
  17. import com.lowagie.database.DatabaseConnection;
  18. import com.lowagie.database.HsqldbConnection;
  19. import com.lowagie.filmfestival.Director;
  20. import com.lowagie.filmfestival.Movie;
  21. import com.lowagie.filmfestival.MovieComparator;
  22. import com.lowagie.filmfestival.PojoFactory;
  23. import com.lowagie.filmfestival.PojoToElementFactory;
  24. import com.itextpdf.text.Chunk;
  25. import com.itextpdf.text.Document;
  26. import com.itextpdf.text.DocumentException;
  27. import com.itextpdf.text.List;
  28. import com.itextpdf.text.ListItem;
  29. import com.itextpdf.text.Paragraph;
  30. import com.itextpdf.text.pdf.PdfWriter;
  31. import com.itextpdf.text.pdf.draw.DottedLineSeparator;
  32. import com.itextpdf.text.pdf.draw.VerticalPositionMark;
  33.  
  34. public class DirectorOverview2 {
  35.  
  36.     /** The resulting PDF file. */
  37.     public static final String RESULT
  38.         = "results/part1/chapter02/director_overview_2.pdf";
  39.  
  40.     /**
  41.      * Creates a PDF with information about the movies
  42.      * @param    filename the name of the PDF file that will be created.
  43.      * @throws    DocumentException
  44.      * @throws    IOException
  45.      * @throws    SQLException
  46.      */
  47.     public void createPdf(String filename)
  48.         throws IOException, DocumentException, SQLException {
  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.         // create database connection and statement
  57.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  58.         Statement stm = connection.createStatement();
  59.         ResultSet rs = stm.executeQuery(
  60.             "SELECT DISTINCT d.id, d.name, d.given_name, count(*) AS c "
  61.             + "FROM film_director d, film_movie_director md WHERE d.id = md.director_id "
  62.             + "GROUP BY d.id, d.name, d.given_name ORDER BY c DESC");
  63.         Director director;
  64.         // loop over the directors
  65.         while (rs.next()) {
  66.             // create a paragraph for the director
  67.             director = PojoFactory.getDirector(rs);
  68.             Paragraph p = new Paragraph(PojoToElementFactory.getDirectorPhrase(director));
  69.             // add a dotted line separator
  70.             p.add(new Chunk(new DottedLineSeparator()));
  71.             // adds the number of movies of this director
  72.             p.add(String.format("movies: %d", rs.getInt("c")));
  73.             document.add(p);
  74.             // Creates a list
  75.             List list = new List(List.ORDERED);
  76.             list.setIndentationLeft(36);
  77.             list.setIndentationRight(36);
  78.             // Gets the movies of the current director
  79.             TreeSet movies =
  80.                 new TreeSet(new MovieComparator(MovieComparator.BY_YEAR));
  81.             movies.addAll(PojoFactory.getMovies(connection, rs.getInt("id")));
  82.             ListItem movieitem;
  83.             // loops over the movies
  84.             for (Movie movie : movies) {
  85.                 // creates a list item with a movie title
  86.                 movieitem = new ListItem(movie.getMovieTitle());
  87.                 // adds a vertical position mark as a separator
  88.                 movieitem.add(new Chunk(new VerticalPositionMark()));
  89.                 // adds the year the movie was produced
  90.                 movieitem.add(new Chunk(String.valueOf(movie.getYear())));
  91.                 // add an arrow to the right if the movie dates from 2000 or later
  92.                 if (movie.getYear() > 1999) {
  93.                     movieitem.add(PositionedArrow.RIGHT);
  94.                 }
  95.                 // add the list item to the list
  96.                 list.add(movieitem);
  97.             }
  98.             // add the list to the document
  99.             document.add(list);
  100.         }
  101.         // step 5
  102.         document.close();
  103.         connection.close();
  104.     }
  105.    
  106.     /**
  107.      * Main method.
  108.      *
  109.      * @param    args    no arguments needed
  110.      * @throws DocumentException
  111.      * @throws IOException
  112.      * @throws SQLException
  113.      */
  114.     public static void main(String[] args)
  115.         throws IOException, DocumentException, SQLException {
  116.         new DirectorOverview2().createPdf(RESULT);
  117.     }
  118. }
DirectorOverview3.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.chapter02;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15. import java.util.TreeSet;
  16.  
  17. import com.lowagie.database.DatabaseConnection;
  18. import com.lowagie.database.HsqldbConnection;
  19. import com.lowagie.filmfestival.Director;
  20. import com.lowagie.filmfestival.Movie;
  21. import com.lowagie.filmfestival.MovieComparator;
  22. import com.lowagie.filmfestival.PojoFactory;
  23. import com.lowagie.filmfestival.PojoToElementFactory;
  24. import com.itextpdf.text.Chunk;
  25. import com.itextpdf.text.Document;
  26. import com.itextpdf.text.DocumentException;
  27. import com.itextpdf.text.Element;
  28. import com.itextpdf.text.Paragraph;
  29. import com.itextpdf.text.pdf.PdfWriter;
  30. import com.itextpdf.text.BaseColor;
  31. import com.itextpdf.text.pdf.draw.DottedLineSeparator;
  32. import com.itextpdf.text.pdf.draw.LineSeparator;
  33. import com.itextpdf.text.pdf.draw.VerticalPositionMark;
  34.  
  35. public class DirectorOverview3 {
  36.  
  37.     /** The resulting PDF file. */
  38.     public static final String RESULT = "results/part1/chapter02/director_overview_3.pdf";
  39.  
  40.     /**
  41.      * Creates a PDF with information about the movies
  42.      * @param    filename the name of the PDF file that will be created.
  43.      * @throws    DocumentException
  44.      * @throws    IOException
  45.      * @throws    SQLException
  46.      */
  47.     public void createPdf(String filename)
  48.         throws IOException, DocumentException, SQLException {
  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.         // creates the database connection and statement
  57.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  58.         Statement stm = connection.createStatement();
  59.         ResultSet rs = stm.executeQuery(
  60.             "SELECT DISTINCT d.id, d.name, d.given_name, count(*) AS c "
  61.             + "FROM film_director d, film_movie_director md "
  62.             + "WHERE d.id = md.director_id "
  63.             + "GROUP BY d.id, d.name, d.given_name ORDER BY c DESC");
  64.         Director director;
  65.         // creates line separators
  66.         Chunk CONNECT = new Chunk(
  67.             new LineSeparator(0.5f, 95, BaseColor.BLUE, Element.ALIGN_CENTER, 3.5f));
  68.         LineSeparator UNDERLINE =
  69.             new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);
  70.         // creates tabs
  71.         Chunk tab1 = new Chunk(new VerticalPositionMark(), 200, true);
  72.         Chunk tab2 = new Chunk(new VerticalPositionMark(), 350, true);
  73.         Chunk tab3 = new Chunk(new DottedLineSeparator(), 450, true);
  74.         // loops over the directors
  75.         while (rs.next()) {
  76.             // creates a paragraph with the director name
  77.             director = PojoFactory.getDirector(rs);
  78.             Paragraph p = new Paragraph(PojoToElementFactory.getDirectorPhrase(director));
  79.             // adds a separator
  80.             p.add(CONNECT);
  81.             // adds more info about the director
  82.             p.add(String.format("movies: %d", rs.getInt("c")));
  83.             // adds a separator
  84.             p.add(UNDERLINE);
  85.             // adds the paragraph to the document
  86.             document.add(p);
  87.             // gets all the movies of the current director
  88.             TreeSet movies
  89.                 = new TreeSet(new MovieComparator(MovieComparator.BY_YEAR));
  90.             movies.addAll(PojoFactory.getMovies(connection, rs.getInt("id")));
  91.             // loop over the movies
  92.             for (Movie movie : movies) {
  93.                 // create a Paragraph with the movie title
  94.                 p = new Paragraph(movie.getMovieTitle());
  95.                 // insert a tab
  96.                 p.add(new Chunk(tab1));
  97.                 // add the origina title
  98.                 if (movie.getOriginalTitle() != null)
  99.                     p.add(new Chunk(movie.getOriginalTitle()));
  100.                 // insert a tab
  101.                 p.add(new Chunk(tab2));
  102.                 // add the run length of the movie
  103.                 p.add(new Chunk(String.format("%d minutes", movie.getDuration())));
  104.                 // insert a tab
  105.                 p.add(new Chunk(tab3));
  106.                 // add the production year of the movie
  107.                 p.add(new Chunk(String.valueOf(movie.getYear())));
  108.                 // add the paragraph to the document
  109.                 document.add(p);
  110.             }
  111.             document.add(Chunk.NEWLINE);
  112.         }
  113.         // step 5
  114.         document.close();
  115.         connection.close();
  116.     }
  117.    
  118.     /**
  119.      * Main method.
  120.      *
  121.      * @param    args    no arguments needed
  122.      * @throws DocumentException
  123.      * @throws IOException
  124.      * @throws SQLException
  125.      */
  126.     public static void main(String[] args)
  127.         throws IOException, DocumentException, SQLException {
  128.         new DirectorOverview3().createPdf(RESULT);
  129.     }
  130. }
MovieLinks1.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.chapter02;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15.  
  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.itextpdf.text.Anchor;
  22. import com.itextpdf.text.Chunk;
  23. import com.itextpdf.text.Document;
  24. import com.itextpdf.text.DocumentException;
  25. import com.itextpdf.text.Paragraph;
  26. import com.itextpdf.text.pdf.PdfWriter;
  27.  
  28. public class MovieLinks1 {
  29.  
  30.     /** The resulting PDF file. */
  31.     public static final String RESULT = "results/part1/chapter02/movie_links_1.pdf";
  32.    
  33.     /**
  34.      * Main method.
  35.      *
  36.      * @param    args    no arguments needed
  37.      * @throws DocumentException
  38.      * @throws IOException
  39.      * @throws SQLException
  40.      */
  41.     public static void main(String[] args)
  42.         throws IOException, DocumentException, SQLException {
  43.         new MovieLinks1().createPdf(RESULT);
  44.     }
  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 IOException, DocumentException, SQLException {
  55.         // step 1
  56.         Document document = new Document();
  57.         // step 2
  58.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  59.         // step 3
  60.         document.open();
  61.         // step 4
  62.         // Create database connection and statement
  63.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  64.         Statement stm = connection.createStatement();
  65.         ResultSet rs = stm.executeQuery(
  66.             "SELECT DISTINCT mc.country_id, c.country, count(*) AS c "
  67.             + "FROM film_country c, film_movie_country mc "
  68.             + "WHERE c.id = mc.country_id "
  69.             + "GROUP BY mc.country_id, country ORDER BY c DESC");
  70.         Anchor imdb;
  71.         // loop over the countries
  72.         while (rs.next()) {
  73.             Paragraph country = new Paragraph();
  74.             // the name of the country will be a destination
  75.             Anchor dest = new Anchor(rs.getString("country"), FilmFonts.BOLD);
  76.             dest.setName(rs.getString("country_id"));
  77.             country.add(dest);
  78.             country.add(String.format(": %d movies", rs.getInt("c")));
  79.             document.add(country);
  80.             // loop over the movies
  81.             for(Movie movie :
  82.                 PojoFactory.getMovies(connection, rs.getString("country_id"))) {
  83.                 // the movie title will be an external link
  84.                 imdb = new Anchor(movie.getMovieTitle());
  85.                 imdb.setReference(
  86.                     String.format("http://www.imdb.com/title/tt%s/", movie.getImdb()));
  87.                 document.add(imdb);
  88.                 document.add(Chunk.NEWLINE);
  89.             }
  90.             document.newPage();
  91.         }
  92.         // Create an internal link to the first page
  93.         Anchor toUS = new Anchor("Go back to the first page.");
  94.         toUS.setReference("#US");
  95.         document.add(toUS);
  96.        
  97.         document.close();
  98.         connection.close();
  99.     }
  100. }
MovieLinks2.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.chapter02;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.net.URL;
  13. import java.sql.ResultSet;
  14. import java.sql.SQLException;
  15. import java.sql.Statement;
  16.  
  17. import com.lowagie.database.DatabaseConnection;
  18. import com.lowagie.database.HsqldbConnection;
  19. import com.lowagie.filmfestival.FilmFonts;
  20. import com.itextpdf.text.Chunk;
  21. import com.itextpdf.text.Document;
  22. import com.itextpdf.text.DocumentException;
  23. import com.itextpdf.text.Paragraph;
  24. import com.itextpdf.text.pdf.PdfWriter;
  25.  
  26. public class MovieLinks2 {
  27.  
  28.     /** The resulting PDF file. */
  29.     public static final String RESULT = "results/part1/chapter02/movie_links_2.pdf";
  30.    
  31.     /**
  32.      * Main method.
  33.      *
  34.      * @param    args    no arguments needed
  35.      * @throws DocumentException
  36.      * @throws IOException
  37.      * @throws SQLException
  38.      */
  39.     public static void main(String[] args)
  40.         throws IOException, DocumentException, SQLException {
  41.         new MovieLinks1().createPdf(MovieLinks1.RESULT);
  42.         new MovieLinks2().createPdf(RESULT);
  43.     }
  44.  
  45.     /**
  46.      * Creates a PDF document.
  47.      * @param filename the path to the new PDF document
  48.      * @throws    DocumentException
  49.      * @throws    IOException
  50.      * @throws    SQLException
  51.      */
  52.     public void createPdf(String filename)
  53.         throws IOException, DocumentException, SQLException {
  54.         // step 1
  55.         Document document = new Document();
  56.         // step 2
  57.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  58.         // step 3
  59.         document.open();
  60.         // step 4
  61.         // Create a local destination at the top of the page
  62.         Paragraph p = new Paragraph();
  63.         Chunk top = new Chunk("Country List", FilmFonts.BOLD);
  64.         top.setLocalDestination("top");
  65.         p.add(top);
  66.         document.add(p);
  67.         // create an external link
  68.         Chunk imdb = new Chunk("Internet Movie Database", FilmFonts.ITALIC);
  69.         imdb.setAnchor(new URL("http://www.imdb.com/"));
  70.         p = new Paragraph("Click on a country, and you'll get a list of movies, "
  71.             + "containing links to the ");
  72.         p.add(imdb);
  73.         p.add(".");
  74.         document.add(p);
  75.         // Create a remote goto
  76.         p = new Paragraph("This list can be found in a ");
  77.         Chunk page1 = new Chunk("separate document");
  78.         page1.setRemoteGoto("movie_links_1.pdf", 1);
  79.         p.add(page1);
  80.         p.add(".");
  81.         document.add(p);
  82.         document.add(Chunk.NEWLINE);
  83.         // Create a database connection and statement
  84.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  85.         Statement stm = connection.createStatement();
  86.         ResultSet rs = stm.executeQuery(
  87.             "SELECT DISTINCT mc.country_id, c.country, count(*) AS c "
  88.             + "FROM film_country c, film_movie_country mc "
  89.             + "WHERE c.id = mc.country_id "
  90.             + "GROUP BY mc.country_id, country ORDER BY c DESC");
  91.         // loop over the results
  92.         while (rs.next()) {
  93.             // add country with remote goto
  94.             Paragraph country = new Paragraph(rs.getString("country"));
  95.             country.add(": ");
  96.             Chunk link = new Chunk(String.format("%d movies", rs.getInt("c")));
  97.             link.setRemoteGoto("movie_links_1.pdf", rs.getString("country_id"));
  98.             country.add(link);
  99.             document.add(country);
  100.         }
  101.         document.add(Chunk.NEWLINE);
  102.         // Create local goto to top
  103.         p = new Paragraph("Go to ");
  104.         top = new Chunk("top");
  105.         top.setLocalGoto("top");
  106.         p.add(top);
  107.         p.add(".");
  108.         document.add(p);
  109.         // step 5
  110.         document.close();
  111.         connection.close();
  112.     }
  113. }
MovieHistory.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.chapter02;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13. import java.util.Set;
  14. import java.util.TreeSet;
  15.  
  16. import com.lowagie.database.DatabaseConnection;
  17. import com.lowagie.database.HsqldbConnection;
  18. import com.lowagie.filmfestival.Movie;
  19. import com.lowagie.filmfestival.MovieComparator;
  20. import com.lowagie.filmfestival.PojoFactory;
  21. import com.lowagie.filmfestival.PojoToElementFactory;
  22. import com.itextpdf.text.Chapter;
  23. import com.itextpdf.text.Document;
  24. import com.itextpdf.text.DocumentException;
  25. import com.itextpdf.text.Font;
  26. import com.itextpdf.text.Paragraph;
  27. import com.itextpdf.text.Section;
  28. import com.itextpdf.text.Font.FontFamily;
  29. import com.itextpdf.text.pdf.PdfWriter;
  30.  
  31. public class MovieHistory {
  32.  
  33.     /** The resulting PDF file. */
  34.     public static final String RESULT = "results/part1/chapter02/movie_history.pdf";
  35.    
  36.     /** The different epochs. */
  37.     public static final String[] EPOCH =
  38.         { "Forties", "Fifties", "Sixties", "Seventies", "Eighties",
  39.           "Nineties", "Twenty-first Century" };
  40.     /** The fonts for the title. */
  41.     public static final Font[] FONT = new Font[4];
  42.     static {
  43.         FONT[0] = new Font(FontFamily.HELVETICA, 24);
  44.         FONT[1] = new Font(FontFamily.HELVETICA, 18);
  45.         FONT[2] = new Font(FontFamily.HELVETICA, 14);
  46.         FONT[3] = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
  47.     }
  48.    
  49.     /**
  50.      * Main method.
  51.      *
  52.      * @param    args    no arguments needed
  53.      * @throws DocumentException
  54.      * @throws IOException
  55.      * @throws SQLException
  56.      */
  57.     public static void main(String[] args)
  58.         throws IOException, DocumentException, SQLException {
  59.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  60.         // step 1
  61.         Document document = new Document();
  62.         // step 2
  63.         PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  64.         // step 3
  65.         document.open();
  66.         // step 4
  67.         Set movies =
  68.             new TreeSet(new MovieComparator(MovieComparator.BY_YEAR));
  69.         movies.addAll(PojoFactory.getMovies(connection));
  70.         int epoch = -1;
  71.         int currentYear = 0;
  72.         Paragraph title = null;
  73.         Chapter chapter = null;
  74.         Section section = null;
  75.         Section subsection = null;
  76.         // loop over the movies
  77.         for (Movie movie : movies) {
  78.             // add the chapter if we're in a new epoch
  79.             if (epoch < (movie.getYear() - 1940) / 10) {
  80.                 epoch = (movie.getYear() - 1940) / 10;
  81.                 if (chapter != null) {
  82.                     document.add(chapter);
  83.                 }
  84.                 title = new Paragraph(EPOCH[epoch], FONT[0]);
  85.                 chapter = new Chapter(title, epoch + 1);
  86.             }
  87.             // switch to a new year
  88.             if (currentYear < movie.getYear()) {
  89.                 currentYear = movie.getYear();
  90.                 title = new Paragraph(
  91.                     String.format("The year %d", movie.getYear()), FONT[1]);
  92.                 section = chapter.addSection(title);
  93.                 section.setBookmarkTitle(String.valueOf(movie.getYear()));
  94.                 section.setIndentation(30);
  95.                 section.setBookmarkOpen(false);
  96.                 section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
  97.                 section.add(new Paragraph(
  98.                     String.format("Movies from the year %d:", movie.getYear())));
  99.             }
  100.             title = new Paragraph(movie.getMovieTitle(), FONT[2]);
  101.             subsection = section.addSection(title);
  102.             subsection.setIndentationLeft(20);
  103.             subsection.setNumberDepth(1);
  104.             subsection.add(new Paragraph("Duration: " + movie.getDuration(), FONT[3]));
  105.             subsection.add(new Paragraph("Director(s):", FONT[3]));
  106.             subsection.add(PojoToElementFactory.getDirectorList(movie));
  107.             subsection.add(new Paragraph("Countries:", FONT[3]));
  108.             subsection.add(PojoToElementFactory.getCountryList(movie));
  109.         }
  110.         document.add(chapter);
  111.         // step 5
  112.         document.close();
  113.         connection.close();
  114.     }
  115. }
MoviePosters1.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.chapter02;
  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.PojoFactory;
  18. import com.lowagie.filmfestival.Movie;
  19. import com.itextpdf.text.Document;
  20. import com.itextpdf.text.DocumentException;
  21. import com.itextpdf.text.Image;
  22. import com.itextpdf.text.Paragraph;
  23. import com.itextpdf.text.Rectangle;
  24. import com.itextpdf.text.pdf.PdfWriter;
  25. import com.itextpdf.text.BaseColor;
  26.  
  27. public class MoviePosters1 {
  28.     /** Path to the resulting PDF */
  29.     public static final String RESULT
  30.         = "results/part1/chapter02/movie_posters_1.pdf";
  31.     /** Path to the resources. */
  32.     public static final String RESOURCE = "resources/posters/%s.jpg";
  33.    
  34.     /**
  35.      * Main method.
  36.      *
  37.      * @param    args    no arguments needed
  38.      * @throws DocumentException
  39.      * @throws IOException
  40.      * @throws SQLException
  41.      */
  42.     public static void main(String[] args)
  43.         throws IOException, DocumentException, SQLException {
  44.         new MoviePosters1().createPdf(RESULT);
  45.     }
  46.    
  47.     /**
  48.      * Creates a PDF with information about the movies
  49.      * @param    filename the name of the PDF file that will be created.
  50.      * @throws    DocumentException
  51.      * @throws    IOException
  52.      * @throws    SQLException
  53.      */
  54.     public void createPdf(String filename)
  55.         throws IOException, DocumentException, SQLException {
  56.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  57.        
  58.         // step 1
  59.         Document document = new Document();
  60.         // step 2
  61.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  62.         // step 3
  63.         document.open();
  64.         Rectangle rect = new Rectangle(0, 806, 36, 842);
  65.         rect.setBackgroundColor(BaseColor.RED);
  66.         document.add(rect);
  67.         // step 4
  68.         List movies = PojoFactory.getMovies(connection);
  69.         for (Movie movie : movies) {
  70.             document.add(new Paragraph(movie.getMovieTitle()));
  71.             // Add an image
  72.             document.add(
  73.                 Image.getInstance(String.format(RESOURCE, movie.getImdb())));
  74.         }
  75.         // step 5
  76.         document.close();
  77.        
  78.         connection.close();
  79.     }
  80. }
MoviePosters2.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.chapter02;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13. import java.util.List;
  14.  
  15. import com.lowagie.database.DatabaseConnection;
  16. import com.lowagie.database.HsqldbConnection;
  17. import com.lowagie.filmfestival.Movie;
  18. import com.lowagie.filmfestival.PojoFactory;
  19. import com.itextpdf.text.Document;
  20. import com.itextpdf.text.DocumentException;
  21. import com.itextpdf.text.Image;
  22. import com.itextpdf.text.Paragraph;
  23. import com.itextpdf.text.pdf.PdfWriter;
  24.  
  25. public class MoviePosters2 {
  26.     /** Path to the resulting PDF */
  27.     public static final String RESULT
  28.         = "results/part1/chapter02/movie_posters_2.pdf";
  29.     /** Path to the resources. */
  30.     public static final String RESOURCE = "resources/posters/%s.jpg";
  31.    
  32.     /**
  33.      * Main method.
  34.      *
  35.      * @param    args    no arguments needed
  36.      * @throws DocumentException
  37.      * @throws IOException
  38.      * @throws SQLException
  39.      */
  40.     public static void main(String[] args)
  41.         throws IOException, DocumentException, SQLException {
  42.         new MoviePosters2().createPdf(RESULT);
  43.     }
  44.    
  45.     /**
  46.      * Creates a PDF with information about the movies
  47.      * @param    filename the name of the PDF file that will be created.
  48.      * @throws    DocumentException
  49.      * @throws    IOException
  50.      * @throws    SQLException
  51.      */
  52.     public void createPdf(String filename)
  53.         throws IOException, DocumentException, SQLException {
  54.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  55.        
  56.         // step 1
  57.         Document document = new Document();
  58.         // step 2
  59.         PdfWriter.getInstance(document,
  60.                 new FileOutputStream(filename)).setStrictImageSequence(true);
  61.         // step 3
  62.         document.open();
  63.         // step 4
  64.         List movies = PojoFactory.getMovies(connection);
  65.         for (Movie movie : movies) {
  66.             document.add(new Paragraph(movie.getMovieTitle()));
  67.             // Add an image
  68.             document.add(
  69.                 Image.getInstance(String.format(RESOURCE, movie.getImdb())));
  70.         }
  71.         // step 5
  72.         document.close();
  73.        
  74.         connection.close();
  75.     }
  76. }
MoviePosters3.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.chapter02;
  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.FilmFonts;
  18. import com.lowagie.filmfestival.Movie;
  19. import com.lowagie.filmfestival.PojoFactory;
  20. import com.lowagie.filmfestival.PojoToElementFactory;
  21. import com.itextpdf.text.Chunk;
  22. import com.itextpdf.text.Document;
  23. import com.itextpdf.text.DocumentException;
  24. import com.itextpdf.text.Image;
  25. import com.itextpdf.text.Paragraph;
  26. import com.itextpdf.text.pdf.PdfWriter;
  27. import com.itextpdf.text.BaseColor;
  28.  
  29. public class MoviePosters3 {
  30.     /** Path to the resulting PDF */
  31.     public static final String RESULT
  32.         = "results/part1/chapter02/movie_posters_3.pdf";
  33.     /** Path to the resources. */
  34.     public static final String RESOURCE = "resources/posters/%s.jpg";
  35.    
  36.     /**
  37.      * Main method.
  38.      *
  39.      * @param    args    no arguments needed
  40.      * @throws DocumentException
  41.      * @throws IOException
  42.      * @throws SQLException
  43.      */
  44.     public static void main(String[] args)
  45.         throws IOException, DocumentException, SQLException {
  46.         new MoviePosters3().createPdf(RESULT);
  47.     }
  48.    
  49.     /**
  50.      * Creates a PDF with information about the movies
  51.      * @param    filename the name of the PDF file that will be created.
  52.      * @throws    DocumentException
  53.      * @throws    IOException
  54.      * @throws    SQLException
  55.      */
  56.     public void createPdf(String filename)
  57.         throws IOException, DocumentException, SQLException {
  58.         // Create a database connection
  59.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  60.         // step 1
  61.         Document document = new Document();
  62.         // step 2
  63.         PdfWriter writer =
  64.             PdfWriter.getInstance(document, new FileOutputStream(filename));
  65.         writer.setStrictImageSequence(true);
  66.         writer.setInitialLeading(18);
  67.         // step 3
  68.         document.open();
  69.         // step 4
  70.         List movies = PojoFactory.getMovies(connection);
  71.         for (Movie movie : movies) {
  72.             // Create an image
  73.             Image img = Image.getInstance(String.format(RESOURCE, movie.getImdb()));
  74.             img.setAlignment(Image.LEFT | Image.TEXTWRAP);
  75.             img.setBorder(Image.BOX);
  76.             img.setBorderWidth(10);
  77.             img.setBorderColor(BaseColor.WHITE);
  78.             img.scaleToFit(1000, 72);
  79.             document.add(img);
  80.             // Create text elements
  81.             document.add(new Paragraph(movie.getMovieTitle(), FilmFonts.BOLD));
  82.             document.add(PojoToElementFactory.getCountryList(movie));
  83.             document.add(new Paragraph(String.format("Year: %d", movie.getYear())));
  84.             document.add(new Paragraph(
  85.                 String.format("Duration: %d minutes", movie.getDuration())));
  86.             document.add(new Paragraph("Directors:"));
  87.             document.add(PojoToElementFactory.getDirectorList(movie));
  88.             document.add(Chunk.NEWLINE);
  89.         }
  90.         // step 5
  91.         document.close();
  92.         // Close the database connection
  93.         connection.close();
  94.     }
  95. }
RiverPhoenix.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.chapter02;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.lowagie.filmfestival.FilmFonts;
  14. import com.itextpdf.text.Chunk;
  15. import com.itextpdf.text.Document;
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.Image;
  18. import com.itextpdf.text.Paragraph;
  19. import com.itextpdf.text.pdf.PdfWriter;
  20.  
  21. public class RiverPhoenix {
  22.     /** Path to the resulting PDF */
  23.     public static final String RESULT = "results/part1/chapter02/river_phoenix.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 IOException, DocumentException {
  32.         new RiverPhoenix().createPdf(RESULT);
  33.     }
  34.    
  35.     /**
  36.      * Creates a PDF with information about the movies
  37.      * @param    filename the name of the PDF file that will be created.
  38.      * @throws    DocumentException
  39.      * @throws    IOException
  40.      */
  41.     public void createPdf(String filename)
  42.         throws IOException, DocumentException {
  43.         // step 1
  44.         Document document = new Document();
  45.         // step 2
  46.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  47.         // step 3
  48.         document.open();
  49.         // step 4
  50.         document.add(new Paragraph("Movies featuring River Phoenix", FilmFonts.BOLD));
  51.         document.add(createParagraph(
  52.             "My favorite movie featuring River Phoenix was ", "0092005"));
  53.         document.add(createParagraph(
  54.             "River Phoenix was nominated for an academy award for his role in ", "0096018"));
  55.         document.add(createParagraph(
  56.             "River Phoenix played the young Indiana Jones in ", "0097576"));
  57.         document.add(createParagraph(
  58.             "His best role was probably in ", "0102494"));
  59.         // step 5
  60.         document.close();
  61.     }
  62.    
  63.     /**
  64.      * Creates a paragraph with some text about a movie with River Phoenix,
  65.      * and a poster of the corresponding movie.
  66.      * @param text the text about the movie
  67.      * @param imdb the IMDB code referring to the poster
  68.      * @throws DocumentException
  69.      * @throws IOException
  70.      */
  71.     public Paragraph createParagraph(String text, String imdb)
  72.         throws DocumentException, IOException {
  73.         Paragraph p = new Paragraph(text);
  74.         Image img = Image.getInstance(
  75.                 String.format("resources/posters/%s.jpg", imdb));
  76.         img.scaleToFit(1000, 72);
  77.         img.setRotationDegrees(-30);
  78.         p.add(new Chunk(img, 0, -15, true));
  79.         return p;
  80.     }
  81. }
DatabaseTest.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Data;
  11. using System.Data.Common;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  15.  
  16. /**
  17.  * We'll test our SQLite database with this example
  18.  */
  19. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  20.   public class DatabaseTest : IWriter {
  21. // ===========================================================================
  22.     public void Write(Stream stream) {
  23.       // step 1
  24.       using (Document document = new Document()) {
  25.         // step 2
  26.         PdfWriter.GetInstance(document, stream);
  27.         // step 3
  28.         document.Open();
  29.         // step 4
  30.         using (var c =  AdoDB.Provider.CreateConnection()) {
  31.           c.ConnectionString = AdoDB.CS;
  32.           using (DbCommand cmd = c.CreateCommand()) {
  33.             cmd.CommandText =
  34.               "SELECT country FROM film_country ORDER BY country";
  35.             c.Open();            
  36.             using (var r = cmd.ExecuteReader()) {
  37.               while (r.Read()) {
  38.                 document.Add(new Paragraph( r.GetString(0) ));
  39.               }
  40.             }
  41.           }
  42.         }
  43.       }
  44.     }
  45. // ===========================================================================
  46.   }
  47. }
CountryChunks.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.Data;
  10. using System.Data.Common;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  14.  
  15. /**
  16.  * Writes a list of countries to a PDF file.
  17.  */
  18. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  19.   public class CountryChunks : IWriter {
  20. // ===========================================================================
  21.     public void Write(Stream stream) {
  22.       // step 1
  23.       using (Document document = new Document()) {
  24.         // step 2
  25.         PdfWriter.GetInstance(document, stream).InitialLeading = 16;
  26.         // step 3
  27.         document.Open();
  28.         // add the ID in another font
  29.         Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
  30.         // step 4
  31.         using (var c =  AdoDB.Provider.CreateConnection()) {
  32.           c.ConnectionString = AdoDB.CS;
  33.           using (DbCommand cmd = c.CreateCommand()) {
  34.             cmd.CommandText =
  35.               "SELECT country,id FROM film_country ORDER BY country";
  36.             c.Open();
  37.             using (var r = cmd.ExecuteReader()) {
  38.               while (r.Read()) {
  39.                 var country = r.GetString(0);
  40.                 var ID = r.GetString(1);
  41.                 document.Add(new Chunk(country));
  42.                 document.Add(new Chunk(" "));
  43.                 Chunk id = new Chunk(ID, font);
  44.                 // with a background color
  45.                 id.SetBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
  46.                 // and a text rise
  47.                 id.SetTextRise(6);
  48.                 document.Add(id);
  49.                 document.Add(Chunk.NEWLINE);
  50.               }
  51.             }
  52.           }
  53.         }
  54.       }
  55.     }
  56. // ===========================================================================
  57.   }
  58. }
DirectorPhrases1.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.Data;
  10. using System.Data.Common;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  14.  
  15. /**
  16.  * Writes a list of directors to a PDF file.
  17.  */
  18. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  19.   public class DirectorPhrases1 : IWriter {
  20. // ===========================================================================
  21.     /** A font that will be used in our PDF. */
  22.     public readonly Font BOLD_UNDERLINED =
  23.         new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD | Font.UNDERLINE);
  24.     /** A font that will be used in our PDF. */
  25.     public readonly Font NORMAL = new Font(Font.FontFamily.TIMES_ROMAN, 12);
  26. // ---------------------------------------------------------------------------
  27.     /**
  28.      * Creates a Phrase with the name and given name of a director using different fonts.
  29.      * @param r the DbDataReader containing director records.
  30.      */
  31.     protected virtual Phrase CreateDirectorPhrase(DbDataReader r) {
  32.       Phrase director = new Phrase();
  33.       director.Add(
  34.         new Chunk(r["name"].ToString(), BOLD_UNDERLINED)
  35.       );
  36.       director.Add(new Chunk(",", BOLD_UNDERLINED));
  37.       director.Add(new Chunk(" ", NORMAL));
  38.       director.Add(
  39.         new Chunk(r["given_name"].ToString(), NORMAL)
  40.       );
  41.       return director;
  42.     }
  43. // ---------------------------------------------------------------------------
  44.     public virtual void Write(Stream stream) {
  45.       var SQL =
  46. @"SELECT name, given_name
  47. FROM film_director
  48. ORDER BY name, given_name";    
  49.       // step 1
  50.       using (Document document = new Document()) {
  51.         // step 2
  52.         PdfWriter.GetInstance(document, stream);
  53.         // step 3
  54.         document.Open();
  55.         // step 4
  56.         using (var c =  AdoDB.Provider.CreateConnection()) {
  57.           c.ConnectionString = AdoDB.CS;
  58.           using (DbCommand cmd = c.CreateCommand()) {
  59.             cmd.CommandText = SQL;        
  60.             c.Open();            
  61.             using (var r = cmd.ExecuteReader()) {
  62.               while (r.Read()) {
  63.                 document.Add(CreateDirectorPhrase(r));
  64.                 document.Add(Chunk.NEWLINE);
  65.               }
  66.             }
  67.           }
  68.         }
  69.       }
  70.     }
  71. // ===========================================================================
  72.   }
  73. }
DirectorPhrases2.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.Data;
  10. using System.Data.Common;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13.  
  14. /**
  15.  * Writes a list of directors to a PDF file.
  16.  */
  17. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  18.   public class DirectorPhrases2 : DirectorPhrases1 {
  19. // ===========================================================================
  20.     /** A font that will be used in our PDF. */
  21.     public Font BOLD;
  22.     /** A font that will be used in our PDF. */
  23.     public new Font NORMAL;
  24. // ---------------------------------------------------------------------------
  25.     public DirectorPhrases2() {
  26.       BaseFont timesbd = null;
  27.       BaseFont times = null;
  28.     // create a font that will be embedded
  29.       timesbd = BaseFont.CreateFont(
  30.         "c:/windows/fonts/timesbd.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED
  31.       );
  32.       // create a font that will be embedded
  33.       times = BaseFont.CreateFont(
  34.         "c:/windows/fonts/times.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED
  35.       );
  36.       BOLD = new Font(timesbd, 12);
  37.       NORMAL = new Font(times, 12);
  38.     }
  39. // ---------------------------------------------------------------------------
  40.     /**
  41.      * Creates a Phrase with the name and given name of a director using different fonts.
  42.      * @param    rs    the ResultSet containing director records.
  43.      */
  44.     protected override Phrase CreateDirectorPhrase(DbDataReader r) {
  45.       Phrase director = new Phrase();
  46.       Chunk name = new Chunk(r["name"].ToString(), BOLD);
  47.       name.SetUnderline(0.2f, -2f);
  48.       director.Add(name);
  49.       director.Add(new Chunk(",", BOLD));
  50.       director.Add(new Chunk(" ", NORMAL));
  51.       director.Add(
  52.         new Chunk(r["given_name"].ToString(), NORMAL)
  53.       );
  54.       director.Leading = 24;
  55.       return director;
  56.     }
  57. // ---------------------------------------------------------------------------
  58.     public override void Write(Stream stream) {
  59.       base.Write(stream);
  60.     }
  61. // ===========================================================================
  62.   }
  63. }
MovieTitles.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.Chapter02 {
  16.   public class MovieTitles : 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.         IEnumerable movies = PojoFactory.GetMovies();
  27.         foreach (Movie movie in movies) {
  28.           document.Add(new Paragraph(movie.Title));
  29.         }
  30.       }
  31.     }
  32. // ===========================================================================
  33.   }
  34. }
MovieParagraphs1.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. /**
  16.  * Writes a list of countries to a PDF file.
  17.  */
  18. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  19.   public class MovieParagraphs1 : IWriter {
  20. // ===========================================================================
  21.     public virtual void Write(Stream stream) {
  22.       // step 1
  23.       using (Document document = new Document()) {
  24.         // step 2
  25.         PdfWriter.GetInstance(document, stream);
  26.         // step 3
  27.         document.Open();
  28.         // step 4
  29.         IEnumerable movies = PojoFactory.GetMovies();
  30.         foreach (Movie movie in movies) {
  31.           Paragraph p = CreateMovieInformation(movie);
  32.           p.Alignment = Element.ALIGN_JUSTIFIED;
  33.           p.IndentationLeft = 18;
  34.           p.FirstLineIndent = -18;
  35.           document.Add(p);
  36.         }
  37.       }
  38.     }
  39. // ---------------------------------------------------------------------------    
  40.     /**
  41.      * Creates a Paragraph containing information about a movie.
  42.      * @param    movie    the movie for which you want to create a Paragraph
  43.      */
  44.     public Paragraph CreateMovieInformation(Movie movie) {
  45.       Paragraph p = new Paragraph();
  46.       p.Font = FilmFonts.NORMAL;
  47.       p.Add(new Phrase("Title: ", FilmFonts.BOLDITALIC));
  48.       p.Add(PojoToElementFactory.GetMovieTitlePhrase(movie));
  49.       p.Add(" ");
  50.       if (!string.IsNullOrEmpty(movie.OriginalTitle)) {
  51.         p.Add(new Phrase("Original title: ", FilmFonts.BOLDITALIC));
  52.         p.Add(PojoToElementFactory.GetOriginalTitlePhrase(movie));
  53.         p.Add(" ");
  54.       }
  55.       p.Add(new Phrase("Country: ", FilmFonts.BOLDITALIC));
  56.       foreach (Country country in movie.Countries) {
  57.         p.Add(PojoToElementFactory.GetCountryPhrase(country));
  58.         p.Add(" ");
  59.       }
  60.       p.Add(new Phrase("Director: ", FilmFonts.BOLDITALIC));
  61.       foreach (Director director in movie.Directors) {
  62.         p.Add(PojoToElementFactory.GetDirectorPhrase(director));
  63.         p.Add(" ");
  64.       }
  65.       p.Add(CreateYearAndDuration(movie));
  66.       return p;
  67.     }
  68. // ---------------------------------------------------------------------------    
  69.     /**
  70.      * Creates a Paragraph containing information about the year
  71.      * and the duration of a movie.
  72.      * @param    movie    the movie for which you want to create a Paragraph
  73.      */
  74.     public Paragraph CreateYearAndDuration(Movie movie) {
  75.       Paragraph info = new Paragraph();
  76.       info.Font = FilmFonts.NORMAL;
  77.       info.Add(new Chunk("Year: ", FilmFonts.BOLDITALIC));
  78.       info.Add(new Chunk(movie.Year.ToString(), FilmFonts.NORMAL));
  79.       info.Add(new Chunk(" Duration: ", FilmFonts.BOLDITALIC));
  80.       info.Add(new Chunk(movie.Duration.ToString(), FilmFonts.NORMAL));
  81.       info.Add(new Chunk(" minutes", FilmFonts.NORMAL));
  82.       return info;
  83.     }    
  84. // ===========================================================================
  85.   }
  86. }
MovieParagraphs2.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. /**
  16.  * Writes a list of countries to a PDF file.
  17.  */
  18. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  19.   public class MovieParagraphs2 : MovieParagraphs1 {
  20. // ===========================================================================
  21.     public override void Write(Stream stream) {
  22.       // step 1
  23.       using (Document document = new Document()) {
  24.         // step 2
  25.         PdfWriter.GetInstance(document, stream);
  26.         // step 3
  27.         document.Open();
  28.         // step 4
  29.         IEnumerable movies = PojoFactory.GetMovies();
  30.         foreach (Movie movie in movies) {
  31.         // Create a paragraph with the title
  32.           Paragraph title = new Paragraph(
  33.             PojoToElementFactory.GetMovieTitlePhrase(movie)
  34.           );
  35.           title.Alignment = Element.ALIGN_LEFT;
  36.           document.Add(title);
  37.           // Add the original title next to it using a dirty hack
  38.           if ( !string.IsNullOrEmpty(movie.OriginalTitle) ) {
  39.             Paragraph dummy = new Paragraph("\u00a0", FilmFonts.NORMAL);
  40.             dummy.Leading = -18;
  41.             document.Add(dummy);
  42.             Paragraph originalTitle = new Paragraph(
  43.               PojoToElementFactory.GetOriginalTitlePhrase(movie)
  44.             );
  45.             originalTitle.Alignment = Element.ALIGN_RIGHT;
  46.             document.Add(originalTitle);
  47.           }
  48.           // Info about the director
  49.           float indent = 20;
  50.           // Loop over the directors
  51.           foreach (Director pojo in movie.Directors) {
  52.             Paragraph director = new Paragraph(
  53.               PojoToElementFactory.GetDirectorPhrase(pojo)
  54.             );
  55.             director.IndentationLeft = indent;
  56.             document.Add(director);
  57.             indent += 20;
  58.           }
  59.           // Info about the country
  60.           indent = 20;
  61.           // Loop over the countries
  62.           foreach (Country pojo in movie.Countries) {
  63.             Paragraph country = new Paragraph(
  64.               PojoToElementFactory.GetCountryPhrase(pojo)
  65.             );
  66.             country.Alignment = Element.ALIGN_RIGHT;
  67.             country.IndentationRight = indent;
  68.             document.Add(country);
  69.             indent += 20;
  70.           }
  71.           // Extra info about the movie
  72.           Paragraph info = CreateYearAndDuration(movie);
  73.           info.Alignment = Element.ALIGN_CENTER;
  74.           info.SpacingAfter = 36;
  75.           document.Add(info);
  76.         }      
  77.       }
  78.     }
  79. // ===========================================================================
  80.   }
  81. }
PipeSplitCharacter.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. /**
  13.  * Writes a list of countries to a PDF file.
  14.  */
  15. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  16.   public class PipeSplitCharacter : ISplitCharacter {
  17. // ===========================================================================
  18.     /**
  19.      * @see com.itextpdf.text.SplitCharacter#isSplitCharacter(int, int, int, char[],
  20.      *      com.itextpdf.text.pdf.PdfChunk[])
  21.      */
  22.     public bool IsSplitCharacter(
  23.       int start, int current, int end, char[] cc, PdfChunk[] ck)
  24.     {
  25.       char c = ck == null
  26.         ? cc[current]
  27.         : (char) ck[Math.Min(current, ck.Length - 1)]
  28.             .GetUnicodeEquivalent(cc[current])
  29.       ;
  30.       return (c == '|' || c
MovieChain.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 System.Text;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  17.   public class MovieChain : IWriter {
  18. // ===========================================================================
  19.     public void Write(Stream stream) {
  20.       // step 1
  21.       using (Document document = new Document(
  22.         new Rectangle(240, 240), 10, 10, 10, 10
  23.       ))
  24.       {
  25.         // step 2
  26.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  27.         // step 3
  28.         document.Open();
  29.         // step 4
  30.         // create a long Stringbuffer with movie titles
  31.         StringBuilder sb = new StringBuilder();
  32.         IEnumerable movies = PojoFactory.GetMovies(1);
  33.         foreach ( Movie movie in movies  ) {
  34.         // replace spaces with non-breaking spaces
  35.           sb.Append(movie.MovieTitle.Replace(' ', '\u00a0'));
  36.           // use pipe as separator
  37.           sb.Append('|');
  38.         }
  39.         // Create a first chunk
  40.         Chunk chunk1 = new Chunk(sb.ToString());
  41.         // wrap the chunk in a paragraph and add it to the document
  42.         Paragraph paragraph = new Paragraph("A:\u00a0");
  43.         paragraph.Add(chunk1);
  44.         paragraph.Alignment = Element.ALIGN_JUSTIFIED;
  45.         document.Add(paragraph);
  46.         document.Add(Chunk.NEWLINE);
  47.         // define the pipe character as split character
  48.         chunk1.SetSplitCharacter(new PipeSplitCharacter());
  49.         // wrap the chunk in a second paragraph and add it
  50.         paragraph = new Paragraph("B:\u00a0");
  51.         paragraph.Add(chunk1);
  52.         paragraph.Alignment = Element.ALIGN_JUSTIFIED;
  53.         document.Add(paragraph);
  54.         document.Add(Chunk.NEWLINE);
  55.  
  56.         // create a new StringBuffer with movie titles
  57.         sb = new StringBuilder();
  58.         foreach ( Movie movie in movies ) {
  59.             sb.Append(movie.MovieTitle);
  60.             sb.Append('|');
  61.         }
  62.         // Create a second chunk
  63.         Chunk chunk2 = new Chunk(sb.ToString());
  64.         // wrap the chunk in a paragraph and add it to the document
  65.         paragraph = new Paragraph("C:\u00a0");
  66.         paragraph.Add(chunk2);
  67.         paragraph.Alignment = Element.ALIGN_JUSTIFIED;
  68.         document.Add(paragraph);
  69.         document.NewPage();
  70.         // define hyphenation for the chunk
  71.         chunk2.SetHyphenation(new HyphenationAuto("en", "US", 2, 2));
  72.         // wrap the second chunk in a second paragraph and add it
  73.         paragraph = new Paragraph("D:\u00a0");
  74.         paragraph.Add(chunk2);
  75.         paragraph.Alignment = Element.ALIGN_JUSTIFIED;
  76.         document.Add(paragraph);
  77.        
  78.         // go to a new page
  79.         document.NewPage();
  80.         // define a new space/char ratio
  81.         writer.SpaceCharRatio = PdfWriter.NO_SPACE_CHAR_RATIO;
  82.         // wrap the second chunk in a third paragraph and add it
  83.         paragraph = new Paragraph("E:\u00a0");
  84.         paragraph.Add(chunk2);
  85.         paragraph.Alignment = Element.ALIGN_JUSTIFIED;
  86.         document.Add(paragraph);
  87.       }
  88.     }
  89. // ===========================================================================
  90.   }
  91. }
MovieLists1.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.Data;
  10. using System.Data.Common;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  16.   public class MovieLists1 : 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.         var SQL =
  27. @"SELECT DISTINCT mc.country_id, c.country, count(*) AS c
  28. FROM film_country c, film_movie_country mc
  29. WHERE c.id = mc.country_id
  30. GROUP BY mc.country_id, country ORDER BY c DESC";  
  31.         // Create a new list
  32.         List list = new List(List.ORDERED);
  33.         // loop over the countries
  34.         using (var c =  AdoDB.Provider.CreateConnection()) {
  35.           c.ConnectionString = AdoDB.CS;
  36.           using (DbCommand cmd = c.CreateCommand()) {
  37.             cmd.CommandText = SQL;        
  38.             c.Open();            
  39.             using (var r = cmd.ExecuteReader()) {
  40.               while (r.Read()) {
  41.               // create a list item for the country
  42.                 ListItem item = new ListItem(
  43.                   string.Format("{0}: {1} movies",
  44.                     r["country"].ToString(), r["c"].ToString()
  45.                   ),
  46.                   FilmFonts.BOLDITALIC
  47.                 );
  48.                 // create a movie list for each country
  49.                 List movielist = new List(List.ORDERED, List.ALPHABETICAL);
  50.                 movielist.Lowercase = List.LOWERCASE;
  51.                 foreach (Movie movie in
  52.                     PojoFactory.GetMovies(r["country_id"].ToString())
  53.                 ) {
  54.                   ListItem movieitem = new ListItem(movie.MovieTitle);
  55.                   List directorlist = new List(List.UNORDERED);
  56.                   foreach (Director director in movie.Directors) {
  57.                     directorlist.Add(String.Format("{0}, {1}",
  58.                       director.Name, director.GivenName
  59.                     ));
  60.                   }
  61.                   movieitem.Add(directorlist);
  62.                   movielist.Add(movieitem);
  63.                 }
  64.                 item.Add(movielist);
  65.                 list.Add(item);
  66.               }
  67.               document.Add(list);
  68.             }
  69.           }
  70.         }
  71.       }
  72.     }
  73. // ===========================================================================
  74.   }
  75. }
MovieLists2.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.Data;
  10. using System.Data.Common;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  16.   public class MovieLists2 : 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.         var SQL =
  27. @"SELECT DISTINCT mc.country_id, c.country, count(*) AS c
  28. FROM film_country c, film_movie_country mc
  29. WHERE c.id = mc.country_id
  30. GROUP BY mc.country_id, country ORDER BY c DESC";
  31.         // Create a new list
  32.         List list = new List(List.ORDERED);
  33.         list.Autoindent = false;
  34.         list.SymbolIndent = 36;
  35.         // loop over the countries
  36.         using (var c =  AdoDB.Provider.CreateConnection()) {
  37.           c.ConnectionString = AdoDB.CS;
  38.           using (DbCommand cmd = c.CreateCommand()) {
  39.             cmd.CommandText = SQL;        
  40.             c.Open();            
  41.             using (var r = cmd.ExecuteReader()) {
  42.               while (r.Read()) {
  43.               // create a list item for the country
  44.                 ListItem item = new ListItem(
  45.                   string.Format("{0}: {1} movies",
  46.                     r["country"].ToString(), r["c"].ToString()
  47.                   )
  48.                 );
  49.                 item.ListSymbol = new Chunk(r["country_id"].ToString());
  50.                 // Create a list for the movies produced in the current country
  51.                 List movielist = new List(List.ORDERED, List.ALPHABETICAL);
  52.                 movielist.Alignindent = false;
  53.  
  54.                 foreach (Movie movie in
  55.                     PojoFactory.GetMovies(r["country_id"].ToString())
  56.                 ) {
  57.                   ListItem movieitem = new ListItem(movie.MovieTitle);
  58.                   List directorlist = new List(List.ORDERED);
  59.                   directorlist.PreSymbol = "Director ";
  60.                   directorlist.PostSymbol = ": ";
  61.                   foreach (Director director in movie.Directors) {
  62.                     directorlist.Add(String.Format("{0}, {1}",
  63.                       director.Name, director.GivenName
  64.                     ));
  65.                   }
  66.  
  67.  
  68.                   movieitem.Add(directorlist);
  69.                   movielist.Add(movieitem);
  70.                 }
  71.                 item.Add(movielist);
  72.                 list.Add(item);
  73.               }
  74.               document.Add(list);
  75.             }
  76.           }
  77.         }
  78.       }
  79.     }
  80. // ===========================================================================
  81.   }
  82. }
MovieLists3.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.Data;
  10. using System.Data.Common;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  16.   public class MovieLists3 : 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.         var SQL =
  27. @"SELECT DISTINCT mc.country_id, c.country, count(*) AS c
  28. FROM film_country c, film_movie_country mc
  29. WHERE c.id = mc.country_id
  30. GROUP BY mc.country_id, country ORDER BY c DESC";  
  31.         // Create a list for the countries
  32.         List list = new RomanList();
  33.         // loop over the countries
  34.         using (var c =  AdoDB.Provider.CreateConnection()) {
  35.           c.ConnectionString = AdoDB.CS;
  36.           using (DbCommand cmd = c.CreateCommand()) {
  37.             cmd.CommandText = SQL;        
  38.             c.Open();            
  39.             using (var r = cmd.ExecuteReader()) {
  40.               while (r.Read()) {
  41.               // create a list item for the country
  42.                 ListItem item = new ListItem(
  43.                   string.Format("{0}: {1} movies",
  44.                     r["country"].ToString(), r["c"].ToString()
  45.                   )
  46.                 );
  47.                 // Create a list for the movies
  48.                 List movielist = new GreekList();
  49.                 movielist.Lowercase = List.LOWERCASE;
  50.                 // Loop over the movies
  51.                 foreach (Movie movie in
  52.                     PojoFactory.GetMovies(r["country_id"].ToString())
  53.                 ) {
  54.                   ListItem movieitem = new ListItem(movie.MovieTitle);
  55.                   // Create a list for the directors
  56.                   List directorlist = new ZapfDingbatsNumberList(0);
  57.                   // Loop over the directors                
  58.                   foreach (Director director in movie.Directors) {
  59.                     directorlist.Add(String.Format("{0}, {1}",
  60.                       director.Name, director.GivenName
  61.                     ));
  62.                   }
  63.                   movieitem.Add(directorlist);
  64.                   movielist.Add(movieitem);
  65.                 }
  66.                 item.Add(movielist);
  67.                 list.Add(item);
  68.               }
  69.               document.Add(list);
  70.             }
  71.           }
  72.         }
  73.       }
  74.     }
  75. // ===========================================================================
  76.   }
  77. }
MovieLists4.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.Data;
  10. using System.Data.Common;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  16.   public class MovieLists4 : 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.         var SQL =
  27.   @"SELECT DISTINCT mc.country_id, c.country, count(*) AS c
  28.  FROM film_country c, film_movie_country mc
  29.  WHERE c.id = mc.country_id
  30.  GROUP BY mc.country_id, country ORDER BY c DESC";  
  31.         // Create a list for the countries
  32.         List list = new List(List.ORDERED);
  33.         list.First = 9;
  34.         // loop over the countries
  35.         using (var c =  AdoDB.Provider.CreateConnection()) {
  36.           c.ConnectionString = AdoDB.CS;
  37.           using (DbCommand cmd = c.CreateCommand()) {
  38.             cmd.CommandText = SQL;        
  39.             c.Open();            
  40.             using (var r = cmd.ExecuteReader()) {
  41.               while (r.Read()) {
  42.               // create a list item for the country
  43.                 ListItem item = new ListItem(
  44.                   string.Format("{0}: {1} movies",
  45.                     r["country"].ToString(), r["c"].ToString()
  46.                   )
  47.                 );
  48.                 // Create a list for the movies
  49.                 List movielist = new List();
  50.                 movielist.ListSymbol= new Chunk("Movie: ", FilmFonts.BOLD);
  51.                 foreach (Movie movie in
  52.                     PojoFactory.GetMovies(r["country_id"].ToString())
  53.                 ) {
  54.                   ListItem movieitem = new ListItem(movie.MovieTitle);
  55.                   // Create a list for the directors
  56.                   List directorlist = new ZapfDingbatsList(42);
  57.                   foreach (Director director in movie.Directors) {
  58.                     directorlist.Add(String.Format("{0}, {1}",
  59.                       director.Name, director.GivenName
  60.                     ));
  61.                   }
  62.                   movieitem.Add(directorlist);
  63.                   movielist.Add(movieitem);
  64.                 }
  65.                 item.Add(movielist);
  66.                 list.Add(item);
  67.               }
  68.               document.Add(list);
  69.             }
  70.           }
  71.         }
  72.       }
  73.     }
  74. // ===========================================================================
  75.   }
  76. }
PositionedArrow.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. using iTextSharp.text.pdf.draw;
  12.  
  13. /**
  14.  * Subclass of VerticalPositionMark that draws an arrow in the left
  15.  * or right margin.
  16.  */
  17. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  18.   public class PositionedArrow : VerticalPositionMark {
  19. // ===========================================================================
  20.     /** Indicates if the arrow needs to be drawn to the left. */
  21.     protected bool left;
  22.    
  23.     /** Thee font that will be used to draw the arrow. */
  24.     protected BaseFont zapfdingbats;
  25.  
  26.     /** An arrow pointing to the right will be added on the left. */
  27.     public static PositionedArrow LEFT {
  28.       get { return new PositionedArrow(true); }
  29.     }
  30.     /** An arrow pointing to the left will be added on the right. */
  31.     public static PositionedArrow RIGHT {
  32.       get { return new PositionedArrow(false); }
  33.     }
  34. // ---------------------------------------------------------------------------    
  35.     /**
  36.      * Constructs a positioned Arrow mark.
  37.      * @param    left    if true, an arrow will be drawn on the left;
  38.      * otherwise, it will be drawn on the right.
  39.      * @throws IOException
  40.      * @throws DocumentException
  41.      */
  42.     public PositionedArrow(bool left) {
  43.       this.left = left;
  44.       try {
  45.         zapfdingbats = BaseFont.CreateFont(
  46.           BaseFont.ZAPFDINGBATS, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED
  47.         );
  48.       }
  49.       catch {
  50.         zapfdingbats = null;
  51.         throw;
  52.       }
  53.     }
  54. // ---------------------------------------------------------------------------    
  55.     /**
  56.      * Draws a character representing an arrow at the current position.
  57.      * @see com.itextpdf.text.pdf.draw.VerticalPositionMark#draw(
  58.      *      com.itextpdf.text.pdf.PdfContentByte, float, float, float, float, float)
  59.      */
  60.     // i'm so stupid; originally forgot to override parent method and wondered
  61.     // why the arrows weren't being drawn...
  62.     public override void Draw(
  63.       PdfContentByte canvas, float llx, float lly, float urx, float ury, float y
  64.     ) {
  65.       canvas.BeginText();
  66.       canvas.SetFontAndSize(zapfdingbats, 12);
  67.       if (left) {
  68.         canvas.ShowTextAligned(Element.ALIGN_CENTER,
  69.           ((char) 220).ToString(), llx - 10, y, 0
  70.         );
  71.       }
  72.       else {
  73.         canvas.ShowTextAligned(Element.ALIGN_CENTER,
  74.           ((char) 220).ToString(), urx + 10, y + 8, 180
  75.         );
  76.       }
  77.       canvas.EndText();
  78.     }
  79. // ===========================================================================
  80.   }
  81. }
StarSeparator.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. using iTextSharp.text.pdf.draw;
  12.  
  13. /**
  14.  * does **NOT** write PDF file; class used for drawing only.
  15.  */
  16. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  17.   public class StarSeparator : IDrawInterface {
  18. // ===========================================================================
  19.     /** The font that will be used to draw the arrow. */
  20.     protected BaseFont bf;
  21. // ---------------------------------------------------------------------------
  22.     public static StarSeparator LINE {
  23.       get { return new StarSeparator(); }
  24.     }
  25. // ---------------------------------------------------------------------------    
  26.     /**
  27.      * Constructs a positioned Arrow mark.
  28.      * @param    left    if true, an arrow will be drawn on the left;
  29.      * otherwise, it will be drawn on the right.
  30.      * @throws IOException
  31.      * @throws DocumentException
  32.      */
  33.     public StarSeparator() {
  34.       try {
  35.         bf = BaseFont.CreateFont();
  36.       } catch {
  37.         bf = null;
  38.         throw;
  39.       }
  40.     }
  41. // ---------------------------------------------------------------------------    
  42.     /**
  43.      * Draws three stars to separate two paragraphs.
  44.      * @see com.itextpdf.text.pdf.draw.DrawInterface#draw(
  45.      * com.itextpdf.text.pdf.PdfContentByte, float, float, float, float, float)
  46.      */
  47.     public void Draw(
  48.       PdfContentByte canvas, float llx, float lly, float urx, float ury, float y
  49.     ) {
  50.       float middle = (llx + urx) / 2;
  51.       canvas.BeginText();
  52.       canvas.SetFontAndSize(bf, 10);
  53.       canvas.ShowTextAligned(Element.ALIGN_CENTER, "*", middle, y, 0);
  54.       canvas.ShowTextAligned(Element.ALIGN_CENTER, "*  *", middle, y -10, 0);
  55.       canvas.EndText();
  56.     }
  57. // ===========================================================================
  58.   }
  59. }
DirectorOverview1.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.Data;
  10. using System.Data.Common;
  11. using System.Linq;
  12. using System.util.collections;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using iTextSharp.text.pdf.draw;
  16. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  17.  
  18. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  19.   public class DirectorOverview1 : IWriter {
  20. // ===========================================================================
  21.     public const string SQL =
  22. @"SELECT DISTINCT d.id, d.name, d.given_name, count(*) AS c
  23.  FROM film_director d, film_movie_director md
  24.  WHERE d.id = md.director_id
  25.  GROUP BY d.id, d.name, d.given_name ORDER BY name";
  26. // ---------------------------------------------------------------------------
  27.     public void Write(Stream stream) {
  28.       // step 1
  29.       using (Document document = new Document()) {
  30.         // step 2
  31.         PdfWriter.GetInstance(document, stream);
  32.         // step 3
  33.         document.Open();
  34.         // step 4
  35.         Director director;
  36.         // creating separators
  37.         LineSeparator line
  38.             = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);
  39.         Paragraph stars = new Paragraph(20);
  40.         stars.Add(new Chunk(StarSeparator.LINE));
  41.         stars.SpacingAfter = 30;
  42.         using (var c =  AdoDB.Provider.CreateConnection()) {
  43.           c.ConnectionString = AdoDB.CS;
  44.           using (DbCommand cmd = c.CreateCommand()) {
  45.             cmd.CommandText = SQL;
  46.             c.Open();
  47.             using (var r = cmd.ExecuteReader()) {
  48.               while (r.Read()) {
  49.                 // get the director object and use it in a Paragraph
  50.                 director = PojoFactory.GetDirector(r);
  51.                 Paragraph p = new Paragraph(
  52.                     PojoToElementFactory.GetDirectorPhrase(director));
  53.                 // if there are more than 2 movies for this director
  54.                 // an arrow is added to the left
  55.                 var count = Convert.ToInt32(r["c"]);
  56.                 if (count > 2) {
  57.                   p.Add(PositionedArrow.LEFT);
  58.                 }
  59.                 p.Add(line);
  60.                 // add the paragraph with the arrow to the document
  61.                 document.Add(p);
  62.                 // Get the movies of the director
  63.                 var director_id = Convert.ToInt32(r["id"]);
  64.                 // LINQ allows us to sort on any movie object property inline;
  65.                 // let's sort by Movie.Year, Movie.Title
  66.                 var by_year = from m in PojoFactory.GetMovies(director_id)
  67.                     orderby m.Year, m.Title
  68.                     select m;
  69.                 foreach (Movie movie in by_year) {
  70.                   p = new Paragraph(movie.MovieTitle);
  71.                   p.Add(": ");
  72.                   p.Add(new Chunk(movie.Year.ToString()));
  73.                   if (movie.Year > 1999) p.Add(PositionedArrow.RIGHT);
  74.                   document.Add(p);
  75.                 }                
  76.                 // add a star separator after the director info is added
  77.                 document.Add(stars);          
  78.               }
  79.             }
  80.           }
  81.         }
  82.       }
  83.     }
  84. // ===========================================================================
  85.   }
  86. }
DirectorOverview2.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.Data;
  10. using System.Data.Common;
  11. using System.Linq;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.draw;
  15. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  18.   public class DirectorOverview2 : IWriter {
  19. // ===========================================================================
  20.     public const string SQL =
  21. @"SELECT DISTINCT d.id, d.name, d.given_name, count(*) AS c
  22. FROM film_director d, film_movie_director md
  23.  WHERE d.id = md.director_id
  24. GROUP BY d.id, d.name, d.given_name ORDER BY c DESC";
  25. // ---------------------------------------------------------------------------
  26.     public void Write(Stream stream) {
  27.       // step 1
  28.       using (Document document = new Document()) {
  29.         // step 2
  30.         PdfWriter.GetInstance(document, stream);
  31.         // step 3
  32.         document.Open();
  33.         // step 4
  34.         Director director;
  35.         using (var c =  AdoDB.Provider.CreateConnection()) {
  36.           c.ConnectionString = AdoDB.CS;
  37.           using (DbCommand cmd = c.CreateCommand()) {
  38.             cmd.CommandText = SQL;
  39.             c.Open();
  40.             using (var r = cmd.ExecuteReader()) {
  41.               while (r.Read()) {
  42.                 // create a paragraph for the director
  43.                 director = PojoFactory.GetDirector(r);
  44.                 Paragraph p = new Paragraph(
  45.                     PojoToElementFactory.GetDirectorPhrase(director));
  46.                 // add a dotted line separator
  47.                 p.Add(new Chunk(new DottedLineSeparator()));
  48.                 // adds the number of movies of this director
  49.                 p.Add(string.Format("movies: {0}", Convert.ToInt32(r["c"])));
  50.                 document.Add(p);
  51.                 // Creates a list
  52.                 List list = new List(List.ORDERED);
  53.                 list.IndentationLeft = 36;
  54.                 list.IndentationRight = 36;
  55.                 // Gets the movies of the current director
  56.                 var director_id = Convert.ToInt32(r["id"]);
  57.                 ListItem movieitem;
  58.                 // LINQ allows us to on sort any movie object property inline;
  59.                 // let's sort by Movie.Year, Movie.Title
  60.                 var by_year = from m in PojoFactory.GetMovies(director_id)
  61.                     orderby m.Year, m.Title
  62.                     select m;
  63.                 // loops over the movies
  64.                 foreach (Movie movie in by_year) {
  65.                 // creates a list item with a movie title
  66.                   movieitem = new ListItem(movie.MovieTitle);
  67.                   // adds a vertical position mark as a separator
  68.                   movieitem.Add(new Chunk(new VerticalPositionMark()));
  69.                   var yr = movie.Year;
  70.                   // adds the year the movie was produced
  71.                   movieitem.Add(new Chunk( yr.ToString() ));
  72.                   // add an arrow to the right if the movie dates from 2000 or later
  73.                   if (yr > 1999) {
  74.                     movieitem.Add(PositionedArrow.RIGHT);
  75.                   }
  76.                   // add the list item to the list
  77.                   list.Add(movieitem);
  78.                 }
  79.                 // add the list to the document
  80.                 document.Add(list);          
  81.               }
  82.             }
  83.           }
  84.         }
  85.       }
  86.     }
  87. // ===========================================================================
  88.   }
  89. }
DirectorOverview3.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.Data;
  10. using System.Data.Common;
  11. using System.Linq;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.draw;
  15. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  18.   public class DirectorOverview3 : IWriter {
  19. // ===========================================================================
  20.     public const string SQL =
  21. @"SELECT DISTINCT d.id, d.name, d.given_name, count(*) AS c
  22. FROM film_director d, film_movie_director md
  23.  WHERE d.id = md.director_id
  24. GROUP BY d.id, d.name, d.given_name ORDER BY c DESC";
  25. // ---------------------------------------------------------------------------
  26.     public void Write(Stream stream) {
  27.       // step 1
  28.       using (Document document = new Document()) {
  29.         // step 2
  30.         PdfWriter.GetInstance(document, stream);
  31.         // step 3
  32.         document.Open();
  33.         // step 4
  34.         Director director;
  35.         // creates line separators
  36.         Chunk CONNECT = new Chunk(
  37.           new LineSeparator(0.5f, 95, BaseColor.BLUE, Element.ALIGN_CENTER, 3.5f)
  38.         );
  39.         LineSeparator UNDERLINE = new LineSeparator(
  40.           1, 100, null, Element.ALIGN_CENTER, -2
  41.         );
  42.         // creates tabs
  43.         Chunk tab1 = new Chunk(new VerticalPositionMark(), 200, true);
  44.         Chunk tab2 = new Chunk(new VerticalPositionMark(), 350, true);
  45.         Chunk tab3 = new Chunk(new DottedLineSeparator(), 450, true);
  46.        
  47.         using (var c =  AdoDB.Provider.CreateConnection()) {
  48.           c.ConnectionString = AdoDB.CS;
  49.           using (DbCommand cmd = c.CreateCommand()) {
  50.             cmd.CommandText = SQL;
  51.             c.Open();
  52.             using (var r = cmd.ExecuteReader()) {
  53.               // loops over the directors
  54.               while (r.Read()) {
  55.                 // creates a paragraph with the director name
  56.                 director = PojoFactory.GetDirector(r);
  57.                 Paragraph p = new Paragraph(
  58.                     PojoToElementFactory.GetDirectorPhrase(director));
  59.                 // adds a separator
  60.                 p.Add(CONNECT);
  61.                 // adds more info about the director
  62.                 p.Add(string.Format("movies: {0}", Convert.ToInt32(r["c"])));
  63.                 // adds a separator
  64.                 p.Add(UNDERLINE);
  65.                 // adds the paragraph to the document
  66.                 document.Add(p);
  67.                 // gets all the movies of the current director
  68.                 var director_id = Convert.ToInt32(r["id"]);
  69.                 // LINQ allows us to sort on any movie object property inline;
  70.                 // let's sort by Movie.Year, Movie.Title
  71.                 var by_year = from m in PojoFactory.GetMovies(director_id)
  72.                     orderby m.Year, m.Title
  73.                     select m;
  74.                 // loops over the movies
  75.                 foreach (Movie movie in by_year) {
  76.                 // create a Paragraph with the movie title
  77.                   p = new Paragraph(movie.MovieTitle);
  78.                   // insert a tab
  79.                   p.Add(new Chunk(tab1));
  80.                   // add the original title
  81.                   var mt = movie.OriginalTitle;
  82.                   if (mt != null) p.Add(new Chunk(mt));
  83.                   // insert a tab
  84.                   p.Add(new Chunk(tab2));
  85.                   // add the run length of the movie
  86.                   p.Add(new Chunk(string.Format("{0} minutes", movie.Duration)));
  87.                   // insert a tab
  88.                   p.Add(new Chunk(tab3));
  89.                   // add the production year of the movie
  90.                   p.Add(new Chunk(
  91.                     string.Format("{0}", movie.Year.ToString())
  92.                   ));
  93.                   // add the paragraph to the document
  94.                   document.Add(p);
  95.                 }
  96.                 document.Add(Chunk.NEWLINE);          
  97.               }
  98.             }
  99.           }
  100.         }
  101.       }
  102.     }
  103. // ===========================================================================
  104.   }
  105. }
MovieLinks1.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.Data;
  10. using System.Data.Common;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  16.   public class MovieLinks1 : IWriter {
  17. // ===========================================================================
  18.     public void Write(Stream stream) {
  19.       var SQL =
  20. @"SELECT DISTINCT mc.country_id, c.country, count(*) AS c
  21. FROM film_country c, film_movie_country mc
  22.  WHERE c.id = mc.country_id
  23. GROUP BY mc.country_id, country ORDER BY c DESC";          
  24.       // step 1
  25.       using (Document document = new Document()) {
  26.         // step 2
  27.         PdfWriter.GetInstance(document, stream);
  28.         // step 3
  29.         document.Open();
  30.         // step 4
  31.         using (var c =  AdoDB.Provider.CreateConnection()) {
  32.           c.ConnectionString = AdoDB.CS;
  33.           using (DbCommand cmd = c.CreateCommand()) {
  34.             cmd.CommandText = SQL;
  35.             c.Open();            
  36.             using (var r = cmd.ExecuteReader()) {
  37.               while (r.Read()) {
  38.                 Paragraph country = new Paragraph();
  39.                 // the name of the country will be a destination
  40.                 Anchor dest = new Anchor(
  41.                   r["country"].ToString(), FilmFonts.BOLD
  42.                 );
  43.                 dest.Name = r["country_id"].ToString();
  44.                 country.Add(dest);
  45.                 country.Add(string.Format(": {0} movies", r["c"].ToString()));
  46.                 document.Add(country);
  47.                 // loop over the movies
  48.                 foreach (Movie movie in
  49.                     PojoFactory.GetMovies(r["country_id"].ToString()))
  50.                 {
  51.                 // the movie title will be an external link
  52.                   Anchor imdb = new Anchor(movie.MovieTitle);
  53.                   imdb.Reference = string.Format(
  54.                     "http://www.imdb.com/title/tt{0}/", movie.Imdb
  55.                   );
  56.                   document.Add(imdb);
  57.                   document.Add(Chunk.NEWLINE);
  58.                 }
  59.                 document.NewPage();
  60.               }
  61.               // Create an internal link to the first page
  62.               Anchor toUS = new Anchor("Go back to the first page.");
  63.               toUS.Reference = "#US";
  64.               document.Add(toUS);          
  65.             }
  66.           }
  67.         }
  68.       }
  69.     }
  70. // ===========================================================================
  71.   }
  72. }
MovieLinks2.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.Data;
  10. using System.Data.Common;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  14.  
  15. /**
  16.  * We'll test our SQLite database with this example
  17.  */
  18. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  19.   public class MovieLinks2 : IWriter {
  20. // ===========================================================================
  21.     public void Write(Stream stream) {
  22.       // step 1
  23.       using (Document document = new Document()) {
  24.         // step 2
  25.         PdfWriter.GetInstance(document, stream);
  26.         // step 3
  27.         document.Open();
  28.         // step 4
  29.         // Create a local destination at the top of the page
  30.         Paragraph p = new Paragraph();
  31.         Chunk top = new Chunk("Country List", FilmFonts.BOLD);
  32.         top.SetLocalDestination("top");
  33.         p.Add(top);
  34.         document.Add(p);
  35.         // create an external link
  36.         Chunk imdb = new Chunk("Internet Movie Database", FilmFonts.ITALIC);
  37.         imdb.SetAnchor(new Uri("http://www.imdb.com/"));
  38.         p = new Paragraph(
  39.           "Click on a country, and you'll get a list of movies, containing links to the "
  40.         );
  41.         p.Add(imdb);
  42.         p.Add(".");
  43.         document.Add(p);
  44.         // Create a remote goto
  45.         p = new Paragraph("This list can be found in a ");
  46.         Chunk page1 = new Chunk("separate document");
  47.         page1.SetRemoteGoto("movie_links_1.pdf", 1);
  48.         p.Add(page1);
  49.         p.Add(".");
  50.         document.Add(p);
  51.         document.Add(Chunk.NEWLINE);
  52.        
  53.         var SQL =
  54. @"SELECT DISTINCT mc.country_id, c.country, count(*) AS c
  55. FROM film_country c, film_movie_country mc
  56. WHERE c.id = mc.country_id
  57. GROUP BY mc.country_id, country ORDER BY c DESC";        
  58.         // Create a database connection and statement
  59.         using (var c =  AdoDB.Provider.CreateConnection()) {
  60.           c.ConnectionString = AdoDB.CS;
  61.           using (DbCommand cmd = c.CreateCommand()) {
  62.             cmd.CommandText = SQL;        
  63.             c.Open();            
  64.             using (var r = cmd.ExecuteReader()) {
  65.               while (r.Read()) {
  66.               // add country with remote goto
  67.                 Paragraph country = new Paragraph(r["country"].ToString());
  68.                 country.Add(": ");
  69.                 Chunk link = new Chunk(string.Format(
  70.                   "{0} movies", Convert.ToInt32(r["c"])
  71.                 ));
  72.                 link.SetRemoteGoto(
  73.                   "movie_links_1.pdf", r["country_id"].ToString()
  74.                 );
  75.                 country.Add(link);
  76.                 document.Add(country);
  77.               }
  78.             }
  79.           }
  80.         }      
  81.         document.Add(Chunk.NEWLINE);
  82.         // Create local goto to top
  83.         p = new Paragraph("Go to ");
  84.         top = new Chunk("top");
  85.         top.SetLocalGoto("top");
  86.         p.Add(top);
  87.         p.Add(".");
  88.         document.Add(p);        
  89.       }
  90.     }
  91. // ===========================================================================
  92.   }
  93. }
MovieHistory.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.Chapter02 {
  16.   public class MovieHistory : IWriter {
  17. // ===========================================================================
  18.     /** The different epochs. */
  19.     public static readonly string[] EPOCH = {
  20.       "Forties", "Fifties", "Sixties", "Seventies", "Eighties",
  21.       "Nineties", "Twenty-first Century"
  22.     };
  23.     /** The fonts for the title. */
  24.     public static Font[] FONT = new Font[4];
  25.     static MovieHistory() {
  26.       FONT[0] = new Font(Font.FontFamily.HELVETICA, 24);
  27.       FONT[1] = new Font(Font.FontFamily.HELVETICA, 18);
  28.       FONT[2] = new Font(Font.FontFamily.HELVETICA, 14);
  29.       FONT[3] = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
  30.     }
  31. // ---------------------------------------------------------------------------
  32.     public void Write(Stream stream) {
  33.       // step 1
  34.       using (Document document = new Document()) {
  35.         // step 2
  36.         PdfWriter.GetInstance(document, stream);
  37.         // step 3
  38.         document.Open();
  39.         // step 4
  40.         int epoch = -1;
  41.         int currentYear = 0;
  42.         Paragraph title = null;
  43.         Chapter chapter = null;
  44.         Section section = null;
  45.         Section subsection = null;        
  46.         IEnumerable movies = PojoFactory.GetMovies(true);
  47.         // loop over the movies
  48.         foreach (Movie movie in movies) {
  49.           int yr = movie.Year;
  50.         // add the chapter if we're in a new epoch
  51.           if (epoch < (yr - 1940) / 10) {
  52.             epoch = (yr - 1940) / 10;
  53.             if (chapter != null) {
  54.               document.Add(chapter);
  55.             }
  56.             title = new Paragraph(EPOCH[epoch], FONT[0]);
  57.             chapter = new Chapter(title, epoch + 1);
  58.           }
  59.           // switch to a new year
  60.           if (currentYear < yr) {
  61.               currentYear = yr;
  62.               title = new Paragraph(
  63.                 string.Format("The year {0}", yr), FONT[1]
  64.               );
  65.               section = chapter.AddSection(title);
  66.               section.BookmarkTitle = yr.ToString();
  67.               section.Indentation = 30;
  68.               section.BookmarkOpen = false;
  69.               section.NumberStyle = Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT;
  70.               section.Add(new Paragraph(
  71.                 string.Format("Movies from the year {0}:", yr)
  72.               ));
  73.           }
  74.           title = new Paragraph(movie.Title, FONT[2]);
  75.           subsection = section.AddSection(title);
  76.           subsection.IndentationLeft = 20;
  77.           subsection.NumberDepth = 1;
  78.           subsection.Add(new Paragraph("Duration: " + movie.Duration.ToString(), FONT[3]));
  79.           subsection.Add(new Paragraph("Director(s):", FONT[3]));
  80.           subsection.Add(PojoToElementFactory.GetDirectorList(movie));
  81.           subsection.Add(new Paragraph("Countries:", FONT[3]));
  82.           subsection.Add(PojoToElementFactory.GetCountryList(movie));
  83.         }
  84.         document.Add(chapter);
  85.       }
  86.     }
  87. // ===========================================================================
  88.   }
  89. }
MoviePosters1.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.Chapter02 {
  16.   public class MoviePosters1 : IWriter {
  17. // ===========================================================================
  18.     public void Write(Stream stream) {
  19.       string RESOURCE = Utility.ResourcePosters;
  20.       // step 1
  21.       using (Document document = new Document()) {
  22.         // step 2
  23.         PdfWriter.GetInstance(document, stream);
  24.         // step 3
  25.         document.Open();
  26.         Rectangle rect = new Rectangle(0, 806, 36, 842);
  27.         rect.BackgroundColor = BaseColor.RED;
  28.         document.Add(rect);
  29.         // step 4
  30.         IEnumerable movies = PojoFactory.GetMovies();
  31.         foreach (Movie movie in movies) {
  32.           document.Add(new Paragraph(movie.MovieTitle));
  33.           // Add an image
  34.           document.Add(
  35.             Image.GetInstance(Path.Combine(RESOURCE, movie.Imdb + ".jpg"))
  36.           );
  37.         }
  38.       }
  39.     }
  40. // ===========================================================================
  41.   }
  42. }
MoviePosters2.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.Chapter02 {
  16.   public class MoviePosters2 : IWriter {
  17. // ===========================================================================
  18.     public void Write(Stream stream) {
  19.       string RESOURCE = Utility.ResourcePosters;
  20.       // step 1
  21.       using (Document document = new Document()) {
  22.         // step 2
  23.         PdfWriter.GetInstance(document, stream)
  24.           .StrictImageSequence = true;
  25.         ;
  26.         // step 3
  27.         document.Open();
  28.         Rectangle rect = new Rectangle(0, 806, 36, 842);
  29.         rect.BackgroundColor = BaseColor.RED;
  30.         document.Add(rect);
  31.         // step 4
  32.         IEnumerable movies = PojoFactory.GetMovies();
  33.         foreach (Movie movie in movies) {
  34.           document.Add(new Paragraph(movie.MovieTitle));
  35.           // Add an image
  36.           document.Add(
  37.             Image.GetInstance(Path.Combine(RESOURCE, movie.Imdb + ".jpg"))
  38.           );
  39.         }
  40.       }
  41.     }
  42. // ===========================================================================
  43.   }
  44. }
MoviePosters3.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.Chapter02 {
  16.   public class MoviePosters3 : IWriter {
  17. // ===========================================================================
  18.     public void Write(Stream stream) {
  19.       string RESOURCE = Utility.ResourcePosters;
  20.       // step 1
  21.       using (Document document = new Document()) {
  22.         // step 2
  23.         var writer = PdfWriter.GetInstance(document, stream);
  24.         writer.StrictImageSequence = true;
  25.         writer.InitialLeading = 18;
  26.         // step 3
  27.         document.Open();
  28.         Rectangle rect = new Rectangle(0, 806, 36, 842);
  29.         rect.BackgroundColor = BaseColor.RED;
  30.         document.Add(rect);
  31.         // step 4
  32.         IEnumerable movies = PojoFactory.GetMovies();
  33.         foreach (Movie movie in movies) {
  34.         // Create an image
  35.           Image img = Image.GetInstance(
  36.             Path.Combine(RESOURCE, movie.Imdb + ".jpg")
  37.           );
  38.           img.Alignment = Image.ALIGN_LEFT | Image.TEXTWRAP;
  39.           img.Border = Image.BOX;
  40.           img.BorderWidth = 10;
  41.           img.BorderColor = BaseColor.WHITE;
  42.           img.ScaleToFit(1000, 72);
  43.           document.Add(img);
  44.           // Create text elements
  45.           document.Add(new Paragraph(movie.MovieTitle, FilmFonts.BOLD));
  46.           document.Add(PojoToElementFactory.GetCountryList(movie));
  47.           document.Add(new Paragraph(
  48.             String.Format("Year: {0}", movie.Year)
  49.           ));
  50.           document.Add(new Paragraph(
  51.               String.Format("Duration: {0} minutes", movie.Duration))
  52.           );
  53.           document.Add(new Paragraph("Directors:"));
  54.           document.Add(PojoToElementFactory.GetDirectorList(movie));
  55.           document.Add(Chunk.NEWLINE);
  56.         }
  57.       }
  58.     }
  59. // ===========================================================================
  60.   }
  61. }
RiverPhoenix.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. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  12.  
  13. namespace kuujinbo.iTextInAction2Ed.Chapter02 {
  14.   public class RiverPhoenix : IWriter {
  15. // ===========================================================================
  16.     public readonly string RESOURCE = Utility.ResourcePosters;
  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(
  27.           "Movies featuring River Phoenix", FilmFonts.BOLD
  28.         ));
  29.         document.Add(CreateParagraph(
  30.           "My favorite movie featuring River Phoenix was ", "0092005"
  31.         ));
  32.         document.Add(CreateParagraph(
  33.           "River Phoenix was nominated for an academy award for his role in ", "0096018"
  34.         ));
  35.         document.Add(CreateParagraph(
  36.           "River Phoenix played the young Indiana Jones in ", "0097576"
  37.         ));
  38.         document.Add(CreateParagraph(
  39.           "His best role was probably in ", "0102494"
  40.         ));
  41.       }
  42.     }
  43. // ---------------------------------------------------------------------------
  44.     /**
  45.      * Creates a paragraph with some text about a movie with River Phoenix,
  46.      * and a poster of the corresponding movie.
  47.      * @param text the text about the movie
  48.      * @param imdb the IMDB code referring to the poster
  49.      */
  50.     public Paragraph CreateParagraph(String text, String imdb) {
  51.       Paragraph p = new Paragraph(text);
  52.       Image img = Image.GetInstance(Path.Combine(RESOURCE, imdb + ".jpg"));
  53.       img.ScaleToFit(1000, 72);
  54.       img.RotationDegrees = -30;
  55.       p.Add(new Chunk(img, 0, -15, true));
  56.       return p;
  57.     }
  58. // ===========================================================================
  59.   }
  60. }
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