Chapter 7: Making documents interactive

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

10th October 2015
admin-marketing

Switch code for this example

NamedActions.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.Chunk;
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.Element;
  16. import com.itextpdf.text.Font;
  17. import com.itextpdf.text.Phrase;
  18. import com.itextpdf.text.Rectangle;
  19. import com.itextpdf.text.Font.FontFamily;
  20. import com.itextpdf.text.pdf.PdfAction;
  21. import com.itextpdf.text.pdf.PdfContentByte;
  22. import com.itextpdf.text.pdf.PdfPTable;
  23. import com.itextpdf.text.pdf.PdfReader;
  24. import com.itextpdf.text.pdf.PdfStamper;
  25.  
  26. import part1.chapter03.MovieTemplates;
  27.  
  28. public class NamedActions {
  29.     /** The resulting PDF. */
  30.     public static final String RESULT
  31.         = "results/part2/chapter07/named_actions.pdf";
  32.  
  33.     /**
  34.      * Manipulates a PDF file src with the file dest as result
  35.      * @param src the original PDF
  36.      * @param dest the resulting PDF
  37.      * @throws IOException
  38.      * @throws DocumentException
  39.      */
  40.     public void manipulatePdf(String src, String dest)
  41.         throws IOException, DocumentException {
  42.         // Create a table with named actions
  43.         Font symbol = new Font(FontFamily.SYMBOL, 20);
  44.         PdfPTable table = new PdfPTable(4);
  45.         table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
  46.         table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
  47.         Chunk first = new Chunk(String.valueOf((char)220), symbol);
  48.         first.setAction(new PdfAction(PdfAction.FIRSTPAGE));
  49.         table.addCell(new Phrase(first));
  50.         Chunk previous = new Chunk(String.valueOf((char)172), symbol);
  51.         previous.setAction(new PdfAction(PdfAction.PREVPAGE));
  52.         table.addCell(new Phrase(previous));
  53.         Chunk next = new Chunk(String.valueOf((char)174), symbol);
  54.         next.setAction(new PdfAction(PdfAction.NEXTPAGE));
  55.         table.addCell(new Phrase(next));
  56.         Chunk last = new Chunk(String.valueOf((char)222), symbol);
  57.         last.setAction(new PdfAction(PdfAction.LASTPAGE));
  58.         table.addCell(new Phrase(last));
  59.         table.setTotalWidth(120);
  60.        
  61.         // Create a reader
  62.         PdfReader reader = new PdfReader(src);
  63.         // Create a stamper
  64.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  65.         // Add the table to each page
  66.         PdfContentByte canvas;
  67.         for (int i = 0; i < reader.getNumberOfPages(); ) {
  68.             canvas = stamper.getOverContent(++i);
  69.             table.writeSelectedRows(0, -1, 696, 36, canvas);
  70.         }
  71.         // Close the stamper
  72.         stamper.close();
  73.         reader.close();
  74.     }
  75.  
  76.     /**
  77.      * Main method.
  78.      * @param    args    no arguments needed
  79.      * @throws DocumentException
  80.      * @throws IOException
  81.      */
  82.     public static void main(String[] args)
  83.         throws IOException, DocumentException {
  84.         MovieTemplates.main(args);
  85.         new NamedActions().manipulatePdf(MovieTemplates.RESULT, RESULT);
  86.     }
  87. }
LinkActions.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 part2.chapter07;
  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. import java.util.HashMap;
  17.  
  18. import part1.chapter02.MovieLinks1;
  19.  
  20. import com.lowagie.database.DatabaseConnection;
  21. import com.lowagie.database.HsqldbConnection;
  22. import com.lowagie.filmfestival.FilmFonts;
  23. import com.itextpdf.text.Chunk;
  24. import com.itextpdf.text.Document;
  25. import com.itextpdf.text.DocumentException;
  26. import com.itextpdf.text.Paragraph;
  27. import com.itextpdf.text.pdf.PdfAction;
  28. import com.itextpdf.text.pdf.PdfReader;
  29. import com.itextpdf.text.pdf.PdfWriter;
  30. import com.itextpdf.text.pdf.SimpleNamedDestination;
  31.  
  32. public class LinkActions {
  33.  
  34.     /** The resulting PDF file. */
  35.     public static final String RESULT1
  36.         = "results/part2/chapter07/movie_links_1.pdf";
  37.     /** The resulting PDF file. */
  38.     public static final String RESULT2
  39.         = "results/part2/chapter07/movie_links_2.pdf";
  40.     /** The resulting XML file. */
  41.     public static final String RESULT3
  42.         = "results/part2/chapter07/destinations.xml";
  43.  
  44.     /**
  45.      * Creates a PDF document.
  46.      * @param filename the path to the new PDF document
  47.      * @throws    DocumentException
  48.      * @throws    IOException
  49.      * @throws    SQLException
  50.      */
  51.     protected void createPdf(String filename)
  52.         throws IOException, DocumentException, SQLException {
  53.         // Open the database connection
  54.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  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.         // Add text with a local destination
  63.         Paragraph p = new Paragraph();
  64.         Chunk top = new Chunk("Country List", FilmFonts.BOLD);
  65.         top.setLocalDestination("top");
  66.         p.add(top);
  67.         document.add(p);
  68.         // Add text with a link to an external URL
  69.         Chunk imdb = new Chunk("Internet Movie Database", FilmFonts.ITALIC);
  70.         imdb.setAction(new PdfAction(new URL("http://www.imdb.com/")));
  71.         p = new Paragraph(
  72.             "Click on a country, and you'll get a list of movies, containing links to the ");
  73.         p.add(imdb);
  74.         p.add(".");
  75.         document.add(p);
  76.         // Add text with a remote goto
  77.         p = new Paragraph("This list can be found in a ");
  78.         Chunk page1 = new Chunk("separate document");
  79.         page1.setAction(new PdfAction("movie_links_1.pdf", 1));
  80.         p.add(page1);
  81.         p.add(".");
  82.         document.add(p);
  83.         document.add(Chunk.NEWLINE);
  84.         // Get a list with countries from the database
  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 WHERE c.id = mc.country_id "
  89.             + "GROUP BY mc.country_id, country ORDER BY c DESC");
  90.         // Loop over the countries
  91.         while (rs.next()) {
  92.             Paragraph country = new Paragraph(rs.getString("country"));
  93.             country.add(": ");
  94.             Chunk link = new Chunk(String.format("%d movies", rs.getInt("c")));
  95.             link.setAction(
  96.                 PdfAction.gotoRemotePage("movie_links_1.pdf", rs.getString("country_id"), false, true));
  97.             country.add(link);
  98.             document.add(country);
  99.         }
  100.         document.add(Chunk.NEWLINE);
  101.         // Add text with a local goto
  102.         p = new Paragraph("Go to ");
  103.         top = new Chunk("top");
  104.         top.setAction(PdfAction.gotoLocalPage("top", false));
  105.         p.add(top);
  106.         p.add(".");
  107.         document.add(p);
  108.         // step 5
  109.         document.close();
  110.         // Close the database connection
  111.         connection.close();
  112.     }
  113.    
  114.     /**
  115.      * Create an XML file with named destinations
  116.      * @param src The path to the PDF with the destinations
  117.      * @param dest The path to the XML file
  118.      * @throws IOException
  119.      */
  120.     public void createXml(String src, String dest) throws IOException {
  121.         PdfReader reader = new PdfReader(src);
  122.         HashMap map = SimpleNamedDestination.getNamedDestination(reader, false);
  123.         SimpleNamedDestination.exportToXML(map, new FileOutputStream(dest),
  124.                 "ISO8859-1", true);
  125.         reader.close();
  126.     }
  127.  
  128.     /**
  129.      * Main method.
  130.      * @param    args    no arguments needed
  131.      * @throws DocumentException
  132.      * @throws IOException
  133.      * @throws SQLException
  134.      */
  135.     public static void main(String[] args)
  136.         throws IOException, DocumentException, SQLException {
  137.         new MovieLinks1().createPdf(RESULT1);
  138.         LinkActions actions = new LinkActions();
  139.         actions.createPdf(RESULT2);
  140.         actions.createXml(RESULT1, RESULT3);
  141.     }
  142. }
ConcatenateNamedDestinations.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13.  
  14. import com.itextpdf.text.Document;
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.pdf.PdfCopy;
  17. import com.itextpdf.text.pdf.PdfReader;
  18. import com.itextpdf.text.pdf.PdfStamper;
  19. import com.itextpdf.text.pdf.SimpleNamedDestination;
  20.  
  21. import part1.chapter02.MovieLinks1;
  22.  
  23. public class ConcatenateNamedDestinations {
  24.  
  25.     /** The resulting PDF file. */
  26.     public static String RESULT1
  27.         = "results/part2/chapter07/concatenated_links_1.pdf";
  28.     /** The resulting PDF file. */
  29.     public static String RESULT2
  30.          = "results/part2/chapter07/concatenated_links_2.pdf";
  31.  
  32.     /**
  33.      * Main method.
  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.         // Use previous examples to create PDF files
  42.         new MovieLinks1().createPdf(LinkActions.RESULT1);
  43.         new LinkActions().createPdf(LinkActions.RESULT2);
  44.         // Create readers.
  45.         PdfReader[] readers = {
  46.                 new PdfReader(LinkActions.RESULT2),
  47.                 new PdfReader(LinkActions.RESULT1) };
  48.         // step 1
  49.         Document document = new Document();
  50.         // step 2
  51.         PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT1));
  52.         // step 3
  53.         document.open();
  54.         // step 4
  55.         int n;
  56.         // copy the pages of the different PDFs into one document
  57.         for (int i = 0; i < readers.length; i++) {
  58.             readers[i].consolidateNamedDestinations();
  59.             n = readers[i].getNumberOfPages();
  60.             for (int page = 0; page < n; ) {
  61.                 copy.addPage(copy.getImportedPage(readers[i], ++page));
  62.             }
  63.         }
  64.         // Add named destination  
  65.         copy.addNamedDestinations(
  66.             // from the second document
  67.             SimpleNamedDestination.getNamedDestination(readers[1], false),
  68.             // using the page count of the first document as offset
  69.             readers[0].getNumberOfPages());
  70.         // step 5
  71.         document.close();
  72.         readers[0].close();
  73.         readers[1].close();
  74.        
  75.         // Create a reader
  76.         PdfReader reader = new PdfReader(RESULT1);
  77.         // Convert the remote destinations into local destinations
  78.         reader.makeRemoteNamedDestinationsLocal();
  79.         // Create a new PDF containing the local destinations
  80.         PdfStamper stamper
  81.             = new PdfStamper(reader, new FileOutputStream(RESULT2));
  82.         stamper.close();
  83.         reader.close();
  84.     }
  85. }
TimetableDestinations.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14.  
  15. import com.itextpdf.text.Chunk;
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.Element;
  18. import com.itextpdf.text.Font;
  19. import com.itextpdf.text.Phrase;
  20. import com.itextpdf.text.Rectangle;
  21. import com.itextpdf.text.Font.FontFamily;
  22. import com.itextpdf.text.pdf.PdfAction;
  23. import com.itextpdf.text.pdf.PdfContentByte;
  24. import com.itextpdf.text.pdf.PdfDestination;
  25. import com.itextpdf.text.pdf.PdfPTable;
  26. import com.itextpdf.text.pdf.PdfReader;
  27. import com.itextpdf.text.pdf.PdfStamper;
  28.  
  29. import part1.chapter03.MovieTemplates;
  30.  
  31. public class TimetableDestinations {
  32.     /** The resulting PDF. */
  33.     public static final String RESULT
  34.         = "results/part2/chapter07/timetable_destinations.pdf";
  35.     /** The font that is used for the navigation links. */
  36.     public static final Font SYMBOL = new Font(FontFamily.SYMBOL, 20);
  37.     /** A list to cache all the possible actions */
  38.     public List actions;
  39.  
  40.     /**
  41.      * Manipulates a PDF file src with the file dest as result
  42.      * @param src the original PDF
  43.      * @param dest the resulting PDF
  44.      * @throws IOException
  45.      * @throws DocumentException
  46.      */
  47.     public void manipulatePdf(String src, String dest)
  48.         throws IOException, DocumentException {
  49.         // Create the reader
  50.         PdfReader reader = new PdfReader(src);
  51.         int n = reader.getNumberOfPages();
  52.         // Create the stamper
  53.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  54.         // Make a list with all the possible actions
  55.         actions = new ArrayList();
  56.         PdfDestination d;
  57.         for (int i = 0; i < n; ) {
  58.             d = new PdfDestination(PdfDestination.FIT);
  59.             actions.add(PdfAction.gotoLocalPage(++i, d, stamper.getWriter()));
  60.         }
  61.         // Add a navigation table to every page
  62.         PdfContentByte canvas;
  63.         for (int i = 0; i < n; ) {
  64.             canvas = stamper.getOverContent(++i);
  65.             createNavigationTable(i, n).writeSelectedRows(0, -1, 696, 36, canvas);
  66.         }
  67.         // Close the stamper
  68.         stamper.close();
  69.         reader.close();
  70.     }
  71.    
  72.     /**
  73.      * Create a table that can be used as a footer
  74.      * @param pagenumber the page that will use the table as footer
  75.      * @param total the total number of pages
  76.      * @return a tabel
  77.      */
  78.     public PdfPTable createNavigationTable(int pagenumber, int total) {
  79.         PdfPTable table = new PdfPTable(4);
  80.         table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
  81.         table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
  82.         Chunk first = new Chunk(String.valueOf((char)220), SYMBOL);
  83.         first.setAction(actions.get(0));
  84.         table.addCell(new Phrase(first));
  85.         Chunk previous = new Chunk(String.valueOf((char)172), SYMBOL);
  86.         previous.setAction(actions.get(pagenumber - 2 < 0 ? 0 : pagenumber - 2));
  87.         table.addCell(new Phrase(previous));
  88.         Chunk next = new Chunk(String.valueOf((char)174), SYMBOL);
  89.         next.setAction(actions.get(pagenumber >= total ? total - 1 : pagenumber));
  90.         table.addCell(new Phrase(next));
  91.         Chunk last = new Chunk(String.valueOf((char)222), SYMBOL);
  92.         last.setAction(actions.get(total - 1));
  93.         table.addCell(new Phrase(last));
  94.         table.setTotalWidth(120);
  95.         return table;
  96.     }
  97.  
  98.     /**
  99.      * Main method.
  100.      * @param    args    no arguments needed
  101.      * @throws DocumentException
  102.      * @throws IOException
  103.      */  
  104.     public static void main(String[] args)
  105.         throws IOException, DocumentException {
  106.         MovieTemplates.main(args);
  107.         new TimetableDestinations().manipulatePdf(
  108.             MovieTemplates.RESULT, RESULT);
  109.     }
  110. }
AddVersionChecker.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13.  
  14. import part1.chapter01.HelloWorld;
  15.  
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.Utilities;
  18. import com.itextpdf.text.pdf.PdfReader;
  19. import com.itextpdf.text.pdf.PdfStamper;
  20.  
  21. public class AddVersionChecker {
  22.  
  23.     /** The resulting PDF file. */
  24.     public static final String RESULT
  25.         = "results/part2/chapter07/version_checker.pdf";
  26.     /** Path to a resource. */
  27.     public static final String RESOURCE
  28.         = "resources/js/viewer_version.js";
  29.  
  30.     /**
  31.      * Main method.
  32.      *
  33.      * @param    args    no arguments needed
  34.      * @throws DocumentException
  35.      * @throws IOException
  36.      * @throws SQLException
  37.      */
  38.     public static void main(String[] args)
  39.         throws IOException, DocumentException, SQLException {
  40.         // Use a previous example to create a PDF
  41.         HelloWorld.main(args);
  42.         // Create a reader
  43.         PdfReader reader = new PdfReader(HelloWorld.RESULT);
  44.         // Create a stamper
  45.         PdfStamper stamper
  46.             = new PdfStamper(reader, new FileOutputStream(RESULT));
  47.         // Add some javascript
  48.         stamper.addJavaScript(Utilities.readFileToString(RESOURCE));
  49.         // Close the stamper
  50.         stamper.close();
  51.         reader.close();
  52.     }
  53. }
FindDirectors.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 part2.chapter07;
  9.  
  10. import java.io.ByteArrayOutputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.io.UnsupportedEncodingException;
  14. import java.sql.ResultSet;
  15. import java.sql.SQLException;
  16. import java.sql.Statement;
  17.  
  18. import part1.chapter04.NestedTables;
  19.  
  20. import com.lowagie.database.DatabaseConnection;
  21. import com.lowagie.database.HsqldbConnection;
  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.Utilities;
  27. import com.itextpdf.text.pdf.PdfAction;
  28. import com.itextpdf.text.pdf.PdfCopy;
  29. import com.itextpdf.text.pdf.PdfReader;
  30. import com.itextpdf.text.pdf.PdfWriter;
  31.  
  32. public class FindDirectors {
  33.    
  34.     /** The resulting PDF file. */
  35.     public static final String RESULT
  36.         = "results/part2/chapter07/find_directors.pdf";
  37.  
  38.     /** Path to the resources. */
  39.     public static final String RESOURCE
  40.         = "resources/js/find_director.js";
  41.    
  42.     /**
  43.      * Creates a PDF file with director names.
  44.      * @param filename the name of the PDF file that needs to be created.
  45.      * @throws DocumentException
  46.      * @throws IOException
  47.      * @throws SQLException
  48.      */
  49.     public void createPdf(String filename)
  50.         throws IOException, DocumentException, SQLException {
  51.         // Create a database connection and statement
  52.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  53.         Statement stm = connection.createStatement();
  54.         // step 1
  55.         Document tmp = new Document();
  56.         // step 2
  57.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  58.         PdfWriter writer = PdfWriter.getInstance(tmp, baos);
  59.         // step 3
  60.         tmp.open();
  61.         // step 4
  62.         ResultSet rs = stm.executeQuery(
  63.            "SELECT name, given_name FROM film_director ORDER BY name, given_name");
  64.         while (rs.next()) {
  65.             tmp.add(createDirectorParagraph(writer, rs));
  66.         }
  67.         // step 5
  68.         tmp.close();
  69.         // Close the database connection and statement
  70.         stm.close();
  71.         connection.close();
  72.        
  73.         // Create readers
  74.         PdfReader[] readers = {
  75.                 new PdfReader(baos.toByteArray()),
  76.                 new PdfReader(NestedTables.RESULT) };
  77.         // step 1
  78.         Document document = new Document();
  79.         // step 2
  80.         PdfCopy copy = new PdfCopy(document, new FileOutputStream(filename));
  81.         // step 3
  82.         document.open();
  83.         // step 4
  84.         copy.addJavaScript(Utilities.readFileToString(RESOURCE));
  85.         int n;
  86.         for (int i = 0; i < readers.length; i++) {
  87.             n = readers[i].getNumberOfPages();
  88.             for (int page = 0; page < n; ) {
  89.                 copy.addPage(copy.getImportedPage(readers[i], ++page));
  90.             }
  91.         }
  92.         // step 5
  93.         document.close();
  94.         readers[0].close();
  95.         readers[1].close();
  96.     }
  97.    
  98.     /**
  99.      * Creates a Phrase with the name and given name of a director
  100.      * using different fonts.
  101.      * @param rs the ResultSet containing director records.
  102.      */
  103.     public Paragraph createDirectorParagraph(PdfWriter writer, ResultSet rs)
  104.         throws UnsupportedEncodingException, SQLException {
  105.         String n = new String(rs.getBytes("name"), "UTF-8");
  106.         Chunk name = new Chunk(n);
  107.         name.setAction(PdfAction.javaScript(
  108.                 String.format("findDirector('%s');", n), writer));
  109.         name.append(", ");
  110.         name.append(new String(rs.getBytes("given_name"), "UTF-8"));
  111.         return new Paragraph(name);
  112.     }
  113.    
  114.     /**
  115.      * Main method.
  116.      *
  117.      * @param    args    no arguments needed
  118.      * @throws DocumentException
  119.      * @throws IOException
  120.      * @throws SQLException
  121.      */
  122.     public static void main(String[] args)
  123.         throws IOException, DocumentException, SQLException {
  124.         NestedTables.main(args);
  125.         new FindDirectors().createPdf(RESULT);
  126.     }
  127. }
LaunchAction.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.Chunk;
  14. import com.itextpdf.text.Document;
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.Paragraph;
  17. import com.itextpdf.text.pdf.PdfAction;
  18. import com.itextpdf.text.pdf.PdfWriter;
  19.  
  20. public class LaunchAction {
  21.     /** The resulting PDF file. */
  22.     public static final String RESULT
  23.         = "results/part2/chapter07/launch_action.pdf";
  24.  
  25.     /**
  26.      * Creates a PDF document.
  27.      * @param filename the path to the new PDF document
  28.      * @throws    DocumentException
  29.      * @throws    IOException
  30.      */
  31.     public void createPdf(String filename)
  32.     throws IOException, DocumentException {
  33.         // step 1
  34.         Document document = new Document();
  35.         // step 2
  36.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  37.         // step 3
  38.         document.open();
  39.         // step 4
  40.         Paragraph p = new Paragraph(new Chunk(
  41.             "Click to open test.txt in Notepad.")
  42.             .setAction(new PdfAction("c:/windows/notepad.exe",
  43.             "test.txt", "open", "C:\\itext-core\\book\\resources\\txt")));
  44.         document.add(p);
  45.         // step 5
  46.         document.close();
  47.     }
  48.    
  49.     /**
  50.      * Main method.
  51.      * @param    args    no arguments needed
  52.      * @throws DocumentException
  53.      * @throws IOException
  54.      */
  55.     public static void main(String[] args)
  56.         throws IOException, DocumentException {
  57.         new LaunchAction().createPdf(RESULT);
  58.     }
  59. }
PrintTimeTable.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import part1.chapter03.MovieTemplates;
  14.  
  15. import com.itextpdf.text.Chunk;
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.Element;
  18. import com.itextpdf.text.Phrase;
  19. import com.itextpdf.text.Utilities;
  20. import com.itextpdf.text.pdf.ColumnText;
  21. import com.itextpdf.text.pdf.PdfAction;
  22. import com.itextpdf.text.pdf.PdfContentByte;
  23. import com.itextpdf.text.pdf.PdfReader;
  24. import com.itextpdf.text.pdf.PdfStamper;
  25.  
  26. public class PrintTimeTable {
  27.     /** The resulting PDF. */
  28.     public static final String RESULT
  29.         = "results/part2/chapter07/print_timetable.pdf";
  30.  
  31.     /** Path to the resources. */
  32.     public static final String RESOURCE
  33.         = "resources/js/print_page.js";
  34.  
  35.     /**
  36.      * Manipulates a PDF file src with the file dest as result
  37.      * @param src the original PDF
  38.      * @param resource a resource that will be used as advertisement
  39.      * @param dest the resulting PDF
  40.      * @throws IOException
  41.      * @throws DocumentException
  42.      */
  43.     public void manipulatePdf(String src, String dest)
  44.         throws IOException, DocumentException {
  45.         // Create the reader
  46.         PdfReader reader = new PdfReader(src);
  47.         int n = reader.getNumberOfPages();
  48.         // Create the stamper
  49.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  50.         // Add JavaScript
  51.         stamper.addJavaScript(Utilities.readFileToString(RESOURCE));
  52.         // Create a Chunk with a chained action
  53.         PdfContentByte canvas;
  54.         Chunk chunk = new Chunk("print this page");
  55.         PdfAction action = PdfAction.javaScript(
  56.             "app.alert('Think before you print!');", stamper.getWriter());
  57.         action.next(PdfAction.javaScript(
  58.             "printCurrentPage(this.pageNum);", stamper.getWriter()));
  59.         action.next(new PdfAction("http://www.panda.org/savepaper/"));
  60.         chunk.setAction(action);
  61.         Phrase phrase = new Phrase(chunk);
  62.         // Add this Chunk to every page
  63.         for (int i = 0; i < n; ) {
  64.             canvas = stamper.getOverContent(++i);
  65.             ColumnText.showTextAligned(
  66.                 canvas, Element.ALIGN_RIGHT, phrase, 816, 18, 0);
  67.         }
  68.         // Close the stamper
  69.         stamper.close();
  70.         reader.close();
  71.     }
  72.  
  73.     /**
  74.      * Main method.
  75.      * @param    args    no arguments needed
  76.      * @throws DocumentException
  77.      * @throws IOException
  78.      */
  79.     public static void main(String[] args)
  80.         throws IOException, DocumentException {
  81.         MovieTemplates.main(args);
  82.         new PrintTimeTable().manipulatePdf(
  83.             MovieTemplates.RESULT, RESULT);
  84.     }
  85. }
EventsAndActions.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import part1.chapter03.MovieTemplates;
  14.  
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.pdf.PdfAction;
  17. import com.itextpdf.text.pdf.PdfDestination;
  18. import com.itextpdf.text.pdf.PdfReader;
  19. import com.itextpdf.text.pdf.PdfStamper;
  20. import com.itextpdf.text.pdf.PdfWriter;
  21.  
  22. public class EventsAndActions {
  23.     /** The resulting PDF. */
  24.     public static final String RESULT
  25.         = "results/part2/chapter07/events_and_actions.pdf";
  26.  
  27.     /**
  28.      * Manipulates a PDF file src with the file dest as result
  29.      * @param src the original PDF
  30.      * @param resource a resource that will be used as advertisement
  31.      * @param dest the resulting PDF
  32.      * @throws IOException
  33.      * @throws DocumentException
  34.      */
  35.     public void manipulatePdf(String src, String dest)
  36.         throws IOException, DocumentException {
  37.         // Create a reader
  38.         PdfReader reader = new PdfReader(src);
  39.         // Create a stamper
  40.         PdfStamper stamper = new PdfStamper(reader,
  41.                 new FileOutputStream(dest));
  42.         // Get the writer (to add actions and annotations)
  43.         PdfWriter writer = stamper.getWriter();
  44.         PdfAction action = PdfAction.gotoLocalPage(2,
  45.             new PdfDestination(PdfDestination.FIT), writer);
  46.         writer.setOpenAction(action);
  47.         action = PdfAction.javaScript(
  48.             "app.alert('Think before you print');", writer);
  49.         writer.setAdditionalAction(PdfWriter.WILL_PRINT, action);
  50.         action = PdfAction.javaScript(
  51.             "app.alert('Think again next time!');", writer);
  52.         writer.setAdditionalAction(PdfWriter.DID_PRINT, action);
  53.         action = PdfAction.javaScript(
  54.             "app.alert('We hope you enjoy the festival');", writer);
  55.         writer.setAdditionalAction(PdfWriter.DOCUMENT_CLOSE, action);
  56.         action = PdfAction.javaScript(
  57.             "app.alert('This day is reserved for people with an accreditation "
  58.             + "or an invitation.');", writer);
  59.         stamper.setPageAction(PdfWriter.PAGE_OPEN, action, 1);
  60.         action = PdfAction.javaScript(
  61.             "app.alert('You can buy tickets for all the other days');", writer);
  62.         stamper.setPageAction(PdfWriter.PAGE_CLOSE, action, 1);
  63.         // Close the stamper
  64.         stamper.close();
  65.         reader.close();
  66.     }
  67.    
  68.     /**
  69.      * Main method creating the PDF.
  70.      * @param    args    no arguments needed
  71.      * @throws DocumentException
  72.      * @throws IOException
  73.      */
  74.     public static void main(String[] args)
  75.         throws IOException, DocumentException {
  76.         MovieTemplates.main(args);
  77.         new EventsAndActions().manipulatePdf(
  78.             MovieTemplates.RESULT, RESULT);
  79.     }
  80. }
CreateOutlineTree.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13. import java.util.HashMap;
  14. import java.util.List;
  15.  
  16. import com.lowagie.database.DatabaseConnection;
  17. import com.lowagie.database.HsqldbConnection;
  18. import com.lowagie.filmfestival.Movie;
  19. import com.lowagie.filmfestival.PojoFactory;
  20. import com.lowagie.filmfestival.PojoToElementFactory;
  21. import com.itextpdf.text.Document;
  22. import com.itextpdf.text.DocumentException;
  23. import com.itextpdf.text.Font;
  24. import com.itextpdf.text.Paragraph;
  25. import com.itextpdf.text.pdf.PdfAction;
  26. import com.itextpdf.text.pdf.PdfDestination;
  27. import com.itextpdf.text.pdf.PdfOutline;
  28. import com.itextpdf.text.pdf.PdfReader;
  29. import com.itextpdf.text.pdf.PdfWriter;
  30. import com.itextpdf.text.BaseColor;
  31. import com.itextpdf.text.pdf.SimpleBookmark;
  32.  
  33. public class CreateOutlineTree {
  34.  
  35.     /** The resulting PDF. */
  36.     public static final String RESULT
  37.         = "results/part2/chapter07/outline_tree.pdf";
  38.     /** An XML representing the outline tree */
  39.     public static final String RESULTXML
  40.         = "results/part2/chapter07/outline_tree.xml";
  41.     /** Pattern of the IMDB urls */
  42.     public static final String RESOURCE
  43.         = "http://imdb.com/title/tt%s/";
  44.     /** JavaScript snippet. */
  45.     public static final String INFO
  46.         = "app.alert('Movie produced in %s; run length: %s');";
  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.         // Create a database connection
  58.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  59.         // step 1
  60.         Document document = new Document();
  61.         // step 2
  62.         PdfWriter writer = PdfWriter.getInstance(document,
  63.                 new FileOutputStream(filename));
  64.         writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
  65.         // step 3
  66.         document.open();
  67.         // step 4
  68.         PdfOutline root = writer.getRootOutline();
  69.         PdfOutline movieBookmark;
  70.         PdfOutline link;
  71.         String title;
  72.         List movies = PojoFactory.getMovies(connection);
  73.         for (Movie movie : movies) {
  74.             title = movie.getMovieTitle();
  75.             if ("3-Iron".equals(title))
  76.                 title = "\ube48\uc9d1";
  77.             movieBookmark = new PdfOutline(root,
  78.                 new PdfDestination(
  79.                     PdfDestination.FITH, writer.getVerticalPosition(true)),
  80.                 title, true);
  81.             movieBookmark.setStyle(Font.BOLD);
  82.             link = new PdfOutline(movieBookmark,
  83.                 new PdfAction(String.format(RESOURCE, movie.getImdb())),
  84.                 "link to IMDB");
  85.             link.setColor(BaseColor.BLUE);
  86.             new PdfOutline(movieBookmark,
  87.                 PdfAction.javaScript(
  88.                     String.format(INFO, movie.getYear(), movie.getDuration()), writer),
  89.                     "instant info");
  90.             document.add(new Paragraph(movie.getMovieTitle()));
  91.             document.add(PojoToElementFactory.getDirectorList(movie));
  92.             document.add(PojoToElementFactory.getCountryList(movie));
  93.         }
  94.         // step 5
  95.         document.close();
  96.         // Close the database connection
  97.         connection.close();
  98.     }
  99.    
  100.     /**
  101.      * Creates an XML file with the bookmarks of a PDF file.
  102.      * @param src the path to the PDF file with the bookmarks
  103.      * @param dest the path to the XML file
  104.      * @throws IOException
  105.      */
  106.     public void createXml(String src, String dest) throws IOException {
  107.         PdfReader reader = new PdfReader(src);
  108.         List list = SimpleBookmark.getBookmark(reader);
  109.         SimpleBookmark.exportToXML(list,
  110.                 new FileOutputStream(dest), "ISO8859-1", true);
  111.         reader.close();
  112.     }
  113.    
  114.     /**
  115.      * Main method.
  116.      * @param    args    no arguments needed
  117.      * @throws DocumentException
  118.      * @throws IOException
  119.      * @throws SQLException
  120.      */
  121.     public static void main(String[] args) throws IOException, DocumentException, SQLException {
  122.         CreateOutlineTree example = new CreateOutlineTree();
  123.         example.createPdf(RESULT);
  124.         example.createXml(RESULT, RESULTXML);
  125.     }
  126. }
BookmarkedTimeTable.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.Date;
  13. import java.sql.SQLException;
  14. import java.util.ArrayList;
  15. import java.util.HashMap;
  16. import java.util.List;
  17.  
  18. import part1.chapter03.MovieTemplates;
  19.  
  20. import com.lowagie.database.DatabaseConnection;
  21. import com.lowagie.database.HsqldbConnection;
  22. import com.lowagie.filmfestival.PojoFactory;
  23. import com.itextpdf.text.DocumentException;
  24. import com.itextpdf.text.pdf.PdfReader;
  25. import com.itextpdf.text.pdf.PdfStamper;
  26.  
  27. public class BookmarkedTimeTable {
  28.    
  29.     /** The resulting PDF. */
  30.     public static final String RESULT
  31.         = "results/part2/chapter07/time_table_bookmarks.pdf";
  32.  
  33.     /**
  34.      * Manipulates a PDF file src with the file dest as result
  35.      * @param src the original PDF
  36.      * @param dest the resulting PDF
  37.      * @throws IOException
  38.      * @throws DocumentException
  39.      * @throws SQLException
  40.      */
  41.     public void manipulatePdf(String src, String dest)
  42.         throws IOException, DocumentException, SQLException {
  43.         // Create a database connection
  44.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  45.         // Create a list with bookmarks
  46.         ArrayList outlines = new ArrayList();
  47.         HashMap map = new HashMap();
  48.         outlines.add(map);
  49.         map.put("Title", "Calendar");
  50.         ArrayList kids = new ArrayList();
  51.         map.put("Kids", kids);
  52.         int page = 1;
  53.         List days = PojoFactory.getDays(connection);
  54.         for (Date day : days) {
  55.             HashMap kid = new HashMap();
  56.             kids.add(kid);
  57.             kid.put("Title", day.toString());
  58.             kid.put("Action", "GoTo");
  59.             kid.put("Page", String.format("%d Fit", page++));
  60.         }
  61.         // Create a reader
  62.         PdfReader reader = new PdfReader(src);
  63.         // Create a stamper
  64.         PdfStamper stamper
  65.             = new PdfStamper(reader, new FileOutputStream(dest));
  66.         stamper.setOutlines(outlines);
  67.         // Close the stamper
  68.         stamper.close();
  69.         reader.close();
  70.         // Close the database connection
  71.         connection.close();
  72.     }
  73.    
  74.     /**
  75.      * Main method creating the PDF.
  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.         MovieTemplates.main(args);
  84.         new BookmarkedTimeTable().manipulatePdf(
  85.             MovieTemplates.RESULT, RESULT);
  86.     }
  87. }
ConcatenateBookmarks.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13. import java.util.ArrayList;
  14. import java.util.HashMap;
  15. import java.util.List;
  16.  
  17. import part1.chapter02.MovieHistory;
  18.  
  19. import com.itextpdf.text.Document;
  20. import com.itextpdf.text.DocumentException;
  21. import com.itextpdf.text.pdf.PdfCopy;
  22. import com.itextpdf.text.pdf.PdfReader;
  23. import com.itextpdf.text.pdf.SimpleBookmark;
  24.  
  25. public class ConcatenateBookmarks {
  26.  
  27.     /** The resulting PDF. */
  28.     public static final String RESULT
  29.         = "results/part2/chapter07/concatenated_bookmarks.pdf";
  30.  
  31.     /**
  32.      * Manipulates a PDF file src with the file dest as result
  33.      * @param src the original PDF
  34.      * @param dest the resulting PDF
  35.      * @throws IOException
  36.      * @throws DocumentException
  37.      */
  38.     public void manipulatePdf(String[] src, String dest)
  39.         throws IOException, DocumentException {
  40.         // step 1
  41.         Document document = new Document();
  42.         // step 2
  43.         PdfCopy copy
  44.             = new PdfCopy(document, new FileOutputStream(dest));
  45.         // step 3
  46.         document.open();
  47.         // step 4
  48.         PdfReader reader;
  49.         int page_offset = 0;
  50.         int n;
  51.         // Create a list for the bookmarks
  52.         ArrayList bookmarks = new ArrayList();
  53.         List tmp;
  54.         for (int i  = 0; i < src.length; i++) {
  55.             reader = new PdfReader(src[i]);
  56.             // merge the bookmarks
  57.             tmp = SimpleBookmark.getBookmark(reader);
  58.             SimpleBookmark.shiftPageNumbers(tmp, page_offset, null);
  59.             bookmarks.addAll(tmp);
  60.             // add the pages
  61.             n = reader.getNumberOfPages();
  62.             page_offset += n;
  63.             for (int page = 0; page < n; ) {
  64.                 copy.addPage(copy.getImportedPage(reader, ++page));
  65.             }
  66.             copy.freeReader(reader);
  67.             reader.close();
  68.         }
  69.         // Add the merged bookmarks
  70.         copy.setOutlines(bookmarks);
  71.         // step 5
  72.         document.close();
  73.     }
  74.  
  75.     /**
  76.      * Main method.
  77.      * @param    args    no arguments needed
  78.      * @throws DocumentException
  79.      * @throws IOException
  80.      * @throws SQLException
  81.      */
  82.     public static void main(String[] args)
  83.         throws IOException, DocumentException, SQLException {
  84.         BookmarkedTimeTable.main(args);
  85.         MovieHistory.main(args);
  86.         new ConcatenateBookmarks().manipulatePdf(
  87.             new String[]{BookmarkedTimeTable.RESULT, MovieHistory.RESULT},
  88.             RESULT);
  89.     }
  90. }
MovieAnnotations1.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13.  
  14. import com.lowagie.database.DatabaseConnection;
  15. import com.lowagie.database.HsqldbConnection;
  16. import com.lowagie.filmfestival.Movie;
  17. import com.lowagie.filmfestival.PojoFactory;
  18. import com.lowagie.filmfestival.PojoToElementFactory;
  19. import com.itextpdf.text.Annotation;
  20. import com.itextpdf.text.Document;
  21. import com.itextpdf.text.DocumentException;
  22. import com.itextpdf.text.Phrase;
  23. import com.itextpdf.text.pdf.PdfWriter;
  24.  
  25. public class MovieAnnotations1 {
  26.  
  27.     /** The resulting PDF. */
  28.     public static final String RESULT
  29.         = "results/part2/chapter07/movie_annotations_1.pdf";
  30.     /** Pattern for an info String. */
  31.     public static final String INFO
  32.         = "Movie produced in %s; run length: %s";
  33.  
  34.     /**
  35.      * Creates a PDF document.
  36.      * @param filename the path to the new PDF document
  37.      * @throws    DocumentException
  38.      * @throws    IOException
  39.      * @throws    SQLExcception
  40.      */
  41.     public void createPdf(String filename)
  42.         throws IOException, DocumentException, SQLException {
  43.         // Create a database connection
  44.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  45.         // step 1
  46.         Document document = new Document();
  47.         // step 2
  48.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  49.         // step 3
  50.         document.open();
  51.         // step 4
  52.         for (Movie movie : PojoFactory.getMovies(connection)) {
  53.             document.add(new Phrase(movie.getMovieTitle()));
  54.             document.add(new Annotation(movie.getTitle(),
  55.                 String.format(INFO, movie.getYear(), movie.getDuration())));
  56.             document.add(PojoToElementFactory.getDirectorList(movie));
  57.             document.add(PojoToElementFactory.getCountryList(movie));
  58.         }
  59.         // step 5
  60.         document.close();
  61.         // Close the database connection
  62.         connection.close();
  63.     }
  64.  
  65.     /**
  66.      * Main method.
  67.      * @param    args    no arguments needed
  68.      * @throws DocumentException
  69.      * @throws IOException
  70.      */
  71.     public static void main(String[] args)
  72.         throws IOException, DocumentException, SQLException {
  73.         MovieAnnotations1 example = new MovieAnnotations1();
  74.         example.createPdf(RESULT);
  75.     }
  76. }
MovieAnnotations2.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13.  
  14. import com.lowagie.database.DatabaseConnection;
  15. import com.lowagie.database.HsqldbConnection;
  16. import com.lowagie.filmfestival.Movie;
  17. import com.lowagie.filmfestival.PojoFactory;
  18. import com.lowagie.filmfestival.PojoToElementFactory;
  19. import com.itextpdf.text.Chunk;
  20. import com.itextpdf.text.Document;
  21. import com.itextpdf.text.DocumentException;
  22. import com.itextpdf.text.Phrase;
  23. import com.itextpdf.text.pdf.PdfAnnotation;
  24. import com.itextpdf.text.pdf.PdfWriter;
  25.  
  26. public class MovieAnnotations2 {
  27.  
  28.     /** The resulting PDF. */
  29.     public static final String RESULT
  30.         = "results/part2/chapter07/movie_annotations_2.pdf";
  31.     /** Pattern for an info String. */
  32.     public static final String INFO
  33.         = "Movie produced in %s; run length: %s";
  34.  
  35.     /**
  36.      * Creates a PDF document.
  37.      * @param filename the path to the new PDF document
  38.      * @throws    DocumentException
  39.      * @throws    IOException
  40.      * @throws    SQLException
  41.      */
  42.     public void createPdf(String filename)
  43.         throws IOException, DocumentException, SQLException {
  44.         // Open the database connection
  45.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  46.         // step 1
  47.         Document document = new Document();
  48.         // step 2
  49.         PdfWriter writer = PdfWriter.getInstance(document,
  50.                 new FileOutputStream(filename));
  51.         // step 3
  52.         document.open();
  53.         // step 4
  54.         Phrase phrase;
  55.         Chunk chunk;
  56.         for (Movie movie : PojoFactory.getMovies(connection)) {
  57.             phrase = new Phrase(movie.getMovieTitle());
  58.             chunk = new Chunk("\u00a0");
  59.             chunk.setAnnotation(
  60.                 PdfAnnotation.createText(writer, null, movie.getMovieTitle(),
  61.                 String.format(INFO, movie.getYear(), movie.getDuration()),
  62.                 false, "Comment"));
  63.             phrase.add(chunk);
  64.             document.add(phrase);
  65.             document.add(PojoToElementFactory.getDirectorList(movie));
  66.             document.add(PojoToElementFactory.getCountryList(movie));
  67.         }
  68.         // step 5
  69.         document.close();
  70.         // close the database connection
  71.         connection.close();
  72.     }
  73.  
  74.     /**
  75.      * Main method.
  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.         MovieAnnotations2 example = new MovieAnnotations2();
  84.         example.createPdf(RESULT);
  85.     }
  86. }
GenericAnnotations.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.Chunk;
  14. import com.itextpdf.text.Document;
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.Paragraph;
  17. import com.itextpdf.text.Rectangle;
  18. import com.itextpdf.text.pdf.PdfAnnotation;
  19. import com.itextpdf.text.pdf.PdfBoolean;
  20. import com.itextpdf.text.pdf.PdfName;
  21. import com.itextpdf.text.pdf.PdfPageEventHelper;
  22. import com.itextpdf.text.pdf.PdfString;
  23. import com.itextpdf.text.pdf.PdfWriter;
  24. import com.itextpdf.text.pdf.draw.VerticalPositionMark;
  25.  
  26. public class GenericAnnotations extends PdfPageEventHelper {
  27.  
  28.     /** The resulting PDF. */
  29.     public static final String RESULT
  30.         = "results/part2/chapter07/generic_annotations.pdf";
  31.     /** Possible icons. */
  32.     public static final String[] ICONS = {
  33.         "Comment", "Key", "Note", "Help", "NewParagraph", "Paragraph", "Insert"
  34.     };
  35.  
  36.     /**
  37.      * Main method.
  38.      * @param    args    no arguments needed
  39.      * @throws DocumentException
  40.      * @throws IOException
  41.      */
  42.     public static void main(String[] args)
  43.         throws IOException, DocumentException {
  44.         // step 1
  45.         Document document = new Document();
  46.         // step 2
  47.         PdfWriter writer
  48.             = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  49.         writer.setPageEvent(new GenericAnnotations());
  50.         // step 3
  51.         document.open();
  52.         // step 4
  53.         Paragraph p = new Paragraph();
  54.         Chunk chunk;
  55.         Chunk tab = new Chunk(new VerticalPositionMark());
  56.         for (int i = 0; i < ICONS.length; i++) {
  57.             chunk = new Chunk(ICONS[i]);
  58.             chunk.setGenericTag(ICONS[i]);
  59.             p.add(chunk);
  60.             p.add(tab);
  61.         }
  62.         document.add(p);
  63.         // step 5
  64.         document.close();
  65.     }
  66.  
  67.     /**
  68.      * @see com.itextpdf.text.pdf.PdfPageEventHelper#onGenericTag(
  69.      *      com.itextpdf.text.pdf.PdfWriter,
  70.      *      com.itextpdf.text.Document,
  71.      *      com.itextpdf.text.Rectangle, java.lang.String)
  72.      */
  73.     @Override
  74.     public void onGenericTag(PdfWriter writer,
  75.         Document document, Rectangle rect, String text) {
  76.         PdfAnnotation annotation = new PdfAnnotation(writer,
  77.             new Rectangle(
  78.                 rect.getRight() + 10, rect.getBottom(),
  79.                 rect.getRight() + 30, rect.getTop()));
  80.         annotation.setTitle("Text annotation");
  81.         annotation.put(PdfName.SUBTYPE, PdfName.TEXT);
  82.         annotation.put(PdfName.OPEN, PdfBoolean.PDFFALSE);
  83.         annotation.put(PdfName.CONTENTS,
  84.             new PdfString(String.format("Icon: %s", text)));
  85.         annotation.put(PdfName.NAME, new PdfName(text));
  86.         writer.addAnnotation(annotation);
  87.     }
  88.    
  89. }
TimetableAnnotations1.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.Date;
  13. import java.sql.SQLException;
  14. import java.util.List;
  15. import java.util.TimeZone;
  16.  
  17. import com.lowagie.database.DatabaseConnection;
  18. import com.lowagie.database.HsqldbConnection;
  19. import com.lowagie.filmfestival.Movie;
  20. import com.lowagie.filmfestival.PojoFactory;
  21. import com.lowagie.filmfestival.Screening;
  22. import com.itextpdf.text.DocumentException;
  23. import com.itextpdf.text.Rectangle;
  24. import com.itextpdf.text.html.WebColors;
  25. import com.itextpdf.text.pdf.PdfAnnotation;
  26. import com.itextpdf.text.pdf.PdfReader;
  27. import com.itextpdf.text.pdf.PdfStamper;
  28.  
  29. import part1.chapter03.MovieTemplates;
  30.  
  31. public class TimetableAnnotations1 {
  32.  
  33.     /** The resulting PDF. */
  34.     public static final String RESULT
  35.         = "results/part2/chapter07/timetable_help.pdf";
  36.     /** A pattern for an info string. */
  37.     public static final String INFO
  38.         = "Movie produced in %s; run length: %s";
  39.  
  40.     static {
  41.         TimeZone.setDefault(TimeZone.getTimeZone("Europe/Brussels"));
  42.     }
  43.  
  44.     /**
  45.      * Manipulates a PDF file src with the file dest as result
  46.      * @param src the original PDF
  47.      * @param dest the resulting PDF
  48.      * @throws IOException
  49.      * @throws DocumentException
  50.      * @throws SQLException
  51.      */
  52.     public void manipulatePdf(String src, String dest)
  53.         throws SQLException, IOException, DocumentException {
  54.         // Create a database connection
  55.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  56.         locations = PojoFactory.getLocations(connection);
  57.         // Create a reader
  58.         PdfReader reader = new PdfReader(src);
  59.         // Create a stamper
  60.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  61.         // Add the annotations
  62.         int page = 1;
  63.         Rectangle rect;
  64.         PdfAnnotation annotation;
  65.         Movie movie;
  66.         for (Date day : PojoFactory.getDays(connection)) {
  67.             for (Screening screening : PojoFactory.getScreenings(connection, day)) {
  68.                 movie = screening.getMovie();
  69.                 rect = getPosition(screening);
  70.                 annotation = PdfAnnotation.createText(
  71.                     stamper.getWriter(), rect, movie.getMovieTitle(),
  72.                     String.format(INFO, movie.getYear(), movie.getDuration()),
  73.                     false, "Help");
  74.                 annotation.setColor(WebColors.getRGBColor(
  75.                     "#" + movie.getEntry().getCategory().getColor()));
  76.                 stamper.addAnnotation(annotation, page);
  77.             }
  78.             page++;
  79.         }
  80.         // Close the stamper
  81.         stamper.close();
  82.         reader.close();
  83.         // Close the database connection
  84.         connection.close();
  85.     }
  86.    
  87.     /**
  88.      * Calculates the position of a rectangle corresponding with a screening.
  89.      * @param    screening    a screening POJO, contains a movie
  90.      * @return    a Rectangle
  91.      */
  92.     protected Rectangle getPosition(Screening screening) {
  93.         float llx, lly, urx, ury;
  94.         long minutesAfter930 = (screening.getTime().getTime() - TIME930) / 60000l;
  95.         llx = OFFSET_LEFT + (MINUTE * minutesAfter930);
  96.         int location = locations.indexOf(screening.getLocation()) + 1;
  97.         lly = OFFSET_BOTTOM + (LOCATIONS - location) * HEIGHT_LOCATION;
  98.         urx = llx + MINUTE * screening.getMovie().getDuration();
  99.         ury = lly + HEIGHT_LOCATION;
  100.         Rectangle rect = new Rectangle(llx, lly, urx, ury);
  101.         return rect;
  102.     }
  103.  
  104.     /** A list containing all the locations. */
  105.     protected List locations;
  106.    
  107.     /** The number of locations on our time table. */
  108.     public static final int LOCATIONS = 9;
  109.     /** The number of time slots on our time table. */
  110.     public static final int TIMESLOTS = 32;
  111.     /** The "offset time" for our calendar sheets. */
  112.     public static final long TIME930 = 30600000l;
  113.     /** The offset to the left of our time table. */
  114.     public static final float OFFSET_LEFT = 76;
  115.     /** The width of our time table. */
  116.     public static final float WIDTH = 740;
  117.     /** The width of a time slot. */
  118.     public static final float WIDTH_TIMESLOT = WIDTH / TIMESLOTS;
  119.     /** The width of one minute. */
  120.     public static final float MINUTE = WIDTH_TIMESLOT / 30f;
  121.     /** The offset from the bottom of our time table. */
  122.     public static final float OFFSET_BOTTOM = 36;
  123.     /** The height of our time table */
  124.     public static final float HEIGHT = 504;
  125.     /** The height of a bar showing the movies at one specific location. */
  126.     public static final float HEIGHT_LOCATION = HEIGHT / LOCATIONS;
  127.  
  128.     /**
  129.      * Main method.
  130.      * @param    args    no arguments needed
  131.      * @throws DocumentException
  132.      * @throws IOException
  133.      * @throws SQLException
  134.      */
  135.     public static void main(String[] args)
  136.         throws IOException, DocumentException, SQLException {
  137.         MovieTemplates.main(args);
  138.         new TimetableAnnotations1().manipulatePdf(
  139.             MovieTemplates.RESULT, RESULT);
  140.     }
  141. }
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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13.  
  14. import com.lowagie.database.DatabaseConnection;
  15. import com.lowagie.database.HsqldbConnection;
  16. import com.lowagie.filmfestival.Movie;
  17. import com.lowagie.filmfestival.PojoFactory;
  18. import com.itextpdf.text.Annotation;
  19. import com.itextpdf.text.Document;
  20. import com.itextpdf.text.DocumentException;
  21. import com.itextpdf.text.Image;
  22. import com.itextpdf.text.PageSize;
  23. import com.itextpdf.text.pdf.PdfContentByte;
  24. import com.itextpdf.text.pdf.PdfTemplate;
  25. import com.itextpdf.text.pdf.PdfWriter;
  26.  
  27. public class MoviePosters1 {
  28.     /** The resulting PDF file. */
  29.     public static final String RESULT
  30.         = "results/part2/chapter07/movie_posters_1.pdf";
  31.     /** Path to the resources. */
  32.     public static final String RESOURCE
  33.         = "resources/posters/%s.jpg";
  34.     /** Path to IMDB. */
  35.     public static final String IMDB
  36.         = "http://imdb.com/title/tt%s/";
  37.    
  38.     /**
  39.      * Creates a PDF with information about the movies
  40.      * @param    filename the name of the PDF file that will be created.
  41.      * @throws    DocumentException
  42.      * @throws    IOException
  43.      * @throws    SQLException
  44.      */
  45.     public void createPdf(String filename)
  46.         throws IOException, DocumentException, SQLException {
  47.         // Create a database connection
  48.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  49.         // step 1
  50.         Document document = new Document(PageSize.A4);
  51.         // step 2
  52.         PdfWriter writer
  53.             = PdfWriter.getInstance(document, new FileOutputStream(filename));
  54.         // step 3
  55.         document.open();
  56.         // step 4
  57.         PdfContentByte canvas = writer.getDirectContent();
  58.         // Create a reusable XObject
  59.         PdfTemplate celluloid = canvas.createTemplate(595, 84.2f);
  60.         celluloid.rectangle(8, 8, 579, 68);
  61.         for (float f = 8.25f; f < 581; f+= 6.5f) {
  62.             celluloid.roundRectangle(f, 8.5f, 6, 3, 1.5f);
  63.             celluloid.roundRectangle(f, 72.5f, 6, 3, 1.5f);
  64.         }
  65.         celluloid.setGrayFill(0.1f);
  66.         celluloid.eoFill();
  67.         writer.releaseTemplate(celluloid);
  68.         // Add the XObject ten times
  69.         for (int i = 0; i < 10; i++) {
  70.             canvas.addTemplate(celluloid, 0, i * 84.2f);
  71.         }
  72.         // Add the movie posters
  73.         Image img;
  74.         Annotation annotation;
  75.         float x = 11.5f;
  76.         float y = 769.7f;
  77.         for (Movie movie : PojoFactory.getMovies(connection)) {
  78.             img = Image.getInstance(String.format(RESOURCE, movie.getImdb()));
  79.             img.scaleToFit(1000, 60);
  80.             img.setAbsolutePosition(x + (45 - img.getScaledWidth()) / 2, y);
  81.             annotation = new Annotation(0, 0, 0, 0,
  82.                 String.format(IMDB, movie.getImdb()));
  83.             img.setAnnotation(annotation);
  84.             canvas.addImage(img);
  85.             x += 48;
  86.             if (x > 578) {
  87.                 x = 11.5f;
  88.                 y -= 84.2f;
  89.             }
  90.         }
  91.         // step 5
  92.         document.close();
  93.         // Close the database connection
  94.         connection.close();
  95.     }
  96.  
  97.     /**
  98.      * Main method.
  99.      * @param    args    no arguments needed
  100.      * @throws DocumentException
  101.      * @throws IOException
  102.      * @throws SQLException
  103.      */
  104.     public static void main(String[] args)
  105.         throws IOException, SQLException, DocumentException {
  106.         new MoviePosters1().createPdf(RESULT);
  107.     }
  108. }
TimetableAnnotations2.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.Date;
  13. import java.sql.SQLException;
  14.  
  15. import com.lowagie.database.DatabaseConnection;
  16. import com.lowagie.database.HsqldbConnection;
  17. import com.lowagie.filmfestival.PojoFactory;
  18. import com.lowagie.filmfestival.Screening;
  19. import com.itextpdf.text.DocumentException;
  20. import com.itextpdf.text.Rectangle;
  21. import com.itextpdf.text.pdf.PdfAction;
  22. import com.itextpdf.text.pdf.PdfAnnotation;
  23. import com.itextpdf.text.pdf.PdfReader;
  24. import com.itextpdf.text.pdf.PdfStamper;
  25.  
  26. import part1.chapter03.MovieTemplates;
  27.  
  28. public class TimetableAnnotations2 extends TimetableAnnotations1 {
  29.  
  30.     /** The resulting PDF. */
  31.     public static final String RESULT
  32.         = "results/part2/chapter07/timetable_links.pdf";
  33.     /** Path to IMDB. */
  34.     public static final String IMDB
  35.         = "http://imdb.com/title/tt%s/";
  36.  
  37.     /**
  38.      * Manipulates a PDF file src with the file dest as result
  39.      * @param src the original PDF
  40.      * @param dest the resulting PDF
  41.      * @throws IOException
  42.      * @throws DocumentException
  43.      * @throws SQLException
  44.      */
  45.     public void manipulatePdf(String src, String dest)
  46.         throws SQLException, IOException, DocumentException {
  47.         // Create a database connection
  48.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  49.         locations = PojoFactory.getLocations(connection);
  50.         // Create a reader
  51.         PdfReader reader = new PdfReader(src);
  52.         // Create a stamper
  53.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  54.         // Add annotations for every screening
  55.         int page = 1;
  56.         Rectangle rect;
  57.         PdfAnnotation annotation;
  58.         for (Date day : PojoFactory.getDays(connection)) {
  59.             for (Screening screening : PojoFactory.getScreenings(connection, day)) {
  60.                 rect = getPosition(screening);
  61.                 annotation = PdfAnnotation.createLink(
  62.                     stamper.getWriter(), rect, PdfAnnotation.HIGHLIGHT_INVERT,
  63.                     new PdfAction(String.format(IMDB, screening.getMovie().getImdb())));
  64.                 stamper.addAnnotation(annotation, page);
  65.             }
  66.             page++;
  67.         }
  68.         // Close the stamper
  69.         stamper.close();
  70.         reader.close();
  71.         // Close the database connection
  72.         connection.close();
  73.     }
  74.     /**
  75.      * Main method.
  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.         MovieTemplates.main(args);
  84.         new TimetableAnnotations2().manipulatePdf(
  85.             MovieTemplates.RESULT, RESULT);
  86.     }
  87. }
MovieAnnotations3.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13.  
  14. import com.lowagie.database.DatabaseConnection;
  15. import com.lowagie.database.HsqldbConnection;
  16. import com.lowagie.filmfestival.Movie;
  17. import com.lowagie.filmfestival.PojoFactory;
  18. import com.lowagie.filmfestival.PojoToElementFactory;
  19. import com.itextpdf.text.Chunk;
  20. import com.itextpdf.text.Document;
  21. import com.itextpdf.text.DocumentException;
  22. import com.itextpdf.text.Phrase;
  23. import com.itextpdf.text.pdf.PdfAnnotation;
  24. import com.itextpdf.text.pdf.PdfName;
  25. import com.itextpdf.text.pdf.PdfString;
  26. import com.itextpdf.text.pdf.PdfWriter;
  27.  
  28. public class MovieAnnotations3 {
  29.  
  30.     /** The resulting PDF. */
  31.     public static final String RESULT
  32.         = "results/part2/chapter07/movie_annotations_3.pdf";
  33.     /** Path to the resources. */
  34.     public static final String RESOURCE
  35.         = "resources/posters/%s.jpg";
  36.  
  37.     /**
  38.      * Creates a PDF document.
  39.      * @param filename the path to the new PDF document
  40.      * @throws    DocumentException
  41.      * @throws    IOException
  42.      * @throws    SQLException
  43.      */
  44.     public void createPdf(String filename)
  45.         throws IOException, DocumentException, SQLException {
  46.         // Create a database connection
  47.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  48.         // step 1
  49.         Document document = new Document();
  50.         // step 2
  51.         PdfWriter writer
  52.             = PdfWriter.getInstance(document, new FileOutputStream(filename));
  53.         // step 3
  54.         document.open();
  55.         // step 4
  56.         Phrase phrase;
  57.         Chunk chunk;
  58.         PdfAnnotation annotation;
  59.         for (Movie movie : PojoFactory.getMovies(connection)) {
  60.             phrase = new Phrase(movie.getMovieTitle());
  61.             chunk = new Chunk("\u00a0\u00a0");
  62.             annotation = PdfAnnotation.createFileAttachment(writer, null,
  63.                     movie.getMovieTitle(), null,
  64.                     String.format(RESOURCE, movie.getImdb()),
  65.                     String.format("img_%s.jpg", movie.getImdb()));
  66.             annotation.put(PdfName.NAME, new PdfString("Paperclip"));
  67.             chunk.setAnnotation(annotation);
  68.             phrase.add(chunk);
  69.             document.add(phrase);
  70.             document.add(PojoToElementFactory.getDirectorList(movie));
  71.             document.add(PojoToElementFactory.getCountryList(movie));
  72.         }
  73.         // step 5
  74.         document.close();
  75.         // Close the database connection
  76.         connection.close();
  77.     }
  78.  
  79.     /**
  80.      * Main method.
  81.      * @param    args    no arguments needed
  82.      * @throws DocumentException
  83.      * @throws IOException
  84.      * @throws SQLException
  85.      */
  86.     public static void main(String[] args)
  87.         throws IOException, DocumentException, SQLException {
  88.         MovieAnnotations3 example = new MovieAnnotations3();
  89.         example.createPdf(RESULT);
  90.     }
  91. }
TimetableAnnotations3.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.Date;
  13. import java.sql.SQLException;
  14.  
  15. import com.lowagie.database.DatabaseConnection;
  16. import com.lowagie.database.HsqldbConnection;
  17. import com.lowagie.filmfestival.Movie;
  18. import com.lowagie.filmfestival.PojoFactory;
  19. import com.lowagie.filmfestival.Screening;
  20. import com.itextpdf.text.DocumentException;
  21. import com.itextpdf.text.Rectangle;
  22. import com.itextpdf.text.pdf.PdfAnnotation;
  23. import com.itextpdf.text.pdf.PdfBorderArray;
  24. import com.itextpdf.text.pdf.PdfBorderDictionary;
  25. import com.itextpdf.text.pdf.PdfDashPattern;
  26. import com.itextpdf.text.pdf.PdfReader;
  27. import com.itextpdf.text.pdf.PdfStamper;
  28. import com.itextpdf.text.BaseColor;
  29.  
  30. import part1.chapter03.MovieTemplates;
  31.  
  32. public class TimetableAnnotations3 extends TimetableAnnotations1 {
  33.     /** The resulting PDF file. */
  34.     public static final String RESULT = "results/part2/chapter07/timetable_tickets.pdf";
  35.     /** Path to IMDB. */
  36.     public static final String IMDB = "http://imdb.com/title/tt%s/";
  37.  
  38.     /**
  39.      * Manipulates a PDF file src with the file dest as result
  40.      * @param src the original PDF
  41.      * @param dest the resulting PDF
  42.      * @throws IOException
  43.      * @throws DocumentException
  44.      * @throws SQLException
  45.      */
  46.     public void manipulatePdf(String src, String dest)
  47.         throws SQLException, IOException, DocumentException {
  48.         // Create a database connection
  49.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  50.         locations = PojoFactory.getLocations(connection);
  51.         // Create a reader
  52.         PdfReader reader = new PdfReader(src);
  53.         // Create a stamper
  54.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  55.         // Loop over the days and screenings
  56.         int page = 1;
  57.         Rectangle rect;
  58.         float top;
  59.         PdfAnnotation annotation;
  60.         Movie movie;
  61.         for (Date day : PojoFactory.getDays(connection)) {
  62.             for (Screening screening : PojoFactory.getScreenings(connection, day)) {
  63.                 rect = getPosition(screening);
  64.                 movie = screening.getMovie();
  65.                 // Annotation for press previews
  66.                 if (screening.isPress()) {
  67.                     annotation = PdfAnnotation.createStamp(stamper.getWriter(),
  68.                         rect, "Press only", "NotForPublicRelease");
  69.                     annotation.setColor(BaseColor.BLACK);
  70.                     annotation.setFlags(PdfAnnotation.FLAGS_PRINT);
  71.                 }
  72.                 // Annotation for screenings that are sold out
  73.                 else if (isSoldOut(screening)) {
  74.                     top = reader.getPageSizeWithRotation(page).getTop();
  75.                     annotation = PdfAnnotation.createLine(
  76.                         stamper.getWriter(), rect, "SOLD OUT",
  77.                         top - rect.getTop(), rect.getRight(),
  78.                         top - rect.getBottom(), rect.getLeft());
  79.                     annotation.setTitle(movie.getMovieTitle());
  80.                     annotation.setColor(BaseColor.WHITE);
  81.                     annotation.setFlags(PdfAnnotation.FLAGS_PRINT);
  82.                     annotation.setBorderStyle(
  83.                         new PdfBorderDictionary(5, PdfBorderDictionary.STYLE_SOLID));
  84.                 }
  85.                 // Annotation for screenings with tickets available
  86.                 else {
  87.                     annotation = PdfAnnotation.createSquareCircle(
  88.                         stamper.getWriter(), rect, "Tickets available", true);
  89.                     annotation.setTitle(movie.getMovieTitle());
  90.                     annotation.setColor(BaseColor.BLUE);
  91.                     annotation.setFlags(PdfAnnotation.FLAGS_PRINT);
  92.                     annotation.setBorder(new PdfBorderArray(0, 0, 2, new PdfDashPattern()));
  93.                 }
  94.                 stamper.addAnnotation(annotation, page);
  95.             }
  96.             page++;
  97.         }
  98.         // Close the stamper
  99.         stamper.close();
  100.         reader.close();
  101.         // Close the database connection
  102.         connection.close();
  103.     }
  104.    
  105.     /**
  106.      * Checks if the screening has been sold out.
  107.      * @param screening a Screening POJO
  108.      * @return true if the screening has been sold out.
  109.      */
  110.     public boolean isSoldOut(Screening screening) {
  111.         if (screening.getMovie().getMovieTitle().startsWith("L"))
  112.             return true;
  113.         return false;
  114.     }
  115.  
  116.     /**
  117.      * Main method.
  118.      * @param    args    no arguments needed
  119.      * @throws DocumentException
  120.      * @throws IOException
  121.      */
  122.     public static void main(String[] args)
  123.         throws IOException, DocumentException, SQLException {
  124.         MovieTemplates.main(args);
  125.         new TimetableAnnotations3().manipulatePdf(
  126.             MovieTemplates.RESULT, RESULT);
  127.     }
  128. }
ButtonsActions.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import part1.chapter03.MovieTemplates;
  14.  
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.Rectangle;
  17. import com.itextpdf.text.pdf.PdfAction;
  18. import com.itextpdf.text.pdf.PdfAnnotation;
  19. import com.itextpdf.text.pdf.PdfReader;
  20. import com.itextpdf.text.pdf.PdfStamper;
  21. import com.itextpdf.text.pdf.PushbuttonField;
  22. import com.itextpdf.text.BaseColor;
  23.  
  24. public class ButtonsActions {
  25.  
  26.     /** The resulting PDF. */
  27.     public static final String RESULT
  28.         = "results/part2/chapter07/save_mail_timetable.pdf";
  29.  
  30.     /**
  31.      * Manipulates a PDF file src with the file dest as result
  32.      * @param src the original PDF
  33.      * @param dest the resulting PDF
  34.      * @throws IOException
  35.      * @throws DocumentException
  36.      */
  37.     public void manipulatePdf(String src, String dest)
  38.         throws IOException, DocumentException {
  39.         // Create a reader
  40.         PdfReader reader = new PdfReader(src);
  41.         int n = reader.getNumberOfPages();
  42.         // Create a stamper
  43.         PdfStamper stamper
  44.             = new PdfStamper(reader, new FileOutputStream(dest));
  45.         // Create pushbutton 1
  46.         PushbuttonField saveAs =
  47.             new PushbuttonField(stamper.getWriter(),
  48.                 new Rectangle(636, 10, 716, 30), "Save");
  49.         saveAs.setBorderColor(BaseColor.BLACK);
  50.         saveAs.setText("Save");
  51.         saveAs.setTextColor(BaseColor.RED);
  52.         saveAs.setLayout(PushbuttonField.LAYOUT_LABEL_ONLY);
  53.         saveAs.setRotation(90);
  54.         PdfAnnotation saveAsButton = saveAs.getField();
  55.         saveAsButton.setAction(PdfAction.javaScript(
  56.             "app.execMenuItem('SaveAs')", stamper.getWriter()));
  57.         // Create pushbutton 2
  58.         PushbuttonField mail
  59.             = new PushbuttonField(stamper.getWriter(),
  60.                 new Rectangle(736, 10, 816, 30), "Mail");
  61.         mail.setBorderColor(BaseColor.BLACK);
  62.         mail.setText("Mail");
  63.         mail.setTextColor(BaseColor.RED);
  64.         mail.setLayout(PushbuttonField.LAYOUT_LABEL_ONLY);
  65.         mail.setRotation(90);
  66.         PdfAnnotation mailButton = mail.getField();
  67.         mailButton.setAction(PdfAction.javaScript(
  68.             "app.execMenuItem('AcroSendMail:SendMail')", stamper.getWriter()));
  69.         // Add the annotations to every page of the document
  70.         for (int page = 1; page
Advertisement.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13.  
  14. import part1.chapter04.NestedTables;
  15.  
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.Image;
  18. import com.itextpdf.text.Rectangle;
  19. import com.itextpdf.text.pdf.PdfAction;
  20. import com.itextpdf.text.pdf.PdfFormField;
  21. import com.itextpdf.text.pdf.PdfReader;
  22. import com.itextpdf.text.pdf.PdfStamper;
  23. import com.itextpdf.text.pdf.PushbuttonField;
  24. import com.itextpdf.text.BaseColor;
  25.  
  26. public class Advertisement {
  27.  
  28.     /** Path to a resource. */
  29.     public static final String RESOURCE = "resources/pdfs/hero.pdf";
  30.     /** Path to a resource. */
  31.     public static final String IMAGE = "resources/img/close.png";
  32.     /** The resulting PDF file. */
  33.     public static final String RESULT
  34.         = "results/part2/chapter07/advertisement.pdf";
  35.  
  36.     /**
  37.      * Manipulates a PDF file src with the file dest as result
  38.      * @param src the original PDF
  39.      * @param resource a resource that will be used as advertisement
  40.      * @param dest the resulting PDF
  41.      * @throws IOException
  42.      * @throws DocumentException
  43.      */
  44.     public void manipulatePdf(String src, String resource, String dest)
  45.         throws IOException, DocumentException {
  46.         // Create a reader for the original document
  47.         PdfReader reader = new PdfReader(src);
  48.         // Create a reader for the advertisement resource
  49.         PdfReader ad = new PdfReader(resource);
  50.         // Create a stamper
  51.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  52.         // Create the advertisement annotation for the menubar
  53.         Rectangle rect = new Rectangle(400, 772, 545, 792);
  54.         PushbuttonField button = new PushbuttonField(
  55.             stamper.getWriter(), rect, "click");
  56.         button.setBackgroundColor(BaseColor.RED);
  57.         button.setBorderColor(BaseColor.RED);
  58.         button.setFontSize(10);
  59.         button.setText("Close this advertisement");
  60.         button.setImage(Image.getInstance(IMAGE));
  61.         button.setLayout(PushbuttonField.LAYOUT_LABEL_LEFT_ICON_RIGHT);
  62.         button.setIconHorizontalAdjustment(1);
  63.         PdfFormField menubar = button.getField();
  64.         String js = "var f1 = getField('click'); f1.display = display.hidden;"
  65.             + "var f2 = getField('advertisement'); f2.display = display.hidden;";
  66.         menubar.setAction(PdfAction.javaScript(js, stamper.getWriter()));
  67.         // Add the annotation
  68.         stamper.addAnnotation(menubar, 1);
  69.         // Create the advertisement annotation for the content
  70.         rect = new Rectangle(400, 550, 545, 772);
  71.         button = new PushbuttonField(
  72.             stamper.getWriter(), rect, "advertisement");
  73.         button.setBackgroundColor(BaseColor.WHITE);
  74.         button.setBorderColor(BaseColor.RED);
  75.         button.setText("Buy the book iText in Action 2nd edition");
  76.         button.setTemplate(stamper.getImportedPage(ad, 1));
  77.         button.setLayout(PushbuttonField.LAYOUT_ICON_TOP_LABEL_BOTTOM);
  78.         PdfFormField advertisement = button.getField();
  79.         advertisement.setAction(
  80.             new PdfAction("http://www.1t3xt.com/docs/book.php"));
  81.         // Add the annotation
  82.         stamper.addAnnotation(advertisement, 1);
  83.         // Close the stamper
  84.         stamper.close();
  85.         reader.close();
  86.     }
  87.  
  88.     /**
  89.      * Main method.
  90.      *
  91.      * @param    args    no arguments needed
  92.      * @throws DocumentException
  93.      * @throws IOException
  94.      * @throws SQLException
  95.      */
  96.     public static void main(String[] args)
  97.         throws SQLException, DocumentException, IOException {
  98.         NestedTables.main(args);
  99.         new Advertisement().manipulatePdf(
  100.             NestedTables.RESULT, RESOURCE, RESULT);
  101.     }
  102. }
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 part2.chapter07;
  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.DocumentException;
  20. import com.itextpdf.text.Image;
  21. import com.itextpdf.text.Rectangle;
  22. import com.itextpdf.text.pdf.PdfAction;
  23. import com.itextpdf.text.pdf.PdfAnnotation;
  24. import com.itextpdf.text.pdf.PdfName;
  25. import com.itextpdf.text.pdf.PdfReader;
  26. import com.itextpdf.text.pdf.PdfStamper;
  27. import com.itextpdf.text.pdf.PushbuttonField;
  28.  
  29. public class MoviePosters2 {
  30.     /** The resulting PDF file. */
  31.     public static final String RESULT
  32.         = "results/part2/chapter07/movie_posters_2.pdf";
  33.     /** A pattern for an info string. */
  34.     public static final String INFO = "Movie produced in %s; run length: %s";
  35.     /** A JavaScript snippet */
  36.     public static final String JS1 =
  37.         "var t = this.getAnnot(this.pageNum, 'IMDB%1$s'); t.popupOpen = true; "
  38.         + "var w = this.getField('b%1$s'); w.setFocus();";
  39.     /** A JavaScript snippet */
  40.     public static final String JS2 =
  41.         "var t = this.getAnnot(this.pageNum, 'IMDB%s'); t.popupOpen = false;";
  42.    
  43.     /**
  44.      * Creates a PDF with information about the movies
  45.      * @param    filename the name of the PDF file that will be created.
  46.      * @throws    DocumentException
  47.      * @throws    IOException
  48.      * @throws    SQLException
  49.      */
  50.     public void manipulatePdf(String src, String dest)
  51.         throws IOException, DocumentException, SQLException {
  52.         // Create a database connection
  53.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  54.         // Create a reader
  55.         PdfReader reader = new PdfReader(src);
  56.         // Create a stamper
  57.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  58.         // Loop over all the movies to add a popup annotation
  59.         List movies = PojoFactory.getMovies(connection);
  60.         Image img;
  61.         float x = 11.5f;
  62.         float y = 769.7f;
  63.         float llx, lly, urx, ury;
  64.         for (Movie movie : movies) {
  65.             img = Image.getInstance(String.format(MoviePosters1.RESOURCE, movie.getImdb()));
  66.             img.scaleToFit(1000, 60);
  67.             llx = x + (45 - img.getScaledWidth()) / 2;
  68.             lly = y;
  69.             urx = x + img.getScaledWidth();
  70.             ury = y + img.getScaledHeight();
  71.             addPopup(stamper, new Rectangle(llx, lly, urx, ury),
  72.                 movie.getMovieTitle(),
  73.                 String.format(INFO, movie.getYear(), movie.getDuration()), movie.getImdb());
  74.             x += 48;
  75.             if (x > 578) {
  76.                 x = 11.5f;
  77.                 y -= 84.2f;
  78.             }
  79.         }
  80.         // Close the stamper
  81.         stamper.close();
  82.         reader.close();
  83.         // Close the database connection
  84.         connection.close();
  85.     }
  86.    
  87.     /**
  88.      * Adds a popup.
  89.      * @param stamper the PdfStamper to which the annotation needs to be added
  90.      * @param rect the position of the annotation
  91.      * @param title the annotation title
  92.      * @param contents the annotation content
  93.      * @param imdb the IMDB number of the movie used as name of the annotation
  94.      * @throws IOException
  95.      * @throws DocumentException
  96.      */
  97.     public void addPopup(PdfStamper stamper, Rectangle rect,
  98.         String title, String contents, String imdb)
  99.         throws IOException, DocumentException {
  100.         // Create the text annotation
  101.         PdfAnnotation text = PdfAnnotation.createText(stamper.getWriter(),
  102.             rect, title, contents, false, "Comment");
  103.         text.setName(String.format("IMDB%s", imdb));
  104.         text.setFlags(PdfAnnotation.FLAGS_READONLY | PdfAnnotation.FLAGS_NOVIEW);
  105.         // Create the popup annotation
  106.         PdfAnnotation popup = PdfAnnotation.createPopup(stamper.getWriter(),
  107.             new Rectangle(rect.getLeft() + 10, rect.getBottom() + 10,
  108.                 rect.getLeft() + 200, rect.getBottom() + 100), null, false);
  109.         // Add the text annotation to the popup
  110.         popup.put(PdfName.PARENT, text.getIndirectReference());
  111.         // Declare the popup annotation as popup for the text
  112.         text.put(PdfName.POPUP, popup.getIndirectReference());
  113.         // Add both annotations
  114.         stamper.addAnnotation(text, 1);
  115.         stamper.addAnnotation(popup, 1);
  116.         // Create a button field
  117.         PushbuttonField field = new PushbuttonField(
  118.                 stamper.getWriter(), rect,
  119.                 String.format("b%s", imdb));
  120.         PdfAnnotation widget = field.getField();
  121.         // Show the popup onMouseEnter
  122.         PdfAction enter = PdfAction.javaScript(
  123.             String.format(JS1, imdb), stamper.getWriter());
  124.         widget.setAdditionalActions(PdfName.E, enter);
  125.         // Hide the popup onMouseExit
  126.         PdfAction exit = PdfAction.javaScript(
  127.             String.format(JS2, imdb), stamper.getWriter());
  128.         widget.setAdditionalActions(PdfName.X, exit);
  129.         // Add the button annotation
  130.         stamper.addAnnotation(widget, 1);
  131.  
  132.     }
  133.  
  134.     /**
  135.      * Main method.
  136.      * @param    args    no arguments needed
  137.      * @throws DocumentException
  138.      * @throws IOException
  139.      * @throws SQLException
  140.      */
  141.     public static void main(String[] args)
  142.         throws IOException, SQLException, DocumentException {
  143.         MoviePosters1.main(args);
  144.         new MoviePosters2().manipulatePdf(MoviePosters1.RESULT, RESULT);
  145.     }
  146. }
Calculator.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 part2.chapter07;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.Document;
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.Element;
  16. import com.itextpdf.text.Rectangle;
  17. import com.itextpdf.text.Utilities;
  18. import com.itextpdf.text.pdf.BaseFont;
  19. import com.itextpdf.text.pdf.PdfAction;
  20. import com.itextpdf.text.pdf.PdfAnnotation;
  21. import com.itextpdf.text.pdf.PdfAppearance;
  22. import com.itextpdf.text.pdf.PdfContentByte;
  23. import com.itextpdf.text.pdf.PdfFormField;
  24. import com.itextpdf.text.pdf.PdfName;
  25. import com.itextpdf.text.pdf.PdfWriter;
  26. import com.itextpdf.text.BaseColor;
  27.  
  28. public class Calculator {
  29.     /** The resulting PDF. */
  30.     public static final String RESULT = "results/part2/chapter07/calculator.pdf";
  31.     /** Path to the resource. */
  32.     public static final String RESOURCE = "resources/js/calculator.js";
  33.    
  34.     /** The font that will be used in the appearances. */
  35.     public BaseFont bf;
  36.     /** Position of the digits */
  37.     Rectangle[] digits = new Rectangle[10];
  38.     /** Position of the operators. */
  39.     Rectangle plus, minus, mult, div, equals;
  40.     /** Position of the other annotations */
  41.     Rectangle clearEntry, clear, result, move;
  42.    
  43.     /**
  44.      * Initializes the font
  45.      * @throws DocumentException
  46.      * @throws IOException
  47.      */
  48.     public void initializeFont() throws DocumentException, IOException {
  49.         bf = BaseFont.createFont();
  50.     }
  51.    
  52.     /**
  53.      * Initializes the rectangles for the calculator keys.
  54.      */
  55.     public void initializeRectangles() {
  56.         digits[0] = createRectangle(3, 1, 1, 1);
  57.         digits[1] = createRectangle(1, 3, 1, 1);
  58.         digits[2] = createRectangle(3, 3, 1, 1);
  59.         digits[3] = createRectangle(5, 3, 1, 1);
  60.         digits[4] = createRectangle(1, 5, 1, 1);
  61.         digits[5] = createRectangle(3, 5, 1, 1);
  62.         digits[6] = createRectangle(5, 5, 1, 1);
  63.         digits[7] = createRectangle(1, 7, 1, 1);
  64.         digits[8] = createRectangle(3, 7, 1, 1);
  65.         digits[9] = createRectangle(5, 7, 1, 1);
  66.         plus = createRectangle(7, 7, 1, 1);
  67.         minus = createRectangle(9, 7, 1, 1);
  68.         mult = createRectangle(7, 5, 1, 1);
  69.         div = createRectangle(9, 5, 1, 1);
  70.         equals = createRectangle(7, 1, 3, 1);
  71.         clearEntry = createRectangle(7, 9, 1, 1);
  72.         clear = createRectangle(9, 9, 1, 1);
  73.         result = createRectangle(1, 9, 5, 1);
  74.         move = createRectangle(8, 3, 1, 1);
  75.     }
  76.  
  77.     /**
  78.      * Creates a PDF document.
  79.      * @param filename the path to the new PDF document
  80.      * @throws    DocumentException
  81.      * @throws    IOException
  82.      */
  83.     public void createPdf(String filename)
  84.         throws IOException, DocumentException {
  85.         // step 1
  86.         Document document = new Document(new Rectangle(360, 360));
  87.         // step 2
  88.         PdfWriter writer =
  89.             PdfWriter.getInstance(document, new FileOutputStream(filename));
  90.         // step 3
  91.         document.open();
  92.         writer.addJavaScript(Utilities.readFileToString(RESOURCE));
  93.         // step 4
  94.         // add the keys for the digits
  95.         for (int i = 0; i < 10; i++) {
  96.             addPushButton(writer, digits[i],
  97.                 String.valueOf(i), "this.augment(" + i + ")");
  98.         }
  99.         // add the keys for the operators
  100.         addPushButton(writer, plus, "+", "this.register('+')");
  101.         addPushButton(writer, minus, "-", "this.register('-')");
  102.         addPushButton(writer, mult, "x", "this.register('*')");
  103.         addPushButton(writer, div, ":", "this.register('/')");
  104.         addPushButton(writer, equals, "=", "this.calculateResult()");
  105.         // add the other keys
  106.         addPushButton(writer, clearEntry, "CE", "this.reset(false)");
  107.         addPushButton(writer, clear, "C", "this.reset(true)");
  108.         addTextField(writer, result, "result");
  109.         addTextField(writer, move, "move");
  110.         // step 5
  111.         document.close();
  112.     }
  113.  
  114.     /**
  115.      * Add a text field.
  116.      * @param writer the PdfWriter
  117.      * @param rect the position of the text field
  118.      * @param name the name of the text field
  119.      */
  120.     public void addTextField(PdfWriter writer, Rectangle rect, String name) {
  121.         PdfFormField field = PdfFormField.createTextField(writer, false, false, 0);
  122.         field.setFieldName(name);
  123.         field.setWidget(rect, PdfAnnotation.HIGHLIGHT_NONE);
  124.         field.setQuadding(PdfFormField.Q_RIGHT);
  125.         field.setFieldFlags(PdfFormField.FF_READ_ONLY);
  126.         writer.addAnnotation(field);
  127.     }
  128.  
  129.     /**
  130.      * Create a pushbutton for a key
  131.      * @param writer the PdfWriter
  132.      * @param rect the position of the key
  133.      * @param btn the label for the key
  134.      * @param script the script to be executed when the button is pushed
  135.      */
  136.     public void addPushButton(PdfWriter writer, Rectangle rect,
  137.         String btn, String script) {
  138.         float w = rect.getWidth();
  139.         float h = rect.getHeight();
  140.         PdfFormField pushbutton = PdfFormField.createPushButton(writer);
  141.         pushbutton.setFieldName("btn_" + btn);
  142.         pushbutton.setWidget(rect, PdfAnnotation.HIGHLIGHT_PUSH);
  143.         PdfContentByte cb = writer.getDirectContent();
  144.         pushbutton.setAppearance(PdfAnnotation.APPEARANCE_NORMAL,
  145.                 createAppearance(cb, btn, BaseColor.GRAY, w, h));
  146.         pushbutton.setAppearance(PdfAnnotation.APPEARANCE_ROLLOVER,
  147.                 createAppearance(cb, btn, BaseColor.RED, w, h));
  148.         pushbutton.setAppearance(PdfAnnotation.APPEARANCE_DOWN,
  149.                 createAppearance(cb, btn, BaseColor.BLUE, w, h));
  150.         pushbutton.setAdditionalActions(PdfName.U,
  151.                 PdfAction.javaScript(script, writer));
  152.         pushbutton.setAdditionalActions(PdfName.E, PdfAction.javaScript(
  153.                 "this.showMove('" + btn + "');", writer));
  154.         pushbutton.setAdditionalActions(PdfName.X, PdfAction.javaScript(
  155.                 "this.showMove(' ');", writer));
  156.         writer.addAnnotation(pushbutton);
  157.     }
  158.  
  159.     /**
  160.      * Creates an appearance for a key
  161.      * @param cb the canvas
  162.      * @param btn the label for the key
  163.      * @param color the color of the key
  164.      * @param w the width
  165.      * @param h the height
  166.      * @return an appearance
  167.      */
  168.     public PdfAppearance createAppearance(
  169.         PdfContentByte cb, String btn, BaseColor color, float w, float h) {
  170.         PdfAppearance app = cb.createAppearance(w, h);
  171.         app.setColorFill(color);
  172.         app.rectangle(2, 2, w - 4, h - 4);
  173.         app.fill();
  174.         app.beginText();
  175.         app.setColorFill(BaseColor.BLACK);
  176.         app.setFontAndSize(bf, h / 2);
  177.         app.showTextAligned(Element.ALIGN_CENTER, btn, w / 2, h / 4, 0);
  178.         app.endText();
  179.         return app;
  180.     }
  181.  
  182.     /**
  183.      * Create a rectangle object for a key.
  184.      * @param column column of the key on the key pad
  185.      * @param row row of the key on the key pad
  186.      * @param width width of the key
  187.      * @param height height of the key
  188.      * @return a rectangle defining the position of a key.
  189.      */
  190.     public Rectangle createRectangle(int column, int row, int width,
  191.             int height) {
  192.         column = column * 36 - 18;
  193.         row = row * 36 - 18;
  194.         return new Rectangle(column, row,
  195.             column + width * 36, row + height * 36);
  196.     }
  197.  
  198.     /**
  199.      * Main method.
  200.      * @param    args    no arguments needed
  201.      * @throws DocumentException
  202.      * @throws IOException
  203.      */
  204.     public static void main(String[] args)
  205.         throws DocumentException, IOException {
  206.         Calculator calc = new Calculator();
  207.         calc.initializeFont();
  208.         calc.initializeRectangles();
  209.         calc.createPdf(RESULT);
  210.     }
  211. }
NamedActions.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 Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using kuujinbo.iTextInAction2Ed.Chapter03;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  15.   public class NamedActions : IWriter {
  16. // ===========================================================================
  17.     public const String RESULT = "named_actions.pdf";
  18. // ---------------------------------------------------------------------------    
  19.     public void Write(Stream stream) {
  20.       using (ZipFile zip = new ZipFile()) {
  21.         MovieTemplates m = new MovieTemplates();
  22.         byte[] pdf = Utility.PdfBytes(m);
  23.         zip.AddEntry(RESULT, new NamedActions().ManipulatePdf(pdf));
  24.         zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdf);
  25.         zip.Save(stream);            
  26.       }
  27.     }
  28. // ---------------------------------------------------------------------------    
  29.     /**
  30.      * Manipulates a PDF file src with the file dest as result
  31.      * @param src the original PDF
  32.      */
  33.     public byte[] ManipulatePdf(byte[] src) {
  34.     // Create a table with named actions
  35.       Font symbol = new Font(Font.FontFamily.SYMBOL, 20);
  36.       PdfPTable table = new PdfPTable(4);
  37.       table.DefaultCell.Border = Rectangle.NO_BORDER;
  38.       table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
  39.       Chunk first = new Chunk( ((char)220).ToString() , symbol);
  40.       first.SetAction(new PdfAction(PdfAction.FIRSTPAGE));
  41.       table.AddCell(new Phrase(first));
  42.       Chunk previous = new Chunk( ((char)172).ToString(), symbol);
  43.       previous.SetAction(new PdfAction(PdfAction.PREVPAGE));
  44.       table.AddCell(new Phrase(previous));
  45.       Chunk next = new Chunk( ((char)174).ToString(), symbol);
  46.       next.SetAction(new PdfAction(PdfAction.NEXTPAGE));
  47.       table.AddCell(new Phrase(next));
  48.       Chunk last = new Chunk( ((char)222).ToString(), symbol);
  49.       last.SetAction(new PdfAction(PdfAction.LASTPAGE));
  50.       table.AddCell(new Phrase(last));
  51.       table.TotalWidth = 120;
  52.      
  53.       // Create a reader
  54.       PdfReader reader = new PdfReader(src);
  55.       using (MemoryStream ms = new MemoryStream()) {
  56.         // Create a stamper
  57.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  58.           // Add the table to each page
  59.           PdfContentByte canvas;
  60.           for (int i = 0; i < reader.NumberOfPages; ) {
  61.             canvas = stamper.GetOverContent(++i);
  62.             table.WriteSelectedRows(0, -1, 696, 36, canvas);
  63.           }
  64.         }
  65.         return ms.ToArray();
  66.       }    
  67.     }    
  68. // ===========================================================================
  69.   }
  70. }
LinkActions.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.  
  8. using System;
  9. using System.IO;
  10. using Ionic.Zip;
  11. using System.Collections;
  12. using System.Collections.Generic;
  13. using System.Data;
  14. using System.Data.Common;
  15. using iTextSharp.text;
  16. using iTextSharp.text.pdf;
  17. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  18. using kuujinbo.iTextInAction2Ed.Chapter02;
  19.  
  20. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  21.   public class LinkActions : IWriter {
  22. // ===========================================================================
  23.     /** The resulting PDF file. */
  24.     public const string RESULT1 = "movie_links_1.pdf";
  25.      /** The resulting PDF file. */
  26.     public const string RESULT2 = "movie_links_2.pdf";
  27.     /** The resulting XML file. */
  28.     public const string RESULT3 = "destinations.xml";    
  29. // ---------------------------------------------------------------------------    
  30.     public void Write(Stream stream) {
  31.       using (ZipFile zip = new ZipFile()) {
  32.         MovieLinks1 m = new MovieLinks1();
  33.         byte[] pdf = Utility.PdfBytes(m);
  34.         LinkActions actions = new LinkActions();
  35.         zip.AddEntry(RESULT2, actions.CreatePdf());
  36.         zip.AddEntry(RESULT3, actions.CreateXml(pdf));
  37.         zip.AddEntry(RESULT1, pdf);
  38.         zip.Save(stream);            
  39.       }
  40.     }
  41. // ---------------------------------------------------------------------------    
  42.     /**
  43.      * Creates a PDF document.
  44.      */
  45.     public byte[] CreatePdf() {
  46.       using (MemoryStream ms = new MemoryStream()) {
  47.         // step 1
  48.         using (Document document = new Document()) {
  49.           // step 2
  50.           PdfWriter.GetInstance(document, ms);
  51.           // step 3
  52.           document.Open();
  53.           // step 4
  54.           // Add text with a local destination
  55.           Paragraph p = new Paragraph();
  56.           Chunk top = new Chunk("Country List", FilmFonts.BOLD);
  57.           top.SetLocalDestination("top");
  58.           p.Add(top);
  59.           document.Add(p);
  60.           // Add text with a link to an external URL
  61.           Chunk imdb = new Chunk("Internet Movie Database", FilmFonts.ITALIC);
  62.           imdb.SetAction(new PdfAction(new Uri("http://www.imdb.com/")));
  63.           p = new Paragraph(
  64.             @"Click on a country, and you'll get a list of movies,
  65.            containing links to the "
  66.           );
  67.           p.Add(imdb);
  68.           p.Add(".");
  69.           document.Add(p);
  70.           // Add text with a remote goto
  71.           p = new Paragraph("This list can be found in a ");
  72.           Chunk page1 = new Chunk("separate document");
  73.           page1.SetAction(new PdfAction(RESULT1, 1));
  74.          
  75.           p.Add(page1);
  76.           p.Add(".");
  77.           document.Add(p);
  78.           document.Add(Chunk.NEWLINE);
  79.           // Get a list with countries from the database      
  80.           var SQL =
  81. @"SELECT DISTINCT mc.country_id, c.country, count(*) AS c
  82. FROM film_country c, film_movie_country mc
  83. WHERE c.id = mc.country_id
  84. GROUP BY mc.country_id, country
  85. ORDER BY c DESC";
  86.           using (var c =  AdoDB.Provider.CreateConnection()) {
  87.             c.ConnectionString = AdoDB.CS;
  88.             using (DbCommand cmd = c.CreateCommand()) {
  89.               cmd.CommandText = SQL;
  90.               c.Open();            
  91.               using (var r = cmd.ExecuteReader()) {
  92.                 while (r.Read()) {
  93.                   Paragraph country = new Paragraph(r["country"].ToString());
  94.                   country.Add(": ");
  95.                   Chunk link = new Chunk(string.Format(
  96.                     "{0} movies", r["c"].ToString()
  97.                   ));
  98.                   link.SetAction(PdfAction.GotoRemotePage(
  99.                     RESULT1,
  100.                     r["country_id"].ToString(),
  101.                     false,
  102.                     true
  103.                   ));
  104.                   country.Add(link);
  105.                   document.Add(country);                
  106.                 }        
  107.               }
  108.             }
  109.           }
  110.           document.Add(Chunk.NEWLINE);
  111.           // Add text with a local goto
  112.           p = new Paragraph("Go to ");
  113.           top = new Chunk("top");
  114.           top.SetAction(PdfAction.GotoLocalPage("top", false));
  115.           p.Add(top);
  116.           p.Add(".");
  117.           document.Add(p);        
  118.         }
  119.         return ms.ToArray();
  120.       }
  121.     }
  122. // ---------------------------------------------------------------------------    
  123.     /**
  124.      * Create an XML file with named destinations
  125.      * @param src the PDF with the destinations
  126.      */
  127.     public string CreateXml(byte[] src) {
  128.       PdfReader reader = new PdfReader(src);
  129.       Dictionary map = SimpleNamedDestination
  130.           .GetNamedDestination(reader, false);
  131.       using (MemoryStream ms = new MemoryStream()) {
  132.         SimpleNamedDestination.ExportToXML(map, ms, "ISO8859-1", true);
  133.         ms.Position = 0;
  134.         using (StreamReader sr =  new StreamReader(ms)) {
  135.           return sr.ReadToEnd();
  136.         }
  137.       }
  138.     }    
  139. // ===========================================================================
  140.   }
  141. }
ConcatenateNamedDestinations.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 Ionic.Zip;
  10. using System.Collections;
  11. using System.Text;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Chapter02;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  17.   public class ConcatenateNamedDestinations : IWriter {
  18. // ===========================================================================
  19.     /** The resulting PDF file. */
  20.     public const string RESULT1 = "concatenated_links_1.pdf";  
  21.     /** The resulting PDF file. */
  22.     public const string RESULT2 = "concatenated_links_2.pdf";    
  23. // ---------------------------------------------------------------------------    
  24.     public void Write(Stream stream) {
  25.       using (ZipFile zip = new ZipFile()) {
  26.         // Use previous examples to create PDF files
  27.         MovieLinks1 m = new MovieLinks1();
  28.         byte[] pdfM = Utility.PdfBytes(m);
  29.         LinkActions l = new LinkActions();
  30.         byte[] pdfL = l.CreatePdf();
  31.         // Create readers.
  32.         PdfReader[] readers = {
  33.           new PdfReader(pdfL),
  34.           new PdfReader(pdfM)
  35.         };
  36.        
  37.         // step 1
  38.         //Document document = new Document();
  39.         // step 2
  40.         using (var ms = new MemoryStream()) {
  41.           // step 1
  42.           using (Document document = new Document()) {
  43.             using (PdfCopy copy = new PdfCopy(document, ms)) {
  44.               // step 3
  45.               document.Open();
  46.               // step 4
  47.               int n;
  48.               // copy the pages of the different PDFs into one document
  49.               for (int i = 0; i < readers.Length; i++) {
  50.                 readers[i].ConsolidateNamedDestinations();
  51.                 n = readers[i].NumberOfPages;
  52.                 for (int page = 0; page < n; ) {
  53.                   copy.AddPage(copy.GetImportedPage(readers[i], ++page));
  54.                 }
  55.               }
  56.               // Add named destination  
  57.               copy.AddNamedDestinations(
  58.                 // from the second document
  59.                 SimpleNamedDestination.GetNamedDestination(readers[1], false),
  60.                 // using the page count of the first document as offset
  61.                 readers[0].NumberOfPages
  62.               );
  63.             }
  64.             zip.AddEntry(RESULT1, ms.ToArray());
  65.           }
  66.          
  67.           // Create a reader
  68.           PdfReader reader = new PdfReader(ms.ToArray());
  69.           // Convert the remote destinations into local destinations
  70.           reader.MakeRemoteNamedDestinationsLocal();
  71.           using (MemoryStream ms2 = new MemoryStream()) {
  72.             // Create a new PDF containing the local destinations
  73.             using (PdfStamper stamper = new PdfStamper(reader, ms2)) {
  74.             }
  75.             zip.AddEntry(RESULT2, ms2.ToArray());
  76.           }
  77.          
  78.         }
  79.         zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdfM);
  80.         zip.AddEntry(Utility.ResultFileName(l.ToString() + ".pdf"), pdfL);
  81.         zip.Save(stream);            
  82.       }  
  83.    }
  84. // ===========================================================================
  85.   }
  86. }
TimetableDestinations.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 Ionic.Zip;
  10. using System.Collections.Generic;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using kuujinbo.iTextInAction2Ed.Chapter03;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  16.   public class TimetableDestinations : IWriter {
  17. // ===========================================================================
  18.     /** The resulting PDF. */
  19.     public const String RESULT = "timetable_destinations.pdf";
  20.     /** The font that is used for the navigation links. */
  21.     public static Font SYMBOL = new Font(Font.FontFamily.SYMBOL, 20);
  22.     /** A list to cache all the possible actions */
  23.     public List actions;
  24. // ---------------------------------------------------------------------------    
  25.     public void Write(Stream stream) {
  26.       using (ZipFile zip = new ZipFile()) {
  27.         MovieTemplates m = new MovieTemplates();
  28.         byte[] pdf = Utility.PdfBytes(m);
  29.         zip.AddEntry(RESULT, new TimetableDestinations().ManipulatePdf(pdf));
  30.         zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdf);
  31.         zip.Save(stream);            
  32.       }
  33.     }
  34. // ---------------------------------------------------------------------------    
  35.     /**
  36.      * Manipulates a PDF file src with the file dest as result
  37.      * @param src the original PDF
  38.      */
  39.     public byte[] ManipulatePdf(byte[] src) {
  40.     // Create the reader
  41.       PdfReader reader = new PdfReader(src);
  42.       int n = reader.NumberOfPages;
  43.       using (MemoryStream ms =  new MemoryStream()) {
  44.         // Create the stamper
  45.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  46.           // Make a list with all the possible actions
  47.           actions = new List();
  48.           PdfDestination d;
  49.           for (int i = 0; i < n; ) {
  50.             d = new PdfDestination(PdfDestination.FIT);
  51.             actions.Add(PdfAction.GotoLocalPage(++i, d, stamper.Writer));
  52.           }
  53.           // Add a navigation table to every page
  54.           PdfContentByte canvas;
  55.           for (int i = 0; i < n; ) {
  56.             canvas = stamper.GetOverContent(++i);
  57.             CreateNavigationTable(i, n).WriteSelectedRows(0, -1, 696, 36, canvas);
  58.           }
  59.         }
  60.         return ms.ToArray();
  61.       }  
  62.     }    
  63. // ---------------------------------------------------------------------------    
  64.     /**
  65.      * Create a table that can be used as a footer
  66.      * @param pagenumber the page that will use the table as footer
  67.      * @param total the total number of pages
  68.      * @return a tabel
  69.      */
  70.     public PdfPTable CreateNavigationTable(int pagenumber, int total) {
  71.       PdfPTable table = new PdfPTable(4);
  72.       table.DefaultCell.Border = Rectangle.NO_BORDER;
  73.       table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
  74.       Chunk first = new Chunk(((char)220).ToString(), SYMBOL);
  75.       first.SetAction(actions[0]);
  76.       table.AddCell(new Phrase(first));
  77.       Chunk previous = new Chunk(((char)172).ToString(), SYMBOL);
  78.       previous.SetAction(actions[pagenumber - 2 < 0 ? 0 : pagenumber - 2]);
  79.       table.AddCell(new Phrase(previous));
  80.       Chunk next = new Chunk(((char)174).ToString(), SYMBOL);
  81.       next.SetAction(actions[pagenumber >= total ? total - 1 : pagenumber]);
  82.       table.AddCell(new Phrase(next));
  83.       Chunk last = new Chunk(((char)222).ToString(), SYMBOL);
  84.       last.SetAction(actions[total - 1]);
  85.       table.AddCell(new Phrase(last));
  86.       table.TotalWidth = 120;
  87.       return table;
  88.     }    
  89. // ===========================================================================
  90.   }
  91. }
AddVersionChecker.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 Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using kuujinbo.iTextInAction2Ed.Chapter01;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  15.   public class AddVersionChecker : IWriter {
  16. // ===========================================================================
  17.     /** The resulting PDF file. */
  18.     public const String RESULT = "version_checker.pdf";
  19.     /** Path to a resource. */
  20.     public const string RESOURCE = "viewer_version.js";
  21. // ---------------------------------------------------------------------------
  22.     public void Write(Stream stream) {
  23.       using (ZipFile zip = new ZipFile()) {
  24.         HelloWorld h = new HelloWorld();
  25.         byte[] pdf = Utility.PdfBytes(h);
  26.         // Create a reader
  27.         PdfReader reader = new PdfReader(pdf);
  28.         string js = File.ReadAllText(
  29.           Path.Combine(Utility.ResourceJavaScript, RESOURCE)
  30.         );        
  31.         using (MemoryStream ms = new MemoryStream()) {
  32.           using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  33.             // Add some javascript
  34.             stamper.JavaScript = js;
  35.           }
  36.           zip.AddEntry(RESULT, ms.ToArray());
  37.         }
  38.         zip.AddEntry(RESOURCE, js);
  39.         zip.AddEntry(Utility.ResultFileName(h.ToString() + ".pdf"), pdf);
  40.         zip.Save(stream);            
  41.       }
  42.     }
  43. // ===========================================================================
  44.   }
  45. }
FindDirectors.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 Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Data;
  12. using System.Data.Common;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  16. using kuujinbo.iTextInAction2Ed.Chapter04;
  17.  
  18. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  19.   public class FindDirectors : IWriter {
  20. // ===========================================================================
  21.     /** The resulting PDF file. */
  22.     public const String RESULT = "find_directors.pdf";
  23.     /** Path to a resource. */
  24.     public const string RESOURCE = "find_director.js";
  25.     protected string jsContents;
  26. // ---------------------------------------------------------------------------    
  27.     public void Write(Stream stream) {
  28.       NestedTables n = new NestedTables();
  29.       byte[] pdf = Utility.PdfBytes(n);        
  30.       using (ZipFile zip = new ZipFile()) {
  31.         FindDirectors f =  new FindDirectors();
  32.         zip.AddEntry(RESULT, f.CreatePdf(pdf));
  33.         zip.AddEntry(RESOURCE, f.jsContents);
  34.         zip.AddEntry(Utility.ResultFileName(n.ToString() + ".pdf"), pdf);
  35.         zip.Save(stream);            
  36.       }    
  37.     }
  38. // ---------------------------------------------------------------------------
  39.     /**
  40.      * Creates a PDF file with director names.
  41.      * @param pdf the PDF file to be used as a reader
  42.      */
  43.     public byte[] CreatePdf(byte[] pdf) {
  44.       byte[] tmpDoc = null;
  45.       using ( MemoryStream ms = new MemoryStream() ) {
  46.         using (Document tmp = new Document()) {
  47.           PdfWriter writer = PdfWriter.GetInstance(tmp, ms);
  48.           // step 3
  49.           tmp.Open();
  50.           // step 4
  51.           var SQL =
  52.   @"SELECT name, given_name
  53.  FROM film_director
  54.  ORDER BY name, given_name";
  55.         using (var c =  AdoDB.Provider.CreateConnection()) {
  56.           c.ConnectionString = AdoDB.CS;
  57.           using (DbCommand cmd = c.CreateCommand()) {
  58.             cmd.CommandText = SQL;            
  59.               c.Open();            
  60.               using (var r = cmd.ExecuteReader()) {
  61.                 while ( r.Read() ) {
  62.                   tmp.Add(CreateDirectorParagraph(writer, r));
  63.                 }
  64.               }
  65.             }
  66.           }
  67.         }
  68.         tmpDoc = ms.ToArray();
  69.       }
  70.  
  71.       jsContents = File.ReadAllText(
  72.         Path.Combine(Utility.ResourceJavaScript, RESOURCE)
  73.       );
  74.       List readers = new List() {tmpDoc, pdf};
  75.       using (MemoryStream ms = new MemoryStream()) {
  76.         // step 1
  77.         using (Document document = new Document()) {
  78.           // step 2
  79.           using (PdfCopy copy = new PdfCopy(document, ms)) {
  80.             // step 3
  81.             document.Open();
  82.             // step 4
  83.             copy.AddJavaScript(jsContents);
  84.             for (int i = 0; i < readers.Count; ++i) {
  85.               PdfReader reader = new PdfReader(readers[i]);
  86.               int n = reader.NumberOfPages;
  87.               for (int page = 0; page < n; ) {
  88.                 copy.AddPage(copy.GetImportedPage(reader, ++page));
  89.               }
  90.             }
  91.           }
  92.         }
  93.         return ms.ToArray();    
  94.       }
  95.     }
  96. // ---------------------------------------------------------------------------
  97.     /**
  98.      * Creates a Phrase with the name and given name of a director
  99.      * using different fonts.
  100.      * @param r the DbDataReader containing director records.
  101.      */
  102.     public Paragraph CreateDirectorParagraph(PdfWriter writer, DbDataReader r) {
  103.       string n = r["name"].ToString();
  104.       Chunk name = new Chunk(n);
  105.       name.SetAction(PdfAction.JavaScript(
  106.         string.Format("findDirector('{0}');", n),
  107.         writer
  108.       ) );
  109.       name.Append(", ");
  110.       name.Append(r["given_name"].ToString());
  111.       return new Paragraph(name);
  112.     }
  113. // ===========================================================================
  114.   }
  115. }
LaunchAction.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 Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12.  
  13. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  14.   public class LaunchAction : IWriter {
  15. // ===========================================================================
  16.     public void Write(Stream stream) {
  17.       // step 1
  18.       using (Document document = new Document()) {
  19.         // step 2
  20.         PdfWriter.GetInstance(document, stream);
  21.         // step 3
  22.         document.Open();
  23.         // step 4
  24.         Paragraph p = new Paragraph(
  25.           new Chunk( "Click to open test.txt in Notepad.")
  26.           .SetAction(
  27.             new PdfAction(
  28.               "c:/windows/notepad.exe",
  29.               "test.txt", "open",
  30.               Path.Combine(Utility.ResourceText, "")
  31.             )
  32.         ));
  33.         document.Add(p);
  34.       }
  35.     }
  36. // ===========================================================================
  37.   }
  38. }
PrintTimeTable.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 Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using kuujinbo.iTextInAction2Ed.Chapter03;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  15.   public class PrintTimeTable : IWriter {
  16. // ===========================================================================
  17.     /** The resulting PDF. */
  18.     public const String RESULT = "print_timetable.pdf";
  19.     /** Path to a resource. */
  20.     public const string RESOURCE = "print_page.js";
  21.     protected string jsString;
  22. // ---------------------------------------------------------------------------
  23.     public void Write(Stream stream) {
  24.       using (ZipFile zip = new ZipFile()) {
  25.         MovieTemplates m = new MovieTemplates();
  26.         byte[] pdf = Utility.PdfBytes(m);
  27.         PrintTimeTable p = new PrintTimeTable();
  28.         zip.AddEntry(RESULT, p.ManipulatePdf(pdf));
  29.         zip.AddEntry(RESOURCE, p.jsString);
  30.         zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdf);
  31.         zip.Save(stream);            
  32.       }    
  33.     }
  34. // ---------------------------------------------------------------------------
  35.     /**
  36.      * Manipulates a PDF file src with the file dest as result (localhost)
  37.      * @param src the original PDF
  38.      */
  39.     public byte[] ManipulatePdf(byte[] src) {
  40.     // Create the reader
  41.       PdfReader reader = new PdfReader(src);
  42.       int n = reader.NumberOfPages;
  43.       using (MemoryStream ms = new MemoryStream()) {
  44.         // Create the stamper
  45.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  46.           // Add JavaScript
  47.           jsString = File.ReadAllText(
  48.             Path.Combine(Utility.ResourceJavaScript, RESOURCE)
  49.           );
  50.           stamper.JavaScript = jsString;
  51.           // Create a Chunk with a chained action
  52.           PdfContentByte canvas;
  53.           Chunk chunk = new Chunk("print this page");
  54.           PdfAction action = PdfAction.JavaScript(
  55.             "app.alert('Think before you print!');",
  56.             stamper.Writer
  57.           );
  58.           action.Next(PdfAction.JavaScript(
  59.             "printCurrentPage(this.pageNum);",
  60.             stamper.Writer
  61.           ));
  62.           action.Next(new PdfAction("http://www.panda.org/savepaper/"));
  63.           chunk.SetAction(action);
  64.           Phrase phrase = new Phrase(chunk);
  65.           // Add this Chunk to every page
  66.           for (int i = 0; i < n; ) {
  67.             canvas = stamper.GetOverContent(++i);
  68.             ColumnText.ShowTextAligned(
  69.               canvas, Element.ALIGN_RIGHT, phrase, 816, 18, 0
  70.             );
  71.           }
  72.         }
  73.         return ms.ToArray();    
  74.       }      
  75.     }        
  76. // ===========================================================================
  77.   }
  78. }
EventsAndActions.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 Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using kuujinbo.iTextInAction2Ed.Chapter03;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  15.   public class EventsAndActions : IWriter {
  16. // ===========================================================================
  17.     /** The resulting PDF. */
  18.     public const String RESULT = "events_and_actions.pdf";
  19. // ---------------------------------------------------------------------------    
  20.     public void Write(Stream stream) {
  21.       using (ZipFile zip = new ZipFile()) {
  22.         MovieTemplates m = new MovieTemplates();
  23.         byte[] pdf = Utility.PdfBytes(m);
  24.         EventsAndActions e = new EventsAndActions();
  25.         zip.AddEntry(RESULT, e.ManipulatePdf(pdf));
  26.         zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdf);
  27.         zip.Save(stream);            
  28.       }          
  29.     }
  30. // ---------------------------------------------------------------------------
  31.     /**
  32.      * Manipulates a PDF file src with the file dest as result (localhost)
  33.      * @param src the original PDF
  34.      */
  35.     public byte[] ManipulatePdf(byte[] src) {
  36.     // Create the reader
  37.       PdfReader reader = new PdfReader(src);
  38.       int n = reader.NumberOfPages;
  39.       using (MemoryStream ms = new MemoryStream()) {
  40.         // Create the stamper
  41.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  42.           // Get the writer (to add actions and annotations)
  43.           PdfWriter writer = stamper.Writer;
  44.           PdfAction action = PdfAction.GotoLocalPage(2,
  45.             new PdfDestination(PdfDestination.FIT), writer
  46.           );
  47.           writer.SetOpenAction(action);
  48.           action = PdfAction.JavaScript(
  49.             "app.alert('Think before you print');", writer
  50.           );
  51.           writer.SetAdditionalAction(PdfWriter.WILL_PRINT, action);
  52.           action = PdfAction.JavaScript(
  53.             "app.alert('Think again next time!');", writer
  54.           );
  55.           writer.SetAdditionalAction(PdfWriter.DID_PRINT, action);
  56.           action = PdfAction.JavaScript(
  57.             "app.alert('We hope you enjoy the festival');", writer
  58.           );
  59.           writer.SetAdditionalAction(PdfWriter.DOCUMENT_CLOSE, action);
  60.           action = PdfAction.JavaScript(
  61.             "app.alert('This day is reserved for people with an accreditation "
  62.             + "or an invitation.');",
  63.             writer
  64.           );
  65.           stamper.SetPageAction(PdfWriter.PAGE_OPEN, action, 1);
  66.           action = PdfAction.JavaScript(
  67.             "app.alert('You can buy tickets for all the other days');", writer
  68.           );
  69.           stamper.SetPageAction(PdfWriter.PAGE_CLOSE, action, 1);      
  70.         }
  71.         return ms.ToArray();      
  72.       }      
  73.     }        
  74. // ===========================================================================
  75.   }
  76. }
CreateOutlineTree.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 Ionic.Zip;
  10. using System.Collections;
  11. using System.Collections.Generic;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  17.   public class CreateOutlineTree : IWriter {
  18. // ===========================================================================
  19.     /** The resulting PDF. */
  20.     public const String RESULT = "outline_tree.pdf";
  21.     /** An XML representing the outline tree */
  22.     public const string RESULTXML = "outline_tree.xml";
  23.     /** Pattern of the IMDB urls */
  24.     public const String RESOURCE = "http://imdb.com/title/tt{0}/";    
  25.     /** JavaScript snippet. */
  26.     public const string INFO
  27.         = "app.alert('Movie produced in {0}; run length: {1}');";    
  28. // ---------------------------------------------------------------------------    
  29.     public void Write(Stream stream) {
  30.       using (ZipFile zip = new ZipFile()) {
  31.         CreateOutlineTree example = new CreateOutlineTree();
  32.         byte[] pdf = example.CreatePdf();
  33.         zip.AddEntry(RESULT, pdf);
  34.         zip.AddEntry(RESULTXML, example.CreateXml(pdf));
  35.         zip.Save(stream);            
  36.       }  
  37.     }
  38. // ---------------------------------------------------------------------------    
  39.     /**
  40.      * Creates a PDF document.
  41.      */
  42.     public byte[] CreatePdf() {
  43.       using (MemoryStream ms = new MemoryStream()) {
  44.         // step 1
  45.         using (Document document = new Document()) {
  46.           // step 2
  47.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  48.           // step 3
  49.           document.Open();
  50.           // step 4
  51.           PdfOutline root = writer.RootOutline;
  52.           PdfOutline movieBookmark;
  53.           PdfOutline link;
  54.           String title;
  55.           IEnumerable movies = PojoFactory.GetMovies();
  56.           foreach (Movie movie in movies) {
  57.             title = movie.MovieTitle;
  58.             if ("3-Iron".Equals(title))
  59.                 title = "\ube48\uc9d1";
  60.             movieBookmark = new PdfOutline(root,
  61.               new PdfDestination(
  62.                 PdfDestination.FITH, writer.GetVerticalPosition(true)
  63.               ),
  64.               title, true
  65.             );
  66.             movieBookmark.Style = Font.BOLD;
  67.             link = new PdfOutline(movieBookmark,
  68.               new PdfAction(String.Format(RESOURCE, movie.Imdb)),
  69.               "link to IMDB"
  70.             );
  71.             link.Color = BaseColor.BLUE;
  72.             new PdfOutline(movieBookmark,
  73.               PdfAction.JavaScript(
  74.                 String.Format(INFO, movie.Year, movie.Duration),
  75.                 writer
  76.               ),
  77.               "instant info"
  78.             );
  79.             document.Add(new Paragraph(movie.MovieTitle));
  80.             document.Add(PojoToElementFactory.GetDirectorList(movie));
  81.             document.Add(PojoToElementFactory.GetCountryList(movie));
  82.           }
  83.         }
  84.         return ms.ToArray();
  85.       }
  86.     }  
  87. // ---------------------------------------------------------------------------    
  88.     /**
  89.      * Creates an XML file with the bookmarks of a PDF file
  90.      * @param pdfIn the byte array with the document
  91.      */
  92.     public string CreateXml(byte[] pdfIn) {
  93.       PdfReader reader = new PdfReader(pdfIn);
  94.       var list = SimpleBookmark.GetBookmark(reader);
  95.       using (MemoryStream ms = new MemoryStream()) {
  96.         SimpleBookmark.ExportToXML(list, ms, "ISO8859-1", true);
  97.         ms.Position = 0;
  98.         using (StreamReader sr =  new StreamReader(ms)) {
  99.           return sr.ReadToEnd();
  100.         }              
  101.       }      
  102.     }
  103. // ===========================================================================
  104.   }
  105. }
BookmarkedTimeTable.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 Ionic.Zip;
  10. using System.Collections;
  11. using System.Collections.Generic;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  15. using kuujinbo.iTextInAction2Ed.Chapter03;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  18.   public class BookmarkedTimeTable : IWriter {
  19. // ===========================================================================
  20.     /** The resulting PDF. */
  21.     public const String RESULT = "time_table_bookmarks.pdf";
  22. // ---------------------------------------------------------------------------            
  23.     public void Write(Stream stream) {
  24.       using (ZipFile zip = new ZipFile()) {
  25.         MovieTemplates m = new MovieTemplates();
  26.         byte[] pdf = Utility.PdfBytes(m);
  27.         BookmarkedTimeTable b = new BookmarkedTimeTable();
  28.         zip.AddEntry(RESULT, b.ManipulatePdf(pdf));
  29.         zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdf);
  30.         zip.Save(stream);            
  31.       }
  32.     }
  33. // ---------------------------------------------------------------------------  
  34.     /**
  35.      * Manipulates a PDF file src with the file dest as result
  36.      * @param src the original PDF
  37.      */
  38.     public byte[] ManipulatePdf(byte[] src) {
  39.       // Create a list with bookmarks
  40.       List outlines =
  41.           new List();
  42.       Dictionary map = new Dictionary();
  43.       outlines.Add(map);
  44.       map.Add("Title", "Calendar");
  45.       List kids =
  46.           new List();
  47.       map.Add("Kids", kids);
  48.       int page = 1;
  49.       IEnumerable days = PojoFactory.GetDays();
  50.       foreach (string day in days) {
  51.         Dictionary kid = new Dictionary();      
  52.         kids.Add(kid);
  53.         kid["Title"] = day;
  54.         kid["Action"] = "GoTo";
  55.         kid["Page"] = String.Format("{0} Fit", page++);
  56.       }      
  57.       // Create a reader
  58.       PdfReader reader = new PdfReader(src);
  59.       using (MemoryStream ms = new MemoryStream()) {
  60.         // Create a stamper
  61.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  62.           stamper.Outlines = outlines;
  63.         }
  64.         return ms.ToArray();
  65.       }
  66.     }    
  67. // ===========================================================================
  68.   }
  69. }
ConcatenateBookmarks.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 Ionic.Zip;
  10. using System.Collections;
  11. using System.Collections.Generic;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Chapter02;
  15. using kuujinbo.iTextInAction2Ed.Chapter03;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  18.   public class ConcatenateBookmarks : IWriter {
  19. // ===========================================================================
  20.     /** The resulting PDF. */
  21.     public const String RESULT = "concatenated_bookmarks.pdf";
  22. // ---------------------------------------------------------------------------      
  23.     public void Write(Stream stream) {
  24.       using (ZipFile zip = new ZipFile()) {
  25.         MovieTemplates m = new MovieTemplates();
  26.         byte[] pdf = Utility.PdfBytes(m);
  27.         BookmarkedTimeTable b = new BookmarkedTimeTable();
  28.         byte[] bttBytes = b.ManipulatePdf(pdf);      
  29.         MovieHistory mh = new MovieHistory();
  30.         byte[] mhBytes = Utility.PdfBytes(mh);
  31.         List src = new List() {bttBytes, mhBytes};
  32.         ConcatenateBookmarks cb = new ConcatenateBookmarks();
  33.         zip.AddEntry(RESULT, cb.ManipulatePdf(src));
  34.         zip.AddEntry(Utility.ResultFileName(b.ToString() + ".pdf"), bttBytes);
  35.         zip.AddEntry(Utility.ResultFileName(mh.ToString() + ".pdf"), mhBytes);
  36.         zip.Save(stream);            
  37.       }
  38.     }
  39. // ---------------------------------------------------------------------------  
  40.     /**
  41.      * Manipulates a PDF file src with the file dest as result
  42.      * @param src the original PDF
  43.      */
  44.     public byte[] ManipulatePdf(List src) {
  45.       using (MemoryStream ms = new MemoryStream()) {
  46.         // step 1
  47.         using (Document document = new Document()) {
  48.           // step 2
  49.           using (PdfCopy copy = new PdfCopy(document, ms)) {
  50.             // step 3
  51.             document.Open();
  52.             // step 4
  53.             int page_offset = 0;
  54.             // Create a list for the bookmarks
  55.             List bookmarks =
  56.                 new List();
  57.                
  58.             for (int i  = 0; i < src.Count; i++) {
  59.               PdfReader reader = new PdfReader(src[i]);
  60.               // merge the bookmarks
  61.               IList tmp =
  62.                   SimpleBookmark.GetBookmark(reader);
  63.               SimpleBookmark.ShiftPageNumbers(tmp, page_offset, null);
  64.               foreach (var d in tmp) bookmarks.Add(d);
  65.              
  66.               // add the pages
  67.               int n = reader.NumberOfPages;
  68.               page_offset += n;
  69.               for (int page = 0; page < n; ) {
  70.                 copy.AddPage(copy.GetImportedPage(reader, ++page));
  71.               }
  72.             }
  73.             // Add the merged bookmarks
  74.             copy.Outlines = bookmarks;
  75.           }
  76.         }
  77.         return ms.ToArray();
  78.       }
  79.     }    
  80. // ===========================================================================
  81.   }
  82. }
MovieAnnotations1.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 Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  15.   public class MovieAnnotations1 : IWriter {
  16. // ===========================================================================
  17.     /** The resulting PDF. */
  18.     public const String RESULT = "movie_annotations_1.pdf";
  19.     /** Pattern for an info String. */
  20.     public const string INFO = "Movie produced in {0}; run length: {1}";
  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.         foreach (Movie movie in PojoFactory.GetMovies()) {
  31.           document.Add(new Phrase(movie.MovieTitle));
  32.           document.Add(new Annotation(
  33.             movie.Title,
  34.             string.Format(INFO, movie.Year, movie.Duration)
  35.           ));
  36.           document.Add(PojoToElementFactory.GetDirectorList(movie));
  37.           document.Add(PojoToElementFactory.GetCountryList(movie));
  38.         }
  39.       }
  40.     }
  41. // ===========================================================================
  42.   }
  43. }
MovieAnnotations2.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 Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  15.   public class MovieAnnotations2 : IWriter {
  16. // ===========================================================================
  17.     /** Pattern for an info String. */
  18.     public const string INFO = "Movie produced in {0}; run length: {1}";
  19. // ---------------------------------------------------------------------------          
  20.     public void Write(Stream stream) {
  21.       // step 1
  22.       using (Document document = new Document()) {
  23.         // step 2
  24.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  25.         // step 3
  26.         document.Open();
  27.         // step 4
  28.         Phrase phrase;
  29.         Chunk chunk;        
  30.         foreach (Movie movie in PojoFactory.GetMovies()) {
  31.           phrase = new Phrase(movie.MovieTitle);
  32.           chunk = new Chunk("\u00a0");
  33.           chunk.SetAnnotation( PdfAnnotation.CreateText(
  34.             writer, null, movie.MovieTitle,
  35.             string.Format(INFO, movie.Year, movie.Duration),
  36.             false, "Comment"
  37.           ));
  38.           phrase.Add(chunk);
  39.           document.Add(phrase);
  40.           document.Add(PojoToElementFactory.GetDirectorList(movie));
  41.           document.Add(PojoToElementFactory.GetCountryList(movie));
  42.         }
  43.       }
  44.     }
  45. // ===========================================================================
  46.   }
  47. }
GenericAnnotations.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 Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using iTextSharp.text.pdf.draw;
  13. /*
  14.  * book example inherits directly from PdfPageEventHelper class, we use
  15.  * nested inner class.
  16. */
  17. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  18.   public class GenericAnnotations : IWriter {
  19. // ===========================================================================
  20.     /** Possible icons. */
  21.     public static readonly string[] ICONS = {
  22.       "Comment", "Key", "Note", "Help", "NewParagraph", "Paragraph", "Insert"
  23.     };
  24. // ---------------------------------------------------------------------------
  25.     public void Write(Stream stream) {
  26.       // step 1
  27.       using (Document document = new Document()) {
  28.         // step 2
  29.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  30.         writer.PageEvent = new AnnotationHelper();
  31.         // step 3
  32.         document.Open();
  33.         // step 4
  34.         Paragraph p = new Paragraph();
  35.         Chunk chunk;
  36.         Chunk tab = new Chunk(new VerticalPositionMark());
  37.         for (int i = 0; i < ICONS.Length; i++) {
  38.           chunk = new Chunk(ICONS[i]);
  39.           chunk.SetGenericTag(ICONS[i]);
  40.           p.Add(chunk);
  41.           p.Add(tab);
  42.         }        
  43.         document.Add(p);
  44.       }
  45.     }
  46. /*
  47.  * ###########################################################################
  48.  * Inner class to write annotations
  49.  * ###########################################################################
  50. */
  51.     class AnnotationHelper : PdfPageEventHelper {
  52.     /**
  53.      * @see com.itextpdf.text.pdf.PdfPageEventHelper#onGenericTag(
  54.      *      com.itextpdf.text.pdf.PdfWriter,
  55.      *      com.itextpdf.text.Document,
  56.      *      com.itextpdf.text.Rectangle, java.lang.String)
  57.      */
  58.       public override void OnGenericTag(PdfWriter writer,
  59.         Document document, Rectangle rect, string text)
  60.       {
  61.         PdfAnnotation annotation = new PdfAnnotation(writer,
  62.           new Rectangle(
  63.             rect.Right+ 10, rect.Bottom,
  64.             rect.Right+ 30, rect.Top
  65.           )
  66.         );
  67.         annotation.Title = "Text annotation";
  68.         annotation.Put(PdfName.SUBTYPE, PdfName.TEXT);
  69.         annotation.Put(PdfName.OPEN, PdfBoolean.PDFFALSE);
  70.         annotation.Put(PdfName.CONTENTS,
  71.           new PdfString(string.Format("Icon: {0}", text))
  72.         );
  73.         annotation.Put(PdfName.NAME, new PdfName(text));
  74.         writer.AddAnnotation(annotation);
  75.       }        
  76.     }
  77. // ===========================================================================
  78.   }
  79. }
TimetableAnnotations1.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 Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Data;
  12. using System.Data.Common;
  13. using System.Linq;
  14. using iTextSharp.text;
  15. using iTextSharp.text.pdf;
  16. using iTextSharp.text.html;
  17. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  18. using kuujinbo.iTextInAction2Ed.Chapter03;
  19.  
  20. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  21.   public class TimetableAnnotations1 : IWriter {
  22. // ===========================================================================
  23.     /** The resulting PDF. */
  24.     public const String RESULT = "timetable_help.pdf";
  25.     /** A pattern for an info string. */
  26.     public const string INFO = "Movie produced in {0}; run length: {1}";
  27.     /** A list containing all the locations. */
  28.     protected List locations;
  29.    
  30.     /** The number of locations on our time table. */
  31.     public const int LOCATIONS = 9;
  32.     /** The number of time slots on our time table. */
  33.     public const int TIMESLOTS = 32;
  34.     /** The "offset time" for our calendar sheets. */
  35.     // public static long TIME930 = 30600000L;
  36.     public const long TIME930 = 34200000L;
  37.     /** The offset to the left of our time table. */
  38.     public const float OFFSET_LEFT = 76;
  39.     /** The width of our time table. */
  40.     public const float WIDTH = 740;
  41.     /** The width of a time slot. */
  42.     public static float WIDTH_TIMESLOT = WIDTH / TIMESLOTS;
  43.     /** The width of one minute. */
  44.     public static float MINUTE = WIDTH_TIMESLOT / 30f;
  45.     /** The offset from the bottom of our time table. */
  46.     public const float OFFSET_BOTTOM = 36;
  47.     /** The height of our time table */
  48.     public const float HEIGHT = 504;
  49.     /** The height of a bar showing the movies at one specific location. */
  50.     public static float HEIGHT_LOCATION = HEIGHT / LOCATIONS;
  51. // ---------------------------------------------------------------------------
  52.     public virtual void Write(Stream stream) {
  53.       using (ZipFile zip = new ZipFile()) {
  54.         MovieTemplates m = new MovieTemplates();
  55.         byte[] pdf = Utility.PdfBytes(m);
  56.         TimetableAnnotations1 t = new TimetableAnnotations1();
  57.         zip.AddEntry(RESULT, t.ManipulatePdf(pdf));
  58.         zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdf);
  59.         zip.Save(stream);            
  60.       }
  61.     }    
  62. // ---------------------------------------------------------------------------
  63.     /**
  64.      * Manipulates a PDF file src with the file dest as result
  65.      * @param src the original PDF
  66.      */
  67.     public virtual byte[] ManipulatePdf(byte[] src) {
  68.       locations = PojoFactory.GetLocations();
  69.       // Create a reader
  70.       PdfReader reader = new PdfReader(src);
  71.       using (MemoryStream ms = new MemoryStream()) {
  72.         // Create a stamper
  73.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  74.           // Add the annotations
  75.           int page = 1;
  76.           Rectangle rect;
  77.           PdfAnnotation annotation;
  78.           Movie movie;
  79.           foreach (string day in PojoFactory.GetDays()) {
  80.             foreach (Screening screening in PojoFactory.GetScreenings(day)) {
  81.               movie = screening.movie;
  82.               rect = GetPosition(screening);
  83.               annotation = PdfAnnotation.CreateText(
  84.                 stamper.Writer, rect, movie.MovieTitle,
  85.                 string.Format(INFO, movie.Year, movie.Duration),
  86.                 false, "Help"
  87.               );
  88.               annotation.Color = WebColors.GetRGBColor(
  89.                 "#" + movie.entry.category.color
  90.               );
  91.               stamper.AddAnnotation(annotation, page);
  92.             }
  93.             page++;
  94.           }
  95.         }
  96.         return ms.ToArray();
  97.       }
  98.     }  
  99. // ---------------------------------------------------------------------------
  100.     /**
  101.      * Calculates the position of a rectangle corresponding with a screening.
  102.      * @param    screening    a screening POJO, contains a movie
  103.      * @return    a Rectangle
  104.      */
  105.     protected Rectangle GetPosition(Screening screening) {
  106.       float llx, lly, urx, ury;
  107.       // long minutesAfter930 = (screening.getTime().getTime() - TIME930) / 60000L;
  108.       long minutesAfter930 = (
  109.         Utility.GetMilliseconds(screening.Time) - TIME930
  110.       ) / 60000L;      
  111.       llx = OFFSET_LEFT + (MINUTE * minutesAfter930);
  112.       int location = locations.IndexOf(screening.Location) + 1;
  113.       lly = OFFSET_BOTTOM + (LOCATIONS - location) * HEIGHT_LOCATION;
  114.       urx = llx + MINUTE * screening.movie.Duration;
  115.       ury = lly + HEIGHT_LOCATION;
  116.       Rectangle rect = new Rectangle(llx, lly, urx, ury);
  117.       return rect;
  118.     }
  119. // ===========================================================================
  120.   }
  121. }
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 iTextSharp.text;
  10. using iTextSharp.text.pdf;
  11. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  12.  
  13. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  14.   public class MoviePosters1 : IWriter {
  15. // ===========================================================================
  16.     /** Path to IMDB. */
  17.     public const string IMDB = "http://imdb.com/title/tt{0}/";
  18. // ---------------------------------------------------------------------------      
  19.     public void Write(Stream stream) {
  20.       // step 1
  21.       using (Document document = new Document(PageSize.A4)) {
  22.         // step 2
  23.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  24.         // step 3
  25.         document.Open();
  26.         // step 4
  27.         PdfContentByte canvas = writer.DirectContent;
  28.         // Create a reusable XObject
  29.         PdfTemplate celluloid = canvas.CreateTemplate(595, 84.2f);
  30.         celluloid.Rectangle(8, 8, 579, 68);
  31.         for (float f = 8.25f; f < 581; f+= 6.5f) {
  32.           celluloid.RoundRectangle(f, 8.5f, 6, 3, 1.5f);
  33.           celluloid.RoundRectangle(f, 72.5f, 6, 3, 1.5f);
  34.         }
  35.         celluloid.SetGrayFill(0.1f);
  36.         celluloid.EoFill();
  37.         writer.ReleaseTemplate(celluloid);
  38.         // Add the XObject ten times
  39.         for (int i = 0; i < 10; i++) {
  40.           canvas.AddTemplate(celluloid, 0, i * 84.2f);
  41.         }
  42.         // Add the movie posters
  43.         Image img;
  44.         Annotation annotation;
  45.         float x = 11.5f;
  46.         float y = 769.7f;
  47.         string RESOURCE = Utility.ResourcePosters;
  48.         foreach (Movie movie in PojoFactory.GetMovies()) {
  49.           img = Image.GetInstance(Path.Combine(RESOURCE, movie.Imdb + ".jpg"));
  50.           img.ScaleToFit(1000, 60);
  51.           img.SetAbsolutePosition(x + (45 - img.ScaledWidth) / 2, y);
  52.           annotation = new Annotation(
  53.             0, 0, 0, 0,
  54.             string.Format(IMDB, movie.Imdb)
  55.           );
  56.           img.Annotation = annotation;
  57.           canvas.AddImage(img);
  58.           x += 48;
  59.           if (x > 578) {
  60.             x = 11.5f;
  61.             y -= 84.2f;
  62.           }
  63.         }
  64.       }
  65.     }
  66. // ===========================================================================
  67.   }
  68. }
TimetableAnnotations2.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 Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Data;
  12. using System.Data.Common;
  13. using System.Linq;
  14. using iTextSharp.text;
  15. using iTextSharp.text.pdf;
  16. using iTextSharp.text.html;
  17. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  18. using kuujinbo.iTextInAction2Ed.Chapter03;
  19.  
  20. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  21.   public class TimetableAnnotations2 : TimetableAnnotations1 {
  22. // ===========================================================================
  23.     /** The resulting PDF. */
  24.     public new const String RESULT = "timetable_links.pdf";
  25.     /** Path to IMDB. */
  26.     public const string IMDB = "http://imdb.com/title/tt{0}/";
  27. // ---------------------------------------------------------------------------
  28.     public override void Write(Stream stream) {
  29.       using (ZipFile zip = new ZipFile()) {
  30.         MovieTemplates m = new MovieTemplates();
  31.         byte[] pdf = Utility.PdfBytes(m);
  32.         TimetableAnnotations2 t = new TimetableAnnotations2();
  33.         zip.AddEntry(RESULT, t.ManipulatePdf(pdf));
  34.         zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdf);
  35.         zip.Save(stream);            
  36.       }
  37.     }
  38. // ---------------------------------------------------------------------------
  39.     /**
  40.      * Manipulates a PDF file src with the file dest as result
  41.      * @param src the original PDF
  42.      */
  43.     public override byte[] ManipulatePdf(byte[] src) {
  44.       locations = PojoFactory.GetLocations();
  45.       // Create a reader
  46.       PdfReader reader = new PdfReader(src);
  47.       using (MemoryStream ms = new MemoryStream()) {
  48.         // Create a stamper
  49.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  50.           // Add annotations for every screening
  51.           int page = 1;
  52.           Rectangle rect;
  53.           PdfAnnotation annotation;
  54.           foreach (string day in PojoFactory.GetDays()) {
  55.             foreach (Screening screening in PojoFactory.GetScreenings(day)) {
  56.               rect = GetPosition(screening);
  57.               annotation = PdfAnnotation.CreateLink(
  58.                 stamper.Writer, rect, PdfAnnotation.HIGHLIGHT_INVERT,
  59.                 new PdfAction(string.Format(IMDB, screening.movie.Imdb))
  60.               );
  61.               stamper.AddAnnotation(annotation, page);
  62.             }
  63.             page++;
  64.           }
  65.         }
  66.         return ms.ToArray();
  67.       }
  68.     }
  69. // ===========================================================================
  70.   }
  71. }
MovieAnnotations3.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 Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  15.   public class MovieAnnotations3 : IWriter {
  16. // ===========================================================================
  17.     public void Write(Stream stream) {
  18.       MovieAnnotations3 example = new MovieAnnotations3();
  19.       example.CreatePdf(stream);        
  20.     }
  21. // ---------------------------------------------------------------------------    
  22.     /**
  23.      * Creates a PDF document.
  24.      * @param stream Stream for the new PDF document
  25.      */
  26.     public void CreatePdf(Stream stream) {
  27.       string RESOURCE = Utility.ResourcePosters;
  28.       // step 1
  29.       using (Document document = new Document()) {
  30.         // step 2
  31.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  32.         // step 3
  33.         document.Open();
  34.         // step 4
  35.         Phrase phrase;
  36.         Chunk chunk;
  37.         PdfAnnotation annotation;
  38.         foreach (Movie movie in PojoFactory.GetMovies()) {
  39.           phrase = new Phrase(movie.MovieTitle);
  40.           chunk = new Chunk("\u00a0\u00a0");
  41.           annotation = PdfAnnotation.CreateFileAttachment(
  42.             writer, null,
  43.             movie.MovieTitle, null,
  44.             Path.Combine(RESOURCE, movie.Imdb + ".jpg"),
  45.             string.Format("img_{0}.jpg", movie.Imdb)
  46.           );
  47.           annotation.Put(PdfName.NAME, new PdfString("Paperclip"));
  48.           chunk.SetAnnotation(annotation);
  49.           phrase.Add(chunk);
  50.           document.Add(phrase);
  51.           document.Add(PojoToElementFactory.GetDirectorList(movie));
  52.           document.Add(PojoToElementFactory.GetCountryList(movie));
  53.         }
  54.       }
  55.     }
  56. // ===========================================================================
  57.   }
  58. }
TimetableAnnotations3.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 Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Data;
  12. using System.Data.Common;
  13. using System.Linq;
  14. using iTextSharp.text;
  15. using iTextSharp.text.pdf;
  16. using iTextSharp.text.html;
  17. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  18. using kuujinbo.iTextInAction2Ed.Chapter03;
  19.  
  20. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  21.   public class TimetableAnnotations3 : TimetableAnnotations1 {
  22. // ===========================================================================
  23.     /** The resulting PDF file. */
  24.     public new const String RESULT = "timetable_tickets.pdf";
  25.     /** Path to IMDB. */
  26.     public const string IMDB = "http://imdb.com/title/tt{0}/";
  27. // ---------------------------------------------------------------------------
  28.     public override void Write(Stream stream) {
  29.       using (ZipFile zip = new ZipFile()) {
  30.         MovieTemplates m = new MovieTemplates();
  31.         byte[] pdf = Utility.PdfBytes(m);
  32.         TimetableAnnotations3 t = new TimetableAnnotations3();
  33.         zip.AddEntry(RESULT, t.ManipulatePdf(pdf));
  34.         zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdf);
  35.         zip.Save(stream);            
  36.       }
  37.     }
  38. // ---------------------------------------------------------------------------
  39.     /**
  40.      * Manipulates a PDF file src with the file dest as result
  41.      * @param src the original PDF
  42.      */
  43.     public override byte[] ManipulatePdf(byte[] src) {
  44.       locations = PojoFactory.GetLocations();
  45.       // Create a reader
  46.       PdfReader reader = new PdfReader(src);
  47.       using (MemoryStream ms = new MemoryStream()) {
  48.         // Create a stamper
  49.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  50.           // Loop over the days and screenings
  51.           int page = 1;
  52.           Rectangle rect;
  53.           float top;
  54.           PdfAnnotation annotation;
  55.           Movie movie;
  56.           foreach (string day in PojoFactory.GetDays()) {
  57.             foreach (Screening screening in PojoFactory.GetScreenings(day)) {
  58.               rect = GetPosition(screening);
  59.               movie = screening.movie;
  60.               // Annotation for press previews
  61.               if (screening.Press) {
  62.                 annotation = PdfAnnotation.CreateStamp(
  63.                   stamper.Writer, rect, "Press only", "NotForPublicRelease"
  64.                 );
  65.                 annotation.Color = BaseColor.BLACK;
  66.                 annotation.Flags = PdfAnnotation.FLAGS_PRINT;
  67.               }
  68.               // Annotation for screenings that are sold out
  69.               else if (IsSoldOut(screening)) {
  70.                 top = reader.GetPageSizeWithRotation(page).Top;
  71.                 annotation = PdfAnnotation.CreateLine(
  72.                     stamper.Writer, rect, "SOLD OUT",
  73.                     top - rect.Top, rect.Right,
  74.                     top - rect.Bottom, rect.Left
  75.                 );
  76.                 annotation.Title = movie.MovieTitle;
  77.                 annotation.Color = BaseColor.WHITE;
  78.                 annotation.Flags = PdfAnnotation.FLAGS_PRINT;
  79.                 annotation.BorderStyle = new PdfBorderDictionary(
  80.                   5, PdfBorderDictionary.STYLE_SOLID
  81.                 );
  82.               }
  83.               // Annotation for screenings with tickets available
  84.               else {
  85.                 annotation = PdfAnnotation.CreateSquareCircle(
  86.                   stamper.Writer, rect, "Tickets available", true
  87.                 );
  88.                 annotation.Title = movie.MovieTitle;
  89.                 annotation.Color = BaseColor.BLUE;
  90.                 annotation.Flags = PdfAnnotation.FLAGS_PRINT;
  91.                 annotation.Border = new PdfBorderArray(
  92.                   0, 0, 2, new PdfDashPattern()
  93.                 );
  94.               }
  95.               stamper.AddAnnotation(annotation, page);
  96.             }
  97.             page++;
  98.           }
  99.         }
  100.         return ms.ToArray();
  101.       }
  102.     }    
  103. // ---------------------------------------------------------------------------
  104.     /**
  105.      * Checks if the screening has been sold out.
  106.      * @param screening a Screening POJO
  107.      * @return true if the screening has been sold out.
  108.      */
  109.     public bool IsSoldOut(Screening screening) {
  110.       return screening.movie.MovieTitle.StartsWith("L")
  111.         ? true : false
  112.       ;
  113.     }    
  114. // ===========================================================================
  115.   }
  116. }
ButtonsActions.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 Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Data;
  12. using System.Data.Common;
  13. using System.Linq;
  14. using iTextSharp.text;
  15. using iTextSharp.text.pdf;
  16. using iTextSharp.text.html;
  17. using kuujinbo.iTextInAction2Ed.Chapter03;
  18.  
  19. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  20.   public class ButtonsActions : IWriter {
  21. // ===========================================================================
  22.     /** The resulting PDF. */
  23.     public const String RESULT = "save_mail_timetable.pdf";
  24. // ---------------------------------------------------------------------------    
  25.     public void Write(Stream stream) {
  26.       using (ZipFile zip = new ZipFile()) {
  27.         MovieTemplates m = new MovieTemplates();
  28.         byte[] pdf = Utility.PdfBytes(m);
  29.         ButtonsActions b = new ButtonsActions();
  30.         zip.AddEntry(RESULT, b.ManipulatePdf(pdf));
  31.         zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdf);        
  32.         zip.Save(stream);            
  33.       }
  34.     }
  35. // ---------------------------------------------------------------------------
  36.     /**
  37.      * Manipulates a PDF file src with the file dest as result
  38.      * @param src the original PDF
  39.      */
  40.     public byte[] ManipulatePdf(byte[] src) {
  41.       // Create a reader
  42.       PdfReader reader = new PdfReader(src);
  43.       int n = reader.NumberOfPages;
  44.       using (MemoryStream ms = new MemoryStream()) {
  45.         // Create a stamper
  46.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  47.           // Create pushbutton 1
  48.           PushbuttonField saveAs = new PushbuttonField(
  49.             stamper.Writer,
  50.             new Rectangle(636, 10, 716, 30),
  51.             "Save"
  52.           );
  53.           saveAs.BorderColor = BaseColor.BLACK;
  54.           saveAs.Text = "Save";
  55.           saveAs.TextColor = BaseColor.RED;
  56.           saveAs.Layout = PushbuttonField.LAYOUT_LABEL_ONLY;
  57.           saveAs.Rotation = 90;
  58.           PdfAnnotation saveAsButton = saveAs.Field;
  59.           saveAsButton.Action = PdfAction.JavaScript(
  60.             "app.execMenuItem('SaveAs')", stamper.Writer
  61.           );
  62.           // Create pushbutton 2
  63.           PushbuttonField mail = new PushbuttonField(
  64.             stamper.Writer,
  65.             new Rectangle(736, 10, 816, 30),
  66.             "Mail"
  67.           );
  68.           mail.BorderColor = BaseColor.BLACK;
  69.           mail.Text = "Mail";
  70.           mail.TextColor = BaseColor.RED;
  71.           mail.Layout = PushbuttonField.LAYOUT_LABEL_ONLY;
  72.           mail.Rotation = 90;
  73.           PdfAnnotation mailButton = mail.Field;
  74.           mailButton.Action = PdfAction.JavaScript(
  75.             "app.execMenuItem('AcroSendMail:SendMail')",
  76.             stamper.Writer
  77.           );
  78.           // Add the annotations to every page of the document
  79.           for (int page = 1; page
Advertisement.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 Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Data;
  12. using System.Data.Common;
  13. using System.Linq;
  14. using iTextSharp.text;
  15. using iTextSharp.text.pdf;
  16. using iTextSharp.text.html;
  17. using kuujinbo.iTextInAction2Ed.Chapter04;
  18.  
  19. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  20.   public class Advertisement : IWriter {
  21. // ===========================================================================
  22.     /** Path to a resource. */
  23.     public static String RESOURCE = Path.Combine(Utility.ResourcePdf, "hero.pdf");
  24.     /** Path to a resource. */
  25.     /** The resulting PDF file. */
  26.     public const String RESULT = "advertisement.pdf";
  27.     /** Path to a resource. */
  28.     public const string IMAGE = "close.png";
  29. // ---------------------------------------------------------------------------
  30.     public void Write(Stream stream) {
  31.       using (ZipFile zip = new ZipFile()) {
  32.         NestedTables n = new NestedTables();
  33.         byte[] pdf = Utility.PdfBytes(n);
  34.         Advertisement a = new Advertisement();
  35.         zip.AddEntry(RESULT, a.ManipulatePdf(pdf));      
  36.         zip.AddEntry(Utility.ResultFileName(n.ToString() + ".pdf"), pdf);
  37.         zip.AddFile(RESOURCE, "");
  38.         zip.Save(stream);            
  39.       }
  40.     }
  41. // ---------------------------------------------------------------------------
  42.     /**
  43.      * Manipulates a PDF file src with the file dest as result
  44.      * @param src the original PDF
  45.      */
  46.     public byte[] ManipulatePdf(byte[] src) {
  47.       // Create a reader for the original document
  48.       PdfReader reader = new PdfReader(src);
  49.       // Create a reader for the advertisement resource
  50.       PdfReader ad = new PdfReader(RESOURCE);
  51.       using (MemoryStream ms = new MemoryStream()) {
  52.         // Create a stamper
  53.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {          
  54.           // Create the advertisement annotation for the menubar
  55.           Rectangle rect = new Rectangle(400, 772, 545, 792);
  56.           PushbuttonField button = new PushbuttonField(
  57.             stamper.Writer, rect, "click"
  58.           );
  59.           button.BackgroundColor = BaseColor.RED;
  60.           button.BorderColor = BaseColor.RED;
  61.           button.FontSize = 10;
  62.           button.Text = "Close this advertisement";
  63.           button.Image = Image.GetInstance(
  64.             Path.Combine(Utility.ResourceImage, IMAGE)
  65.           );
  66.           button.Layout = PushbuttonField.LAYOUT_LABEL_LEFT_ICON_RIGHT;
  67.           button.IconHorizontalAdjustment = 1;
  68.           PdfFormField menubar = button.Field;
  69.           String js = "var f1 = getField('click'); f1.display = display.hidden;"
  70.             + "var f2 = getField('advertisement'); f2.display = display.hidden;"
  71.           ;
  72.           menubar.Action = PdfAction.JavaScript(js, stamper.Writer);
  73.           // Add the annotation
  74.           stamper.AddAnnotation(menubar, 1);
  75.           // Create the advertisement annotation for the content
  76.           rect = new Rectangle(400, 550, 545, 772);
  77.           button = new PushbuttonField(
  78.             stamper.Writer, rect, "advertisement"
  79.           );
  80.           button.BackgroundColor = BaseColor.WHITE;
  81.           button.BorderColor = BaseColor.RED;
  82.           button.Text = "Buy the book iText in Action 2nd edition";
  83.           button.Template = stamper.GetImportedPage(ad, 1);
  84.           button.Layout = PushbuttonField.LAYOUT_ICON_TOP_LABEL_BOTTOM;
  85.           PdfFormField advertisement = button.Field;
  86.           advertisement.Action = new PdfAction(
  87.             "http://www.1t3xt.com/docs/book.php"
  88.           );
  89.           // Add the annotation
  90.           stamper.AddAnnotation(advertisement, 1);      
  91.         }
  92.         return ms.ToArray();
  93.       }
  94.     }
  95. // ===========================================================================
  96.   }
  97. }
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 Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Data;
  12. using System.Data.Common;
  13. using System.Linq;
  14. using iTextSharp.text;
  15. using iTextSharp.text.pdf;
  16. using iTextSharp.text.html;
  17. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  18.  
  19. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  20.   public class MoviePosters2 : IWriter {
  21. // ===========================================================================
  22.     /** The resulting PDF file. */
  23.     public const String RESULT = "movie_posters_2.pdf";
  24.     /** A pattern for an info string. */
  25.     public const string INFO = "Movie produced in {0}; run length: {1}";
  26.     /** A JavaScript snippet */
  27.     public const string JS1 =
  28.       "var t = this.getAnnot(this.pageNum, 'IMDB{0}'); t.popupOpen = true; "
  29.     + "var w = this.getField('b{0}'); w.Focus();";
  30.     /** A JavaScript snippet */
  31.     public const string JS2 =
  32.       "var t = this.getAnnot(this.pageNum, 'IMDB{0}'); t.popupOpen = false;";
  33. // ---------------------------------------------------------------------------
  34.     public void Write(Stream stream) {
  35.       using (ZipFile zip = new ZipFile()) {
  36.         MoviePosters1 m = new MoviePosters1();
  37.         byte[] pdf = Utility.PdfBytes(m);
  38.         MoviePosters2 m2 = new MoviePosters2();
  39.         zip.AddEntry(RESULT, m2.ManipulatePdf(pdf));
  40.         zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdf);
  41.         zip.Save(stream);            
  42.       }
  43.     }
  44. // ---------------------------------------------------------------------------
  45.     /**
  46.      * Manipulates a PDF file src with the file dest as result
  47.      * @param src the original PDF
  48.      */
  49.     public byte[] ManipulatePdf(byte[] src) {
  50.       // Create a reader
  51.       PdfReader reader = new PdfReader(src);
  52.       using (MemoryStream ms = new MemoryStream()) {
  53.         // Create a stamper
  54.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {          
  55.           Image img;
  56.           float x = 11.5f;
  57.           float y = 769.7f;
  58.           float llx, lly, urx, ury;
  59.           string RESOURCE = Utility.ResourcePosters;
  60.           // Loop over all the movies to add a popup annotation
  61.           foreach (Movie movie in PojoFactory.GetMovies()) {
  62.             img = Image.GetInstance(Path.Combine(RESOURCE, movie.Imdb + ".jpg"));
  63.             img.ScaleToFit(1000, 60);
  64.             llx = x + (45 - img.ScaledWidth) / 2;
  65.             lly = y;
  66.             urx = x + img.ScaledWidth;
  67.             ury = y + img.ScaledHeight;
  68.             AddPopup(stamper, new Rectangle(llx, lly, urx, ury),
  69.               movie.MovieTitle,
  70.               string.Format(INFO, movie.Year, movie.Duration),
  71.               movie.Imdb
  72.             );
  73.             x += 48;
  74.             if (x > 578) {
  75.               x = 11.5f;
  76.               y -= 84.2f;
  77.             }
  78.           }
  79.         }
  80.         return ms.ToArray();
  81.       }
  82.     }  
  83. // ---------------------------------------------------------------------------
  84.     /**
  85.      * Adds a popup.
  86.      * @param stamper the PdfStamper to which the annotation needs to be added
  87.      * @param rect the position of the annotation
  88.      * @param title the annotation title
  89.      * @param contents the annotation content
  90.      * @param imdb the IMDB number of the movie used as name of the annotation
  91.      */
  92.     public void AddPopup(PdfStamper stamper, Rectangle rect,
  93.       String title, String contents, String imdb)
  94.     {
  95.   // Create the text annotation
  96.       PdfAnnotation text = PdfAnnotation.CreateText(
  97.         stamper.Writer,
  98.         rect, title, contents, false, "Comment"
  99.       );
  100.       text.Name = string.Format("IMDB{0}", imdb);
  101.       text.Flags = PdfAnnotation.FLAGS_READONLY | PdfAnnotation.FLAGS_NOVIEW;
  102.       // Create the popup annotation
  103.       PdfAnnotation popup = PdfAnnotation.CreatePopup(
  104.         stamper.Writer,
  105.         new Rectangle(
  106.           rect.Left + 10, rect.Bottom + 10,
  107.           rect.Left + 200, rect.Bottom + 100
  108.         ),
  109.         null, false
  110.       );
  111.       // Add the text annotation to the popup
  112.       popup.Put(PdfName.PARENT, text.IndirectReference);
  113.       // Declare the popup annotation as popup for the text
  114.       text.Put(PdfName.POPUP, popup.IndirectReference);
  115.       // Add both annotations
  116.       stamper.AddAnnotation(text, 1);
  117.       stamper.AddAnnotation(popup, 1);
  118.       // Create a button field
  119.       PushbuttonField field = new PushbuttonField(
  120.         stamper.Writer, rect,
  121.         string.Format("b{0}", imdb)
  122.       );
  123.       PdfAnnotation widget = field.Field;
  124.       // Show the popup onMouseEnter
  125.       PdfAction enter = PdfAction.JavaScript(
  126.         string.Format(JS1, imdb), stamper.Writer
  127.       );
  128.       widget.SetAdditionalActions(PdfName.E, enter);
  129.       // Hide the popup onMouseExit
  130.       PdfAction exit = PdfAction.JavaScript(
  131.         string.Format(JS2, imdb), stamper.Writer
  132.       );
  133.       widget.SetAdditionalActions(PdfName.X, exit);
  134.       // Add the button annotation
  135.       stamper.AddAnnotation(widget, 1);
  136.     }
  137. // ===========================================================================
  138.   }
  139. }
Calculator.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 Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12.  
  13. namespace kuujinbo.iTextInAction2Ed.Chapter07 {
  14.   public class Calculator : IWriter {
  15. // ===========================================================================
  16.     /** The resulting PDF. */
  17.     public const String RESULT = "calculator.pdf";
  18.     /** Path to the resource. */
  19.     public const string RESOURCE = "calculator.js";
  20. // ---------------------------------------------------------------------------            
  21.     /** The font that will be used in the appearances. */
  22.     public BaseFont bf;
  23.     /** Position of the digits */
  24.     Rectangle[] digits = new Rectangle[10];
  25.     /** Position of the operators. */
  26.     Rectangle plus, minus, mult, div, equals;
  27.     /** Position of the other annotations */
  28.     Rectangle clearEntry, clear, result, move;
  29. // ---------------------------------------------------------------------------                
  30.     /**
  31.      * Initializes the font
  32.      */
  33.     public void InitializeFont() {
  34.       bf = BaseFont.CreateFont();
  35.     }
  36. // ---------------------------------------------------------------------------
  37.     protected string jsString;
  38.     public void Write(Stream stream) {
  39.       using (ZipFile zip = new ZipFile()) {
  40.         Calculator calc = new Calculator();
  41.         calc.InitializeFont();
  42.         calc.InitializeRectangles();
  43.         zip.AddEntry(RESULT, calc.CreatePdf());
  44.         zip.AddEntry(RESOURCE, calc.jsString);
  45.         zip.Save(stream);            
  46.       }
  47.     }
  48. // ---------------------------------------------------------------------------    
  49.     /**
  50.      * Initializes the rectangles for the calculator keys.
  51.      */
  52.     public void InitializeRectangles() {
  53.       digits[0] = CreateRectangle(3, 1, 1, 1);
  54.       digits[1] = CreateRectangle(1, 3, 1, 1);
  55.       digits[2] = CreateRectangle(3, 3, 1, 1);
  56.       digits[3] = CreateRectangle(5, 3, 1, 1);
  57.       digits[4] = CreateRectangle(1, 5, 1, 1);
  58.       digits[5] = CreateRectangle(3, 5, 1, 1);
  59.       digits[6] = CreateRectangle(5, 5, 1, 1);
  60.       digits[7] = CreateRectangle(1, 7, 1, 1);
  61.       digits[8] = CreateRectangle(3, 7, 1, 1);
  62.       digits[9] = CreateRectangle(5, 7, 1, 1);
  63.       plus = CreateRectangle(7, 7, 1, 1);
  64.       minus = CreateRectangle(9, 7, 1, 1);
  65.       mult = CreateRectangle(7, 5, 1, 1);
  66.       div = CreateRectangle(9, 5, 1, 1);
  67.       equals = CreateRectangle(7, 1, 3, 1);
  68.       clearEntry = CreateRectangle(7, 9, 1, 1);
  69.       clear = CreateRectangle(9, 9, 1, 1);
  70.       result = CreateRectangle(1, 9, 5, 1);
  71.       move = CreateRectangle(8, 3, 1, 1);
  72.     }
  73. // ---------------------------------------------------------------------------    
  74.     /**
  75.      * Creates a PDF document for PdfReader.
  76.      * @param stream the stream to create new PDF document
  77.      */
  78.     public byte[] CreatePdf() {
  79.       using (MemoryStream ms = new MemoryStream()) {
  80.         // step 1
  81.         using (Document document = new Document(new Rectangle(360, 360))) {
  82.           // step 2
  83.           PdfWriter writer = PdfWriter.GetInstance(document, ms);      
  84.           // step 3
  85.           document.Open();
  86.           jsString = File.ReadAllText(
  87.             Path.Combine(Utility.ResourceJavaScript, RESOURCE)
  88.           );
  89.           writer.AddJavaScript(jsString);
  90.           // step 4
  91.           // add the keys for the digits
  92.           for (int i = 0; i < 10; i++) {
  93.             AddPushButton(
  94.               writer, digits[i],
  95.               i.ToString(), "this.augment(" + i + ")"
  96.             );
  97.           }
  98.           // add the keys for the operators
  99.           AddPushButton(writer, plus, "+", "this.register('+')");
  100.           AddPushButton(writer, minus, "-", "this.register('-')");
  101.           AddPushButton(writer, mult, "x", "this.register('*')");
  102.           AddPushButton(writer, div, ":", "this.register('/')");
  103.           AddPushButton(writer, equals, "=", "this.calculateResult()");
  104.           // add the other keys
  105.           AddPushButton(writer, clearEntry, "CE", "this.reset(false)");
  106.           AddPushButton(writer, clear, "C", "this.reset(true)");
  107.           AddTextField(writer, result, "result");
  108.           AddTextField(writer, move, "move");
  109.         }
  110.         return ms.ToArray();
  111.       }
  112.     }
  113. // ---------------------------------------------------------------------------    
  114.     /**
  115.      * Add a text field.
  116.      * @param writer the PdfWriter
  117.      * @param rect the position of the text field
  118.      * @param name the name of the text field
  119.      */
  120.     public void AddTextField(PdfWriter writer, Rectangle rect, String name) {
  121.       PdfFormField field = PdfFormField.CreateTextField(
  122.         writer, false, false, 0
  123.       );
  124.       field.FieldName = name;
  125.       field.SetWidget(rect, PdfAnnotation.HIGHLIGHT_NONE);
  126.       field.Quadding = PdfFormField.Q_RIGHT;
  127.       field.SetFieldFlags(PdfFormField.FF_READ_ONLY);
  128.       writer.AddAnnotation(field);
  129.     }
  130. // ---------------------------------------------------------------------------    
  131.     /**
  132.      * Create a pushbutton for a key
  133.      * @param writer the PdfWriter
  134.      * @param rect the position of the key
  135.      * @param btn the label for the key
  136.      * @param script the script to be executed when the button is pushed
  137.      */
  138.     public void AddPushButton(PdfWriter writer, Rectangle rect,
  139.       String btn, String script)
  140.     {
  141.       float w = rect.Width;
  142.       float h = rect.Height;
  143.       PdfFormField pushbutton = PdfFormField.CreatePushButton(writer);
  144.       pushbutton.FieldName = "btn_" + btn;
  145.       pushbutton.SetWidget(rect, PdfAnnotation.HIGHLIGHT_PUSH);
  146.       PdfContentByte cb = writer.DirectContent;
  147.       pushbutton.SetAppearance(
  148.         PdfAnnotation.APPEARANCE_NORMAL,
  149.         CreateAppearance(cb, btn, BaseColor.GRAY, w, h)
  150.       );
  151.       pushbutton.SetAppearance(
  152.         PdfAnnotation.APPEARANCE_ROLLOVER,
  153.         CreateAppearance(cb, btn, BaseColor.RED, w, h)
  154.       );
  155.       pushbutton.SetAppearance(
  156.         PdfAnnotation.APPEARANCE_DOWN,
  157.         CreateAppearance(cb, btn, BaseColor.BLUE, w, h)
  158.       );
  159.       pushbutton.SetAdditionalActions(
  160.         PdfName.U,
  161.         PdfAction.JavaScript(script, writer)
  162.       );
  163.       pushbutton.SetAdditionalActions(
  164.         PdfName.E, PdfAction.JavaScript(
  165.           "this.showMove('" + btn + "');", writer
  166.         )
  167.       );
  168.       pushbutton.SetAdditionalActions(
  169.         PdfName.X, PdfAction.JavaScript(
  170.           "this.showMove(' ');", writer
  171.         )
  172.       );
  173.       writer.AddAnnotation(pushbutton);
  174.     }
  175. // ---------------------------------------------------------------------------    
  176.     /**
  177.      * Creates an appearance for a key
  178.      * @param cb the canvas
  179.      * @param btn the label for the key
  180.      * @param color the color of the key
  181.      * @param w the width
  182.      * @param h the height
  183.      * @return an appearance
  184.      */
  185.     public PdfAppearance CreateAppearance(
  186.       PdfContentByte cb, String btn, BaseColor color, float w, float h)
  187.     {
  188.       PdfAppearance app = cb.CreateAppearance(w, h);
  189.       app.SetColorFill(color);
  190.       app.Rectangle(2, 2, w - 4, h - 4);
  191.       app.Fill();
  192.       app.BeginText();
  193.       app.SetColorFill(BaseColor.BLACK);
  194.       app.SetFontAndSize(bf, h / 2);
  195.       app.ShowTextAligned(Element.ALIGN_CENTER, btn, w / 2, h / 4, 0);
  196.       app.EndText();
  197.       return app;
  198.     }
  199. // ---------------------------------------------------------------------------    
  200.     /**
  201.      * Create a rectangle object for a key.
  202.      * @param column column of the key on the key pad
  203.      * @param row row of the key on the key pad
  204.      * @param width width of the key
  205.      * @param height height of the key
  206.      * @return a rectangle defining the position of a key.
  207.      */
  208.     public Rectangle CreateRectangle(
  209.       int column, int row, int width, int height)
  210.     {
  211.       column = column * 36 - 18;
  212.       row = row * 36 - 18;
  213.       return new Rectangle(
  214.         column, row,
  215.         column + width * 36, row + height * 36
  216.       );
  217.     }
  218. // ===========================================================================
  219.   }
  220. }
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