Chapter 16: PDF streams

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

10th October 2015
admin-marketing

Switch code for this example

SpecialId.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. package part4.chapter16;
  8.  
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11.  
  12. import com.itextpdf.text.Document;
  13. import com.itextpdf.text.DocumentException;
  14. import com.itextpdf.text.Image;
  15. import com.itextpdf.text.Rectangle;
  16. import com.itextpdf.text.pdf.PdfImage;
  17. import com.itextpdf.text.pdf.PdfIndirectObject;
  18. import com.itextpdf.text.pdf.PdfName;
  19. import com.itextpdf.text.pdf.PdfWriter;
  20.  
  21. public class SpecialId {
  22.  
  23.     /** The resulting PDF file. */
  24.     public static String RESULT = "results/part4/chapter16/special_id.pdf";
  25.     /** An image file. */
  26.     public static String RESOURCE = "resources/img/bruno.jpg";
  27.  
  28.     /**
  29.      * Creates a PDF document.
  30.      * @param filename the path to the new PDF document
  31.      * @throws    DocumentException
  32.      * @throws    IOException
  33.      */
  34.     public void createPdf(String filename) throws IOException, DocumentException {
  35.         Document document = new Document(new Rectangle(400, 300));
  36.         PdfWriter writer = PdfWriter.getInstance(document,
  37.                 new FileOutputStream(filename));
  38.         document.open();
  39.         Image img = Image.getInstance(RESOURCE);
  40.         img.scaleAbsolute(400, 300);
  41.         img.setAbsolutePosition(0, 0);
  42.         PdfImage stream = new PdfImage(img, "", null);
  43.         stream.put(new PdfName("ITXT_SpecialId"), new PdfName("123456789"));
  44.         PdfIndirectObject ref = writer.addToBody(stream);
  45.         img.setDirectReference(ref.getIndirectReference());
  46.         document.add(img);
  47.         document.close();
  48.     }
  49.  
  50.     /**
  51.      * Main method.
  52.      *
  53.      * @param    args    no arguments needed
  54.      * @throws DocumentException
  55.      * @throws IOException
  56.      */
  57.     public static void main(String[] args) throws IOException, DocumentException {
  58.         new SpecialId().createPdf(RESULT);
  59.     }
  60. }
ResizeImage.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. package part4.chapter16;
  8.  
  9. import java.awt.Graphics2D;
  10. import java.awt.geom.AffineTransform;
  11. import java.awt.image.BufferedImage;
  12. import java.io.ByteArrayOutputStream;
  13. import java.io.FileOutputStream;
  14. import java.io.IOException;
  15.  
  16. import javax.imageio.ImageIO;
  17.  
  18. import com.itextpdf.text.DocumentException;
  19. import com.itextpdf.text.pdf.PRStream;
  20. import com.itextpdf.text.pdf.PdfName;
  21. import com.itextpdf.text.pdf.PdfNumber;
  22. import com.itextpdf.text.pdf.PdfObject;
  23. import com.itextpdf.text.pdf.PdfReader;
  24. import com.itextpdf.text.pdf.PdfStamper;
  25. import com.itextpdf.text.pdf.parser.PdfImageObject;
  26.  
  27. public class ResizeImage {
  28.  
  29.     /** The resulting PDF file. */
  30.     public static String RESULT = "results/part4/chapter16/resized_image.pdf";
  31.     /** The multiplication factor for the image. */
  32.     public static float FACTOR = 0.5f;
  33.    
  34.     /**
  35.      * Manipulates a PDF file src with the file dest as result
  36.      * @param src the original PDF
  37.      * @param dest the resulting PDF
  38.      * @throws IOException
  39.      * @throws DocumentException
  40.      */
  41.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  42.         PdfName key = new PdfName("ITXT_SpecialId");
  43.         PdfName value = new PdfName("123456789");
  44.         // Read the file
  45.         PdfReader reader = new PdfReader(SpecialId.RESULT);
  46.         int n = reader.getXrefSize();
  47.         PdfObject object;
  48.         PRStream stream;
  49.         // Look for image and manipulate image stream
  50.         for (int i = 0; i < n; i++) {
  51.             object = reader.getPdfObject(i);
  52.             if (object == null || !object.isStream())
  53.                 continue;
  54.             stream = (PRStream)object;
  55.             if (value.equals(stream.get(key))) {
  56.                 PdfImageObject image = new PdfImageObject(stream);
  57.                 BufferedImage bi = image.getBufferedImage();
  58.                 if (bi == null) continue;
  59.                 int width = (int)(bi.getWidth() * FACTOR);
  60.                 int height = (int)(bi.getHeight() * FACTOR);
  61.                 BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  62.                 AffineTransform at = AffineTransform.getScaleInstance(FACTOR, FACTOR);
  63.                 Graphics2D g = img.createGraphics();
  64.                 g.drawRenderedImage(bi, at);
  65.                 ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
  66.                 ImageIO.write(img, "JPG", imgBytes);
  67.                 stream.clear();
  68.                 stream.setData(imgBytes.toByteArray(), false, PRStream.NO_COMPRESSION);
  69.                 stream.put(PdfName.TYPE, PdfName.XOBJECT);
  70.                 stream.put(PdfName.SUBTYPE, PdfName.IMAGE);
  71.                 stream.put(key, value);
  72.                 stream.put(PdfName.FILTER, PdfName.DCTDECODE);
  73.                 stream.put(PdfName.WIDTH, new PdfNumber(width));
  74.                 stream.put(PdfName.HEIGHT, new PdfNumber(height));
  75.                 stream.put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
  76.                 stream.put(PdfName.COLORSPACE, PdfName.DEVICERGB);
  77.             }
  78.         }
  79.         // Save altered PDF
  80.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
  81.         stamper.close();
  82.         reader.close();
  83.     }
  84.  
  85.     /**
  86.      * Main method.
  87.      *
  88.      * @param    args    no arguments needed
  89.      * @throws DocumentException
  90.      * @throws IOException
  91.      */
  92.     public static void main(String[] args) throws IOException, DocumentException {
  93.         new SpecialId().createPdf(SpecialId.RESULT);
  94.         new ResizeImage().manipulatePdf(SpecialId.RESULT, RESULT);
  95.     }
  96. }
ListUsedFonts.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 part4.chapter16;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.PrintWriter;
  13. import java.util.Set;
  14. import java.util.TreeSet;
  15.  
  16. import part3.chapter11.FontTypes;
  17.  
  18. import com.itextpdf.text.DocumentException;
  19. import com.itextpdf.text.pdf.PdfDictionary;
  20. import com.itextpdf.text.pdf.PdfName;
  21. import com.itextpdf.text.pdf.PdfReader;
  22.  
  23. public class ListUsedFonts {
  24.  
  25.     /** The resulting PDF file. */
  26.     public static String RESULT
  27.         = "results/part4/chapter16/fonts.txt";
  28.  
  29.     /**
  30.      * Creates a Set containing information about the fonts in the src PDF file.
  31.      * @param src the path to a PDF file
  32.      * @throws IOException
  33.      */
  34.     public Set listFonts(String src) throws IOException {
  35.         Set set = new TreeSet();
  36.         PdfReader reader = new PdfReader(src);
  37.         PdfDictionary resources;
  38.         for (int k = 1; k  8 && name.charAt(7) == '+') {
  39.                 name = String.format("%s subset (%s)", name.substring(8), name.substring(1, 7));
  40.             }
  41.             else {
  42.                 name = name.substring(1);
  43.                 PdfDictionary desc = font.getAsDict(PdfName.FONTDESCRIPTOR);
  44.                 if (desc == null)
  45.                     name += " nofontdescriptor";
  46.                 else if (desc.get(PdfName.FONTFILE) != null)
  47.                     name += " (Type 1) embedded";
  48.                 else if (desc.get(PdfName.FONTFILE2) != null)
  49.                     name += " (TrueType) embedded";
  50.                 else if (desc.get(PdfName.FONTFILE3) != null)
  51.                     name += " (" + font.getAsName(PdfName.SUBTYPE).toString().substring(1) + ") embedded";
  52.             }
  53.             set.add(name);
  54.         }
  55.     }
  56.    
  57.     /**
  58.      * Main method.
  59.      *
  60.      * @param    args    no arguments needed
  61.      * @throws DocumentException
  62.      * @throws IOException
  63.      */
  64.     public static void main(String[] args) throws IOException, DocumentException {
  65.         new FontTypes().createPdf(FontTypes.RESULT);
  66.         Set set = new ListUsedFonts().listFonts(FontTypes.RESULT);
  67.         PrintWriter out = new PrintWriter(new FileOutputStream(RESULT));
  68.         for (String fontname : set)
  69.             out.println(fontname);
  70.         out.flush();
  71.         out.close();
  72.     }
  73. }
EmbedFontPostFacto.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 part4.chapter16;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.RandomAccessFile;
  13.  
  14. import com.itextpdf.text.Document;
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.Font;
  17. import com.itextpdf.text.Paragraph;
  18. import com.itextpdf.text.pdf.BaseFont;
  19. import com.itextpdf.text.pdf.PdfDictionary;
  20. import com.itextpdf.text.pdf.PdfIndirectObject;
  21. import com.itextpdf.text.pdf.PdfName;
  22. import com.itextpdf.text.pdf.PdfNumber;
  23. import com.itextpdf.text.pdf.PdfObject;
  24. import com.itextpdf.text.pdf.PdfReader;
  25. import com.itextpdf.text.pdf.PdfStamper;
  26. import com.itextpdf.text.pdf.PdfStream;
  27. import com.itextpdf.text.pdf.PdfWriter;
  28.  
  29. public class EmbedFontPostFacto {
  30.  
  31.     /** The first resulting PDF file. */
  32.     public static String RESULT1 = "results/part4/chapter16/without_font.pdf";
  33.     /** The second resulting PDF file. */
  34.     public static String RESULT2 = "results/part4/chapter16/with_font.pdf";
  35.     /** A special font. */
  36.     public static String FONT = "resources/fonts/wds011402.ttf";
  37.     /** The name of the special font. */
  38.     public static String FONTNAME = "WaltDisneyScriptv4.1";
  39.  
  40.     /**
  41.      * Creates a PDF document.
  42.      * @param filename the path to the new PDF document
  43.      * @throws    DocumentException
  44.      * @throws    IOException
  45.      */
  46.     public void createPdf(String filename) throws IOException, DocumentException {
  47.         // step 1
  48.         Document document = new Document();
  49.         // step 2
  50.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  51.         // step 3
  52.         document.open();
  53.         // step 4:
  54.         Font font = new Font(BaseFont.createFont(FONT, "", BaseFont.NOT_EMBEDDED), 60);
  55.         document.add(new Paragraph("iText in Action", font));
  56.         // step 5
  57.         document.close();
  58.     }
  59.    
  60.     /**
  61.      * Manipulates a PDF file src with the file dest as result
  62.      * @param src the original PDF
  63.      * @param dest the resulting PDF
  64.      * @throws IOException
  65.      * @throws DocumentException
  66.      */
  67.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  68.         // the font file
  69.         RandomAccessFile raf = new RandomAccessFile(FONT, "r");
  70.         byte fontfile[] = new byte[(int)raf.length()];
  71.         raf.readFully(fontfile);
  72.         raf.close();
  73.         // create a new stream for the font file
  74.         PdfStream stream = new PdfStream(fontfile);
  75.         stream.flateCompress();
  76.         stream.put(PdfName.LENGTH1, new PdfNumber(fontfile.length));
  77.         // create a reader object
  78.         PdfReader reader = new PdfReader(src);
  79.         int n = reader.getXrefSize();
  80.         PdfObject object;
  81.         PdfDictionary font;
  82.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  83.         PdfName fontname = new PdfName(FONTNAME);
  84.         for (int i = 0; i < n; i++) {
  85.             object = reader.getPdfObject(i);
  86.             if (object == null || !object.isDictionary())
  87.                 continue;
  88.             font = (PdfDictionary)object;
  89.             if (PdfName.FONTDESCRIPTOR.equals(font.get(PdfName.TYPE))
  90.                 && fontname.equals(font.get(PdfName.FONTNAME))) {
  91.                 PdfIndirectObject objref = stamper.getWriter().addToBody(stream);
  92.                 font.put(PdfName.FONTFILE2, objref.getIndirectReference());
  93.             }
  94.         }
  95.         stamper.close();
  96.         reader.close();
  97.     }
  98.  
  99.     /**
  100.      * Main method.
  101.      *
  102.      * @param    args    no arguments needed
  103.      * @throws DocumentException
  104.      * @throws IOException
  105.      */
  106.     public static void main(String[] args) throws IOException, DocumentException {
  107.         EmbedFontPostFacto example = new EmbedFontPostFacto();
  108.         example.createPdf(RESULT1);
  109.         example.manipulatePdf(RESULT1, RESULT2);
  110.     }
  111. }
KubrickDvds.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. package part4.chapter16;
  8.  
  9. import java.io.ByteArrayOutputStream;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13. import java.util.Set;
  14. import java.util.TreeSet;
  15.  
  16. import com.itextpdf.text.Chunk;
  17. import com.itextpdf.text.Document;
  18. import com.itextpdf.text.DocumentException;
  19. import com.itextpdf.text.List;
  20. import com.itextpdf.text.ListItem;
  21. import com.itextpdf.text.Paragraph;
  22. import com.itextpdf.text.pdf.PRStream;
  23. import com.itextpdf.text.pdf.PdfAnnotation;
  24. import com.itextpdf.text.pdf.PdfArray;
  25. import com.itextpdf.text.pdf.PdfDictionary;
  26. import com.itextpdf.text.pdf.PdfName;
  27. import com.itextpdf.text.pdf.PdfReader;
  28. import com.itextpdf.text.pdf.PdfWriter;
  29. import com.lowagie.database.DatabaseConnection;
  30. import com.lowagie.database.HsqldbConnection;
  31. import com.lowagie.filmfestival.Movie;
  32. import com.lowagie.filmfestival.PojoFactory;
  33.  
  34. /**
  35.  * Creates a PDF listing Stanley Kubrick movies and the corresponding posters.
  36.  * JPGs of the movie posters are added as file attachment annotations.
  37.  * The attachments can be extracted.
  38.  */
  39. public class KubrickDvds {
  40.    
  41.     /** Path to the resources. */
  42.     public static final String RESOURCE
  43.         = "resources/posters/%s.jpg";
  44.     /** The filename of the resulting PDF. */
  45.     public static final String FILENAME = "kubrick_dvds.pdf";
  46.     /** The path to the resulting PDFs */
  47.     public static final String PATH = "results/part4/chapter16/%s";
  48.     /** The filename of the PDF with the movies by Stanley Kubrick. */
  49.     public static final String RESULT = String.format(PATH, FILENAME);
  50.    
  51.     /**
  52.      * Creates a PDF listing Stanley Kubrick movies in my DVD Collection.
  53.      * @throws IOException
  54.      * @throws DocumentException
  55.      * @throws SQLException
  56.      */
  57.     public static void main(String[] args) throws IOException, DocumentException, SQLException {
  58.         KubrickDvds kubrick = new KubrickDvds();
  59.         FileOutputStream os = new FileOutputStream(RESULT);
  60.         os.write(kubrick.createPdf());
  61.         os.flush();
  62.         os.close();
  63.         kubrick.extractAttachments(RESULT);
  64.     }
  65.    
  66.     /**
  67.      * Extracts attachments from an existing PDF.
  68.      * @param src   the path to the existing PDF
  69.      * @param dest  where to put the extracted attachments
  70.      * @throws IOException
  71.      */
  72.     public void extractAttachments(String src) throws IOException {
  73.         PdfReader reader = new PdfReader(src);
  74.         PdfArray array;
  75.         PdfDictionary annot;
  76.         PdfDictionary fs;
  77.         PdfDictionary refs;
  78.         for (int i = 1; i
KubrickDocumentary.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 part4.chapter16;
  9.  
  10. import java.io.ByteArrayOutputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.io.PrintStream;
  14. import java.sql.SQLException;
  15.  
  16. import com.itextpdf.text.Document;
  17. import com.itextpdf.text.DocumentException;
  18. import com.itextpdf.text.List;
  19. import com.itextpdf.text.ListItem;
  20. import com.itextpdf.text.Paragraph;
  21. import com.itextpdf.text.pdf.PRStream;
  22. import com.itextpdf.text.pdf.PdfArray;
  23. import com.itextpdf.text.pdf.PdfDictionary;
  24. import com.itextpdf.text.pdf.PdfFileSpecification;
  25. import com.itextpdf.text.pdf.PdfName;
  26. import com.itextpdf.text.pdf.PdfReader;
  27. import com.itextpdf.text.pdf.PdfWriter;
  28. import com.itextpdf.text.xml.XMLUtil;
  29. import com.lowagie.database.DatabaseConnection;
  30. import com.lowagie.database.HsqldbConnection;
  31. import com.lowagie.filmfestival.Movie;
  32. import com.lowagie.filmfestival.PojoFactory;
  33.  
  34. public class KubrickDocumentary {
  35.     /** The filename of the PDF. */
  36.     public static final String FILENAME = "kubrick_documentary.pdf";
  37.     /** The path to the resulting PDFs */
  38.     public static final String PATH = "results/part4/chapter16/%s";
  39.     /** The filename of the PDF with the movies by Stanley Kubrick. */
  40.     public static final String RESULT = String.format(PATH, FILENAME);
  41.    
  42.     /**
  43.      * Creates the PDF.
  44.      * @return the bytes of a PDF file.
  45.      * @throws DocumentExcetpion
  46.      * @throws IOException
  47.      * @throws SQLException
  48.      */
  49.     public byte[] createPdf() throws DocumentException, IOException, SQLException {
  50.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  51.         java.util.List movies = PojoFactory.getMovies(connection, 1);
  52.         connection.close();
  53.         // step 1
  54.         Document document = new Document();
  55.         // step 2
  56.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  57.         PdfWriter writer = PdfWriter.getInstance(document, baos);
  58.         // step 3
  59.         document.open();
  60.         // step 4
  61.         document.add(new Paragraph(
  62.             "'Stanley Kubrick: A Life in Pictures' is a documentary about Stanley Kubrick and his films:"));
  63.  
  64.         ByteArrayOutputStream txt = new ByteArrayOutputStream();
  65.         PrintStream out = new PrintStream(txt);
  66.         out.println("");
  67.         List list = new List(List.UNORDERED, 20);
  68.         ListItem item;
  69.         for (Movie movie : movies) {
  70.             out.println("");
  71.             out.println(
  72.                 String.format("%s", XMLUtil.escapeXML(movie.getMovieTitle(), true)));
  73.             out.println(String.format("%s", movie.getYear()));
  74.             out.println(String.format("%s", movie.getDuration()));
  75.             out.println("");
  76.             item = new ListItem(movie.getMovieTitle());
  77.             list.add(item);
  78.         }
  79.         document.add(list);
  80.         out.print("");
  81.         out.flush();
  82.         out.close();
  83.         PdfFileSpecification fs
  84.           = PdfFileSpecification.fileEmbedded(writer,
  85.                   null, "kubrick.xml", txt.toByteArray());
  86.         writer.addFileAttachment(fs);
  87.         // step 5
  88.         document.close();
  89.         return baos.toByteArray();
  90.     }
  91.    
  92.     /**
  93.      * Extracts document level attachments
  94.      * @param filename     a file from which document level attachments will be extracted
  95.      * @throws IOException
  96.      */
  97.     public void extractDocLevelAttachments(String filename) throws IOException {
  98.         PdfReader reader = new PdfReader(filename);
  99.         PdfDictionary root = reader.getCatalog();
  100.         PdfDictionary documentnames = root.getAsDict(PdfName.NAMES);
  101.         PdfDictionary embeddedfiles = documentnames.getAsDict(PdfName.EMBEDDEDFILES);
  102.         PdfArray filespecs = embeddedfiles.getAsArray(PdfName.NAMES);
  103.         PdfDictionary filespec;
  104.         PdfDictionary refs;
  105.         FileOutputStream fos;
  106.         PRStream stream;
  107.         for (int i = 0; i < filespecs.size(); ) {
  108.           filespecs.getAsString(i++);
  109.           filespec = filespecs.getAsDict(i++);
  110.           refs = filespec.getAsDict(PdfName.EF);
  111.           for (PdfName key : refs.getKeys()) {
  112.             fos = new FileOutputStream(String.format(PATH, filespec.getAsString(key).toString()));
  113.             stream = (PRStream) PdfReader.getPdfObject(refs.getAsIndirectObject(key));
  114.             fos.write(PdfReader.getStreamBytes(stream));
  115.             fos.flush();
  116.             fos.close();
  117.           }
  118.         }
  119.         reader.close();
  120.     }
  121.  
  122.     /**
  123.      * Main method.
  124.      *
  125.      * @param    args    no arguments needed
  126.      * @throws DocumentException
  127.      * @throws IOException
  128.      * @throws SQLException
  129.      */
  130.     public static void main(String[] args) throws IOException, DocumentException, SQLException {
  131.         KubrickDocumentary kubrick = new KubrickDocumentary();
  132.         FileOutputStream os = new FileOutputStream(RESULT);
  133.         os.write(kubrick.createPdf());
  134.         os.flush();
  135.         os.close();
  136.         kubrick.extractDocLevelAttachments(RESULT);
  137.     }
  138. }
KubrickBox.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. package part4.chapter16;
  8.  
  9. import java.io.ByteArrayOutputStream;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13. import java.util.Set;
  14. import java.util.TreeSet;
  15.  
  16. import com.itextpdf.text.Chunk;
  17. import com.itextpdf.text.Document;
  18. import com.itextpdf.text.DocumentException;
  19. import com.itextpdf.text.FontFactory;
  20. import com.itextpdf.text.Image;
  21. import com.itextpdf.text.List;
  22. import com.itextpdf.text.ListItem;
  23. import com.itextpdf.text.Paragraph;
  24. import com.itextpdf.text.pdf.BaseFont;
  25. import com.itextpdf.text.pdf.PdfAction;
  26. import com.itextpdf.text.pdf.PdfDestination;
  27. import com.itextpdf.text.pdf.PdfFileSpecification;
  28. import com.itextpdf.text.pdf.PdfNumber;
  29. import com.itextpdf.text.pdf.PdfPCell;
  30. import com.itextpdf.text.pdf.PdfPTable;
  31. import com.itextpdf.text.pdf.PdfWriter;
  32. import com.itextpdf.text.pdf.collection.PdfTargetDictionary;
  33. import com.lowagie.database.DatabaseConnection;
  34. import com.lowagie.database.HsqldbConnection;
  35. import com.lowagie.filmfestival.Movie;
  36. import com.lowagie.filmfestival.PojoFactory;
  37.  
  38. /**
  39.  * This example explains the use of portable collections,
  40.  * a new feature introduced in PDF 1.7
  41.  */
  42. public class KubrickBox {
  43.  
  44.     /** The resulting PDF. */
  45.     public static final String RESULT = "results/part4/chapter16/kubrick_box.pdf";
  46.     /** The path to an image used in the example. */
  47.     public static final String IMG_BOX = "resources/img/kubrick_box.jpg";
  48.     /** Path to the resources. */
  49.     public static final String RESOURCE = "resources/posters/%s.jpg";
  50.     /** The relative widths of the PdfPTable columns. */
  51.     public static final float[] WIDTHS = { 1 , 7 };
  52.  
  53.     /**
  54.      * Creates the PDF.
  55.      * @return the bytes of a PDF file.
  56.      * @throws DocumentException
  57.      * @throws IOException
  58.      * @throws SQLException
  59.      */
  60.     public void createPdf(String filename) throws DocumentException, IOException, SQLException {
  61.         // step 1
  62.         Document document = new Document();
  63.         // step 2
  64.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  65.         // step 3
  66.         document.open();
  67.         // step 4
  68.         Image img = Image.getInstance(IMG_BOX);
  69.         document.add(img);
  70.         List list = new List(List.UNORDERED, 20);
  71.         PdfDestination dest = new PdfDestination(PdfDestination.FIT);
  72.         dest.addFirst(new PdfNumber(1));
  73.         PdfTargetDictionary target;
  74.         Chunk chunk;
  75.         ListItem item;
  76.         PdfAction action = null;
  77.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  78.         Set box = new TreeSet();
  79.         box.addAll(PojoFactory.getMovies(connection, 1));
  80.         box.addAll(PojoFactory.getMovies(connection, 4));
  81.         connection.close();
  82.         PdfFileSpecification fs;
  83.         for (Movie movie : box) {
  84.             if (movie.getYear() > 1960) {
  85.                 fs = PdfFileSpecification.fileEmbedded(writer, null,
  86.                         String.format("kubrick_%s.pdf", movie.getImdb()),
  87.                         createMoviePage(movie));
  88.                 fs.addDescription(movie.getTitle(), false);
  89.                 writer.addFileAttachment(fs);
  90.                 item = new ListItem(movie.getMovieTitle());
  91.                 target = new PdfTargetDictionary(true);
  92.                 target.setEmbeddedFileName(movie.getTitle());
  93.                 action = PdfAction.gotoEmbedded(null, target, dest, true);
  94.                 chunk = new Chunk(" (see info)");
  95.                 chunk.setAction(action);
  96.                 item.add(chunk);
  97.                 list.add(item);
  98.             }
  99.         }
  100.         document.add(list);
  101.         // step 5
  102.         document.close();
  103.     }
  104.  
  105.     /**
  106.      * Creates the PDF.
  107.      * @return the bytes of a PDF file.
  108.      * @throws DocumentExcetpion
  109.      * @throws IOException
  110.      * @throws SQLException
  111.      */
  112.     public byte[] createMoviePage(Movie movie) throws DocumentException, IOException {
  113.         // step 1
  114.         Document document = new Document();
  115.         // step 2
  116.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  117.         PdfWriter.getInstance(document, baos);
  118.         // step 3
  119.         document.open();
  120.         // step 4
  121.         Paragraph p = new Paragraph(movie.getMovieTitle(),
  122.                 FontFactory.getFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED, 16));
  123.         document.add(p);
  124.         document.add(Chunk.NEWLINE);
  125.         PdfPTable table = new PdfPTable(WIDTHS);
  126.         table.addCell(Image.getInstance(String.format(RESOURCE, movie.getImdb())));
  127.         PdfPCell cell = new PdfPCell();
  128.         cell.addElement(new Paragraph("Year: " + movie.getYear()));
  129.         cell.addElement(new Paragraph("Duration: " + movie.getDuration()));
  130.         table.addCell(cell);
  131.         document.add(table);
  132.         PdfDestination dest = new PdfDestination(PdfDestination.FIT);
  133.         dest.addFirst(new PdfNumber(1));
  134.         PdfTargetDictionary target = new PdfTargetDictionary(false);
  135.         Chunk chunk = new Chunk("Go to original document");
  136.         PdfAction action = PdfAction.gotoEmbedded(null, target, dest, false);
  137.         chunk.setAction(action);
  138.         document.add(chunk);
  139.         // step 5
  140.         document.close();
  141.         return baos.toByteArray();
  142.     }
  143.  
  144.     /**
  145.      * Main method.
  146.      *
  147.      * @param    args    no arguments needed
  148.      * @throws DocumentException
  149.      * @throws IOException
  150.      * @throws SQLException
  151.      */
  152.     public static void main(String[] args) throws DocumentException, IOException, SQLException {
  153.         new KubrickBox().createPdf(RESULT);
  154.     }
  155. }
KubrickMovies.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. package part4.chapter16;
  8.  
  9. import java.io.ByteArrayOutputStream;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13.  
  14. import com.itextpdf.text.Chunk;
  15. import com.itextpdf.text.Document;
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.FontFactory;
  18. import com.itextpdf.text.Image;
  19. import com.itextpdf.text.Paragraph;
  20. import com.itextpdf.text.pdf.BaseFont;
  21. import com.itextpdf.text.pdf.PdfAction;
  22. import com.itextpdf.text.pdf.PdfFileSpecification;
  23. import com.itextpdf.text.pdf.PdfPCell;
  24. import com.itextpdf.text.pdf.PdfPTable;
  25. import com.itextpdf.text.pdf.PdfString;
  26. import com.itextpdf.text.pdf.PdfWriter;
  27. import com.itextpdf.text.pdf.collection.PdfCollection;
  28. import com.itextpdf.text.pdf.collection.PdfCollectionField;
  29. import com.itextpdf.text.pdf.collection.PdfCollectionItem;
  30. import com.itextpdf.text.pdf.collection.PdfCollectionSchema;
  31. import com.itextpdf.text.pdf.collection.PdfCollectionSort;
  32. import com.itextpdf.text.pdf.collection.PdfTargetDictionary;
  33. import com.lowagie.database.DatabaseConnection;
  34. import com.lowagie.database.HsqldbConnection;
  35. import com.lowagie.filmfestival.Movie;
  36. import com.lowagie.filmfestival.PojoFactory;
  37.  
  38. public class KubrickMovies {
  39.  
  40.     /** Path to the resources. */
  41.     public static final String RESOURCE
  42.         = "resources/posters/%s.jpg";
  43.     /** The relative widths of the PdfPTable columns. */
  44.     public static final float[] WIDTHS = { 1 , 7 };
  45.    
  46.     /** The filename of the PDF. */
  47.     public static final String FILENAME = "kubrick_movies.pdf";
  48.     /** The filename of the PDF with the movies by Stanley Kubrick. */
  49.     public static final String RESULT = "results/part4/chapter16/" + FILENAME;
  50.    
  51.     /**
  52.      * Creates a Collection schema that can be used to organize the movies of Stanley Kubrick
  53.      * in a collection: year, title, duration, DVD acquisition, filesize (filename is present, but hidden).
  54.      * @return    a collection schema
  55.      */
  56.     private static PdfCollectionSchema getCollectionSchema() {
  57.         PdfCollectionSchema schema = new PdfCollectionSchema();
  58.        
  59.         PdfCollectionField size = new PdfCollectionField("File size", PdfCollectionField.SIZE);
  60.         size.setOrder(4);
  61.         schema.addField("SIZE", size);
  62.        
  63.         PdfCollectionField filename = new PdfCollectionField("File name", PdfCollectionField.FILENAME);
  64.         filename.setVisible(false);
  65.         schema.addField("FILE", filename);
  66.        
  67.         PdfCollectionField title = new PdfCollectionField("Movie title", PdfCollectionField.TEXT);
  68.         title.setOrder(1);
  69.         schema.addField("TITLE", title);
  70.        
  71.         PdfCollectionField duration = new PdfCollectionField("Duration", PdfCollectionField.NUMBER);
  72.         duration.setOrder(2);
  73.         schema.addField("DURATION", duration);
  74.        
  75.         PdfCollectionField year = new PdfCollectionField("Year", PdfCollectionField.NUMBER);
  76.         year.setOrder(0);
  77.         schema.addField("YEAR", year);
  78.        
  79.         return schema;
  80.     }
  81.  
  82.     /**
  83.      * Creates the PDF.
  84.      * @return the bytes of a PDF file.
  85.      * @throws SQLException
  86.      */
  87.     public byte[] createPdf() throws DocumentException, IOException, SQLException {
  88.         // step 1
  89.         Document document = new Document();
  90.         // step 2
  91.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  92.         PdfWriter writer = PdfWriter.getInstance(document, baos);
  93.         // step 3
  94.         document.open();
  95.         // step 4
  96.         document.add(new Paragraph(
  97.             "This document contains a collection of PDFs, one per Stanley Kubrick movie."));
  98.        
  99.         PdfCollection collection = new PdfCollection(PdfCollection.DETAILS);
  100.         PdfCollectionSchema schema = getCollectionSchema();
  101.         collection.setSchema(schema);
  102.         PdfCollectionSort sort = new PdfCollectionSort("YEAR");
  103.         sort.setSortOrder(false);
  104.         collection.setSort(sort);
  105.         collection.setInitialDocument("Eyes Wide Shut");
  106.         writer.setCollection(collection);
  107.        
  108.         PdfFileSpecification fs;
  109.         PdfCollectionItem item;
  110.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  111.         java.util.List movies = PojoFactory.getMovies(connection, 1);
  112.         connection.close();
  113.         for (Movie movie : movies) {
  114.             fs = PdfFileSpecification.fileEmbedded(writer, null,
  115.                 String.format("kubrick_%s.pdf", movie.getImdb()),
  116.                 createMoviePage(movie));
  117.             fs.addDescription(movie.getTitle(), false);
  118.  
  119.             item = new PdfCollectionItem(schema);
  120.             item.addItem("TITLE", movie.getMovieTitle(false));
  121.             if (movie.getMovieTitle(true) != null) {
  122.                 item.setPrefix("TITLE", movie.getMovieTitle(true));
  123.             }
  124.             item.addItem("DURATION", movie.getDuration());
  125.             item.addItem("YEAR", movie.getYear());
  126.             fs.addCollectionItem(item);
  127.             writer.addFileAttachment(fs);
  128.         }
  129.         // step 5
  130.         document.close();
  131.         return baos.toByteArray();
  132.     }
  133.  
  134.     /**
  135.      * Creates the PDF.
  136.      * @return the bytes of a PDF file.
  137.      */
  138.     public byte[] createMoviePage(Movie movie) throws DocumentException, IOException {
  139.         // step 1
  140.         Document document = new Document();
  141.         // step 2
  142.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  143.         PdfWriter.getInstance(document, baos);
  144.         // step 3
  145.         document.open();
  146.         // step 4
  147.         Paragraph p = new Paragraph(movie.getMovieTitle(),
  148.             FontFactory.getFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED, 16));
  149.         document.add(p);
  150.         document.add(Chunk.NEWLINE);
  151.         PdfPTable table = new PdfPTable(WIDTHS);
  152.         table.addCell(Image.getInstance(String.format(RESOURCE, movie.getImdb())));
  153.         PdfPCell cell = new PdfPCell();
  154.         cell.addElement(new Paragraph("Year: " + movie.getYear()));
  155.         cell.addElement(new Paragraph("Duration: " + movie.getDuration()));
  156.         table.addCell(cell);
  157.         document.add(table);
  158.         PdfTargetDictionary target = new PdfTargetDictionary(false);
  159.         target.setAdditionalPath(new PdfTargetDictionary(false));
  160.         Chunk chunk = new Chunk("Go to original document");
  161.         PdfAction action = PdfAction.gotoEmbedded(null, target, new PdfString("movies"), false);
  162.         chunk.setAction(action);
  163.         document.add(chunk);
  164.         // step 5
  165.         document.close();
  166.         return baos.toByteArray();
  167.     }
  168.  
  169.     public static void main(String[] args) throws IOException, DocumentException, SQLException {
  170.         KubrickMovies kubrick = new KubrickMovies();
  171.         FileOutputStream os = new FileOutputStream(RESULT);
  172.         os.write(kubrick.createPdf());
  173.         os.flush();
  174.         os.close();
  175.     }
  176. }
KubrickCollection.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. package part4.chapter16;
  8.  
  9. import java.io.ByteArrayOutputStream;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.PrintStream;
  13. import java.sql.SQLException;
  14. import java.util.Set;
  15. import java.util.TreeSet;
  16.  
  17. import com.itextpdf.text.Chunk;
  18. import com.itextpdf.text.Document;
  19. import com.itextpdf.text.DocumentException;
  20. import com.itextpdf.text.Image;
  21. import com.itextpdf.text.List;
  22. import com.itextpdf.text.ListItem;
  23. import com.itextpdf.text.Phrase;
  24. import com.itextpdf.text.pdf.PdfAction;
  25. import com.itextpdf.text.pdf.PdfDestination;
  26. import com.itextpdf.text.pdf.PdfFileSpecification;
  27. import com.itextpdf.text.pdf.PdfNumber;
  28. import com.itextpdf.text.pdf.PdfPCell;
  29. import com.itextpdf.text.pdf.PdfPTable;
  30. import com.itextpdf.text.pdf.PdfWriter;
  31. import com.itextpdf.text.pdf.collection.PdfCollection;
  32. import com.itextpdf.text.pdf.collection.PdfCollectionField;
  33. import com.itextpdf.text.pdf.collection.PdfCollectionItem;
  34. import com.itextpdf.text.pdf.collection.PdfCollectionSchema;
  35. import com.itextpdf.text.pdf.collection.PdfCollectionSort;
  36. import com.itextpdf.text.pdf.collection.PdfTargetDictionary;
  37. import com.lowagie.database.DatabaseConnection;
  38. import com.lowagie.database.HsqldbConnection;
  39. import com.lowagie.filmfestival.Movie;
  40. import com.lowagie.filmfestival.PojoFactory;
  41.  
  42. /**
  43.  * This example explains the use of portable collections,
  44.  * a new feature introduced in PDF 1.7
  45.  */
  46. public class KubrickCollection {
  47.  
  48.     /** An image file used in this example */
  49.     public static final String IMG_BOX = "resources/img/kubrick_box.jpg";
  50.     /** An image file used in this example */
  51.     public static final String IMG_KUBRICK = "resources/img/kubrick.jpg";
  52.     /** The resulting PDF file. */
  53.     public static final String RESULT = "results/part4/chapter16/kubrick_collection.pdf";
  54.     /** The name of a field in the collection schema. */
  55.     public static final String TYPE_FIELD        = "TYPE";
  56.     /** A caption of a field in the collection schema. */
  57.     public static final String TYPE_CAPTION        = "File type";
  58.     /** The name of a field in the collection schema. */
  59.     public static final String FILE_FIELD        = "FILE";
  60.     /** A caption of a field in the collection schema. */
  61.     public static final String FILE_CAPTION        = "File name";
  62.     /** Sort order for the keys in the collection. */
  63.     public String[] KEYS = { TYPE_FIELD, FILE_FIELD };
  64.    
  65.     /**
  66.      * Creates the PDF.
  67.      * @return the bytes of a PDF file.
  68.      * @throws SQLException
  69.      */
  70.     public void createPdf(String filename) throws DocumentException, IOException, SQLException {
  71.         // step 1
  72.         Document document = new Document();
  73.         // step 2
  74.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  75.         // step 3
  76.         document.open();
  77.         // step 4
  78.         PdfCollection collection = new PdfCollection(PdfCollection.HIDDEN);
  79.         PdfCollectionSchema schema = getCollectionSchema();
  80.         collection.setSchema(schema);
  81.         PdfCollectionSort sort = new PdfCollectionSort(KEYS);
  82.         collection.setSort(sort);
  83.         writer.setCollection(collection);
  84.  
  85.         PdfCollectionItem collectionitem = new PdfCollectionItem(schema);
  86.         PdfFileSpecification fs;
  87.         fs = PdfFileSpecification.fileEmbedded(writer, IMG_KUBRICK, "kubrick.jpg", null);
  88.         fs.addDescription("Stanley Kubrick", false);
  89.         collectionitem.addItem(TYPE_FIELD, "JPEG");
  90.         fs.addCollectionItem(collectionitem);
  91.         writer.addFileAttachment(fs);
  92.        
  93.         ByteArrayOutputStream txt = new ByteArrayOutputStream();
  94.         PrintStream out = new PrintStream(txt);
  95.         Image img = Image.getInstance(IMG_BOX);
  96.         document.add(img);
  97.         List list = new List(List.UNORDERED, 20);
  98.         PdfDestination dest = new PdfDestination(PdfDestination.FIT);
  99.         dest.addFirst(new PdfNumber(1));
  100.         PdfTargetDictionary intermediate;
  101.         PdfTargetDictionary target;
  102.         Chunk chunk;
  103.         ListItem item;
  104.         PdfAction action = null;
  105.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  106.         Set box = new TreeSet();
  107.         java.util.List movies = PojoFactory.getMovies(connection, 1);
  108.         box.addAll(movies);
  109.         box.addAll(PojoFactory.getMovies(connection, 4));
  110.         connection.close();
  111.         for (Movie movie : box) {
  112.             if (movie.getYear() > 1960) {
  113.                 out.println(String.format(
  114.                     "%s;%s;%s", movie.getMovieTitle(), movie.getYear(), movie.getDuration()));
  115.                 item = new ListItem(movie.getMovieTitle());
  116.                 if (!"0278736".equals(movie.getImdb())) {
  117.                     target = new PdfTargetDictionary(true);
  118.                     target.setEmbeddedFileName(movie.getTitle());
  119.                     intermediate = new PdfTargetDictionary(true);
  120.                     intermediate.setFileAttachmentPage(1);
  121.                     intermediate.setFileAttachmentIndex(1);
  122.                     intermediate.setAdditionalPath(target);
  123.                     action = PdfAction.gotoEmbedded(null, intermediate, dest, true);
  124.                     chunk = new Chunk(" (see info)");
  125.                     chunk.setAction(action);
  126.                     item.add(chunk);
  127.                 }
  128.                 list.add(item);
  129.             }
  130.         }
  131.         out.flush();
  132.         out.close();
  133.         document.add(list);
  134.         fs = PdfFileSpecification.fileEmbedded(writer, null, "kubrick.txt", txt.toByteArray());
  135.         fs.addDescription("Kubrick box: the movies", false);
  136.         collectionitem.addItem(TYPE_FIELD, "TXT");
  137.         fs.addCollectionItem(collectionitem);
  138.         writer.addFileAttachment(fs);
  139.  
  140.         PdfPTable table = new PdfPTable(1);
  141.         table.setSpacingAfter(10);
  142.         PdfPCell cell = new PdfPCell(new Phrase("All movies by Kubrick"));
  143.         cell.setBorder(PdfPCell.NO_BORDER);
  144.         fs = PdfFileSpecification.fileEmbedded(
  145.             writer, null, KubrickMovies.FILENAME, new KubrickMovies().createPdf());
  146.         collectionitem.addItem(TYPE_FIELD, "PDF");
  147.         fs.addCollectionItem(collectionitem);
  148.         target = new PdfTargetDictionary(true);
  149.         target.setFileAttachmentPagename("movies");
  150.         target.setFileAttachmentName("The movies of Stanley Kubrick");
  151.         cell.setCellEvent(new PdfActionEvent(writer, PdfAction.gotoEmbedded(null, target, dest, true)));
  152.         cell.setCellEvent(new FileAttachmentEvent(writer, fs, "The movies of Stanley Kubrick"));
  153.         cell.setCellEvent(new LocalDestinationEvent(writer, "movies"));
  154.         table.addCell(cell);
  155.         writer.addFileAttachment(fs);
  156.  
  157.         cell = new PdfPCell(new Phrase("Kubrick DVDs"));
  158.         cell.setBorder(PdfPCell.NO_BORDER);
  159.         fs = PdfFileSpecification.fileEmbedded(
  160.             writer, null, KubrickDvds.FILENAME, new KubrickDvds().createPdf());
  161.         collectionitem.addItem(TYPE_FIELD, "PDF");
  162.         fs.addCollectionItem(collectionitem);
  163.         cell.setCellEvent(new FileAttachmentEvent(writer, fs, "Kubrick DVDs"));
  164.         table.addCell(cell);
  165.         writer.addFileAttachment(fs);
  166.        
  167.         cell = new PdfPCell(new Phrase("Kubrick documentary"));
  168.         cell.setBorder(PdfPCell.NO_BORDER);
  169.         fs = PdfFileSpecification.fileEmbedded(
  170.             writer, null, KubrickDocumentary.FILENAME, new KubrickDocumentary().createPdf());
  171.         collectionitem.addItem(TYPE_FIELD, "PDF");
  172.         fs.addCollectionItem(collectionitem);
  173.         cell.setCellEvent(new FileAttachmentEvent(writer, fs, "Kubrick Documentary"));
  174.         table.addCell(cell);
  175.         writer.addFileAttachment(fs);
  176.  
  177.         document.newPage();
  178.         document.add(table);
  179.         // step 5
  180.         document.close();
  181.     }
  182.    
  183.     /**
  184.      * Creates a Collection schema that can be used to organize the movies of Stanley Kubrick
  185.      * in a collection: year, title, duration, DVD acquisition, filesize (filename is present, but hidden).
  186.      * @return    a collection schema
  187.      */
  188.     private static PdfCollectionSchema getCollectionSchema() {
  189.         PdfCollectionSchema schema = new PdfCollectionSchema();
  190.        
  191.         PdfCollectionField type = new PdfCollectionField(TYPE_CAPTION, PdfCollectionField.TEXT);
  192.         type.setOrder(0);
  193.         schema.addField(TYPE_FIELD, type);
  194.        
  195.         PdfCollectionField filename = new PdfCollectionField(FILE_FIELD, PdfCollectionField.FILENAME);
  196.         filename.setOrder(1);
  197.         schema.addField(FILE_FIELD, filename);
  198.        
  199.         return schema;
  200.     }
  201.  
  202.     /**
  203.      * Main method.
  204.      *
  205.      * @param    args    no arguments needed
  206.      * @throws DocumentException
  207.      * @throws IOException
  208.      * @throws SQLException
  209.      */
  210.     public static void main(String[] args) throws DocumentException, IOException, SQLException {
  211.         new KubrickCollection().createPdf(RESULT);
  212.     }
  213. }
FileAttachmentEvent.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 part4.chapter16;
  9.  
  10. import java.io.IOException;
  11.  
  12. import com.itextpdf.text.Rectangle;
  13. import com.itextpdf.text.pdf.PdfAnnotation;
  14. import com.itextpdf.text.pdf.PdfContentByte;
  15. import com.itextpdf.text.pdf.PdfFileSpecification;
  16. import com.itextpdf.text.pdf.PdfPCell;
  17. import com.itextpdf.text.pdf.PdfPCellEvent;
  18. import com.itextpdf.text.pdf.PdfWriter;
  19.  
  20. public class FileAttachmentEvent implements PdfPCellEvent {
  21.  
  22.     /** The PdfWriter to which the file has to be attached. */
  23.     protected PdfWriter writer;
  24.     /** The file specification that will be used to create an annotation. */
  25.     protected PdfFileSpecification fs;
  26.     /** The description that comes with the annotation. */
  27.     protected String description;
  28.    
  29.     /**
  30.      * Creates a FileAttachmentEvent.
  31.      *
  32.      * @param writer      the writer to which the file attachment has to be added.
  33.      * @param fs          the file specification.
  34.      * @param description a description for the file attachment.
  35.      */
  36.     public FileAttachmentEvent(PdfWriter writer, PdfFileSpecification fs, String description) {
  37.         this.writer = writer;
  38.         this.fs = fs;
  39.         this.description = description;
  40.     }
  41.    
  42.     /**
  43.      * Implementation of the cellLayout method.
  44.      * @see com.itextpdf.text.pdf.PdfPCellEvent#cellLayout(
  45.      *     com.itextpdf.text.pdf.PdfPCell, com.itextpdf.text.Rectangle, com.itextpdf.text.pdf.PdfContentByte[])
  46.      */
  47.     public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
  48.         try {
  49.             PdfAnnotation annotation = PdfAnnotation.createFileAttachment(writer,
  50.                 new Rectangle(position.getLeft() - 20, position.getTop() - 15,
  51.                     position.getLeft() - 5, position.getTop() - 5),
  52.                 description, fs);
  53.             annotation.setName(description);
  54.             writer.addAnnotation(annotation);
  55.         } catch (IOException e) {
  56.             e.printStackTrace();
  57.         }
  58.     }
  59. }
PdfActionEvent.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. package part4.chapter16;
  8.  
  9. import com.itextpdf.text.Rectangle;
  10. import com.itextpdf.text.pdf.PdfAction;
  11. import com.itextpdf.text.pdf.PdfAnnotation;
  12. import com.itextpdf.text.pdf.PdfContentByte;
  13. import com.itextpdf.text.pdf.PdfPCell;
  14. import com.itextpdf.text.pdf.PdfPCellEvent;
  15. import com.itextpdf.text.pdf.PdfWriter;
  16.  
  17. public class PdfActionEvent implements PdfPCellEvent {
  18.  
  19.     /** The writer to which we are going to add the action. */
  20.     protected PdfWriter writer;
  21.     /** The action we're going to add. */
  22.     protected PdfAction action;
  23.    
  24.     /** Creates a new Action event. */
  25.     public PdfActionEvent(PdfWriter writer, PdfAction action) {
  26.         this.writer = writer;
  27.         this.action = action;
  28.     }
  29.    
  30.     /** Implementation of the cellLayout method. */
  31.     public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
  32.         writer.addAnnotation(new PdfAnnotation(writer,
  33.             position.getLeft(), position.getBottom(), position.getRight(), position.getTop(),
  34.             action));
  35.     }
  36. }
LocalDestinationEvent.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 part4.chapter16;
  9.  
  10. import com.itextpdf.text.Rectangle;
  11. import com.itextpdf.text.pdf.PdfContentByte;
  12. import com.itextpdf.text.pdf.PdfDestination;
  13. import com.itextpdf.text.pdf.PdfPCell;
  14. import com.itextpdf.text.pdf.PdfPCellEvent;
  15. import com.itextpdf.text.pdf.PdfWriter;
  16.  
  17. public class LocalDestinationEvent implements PdfPCellEvent {
  18.  
  19.     /** The writer to which the local destination will be added. */
  20.     protected PdfWriter writer;
  21.     /** The name of the local destination. */
  22.     protected String name;
  23.    
  24.     /** Constructs a local destination event. */
  25.     public LocalDestinationEvent(PdfWriter writer, String name) {
  26.         this.writer = writer;
  27.         this.name = name;
  28.     }
  29.    
  30.     /** Implementation of the cellLayout method. */
  31.     public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
  32.         writer.getDirectContent().localDestination(name,
  33.             new PdfDestination(PdfDestination.FITH, position.getTop()));
  34.     }
  35. }
MovieAnnotation.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 part4.chapter16;
  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.Rectangle;
  16. import com.itextpdf.text.pdf.PdfAnnotation;
  17. import com.itextpdf.text.pdf.PdfFileSpecification;
  18. import com.itextpdf.text.pdf.PdfWriter;
  19.  
  20. public class MovieAnnotation {
  21.  
  22.     /** The resulting PDF file. */
  23.     public static final String RESULT
  24.         = "results/part4/chapter16/movie.pdf";
  25.     /** One of the resources. */
  26.     public static final String RESOURCE
  27.         = "resources/img/foxdog.mpg";
  28.    
  29.     /**
  30.      * Creates a PDF document.
  31.      * @param filename the path to the new PDF document
  32.      * @throws    DocumentException
  33.      * @throws    IOException
  34.      */
  35.     public void createPdf(String filename) throws IOException, DocumentException {
  36.         // step 1
  37.         Document document = new Document();
  38.         // step 2
  39.         PdfWriter writer
  40.           = PdfWriter.getInstance(document, new FileOutputStream(filename));
  41.         // step 3
  42.         document.open();
  43.         // step 4
  44.         PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(writer,
  45.                 RESOURCE, "foxdog.mpg", null);
  46.         writer.addAnnotation(PdfAnnotation.createScreen(writer,
  47.                 new Rectangle(200f, 700f, 400f, 800f), "Fox and Dog", fs,
  48.                 "video/mpeg", true));
  49.         // step 5
  50.         document.close();
  51.     }
  52.    
  53.     /**
  54.      * Main method.
  55.      *
  56.      * @param    args    no arguments needed
  57.      * @throws DocumentException
  58.      * @throws IOException
  59.      * @throws DocumentException
  60.      * @throws IOException
  61.      */
  62.     public static void main(String[] args) throws IOException, DocumentException {
  63.         new MovieAnnotation().createPdf(RESULT);
  64.     }
  65. }
Pdf3D.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 part4.chapter16;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13.  
  14. import com.itextpdf.text.BaseColor;
  15. import com.itextpdf.text.Document;
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.Rectangle;
  18. import com.itextpdf.text.pdf.PdfAnnotation;
  19. import com.itextpdf.text.pdf.PdfAppearance;
  20. import com.itextpdf.text.pdf.PdfArray;
  21. import com.itextpdf.text.pdf.PdfDictionary;
  22. import com.itextpdf.text.pdf.PdfIndirectObject;
  23. import com.itextpdf.text.pdf.PdfName;
  24. import com.itextpdf.text.pdf.PdfNumber;
  25. import com.itextpdf.text.pdf.PdfStream;
  26. import com.itextpdf.text.pdf.PdfString;
  27. import com.itextpdf.text.pdf.PdfWriter;
  28.  
  29. public class Pdf3D {
  30.  
  31.     /** The resulting PDF file. */
  32.     public static String RESULT = "results/part4/chapter16/pdf3d.pdf";
  33.     /** The path to a 3D file. */
  34.     public static String RESOURCE = "resources/img/teapot.u3d";
  35.  
  36.     /**
  37.      * Main method.
  38.      *
  39.      * @param    args    no arguments needed
  40.      * @throws DocumentException
  41.      * @throws IOException
  42.      */
  43.     public static void main(String[] args) throws IOException, DocumentException {
  44.         new Pdf3D().createPdf(RESULT);
  45.     }
  46.  
  47.     /**
  48.      * Creates the PDF.
  49.      * @param  filename   the path to the resulting PDF file
  50.      * @throws DocumentException
  51.      * @throws IOException
  52.      */
  53.     public void createPdf(String filename) throws IOException, DocumentException {
  54.         // step 1
  55.         Document document = new Document();
  56.         // step 2
  57.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  58.         // step 3
  59.         document.open();
  60.         // step 4
  61.         Rectangle rect = new Rectangle(100, 400, 500, 800);
  62.         rect.setBorder(Rectangle.BOX);
  63.         rect.setBorderWidth(0.5f);
  64.         rect.setBorderColor(new BaseColor(0xFF, 0x00, 0x00));
  65.         document.add(rect);
  66.            
  67.         PdfStream stream3D = new PdfStream(new FileInputStream(RESOURCE), writer);
  68.         stream3D.put(PdfName.TYPE, new PdfName("3D"));
  69.         stream3D.put(PdfName.SUBTYPE, new PdfName("U3D"));
  70.         stream3D.flateCompress();
  71.         PdfIndirectObject streamObject = writer.addToBody(stream3D);
  72.         stream3D.writeLength();
  73.            
  74.         PdfDictionary dict3D = new PdfDictionary();
  75.         dict3D.put(PdfName.TYPE, new PdfName("3DView"));
  76.         dict3D.put(new PdfName("XN"), new PdfString("Default"));
  77.         dict3D.put(new PdfName("IN"), new PdfString("Unnamed"));
  78.         dict3D.put(new PdfName("MS"), PdfName.M);
  79.         dict3D.put(new PdfName("C2W"),
  80.             new PdfArray(new float[] { 1, 0, 0, 0, 0, -1, 0, 1, 0, 3, -235, 28 } ));
  81.         dict3D.put(PdfName.CO, new PdfNumber(235));
  82.  
  83.         PdfIndirectObject dictObject = writer.addToBody(dict3D);
  84.            
  85.         PdfAnnotation annot = new PdfAnnotation(writer, rect);
  86.         annot.put(PdfName.CONTENTS, new PdfString("3D Model"));
  87.         annot.put(PdfName.SUBTYPE, new PdfName("3D"));
  88.         annot.put(PdfName.TYPE, PdfName.ANNOT);
  89.         annot.put(new PdfName("3DD"), streamObject.getIndirectReference());
  90.         annot.put(new PdfName("3DV"), dictObject.getIndirectReference());
  91.         PdfAppearance ap = writer.getDirectContent().createAppearance(rect.getWidth(), rect.getHeight());
  92.         annot.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, ap);
  93.         annot.setPage();
  94.  
  95.         writer.addAnnotation(annot);
  96.         // step 5
  97.         document.close();
  98.     }
  99. }
FestivalCalendar1.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. package part4.chapter16;
  8. import java.io.FileOutputStream;
  9. import java.io.IOException;
  10.  
  11. import com.itextpdf.text.Document;
  12. import com.itextpdf.text.DocumentException;
  13. import com.itextpdf.text.Rectangle;
  14. import com.itextpdf.text.pdf.PdfAnnotation;
  15. import com.itextpdf.text.pdf.PdfDeveloperExtension;
  16. import com.itextpdf.text.pdf.PdfFileSpecification;
  17. import com.itextpdf.text.pdf.PdfIndirectReference;
  18. import com.itextpdf.text.pdf.PdfName;
  19. import com.itextpdf.text.pdf.PdfWriter;
  20. import com.itextpdf.text.pdf.richmedia.RichMediaActivation;
  21. import com.itextpdf.text.pdf.richmedia.RichMediaAnnotation;
  22. import com.itextpdf.text.pdf.richmedia.RichMediaConfiguration;
  23. import com.itextpdf.text.pdf.richmedia.RichMediaInstance;
  24. import com.itextpdf.text.pdf.richmedia.RichMediaParams;
  25.  
  26.  
  27. public class FestivalCalendar1 {
  28.    
  29.     /** The resulting PDF file. */
  30.     public static final String RESULT = "results/part4/chapter16/festival_calendar1.pdf";
  31.     /** The path to a Flash application. */
  32.     public static final String RESOURCE = "resources/swf/FestivalCalendar1.swf";
  33.  
  34.     /**
  35.      * Main method.
  36.      *
  37.      * @param    args    no arguments needed
  38.      * @throws DocumentException
  39.      * @throws IOException
  40.      */
  41.     public static void main(String[] args) throws IOException, DocumentException {
  42.         // step 1
  43.         Document document = new Document();
  44.         // step 2
  45.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  46.         writer.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
  47.         writer.addDeveloperExtension(PdfDeveloperExtension.ADOBE_1_7_EXTENSIONLEVEL3);
  48.         // step 3
  49.         document.open();
  50.         // step 4
  51.         // we prepare a RichMediaAnnotation
  52.         RichMediaAnnotation richMedia = new RichMediaAnnotation(writer, new Rectangle(36, 400, 559,806));
  53.         // we embed the swf file
  54.         PdfFileSpecification fs
  55.             = PdfFileSpecification.fileEmbedded(writer, RESOURCE, "FestivalCalendar1.swf", null);
  56.         // we declare the swf file as an asset
  57.         PdfIndirectReference asset = richMedia.addAsset("FestivalCalendar1.swf", fs);
  58.         // we create a configuration
  59.         RichMediaConfiguration configuration = new RichMediaConfiguration(PdfName.FLASH);
  60.         RichMediaInstance instance = new RichMediaInstance(PdfName.FLASH);
  61.         RichMediaParams flashVars = new RichMediaParams();
  62.         String vars = new String("&day=2011-10-13");
  63.         flashVars.setFlashVars(vars);
  64.         instance.setParams(flashVars);
  65.         instance.setAsset(asset);
  66.         configuration.addInstance(instance);
  67.         // we add the configuration to the annotation
  68.         PdfIndirectReference configurationRef = richMedia.addConfiguration(configuration);
  69.         // activation of the rich media
  70.         RichMediaActivation activation = new RichMediaActivation();
  71.         activation.setConfiguration(configurationRef);
  72.         richMedia.setActivation(activation);
  73.         // we add the annotation
  74.         PdfAnnotation richMediaAnnotation = richMedia.createAnnotation();
  75.         richMediaAnnotation.setFlags(PdfAnnotation.FLAGS_PRINT);
  76.         writer.addAnnotation(richMediaAnnotation);
  77.         // step 5
  78.         document.close();
  79.     }
  80. }
FestivalCalendar2.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. package part4.chapter16;
  8. import java.io.FileOutputStream;
  9. import java.io.IOException;
  10.  
  11. import com.itextpdf.text.Document;
  12. import com.itextpdf.text.DocumentException;
  13. import com.itextpdf.text.Rectangle;
  14. import com.itextpdf.text.Utilities;
  15. import com.itextpdf.text.pdf.GrayColor;
  16. import com.itextpdf.text.pdf.PdfAnnotation;
  17. import com.itextpdf.text.pdf.PdfBorderDictionary;
  18. import com.itextpdf.text.pdf.PdfDeveloperExtension;
  19. import com.itextpdf.text.pdf.PdfFileSpecification;
  20. import com.itextpdf.text.pdf.PdfFormField;
  21. import com.itextpdf.text.pdf.PdfIndirectReference;
  22. import com.itextpdf.text.pdf.PdfName;
  23. import com.itextpdf.text.pdf.PdfString;
  24. import com.itextpdf.text.pdf.PdfWriter;
  25. import com.itextpdf.text.pdf.PushbuttonField;
  26. import com.itextpdf.text.pdf.TextField;
  27. import com.itextpdf.text.pdf.richmedia.RichMediaActivation;
  28. import com.itextpdf.text.pdf.richmedia.RichMediaAnnotation;
  29. import com.itextpdf.text.pdf.richmedia.RichMediaCommand;
  30. import com.itextpdf.text.pdf.richmedia.RichMediaConfiguration;
  31. import com.itextpdf.text.pdf.richmedia.RichMediaExecuteAction;
  32. import com.itextpdf.text.pdf.richmedia.RichMediaInstance;
  33.  
  34.  
  35. public class FestivalCalendar2 {
  36.  
  37.     /** The resulting PDF file. */
  38.     public static final String RESULT = "results/part4/chapter16/festival_calendar2.pdf";
  39.     /** The path to a Flash application. */
  40.     public static final String RESOURCE = "resources/swf/FestivalCalendar2.swf";
  41.     /** The path to a JavaScript file. */
  42.     public static final String JS = "resources/js/show_date.js";
  43.  
  44.     /**
  45.      * Main method.
  46.      *
  47.      * @param    args    no arguments needed
  48.      * @throws DocumentException
  49.      * @throws IOException
  50.      */
  51.     public static void main(String[] args) throws IOException, DocumentException {
  52.         // step 1
  53.         Document document = new Document();
  54.         // step 2
  55.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  56.         writer.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
  57.         writer.addDeveloperExtension(PdfDeveloperExtension.ADOBE_1_7_EXTENSIONLEVEL3);
  58.         // step 3
  59.         document.open();
  60.         // step 4
  61.         writer.addJavaScript(Utilities.readFileToString(JS));
  62.         // we prepare a RichMediaAnnotation
  63.         RichMediaAnnotation richMedia = new RichMediaAnnotation(writer, new Rectangle(36, 560, 561, 760));
  64.         // we embed the swf file
  65.         PdfFileSpecification fs
  66.             = PdfFileSpecification.fileEmbedded(writer, RESOURCE, "FestivalCalendar2.swf", null);
  67.         // we declare the swf file as an asset
  68.         PdfIndirectReference asset = richMedia.addAsset("FestivalCalendar2.swf", fs);
  69.         // we create a configuration
  70.         RichMediaConfiguration configuration = new RichMediaConfiguration(PdfName.FLASH);
  71.         RichMediaInstance instance = new RichMediaInstance(PdfName.FLASH);
  72.         instance.setAsset(asset);
  73.         configuration.addInstance(instance);
  74.         // we add the configuration to the annotation
  75.         PdfIndirectReference configurationRef = richMedia.addConfiguration(configuration);
  76.         // activation of the rich media
  77.         RichMediaActivation activation = new RichMediaActivation();
  78.         activation.setConfiguration(configurationRef);
  79.         richMedia.setActivation(activation);
  80.         // we add the annotation
  81.         PdfAnnotation richMediaAnnotation = richMedia.createAnnotation();
  82.         richMediaAnnotation.setFlags(PdfAnnotation.FLAGS_PRINT);
  83.         writer.addAnnotation(richMediaAnnotation);
  84.        
  85.         String[] days = new String[]{"2011-10-12", "2011-10-13", "2011-10-14", "2011-10-15",
  86.                 "2011-10-16", "2011-10-17", "2011-10-18", "2011-10-19"};
  87.         for (int i = 0; i < days.length; i++) {
  88.             Rectangle rect = new Rectangle(36 + (65 * i), 765, 100 + (65 * i), 780);
  89.             PushbuttonField button = new PushbuttonField(writer, rect, "button" + i);
  90.             button.setBackgroundColor(new GrayColor(0.75f));
  91.             button.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
  92.             button.setTextColor(GrayColor.GRAYBLACK);
  93.             button.setFontSize(12);
  94.             button.setText(days[i]);
  95.             button.setLayout(PushbuttonField.LAYOUT_ICON_LEFT_LABEL_RIGHT);
  96.             button.setScaleIcon(PushbuttonField.SCALE_ICON_ALWAYS);
  97.             button.setProportionalIcon(true);
  98.             button.setIconHorizontalAdjustment(0);
  99.             PdfFormField field = button.getField();
  100.             RichMediaCommand command = new RichMediaCommand(new PdfString("getDateInfo"));
  101.             command.setArguments(new PdfString(days[i]));
  102.             RichMediaExecuteAction action
  103.                 = new RichMediaExecuteAction(richMediaAnnotation.getIndirectReference(), command);
  104.             field.setAction(action);
  105.             writer.addAnnotation(field);
  106.         }
  107.         TextField text = new TextField(writer, new Rectangle(36, 785, 559, 806), "date");
  108.         text.setOptions(TextField.READ_ONLY);
  109.         writer.addAnnotation(text.getTextField());
  110.         // step 5
  111.         document.close();
  112.     }
  113. }
SpecialId.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using Ionic.Zip;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  15.   public class SpecialId : IWriter {
  16. // ===========================================================================
  17.     /** The resulting PDF file. */
  18.     public const String RESULT = "special_id.pdf";
  19.     /** An image file. */
  20.     public readonly String RESOURCE = Path.Combine(
  21.       Utility.ResourceImage, "bruno.jpg"
  22.     );    
  23. // ---------------------------------------------------------------------------    
  24.     public void Write(Stream stream) {
  25.       using (ZipFile zip = new ZipFile()) {
  26.         zip.AddFile(RESOURCE, "");
  27.         zip.AddEntry(RESULT, new SpecialId().CreatePdf());      
  28.         zip.Save(stream);            
  29.       }
  30.     }
  31. // ---------------------------------------------------------------------------    
  32.     /**
  33.      * Creates a PDF document.
  34.      */
  35.     public byte[] CreatePdf() {
  36.       using (MemoryStream ms = new MemoryStream()) {
  37.         using (Document document = new Document(new Rectangle(400, 300))) {
  38.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  39.           document.Open();
  40.           Image img = Image.GetInstance(
  41.             Path.Combine(Utility.ResourceImage, "bruno.jpg"
  42.           ));
  43.           img.ScaleAbsolute(400, 300);
  44.           img.SetAbsolutePosition(0, 0);
  45.           PdfImage pi = new PdfImage(img, "", null);
  46.           pi.Put(new PdfName("ITXT_SpecialId"), new PdfName("123456789"));
  47.           PdfIndirectObject pio = writer.AddToBody(pi);
  48.           img.DirectReference = pio.IndirectReference;
  49.           document.Add(img);
  50.         }
  51.         return ms.ToArray();
  52.       }
  53.     }
  54. // ===========================================================================
  55.   }
  56. }
ResizeImage.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.Drawing;
  9. using System.Drawing.Imaging;
  10. using System.IO;
  11. using System.Collections.Generic;
  12. using Ionic.Zip;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using iTextSharp.text.pdf.parser;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  18.   public class ResizeImage : IWriter {
  19. // ===========================================================================
  20.     /** The resulting PDF file. */
  21.     public const String RESULT = "resized_image.pdf";
  22.     /** The multiplication factor for the image. */
  23.     public const float FACTOR = 0.5f;
  24. // ---------------------------------------------------------------------------    
  25.     public void Write(Stream stream) {
  26.       using (ZipFile zip = new ZipFile()) {
  27.         SpecialId s = new SpecialId();
  28.         byte[] pdf = s.CreatePdf();
  29.         zip.AddEntry(Utility.ResultFileName(s.ToString() + ".pdf"), pdf);      
  30.         zip.AddEntry(RESULT, new ResizeImage().ManipulatePdf(pdf));      
  31.         zip.Save(stream);            
  32.       }
  33.     }
  34. // ---------------------------------------------------------------------------
  35.     /**
  36.      * Manipulates a PDF file src with the byte array as result
  37.      */    
  38.     public byte[] ManipulatePdf(byte[] pdf) {
  39.       PdfName key = new PdfName("ITXT_SpecialId");
  40.       PdfName value = new PdfName("123456789");
  41.       // Read the file
  42.       PdfReader reader = new PdfReader(pdf);
  43.       int n = reader.XrefSize;
  44.       PdfObject pdfObject;
  45.       PRStream prStream;
  46.       // Look for image and manipulate image prStream
  47.       for (int i = 0; i < n; i++) {
  48.         pdfObject = reader.GetPdfObject(i);
  49.         if (pdfObject == null || !pdfObject.IsStream()) continue;
  50.        
  51.         prStream = (PRStream) pdfObject;
  52.         byte[] imageBytes;
  53.         if (value.Equals(prStream.Get(key))) {
  54.           PdfImageObject image = new PdfImageObject(prStream);
  55.           using (System.Drawing.Image original = image.GetDrawingImage()) {
  56.             if (original == null) continue;
  57.             int width = (int)(original.Width * FACTOR);
  58.             int height = (int)(original.Height * FACTOR);
  59.            
  60.             using (System.Drawing.Image thumb = new Bitmap(width, height) ) {
  61.               using ( Graphics graphic = Graphics.FromImage(thumb) ) {
  62.                 graphic.DrawImage(original, 0, 0, width, height);
  63.                 using (MemoryStream ms = new MemoryStream()) {
  64.                   thumb.Save(ms, ImageFormat.Jpeg);
  65.                   imageBytes = ms.ToArray();
  66.                 }
  67.               }
  68.             }
  69.             prStream.Clear();
  70.             prStream.SetData(imageBytes, false, PRStream.NO_COMPRESSION);
  71.             prStream.Put(PdfName.TYPE, PdfName.XOBJECT);
  72.             prStream.Put(PdfName.SUBTYPE, PdfName.IMAGE);
  73.             prStream.Put(key, value);
  74.             prStream.Put(PdfName.FILTER, PdfName.DCTDECODE);
  75.             prStream.Put(PdfName.WIDTH, new PdfNumber(width));
  76.             prStream.Put(PdfName.HEIGHT, new PdfNumber(height));
  77.             prStream.Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
  78.             prStream.Put(PdfName.COLORSPACE, PdfName.DEVICERGB);            
  79.           }
  80.         }
  81.       }
  82.       // Save altered PDF
  83.       using (MemoryStream ms = new MemoryStream()) {
  84.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  85.         }
  86.         return ms.ToArray();
  87.       }
  88.     }
  89. // ===========================================================================
  90.   }
  91. }
ListUsedFonts.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using Ionic.Zip;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using iTextSharp.text.pdf.parser;
  16. using kuujinbo.iTextInAction2Ed.Chapter11;
  17.  
  18. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  19.   public class ListUsedFonts : IWriter {
  20. // ===========================================================================
  21.     /** The resulting PDF file. */
  22.     public const String RESULT = "fonts.txt";
  23. // ---------------------------------------------------------------------------    
  24.     public void Write(Stream stream) {
  25.       using (ZipFile zip = new ZipFile()) {
  26.         FontTypes f = new FontTypes();
  27.         byte[] pdf = Utility.PdfBytes(f);
  28.         zip.AddEntry(Utility.ResultFileName(f.ToString() + ".pdf"), pdf);
  29.         IEnumerable set1 = from m
  30.           in new ListUsedFonts().ListFonts(pdf)
  31.           orderby m select m;
  32.         StringBuilder sb = new StringBuilder();
  33. /*
  34.  * i don't have c:/windows/fonts/ARBLI__.TTF on my system;
  35.  * if you compare to Java example __THIS__ result file will have
  36.  * one __LESS__ font listed!
  37.  */
  38.         foreach (String fontname in set1) {
  39.           sb.AppendLine(fontname);
  40.         }        
  41.         zip.AddEntry(RESULT, sb.ToString());      
  42.         zip.Save(stream);
  43.       }
  44.     }
  45. // ---------------------------------------------------------------------------    
  46.     /**
  47.      * Creates a HashSet containing information about the fonts in the src PDF file.
  48.      * @param src the PDF file
  49.      *
  50.      * HashSet only available in .NET >= 3.5
  51.      */
  52.     public HashSet ListFonts(byte[] src) {
  53.       HashSet set = new HashSet();
  54.       PdfReader reader = new PdfReader(src);
  55.       PdfDictionary resources;
  56.       for (int k = 1; k  8 && name.Substring(7, 1) == "+") {
  57.             name = String.Format(
  58.               "{0} subset ({1})",
  59.               name.Substring(8), name.Substring(1, 7)
  60.             );
  61.           }
  62.           else {
  63.               name = name.Substring(1);
  64.               PdfDictionary desc = font.GetAsDict(PdfName.FONTDESCRIPTOR);
  65.               if (desc == null) {
  66.                 name += " nofontdescriptor";
  67.               }
  68.               else if (desc.Get(PdfName.FONTFILE) != null) {
  69.                 name += " (Type 1) embedded";
  70.               }
  71.               else if (desc.Get(PdfName.FONTFILE2) != null) {
  72.                 name += " (TrueType) embedded";
  73.               }
  74.               else if (desc.Get(PdfName.FONTFILE3) != null) {
  75.                 name += " (" + font.GetAsName(PdfName.SUBTYPE).ToString().Substring(1) + ") embedded";
  76.               }
  77.           }
  78.           set.Add(name);
  79.         }
  80.     }
  81. // ===========================================================================  
  82.   }
  83. }
EmbedFontPostFacto.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using Ionic.Zip;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  15.   public class EmbedFontPostFacto : IWriter {
  16. // ===========================================================================
  17.     /** The first resulting PDF file. */
  18.     public const String RESULT1 = "without_font.pdf";
  19.     /** The second resulting PDF file. */
  20.     public const String RESULT2 = "with_font.pdf";
  21.     /** A special font. */
  22.     public readonly String FONT = Path.Combine(
  23.       Utility.ResourceFonts, "wds011402.ttf"
  24.     );    
  25.     /** The name of the special font. */
  26.     public const String FONTNAME = "WaltDisneyScriptv4.1";
  27. // ---------------------------------------------------------------------------    
  28.     public void Write(Stream stream) {
  29.       using (ZipFile zip = new ZipFile()) {
  30.         EmbedFontPostFacto example = new EmbedFontPostFacto();
  31.         byte[] pdf = example.CreatePdf();
  32.         zip.AddEntry(RESULT1, pdf);      
  33.         zip.AddEntry(RESULT2, example.ManipulatePdf(pdf));      
  34.         zip.Save(stream);            
  35.       }
  36.     }    
  37. // ---------------------------------------------------------------------------
  38.     /**
  39.      * Creates a PDF document.
  40.      */
  41.     public byte[] CreatePdf() {
  42.       using (MemoryStream ms = new MemoryStream()) {
  43.         // step 1
  44.         using (Document document = new Document()) {    
  45.           // step 2
  46.           PdfWriter.GetInstance(document, ms);
  47.           // step 3
  48.           document.Open();
  49.           // step 4:
  50.           Font font = new Font(
  51.             BaseFont.CreateFont(FONT, "", BaseFont.NOT_EMBEDDED), 60
  52.           );
  53.           document.Add(new Paragraph("iText in Action", font));
  54.         }
  55.         return ms.ToArray();
  56.       }
  57.     }
  58. // ---------------------------------------------------------------------------    
  59.     /**
  60.      * Manipulates a PDF file src with the file dest as result
  61.      * @param src the original PDF
  62.      */
  63.     public byte[] ManipulatePdf(byte[] src) {
  64.       // the font file
  65.       byte[] fontfile = null;
  66.       using (FileStream fs = new FileStream(
  67.         FONT, FileMode.Open, FileAccess.Read))
  68.       {
  69.         fontfile = new byte[fs.Length];
  70.         fs.Read(fontfile, 0, (int) fs.Length);
  71.       }
  72.       // create a new stream for the font file
  73.       PdfStream stream = new PdfStream(fontfile);
  74.       stream.FlateCompress();
  75.       stream.Put(PdfName.LENGTH1, new PdfNumber(fontfile.Length));
  76.       // create a reader object
  77.       PdfReader reader = new PdfReader(src);
  78.       int n = reader.XrefSize;
  79.       PdfDictionary font;
  80.       using (MemoryStream ms = new MemoryStream()) {      
  81.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  82.           PdfName fontname = new PdfName(FONTNAME);
  83.           for (int i = 0; i < n; i++) {
  84.             PdfObject objectPdf = reader.GetPdfObject(i);
  85.             if (objectPdf == null || !objectPdf.IsDictionary()) {
  86.               continue;
  87.             }
  88.             font = (PdfDictionary)objectPdf;
  89.             if (PdfName.FONTDESCRIPTOR.Equals(font.Get(PdfName.TYPE))
  90.                 && fontname.Equals(font.Get(PdfName.FONTNAME)))
  91.             {
  92.               PdfIndirectObject objref = stamper.Writer.AddToBody(stream);
  93.               font.Put(PdfName.FONTFILE2, objref.IndirectReference);
  94.             }
  95.           }
  96.         }
  97.         return ms.ToArray();
  98.       }
  99.     }
  100. // ===========================================================================    
  101.   }
  102. }
KubrickDvds.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Collections.Generic;
  11. using Ionic.Zip;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  17.   public class KubrickDvds : IWriter {
  18. // ===========================================================================
  19.     /** The filename of the resulting PDF. */
  20.     public const String RESULT = "kubrick_dvds.pdf";
  21. // ---------------------------------------------------------------------------
  22.     public void Write(Stream stream) {
  23.       using (ZipFile zip = new ZipFile()) {
  24.         KubrickDvds kubrick = new KubrickDvds();
  25.         byte[] ePdf = kubrick.CreatePdf();
  26.         zip.AddEntry(RESULT, ePdf);
  27.         kubrick.ExtractAttachments(ePdf, zip);
  28.         zip.Save(stream);            
  29.       }
  30.     }
  31. // ---------------------------------------------------------------------------    
  32.     /**
  33.      * Extracts attachments from an existing PDF.
  34.      * @param src the path to the existing PDF
  35.      * @param zip the ZipFile object to add the extracted images
  36.      */
  37.     public void ExtractAttachments(byte[] src, ZipFile zip) {
  38.       PdfReader reader = new PdfReader(src);
  39.       for (int i = 1; i
KubrickDocumentary.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using Ionic.Zip;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using iTextSharp.text.xml;
  16. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  17.  
  18. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  19.   public class KubrickDocumentary : IWriter {
  20. // ===========================================================================
  21.     /** The filename of the resulting PDF. */
  22.     public const String RESULT = "kubrick_documentary.pdf";
  23. // ---------------------------------------------------------------------------
  24.     public void Write(Stream stream) {
  25.       using (ZipFile zip = new ZipFile()) {
  26.         KubrickDocumentary kubrick = new KubrickDocumentary();
  27.         byte[] ePdf = kubrick.CreatePdf();
  28.         zip.AddEntry(RESULT, ePdf);
  29.         kubrick.ExtractDocLevelAttachments(ePdf, zip);
  30.         zip.Save(stream);            
  31.       }
  32.     }
  33. // ---------------------------------------------------------------------------
  34.     /**
  35.      * Creates the PDF.
  36.      * @return the bytes of a PDF file.
  37.      */
  38.     public byte[] CreatePdf() {
  39.       IEnumerable movies = PojoFactory.GetMovies(1);
  40.       using (MemoryStream ms = new MemoryStream()) {
  41.         using (Document document = new Document()) {
  42.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  43.           document.Open();
  44.           document.Add(new Paragraph(
  45.             "'Stanley Kubrick: A Life in Pictures'"
  46.             + " is a documentary about Stanley Kubrick and his films:"
  47.           ));
  48.           StringBuilder sb = new StringBuilder();
  49.           sb.AppendLine("");
  50.           List list = new List(List.UNORDERED, 20);
  51.           foreach (Movie movie in movies) {
  52.             sb.AppendLine("");
  53.             sb.AppendLine(String.Format(
  54.               "{0}",
  55.               XMLUtil.EscapeXML(movie.MovieTitle, true)
  56.             ));
  57.             sb.AppendLine(String.Format("{0}", movie.Year));
  58.             sb.AppendLine(String.Format(
  59.               "{0}", movie.Duration
  60.             ));
  61.             sb.AppendLine("");
  62.             ListItem item = new ListItem(movie.MovieTitle);
  63.             list.Add(item);
  64.           }
  65.           document.Add(list);
  66.           sb.Append("");
  67.           PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
  68.             writer, null, "kubrick.xml", Encoding.UTF8.GetBytes(sb.ToString())
  69.             //txt.toByteArray()
  70.           );
  71.           writer.AddFileAttachment(fs);
  72.         }
  73.         return ms.ToArray();
  74.       }
  75.     }
  76. // ---------------------------------------------------------------------------
  77.     /**
  78.      * Extracts document level attachments
  79.      * @param PDF from which document level attachments will be extracted
  80.      * @param zip the ZipFile object to add the extracted images
  81.      */
  82.     public void ExtractDocLevelAttachments(byte[] pdf, ZipFile zip) {
  83.       PdfReader reader = new PdfReader(pdf);
  84.       PdfDictionary root = reader.Catalog;
  85.       PdfDictionary documentnames = root.GetAsDict(PdfName.NAMES);
  86.       PdfDictionary embeddedfiles =
  87.           documentnames.GetAsDict(PdfName.EMBEDDEDFILES);
  88.       PdfArray filespecs = embeddedfiles.GetAsArray(PdfName.NAMES);
  89.       for (int i = 0; i < filespecs.Size; ) {
  90.         filespecs.GetAsString(i++);
  91.         PdfDictionary filespec = filespecs.GetAsDict(i++);
  92.         PdfDictionary refs = filespec.GetAsDict(PdfName.EF);
  93.         foreach (PdfName key in refs.Keys) {
  94.           PRStream stream = (PRStream) PdfReader.GetPdfObject(
  95.             refs.GetAsIndirectObject(key)
  96.           );
  97.           zip.AddEntry(
  98.             filespec.GetAsString(key).ToString(),
  99.             PdfReader.GetStreamBytes(stream)
  100.           );
  101.         }
  102.       }
  103.     }
  104. // ===========================================================================
  105.     }
  106. }
KubrickBox.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using Ionic.Zip;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using iTextSharp.text.pdf.collection;
  16. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  17.  
  18. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  19.   public class KubrickBox : IWriter {
  20. // ===========================================================================
  21.     /** The resulting PDF. */
  22.     public const String RESULT = "kubrick_box.pdf";
  23.     /** The path to an image used in the example. */
  24.     public readonly String IMG_BOX =  Path.Combine(
  25.       Utility.ResourceImage, "kubrick_box.jpg"
  26.     );
  27.     /** Path to the resources. */
  28.     public readonly String RESOURCE =  Path.Combine(
  29.       Utility.ResourcePosters, "{0}.jpg"
  30.     );    
  31.     /** The relative widths of the PdfPTable columns. */
  32.     public readonly float[] WIDTHS = { 1 , 7 };
  33. // ---------------------------------------------------------------------------
  34.     public void Write(Stream stream) {
  35.       // step 1
  36.       using (Document document = new Document()) {
  37.         // step 2
  38.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  39.         // step 3
  40.         document.Open();
  41.         // step 4
  42.         Image img = Image.GetInstance(IMG_BOX);
  43.         document.Add(img);
  44.         List list = new List(List.UNORDERED, 20);
  45.         PdfDestination dest = new PdfDestination(PdfDestination.FIT);
  46.         dest.AddFirst(new PdfNumber(1));
  47.         IEnumerable box = PojoFactory.GetMovies(1)
  48.           .Concat(PojoFactory.GetMovies(4))
  49.         ;
  50.         foreach (Movie movie in box) {
  51.           if (movie.Year > 1960) {
  52.             PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
  53.               writer, null,
  54.               String.Format("kubrick_{0}.pdf", movie.Imdb),
  55.               CreateMoviePage(movie)
  56.             );
  57.             fs.AddDescription(movie.Title, false);
  58.             writer.AddFileAttachment(fs);
  59.             ListItem item = new ListItem(movie.MovieTitle);
  60.             PdfTargetDictionary target = new PdfTargetDictionary(true);
  61.             target.EmbeddedFileName = movie.Title;
  62.             PdfAction action = PdfAction.GotoEmbedded(null, target, dest, true);
  63.             Chunk chunk = new Chunk(" (see info)");
  64.             chunk.SetAction(action);
  65.             item.Add(chunk);
  66.             list.Add(item);
  67.           }
  68.         }
  69.         document.Add(list);
  70.       }
  71.     }
  72. // ---------------------------------------------------------------------------
  73.     /**
  74.      * Creates the PDF.
  75.      * @return the bytes of a PDF file.
  76.      */
  77.     public byte[] CreateMoviePage(Movie movie) {
  78.       using (MemoryStream ms = new MemoryStream()) {
  79.         // step 1
  80.         using (Document document = new Document()) {
  81.           // step 2
  82.           PdfWriter.GetInstance(document, ms);
  83.           // step 3
  84.           document.Open();
  85.           // step 4
  86.           Paragraph p = new Paragraph(
  87.             movie.MovieTitle,
  88.             FontFactory.GetFont(
  89.               BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED, 16
  90.             )
  91.           );
  92.           document.Add(p);
  93.           document.Add(Chunk.NEWLINE);
  94.           PdfPTable table = new PdfPTable(WIDTHS);
  95.           table.AddCell(Image.GetInstance(
  96.             String.Format(RESOURCE, movie.Imdb)
  97.           ));
  98.           PdfPCell cell = new PdfPCell();
  99.           cell.AddElement(new Paragraph("Year: " + movie.Year.ToString()));
  100.           cell.AddElement(new Paragraph("Duration: " + movie.Duration.ToString()));
  101.           table.AddCell(cell);
  102.           document.Add(table);
  103.           PdfDestination dest = new PdfDestination(PdfDestination.FIT);
  104.           dest.AddFirst(new PdfNumber(1));
  105.           PdfTargetDictionary target = new PdfTargetDictionary(false);
  106.           Chunk chunk = new Chunk("Go to original document");
  107.           PdfAction action = PdfAction.GotoEmbedded(null, target, dest, false);
  108.           chunk.SetAction(action);
  109.           document.Add(chunk);
  110.         }
  111.         return ms.ToArray();
  112.       }
  113.     }
  114.    
  115. // ===========================================================================
  116.   }
  117. }
KubrickMovies.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.collection;
  15. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  18.   public class KubrickMovies : IWriter {
  19. // ===========================================================================
  20.     /** Path to the resources. */
  21.     public readonly String RESOURCE =  Path.Combine(
  22.       Utility.ResourcePosters, "{0}.jpg"
  23.     );    
  24.     /** The relative widths of the PdfPTable columns. */
  25.     public readonly float[] WIDTHS = { 1 , 7 };
  26.     /** The filename of the PDF */
  27.     public const String FILENAME = "kubrick_movies.pdf";    
  28. // ---------------------------------------------------------------------------
  29.     public void Write(Stream stream) {
  30.       // step 1
  31.       using (Document document = new Document()) {
  32.         // step 2
  33.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  34.         // step 3
  35.         document.Open();
  36.         // step 4
  37.         document.Add(new Paragraph(
  38.           "This document contains a collection of PDFs,"
  39.           + " one per Stanley Kubrick movie."
  40.         ));
  41.        
  42.         PdfCollection collection = new PdfCollection(PdfCollection.DETAILS);
  43.         PdfCollectionSchema schema = _collectionSchema();
  44.         collection.Schema = schema;
  45.         PdfCollectionSort sort = new PdfCollectionSort("YEAR");
  46.         sort.SetSortOrder(false);
  47.         collection.Sort = sort;
  48.         collection.InitialDocument = "Eyes Wide Shut";
  49.         writer.Collection = collection;
  50.        
  51.         PdfCollectionItem item;
  52.         IEnumerable movies = PojoFactory.GetMovies(1);
  53.         foreach (Movie movie in movies) {
  54.           PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
  55.             writer, null,
  56.             String.Format("kubrick_{0}.pdf", movie.Imdb),
  57.             CreateMoviePage(movie)
  58.           );
  59.           fs.AddDescription(movie.Title, false);
  60.  
  61.           item = new PdfCollectionItem(schema);
  62.           item.AddItem("TITLE", movie.GetMovieTitle(false));
  63.           if (movie.GetMovieTitle(true) != null) {
  64.             item.SetPrefix("TITLE", movie.GetMovieTitle(true));
  65.           }
  66.           item.AddItem("DURATION", movie.Duration.ToString());
  67.           item.AddItem("YEAR", movie.Year.ToString());
  68.           fs.AddCollectionItem(item);
  69.           writer.AddFileAttachment(fs);
  70.         }
  71.       }
  72.     }
  73. // ---------------------------------------------------------------------------    
  74.     /**
  75.      * Creates a Collection schema that can be used to organize the movies
  76.      * of Stanley Kubrick in a collection: year, title, duration, DVD
  77.      * acquisition, filesize (filename is present, but hidden).
  78.      * @return a collection schema
  79.      */
  80.     private PdfCollectionSchema _collectionSchema() {
  81.       PdfCollectionSchema schema = new PdfCollectionSchema();
  82.       PdfCollectionField size = new PdfCollectionField(
  83.         "File size", PdfCollectionField.SIZE
  84.       );
  85.      
  86.       size.Order = 4;
  87.       schema.AddField("SIZE", size);
  88.      
  89.       PdfCollectionField filename = new PdfCollectionField(
  90.         "File name", PdfCollectionField.FILENAME
  91.       );
  92.       filename.Visible = false;
  93.       schema.AddField("FILE", filename);
  94.      
  95.       PdfCollectionField title = new PdfCollectionField(
  96.         "Movie title", PdfCollectionField.TEXT
  97.       );
  98.       title.Order = 1;
  99.       schema.AddField("TITLE", title);
  100.      
  101.       PdfCollectionField duration = new PdfCollectionField(
  102.         "Duration", PdfCollectionField.NUMBER
  103.       );
  104.       duration.Order = 2;
  105.       schema.AddField("DURATION", duration);
  106.      
  107.       PdfCollectionField year = new PdfCollectionField(
  108.         "Year", PdfCollectionField.NUMBER
  109.       );
  110.       year.Order = 0;
  111.       schema.AddField("YEAR", year);
  112.      
  113.       return schema;
  114.     }
  115. // ---------------------------------------------------------------------------
  116.     /**
  117.      * Creates the PDF.
  118.      * @return the bytes of a PDF file.
  119.      */
  120.     public byte[] CreateMoviePage(Movie movie) {
  121.       using (MemoryStream ms = new MemoryStream()) {
  122.         // step 1
  123.         using (Document document = new Document()) {
  124.           // step 2
  125.           PdfWriter.GetInstance(document, ms);
  126.           // step 3
  127.           document.Open();
  128.           // step 4
  129.           Paragraph p = new Paragraph(
  130.             movie.MovieTitle,
  131.             FontFactory.GetFont(
  132.               BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED, 16
  133.             )
  134.           );
  135.           document.Add(p);
  136.           document.Add(Chunk.NEWLINE);
  137.           PdfPTable table = new PdfPTable(WIDTHS);
  138.           table.AddCell(Image.GetInstance(
  139.             String.Format(RESOURCE, movie.Imdb)
  140.           ));
  141.           PdfPCell cell = new PdfPCell();
  142.           cell.AddElement(new Paragraph("Year: " + movie.Year.ToString()));
  143.           cell.AddElement(new Paragraph("Duration: " + movie.Duration.ToString()));
  144.           table.AddCell(cell);
  145.           document.Add(table);
  146.          
  147.           PdfTargetDictionary target = new PdfTargetDictionary(false);
  148.           target.AdditionalPath = new PdfTargetDictionary(false);
  149.           Chunk chunk = new Chunk("Go to original document");
  150.           PdfAction action = PdfAction.GotoEmbedded(
  151.             null, target, new PdfString("movies"), false
  152.           );
  153.           chunk.SetAction(action);
  154.           document.Add(chunk);
  155.         }
  156.         return ms.ToArray();
  157.       }
  158.     }
  159. // ===========================================================================
  160.   }
  161. }
KubrickCollection.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using Ionic.Zip;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using iTextSharp.text.pdf.collection;
  16. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  17.  
  18. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  19.   public class KubrickCollection : IWriter {
  20. // ===========================================================================
  21.     /** An image file used in this example */
  22.     public readonly String IMG_BOX =  Path.Combine(
  23.       Utility.ResourceImage, "kubrick_box.jpg"
  24.     );
  25.     /** An image file used in this example */
  26.     public readonly String IMG_KUBRICK =  Path.Combine(
  27.       Utility.ResourceImage, "kubrick.jpg"
  28.     );      
  29.     /** The name of a field in the collection schema. */
  30.     public const String TYPE_FIELD = "TYPE";
  31.     /** A caption of a field in the collection schema. */
  32.     public const String TYPE_CAPTION = "File type";
  33.     /** The name of a field in the collection schema. */
  34.     public const String FILE_FIELD = "FILE";
  35.     /** A caption of a field in the collection schema. */
  36.     public const String FILE_CAPTION = "File name";
  37.     /** Sort order for the keys in the collection. */
  38.     public String[] KEYS = { TYPE_FIELD, FILE_FIELD };
  39. // ---------------------------------------------------------------------------
  40.     public void Write(Stream stream) {
  41.       // step 1
  42.       using (Document document = new Document()) {
  43.         // step 2
  44.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  45.         // step 3
  46.         document.Open();
  47.        
  48.        
  49.         // step 4
  50.         PdfCollection collection = new PdfCollection(PdfCollection.HIDDEN);
  51.         PdfCollectionSchema schema = _collectionSchema();
  52.         collection.Schema = schema;
  53.         PdfCollectionSort sort = new PdfCollectionSort(KEYS);
  54.         collection.Sort = sort;
  55.         writer.Collection = collection;
  56.  
  57.         PdfCollectionItem collectionitem = new PdfCollectionItem(schema);
  58.         PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
  59.           writer, IMG_KUBRICK, "kubrick.jpg", null
  60.         );
  61.         fs.AddDescription("Stanley Kubrick", false);
  62.         collectionitem.AddItem(TYPE_FIELD, "JPEG");
  63.         fs.AddCollectionItem(collectionitem);
  64.         writer.AddFileAttachment(fs);
  65.        
  66.         Image img = Image.GetInstance(IMG_BOX);
  67.         document.Add(img);
  68.         List list = new List(List.UNORDERED, 20);
  69.         PdfDestination dest = new PdfDestination(PdfDestination.FIT);
  70.         dest.AddFirst(new PdfNumber(1));
  71.         PdfTargetDictionary intermediate;
  72.         PdfTargetDictionary target;
  73.         Chunk chunk;
  74.         ListItem item;
  75.         PdfAction action = null;
  76.  
  77.         IEnumerable box = PojoFactory.GetMovies(1)
  78.           .Concat(PojoFactory.GetMovies(4))
  79.         ;
  80.         StringBuilder sb = new StringBuilder();
  81.         foreach (Movie movie in box) {
  82.           if (movie.Year > 1960) {
  83.             sb.AppendLine(String.Format(
  84.               "{0};{1};{2}", movie.MovieTitle, movie.Year, movie.Duration
  85.             ));
  86.             item = new ListItem(movie.MovieTitle);
  87.             if (!"0278736".Equals(movie.Imdb)) {
  88.               target = new PdfTargetDictionary(true);
  89.               target.EmbeddedFileName = movie.Title;
  90.               intermediate = new PdfTargetDictionary(true);
  91.               intermediate.FileAttachmentPage = 1;
  92.               intermediate.FileAttachmentIndex = 1;
  93.               intermediate.AdditionalPath = target;
  94.               action = PdfAction.GotoEmbedded(null, intermediate, dest, true);
  95.               chunk = new Chunk(" (see info)");
  96.               chunk.SetAction(action);
  97.               item.Add(chunk);
  98.             }
  99.             list.Add(item);
  100.           }
  101.         }
  102.         document.Add(list);
  103.        
  104.         fs = PdfFileSpecification.FileEmbedded(
  105.           writer, null, "kubrick.txt",
  106.           Encoding.UTF8.GetBytes(sb.ToString())
  107.         );
  108.         fs.AddDescription("Kubrick box: the movies", false);
  109.         collectionitem.AddItem(TYPE_FIELD, "TXT");
  110.         fs.AddCollectionItem(collectionitem);
  111.         writer.AddFileAttachment(fs);
  112.  
  113.         PdfPTable table = new PdfPTable(1);
  114.         table.SpacingAfter = 10;
  115.         PdfPCell cell = new PdfPCell(new Phrase("All movies by Kubrick"));
  116.         cell.Border = PdfPCell.NO_BORDER;
  117.         fs = PdfFileSpecification.FileEmbedded(
  118.           writer, null, KubrickMovies.FILENAME,
  119.           Utility.PdfBytes(new KubrickMovies())
  120.           //new KubrickMovies().createPdf()
  121.         );
  122.         collectionitem.AddItem(TYPE_FIELD, "PDF");
  123.         fs.AddCollectionItem(collectionitem);
  124.         target = new PdfTargetDictionary(true);
  125.         target.FileAttachmentPagename = "movies";
  126.         target.FileAttachmentName = "The movies of Stanley Kubrick";
  127.         cell.CellEvent = new PdfActionEvent(
  128.           writer, PdfAction.GotoEmbedded(null, target, dest, true)
  129.         );
  130.         cell.CellEvent = new FileAttachmentEvent(
  131.           writer, fs, "The movies of Stanley Kubrick"
  132.         );
  133.         cell.CellEvent = new LocalDestinationEvent(writer, "movies");
  134.         table.AddCell(cell);
  135.         writer.AddFileAttachment(fs);
  136.  
  137.         cell = new PdfPCell(new Phrase("Kubrick DVDs"));
  138.         cell.Border = PdfPCell.NO_BORDER;
  139.         fs = PdfFileSpecification.FileEmbedded(
  140.           writer, null,
  141.           KubrickDvds.RESULT, new KubrickDvds().CreatePdf()
  142.         );
  143.         collectionitem.AddItem(TYPE_FIELD, "PDF");
  144.         fs.AddCollectionItem(collectionitem);
  145.         cell.CellEvent = new FileAttachmentEvent(writer, fs, "Kubrick DVDs");
  146.         table.AddCell(cell);
  147.         writer.AddFileAttachment(fs);
  148.        
  149.         cell = new PdfPCell(new Phrase("Kubrick documentary"));
  150.         cell.Border = PdfPCell.NO_BORDER;
  151.         fs = PdfFileSpecification.FileEmbedded(
  152.           writer, null,
  153.           KubrickDocumentary.RESULT, new KubrickDocumentary().CreatePdf()
  154.         );
  155.         collectionitem.AddItem(TYPE_FIELD, "PDF");
  156.         fs.AddCollectionItem(collectionitem);
  157.         cell.CellEvent = new FileAttachmentEvent(
  158.           writer, fs, "Kubrick Documentary"
  159.         );
  160.         table.AddCell(cell);
  161.         writer.AddFileAttachment(fs);
  162.  
  163.         document.NewPage();
  164.         document.Add(table);
  165.       }
  166.     }
  167. // ---------------------------------------------------------------------------    
  168.     /**
  169.      * Creates a Collection schema that can be used to organize the movies
  170.      * of Stanley Kubrick in a collection: year, title, duration,
  171.      * DVD acquisition, filesize (filename is present, but hidden).
  172.      * @return a collection schema
  173.      */
  174.     private PdfCollectionSchema _collectionSchema() {
  175.       PdfCollectionSchema schema = new PdfCollectionSchema();
  176.      
  177.       PdfCollectionField type = new PdfCollectionField(
  178.         TYPE_CAPTION, PdfCollectionField.TEXT
  179.       );
  180.       type.Order = 0;
  181.       schema.AddField(TYPE_FIELD, type);
  182.      
  183.       PdfCollectionField filename = new PdfCollectionField(
  184.         FILE_FIELD, PdfCollectionField.FILENAME
  185.       );
  186.       filename.Order = 1;
  187.       schema.AddField(FILE_FIELD, filename);
  188.      
  189.       return schema;
  190.     }
  191. // ===========================================================================
  192.   }
  193. }
FileAttachmentEvent.cs
  1. using System;
  2. using System.Collections.Generic;
  3. using iTextSharp.text;
  4. using iTextSharp.text.pdf;
  5.  
  6. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  7.   public class FileAttachmentEvent : IPdfPCellEvent {
  8. // ===========================================================================
  9.     /** The writer to which we are going to add the action. */
  10.     protected PdfWriter writer;
  11.     /** The file specification that will be used to create an annotation. */
  12.     protected PdfFileSpecification fs;
  13.     /** The description that comes with the annotation. */
  14.     protected String description;
  15. // ---------------------------------------------------------------------------    
  16.     /**
  17.      * Creates a FileAttachmentEvent.
  18.      *
  19.      * @param writer      the writer to which the file attachment has to be added.
  20.      * @param fs          the file specification.
  21.      * @param description a description for the file attachment.
  22.      */
  23.     public FileAttachmentEvent(
  24.         PdfWriter writer, PdfFileSpecification fs, String description)
  25.     {
  26.       this.writer = writer;
  27.       this.fs = fs;
  28.       this.description = description;
  29.     }
  30. // ---------------------------------------------------------------------------    
  31.     /**
  32.      * Implementation of the cellLayout method.
  33.      * @see com.itextpdf.text.pdf.PdfPCellEvent#cellLayout(
  34.      * com.itextpdf.text.pdf.PdfPCell, com.itextpdf.text.Rectangle,
  35.      * com.itextpdf.text.pdf.PdfContentByte[])
  36.      */
  37.     public void CellLayout(
  38.         PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
  39.     {
  40.       try {
  41.         PdfAnnotation annotation = PdfAnnotation.CreateFileAttachment(
  42.           writer,
  43.           new Rectangle(
  44.             position.Left - 20, position.Top - 15,
  45.             position.Left - 5, position.Top - 5
  46.           ),
  47.           description, fs
  48.         );
  49.         annotation.Name = description;
  50.         writer.AddAnnotation(annotation);
  51.       }
  52.       catch {
  53.         throw;
  54.       }
  55.     }
  56. // ===========================================================================
  57.     }
  58. }
PdfActionEvent.cs
  1. using System;
  2. using System.Collections.Generic;
  3. using iTextSharp.text;
  4. using iTextSharp.text.pdf;
  5.  
  6. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  7.   public class PdfActionEvent : IPdfPCellEvent {
  8. // ===========================================================================
  9.     /** The writer to which we are going to add the action. */
  10.     protected PdfWriter writer;
  11.     /** The action we're going to add. */
  12.     protected PdfAction action;
  13. // ---------------------------------------------------------------------------    
  14.     /** Creates a new Action event. */
  15.     public PdfActionEvent(PdfWriter writer, PdfAction action) {
  16.       this.writer = writer;
  17.       this.action = action;
  18.     }
  19. // ---------------------------------------------------------------------------    
  20.     /** Implementation of the cellLayout method. */
  21.     public void CellLayout(
  22.         PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
  23.     {
  24.       writer.AddAnnotation(new PdfAnnotation(
  25.         writer,
  26.         position.Left, position.Bottom, position.Right, position.Top,
  27.         action
  28.       ));
  29.     }
  30. // ===========================================================================
  31.     }
  32. }
LocalDestinationEvent.cs
  1. using System;
  2. using System.Collections.Generic;
  3. using iTextSharp.text;
  4. using iTextSharp.text.pdf;
  5.  
  6. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  7.   public class LocalDestinationEvent : IPdfPCellEvent {
  8. // ===========================================================================
  9.     /** The writer to which we are going to add the action. */
  10.     protected PdfWriter writer;
  11.     /** The name of the local destination. */
  12.     protected String name;
  13. // ---------------------------------------------------------------------------    
  14.     /** Creates a new Action event. */
  15.     public LocalDestinationEvent(PdfWriter writer,  String name) {
  16.       this.writer = writer;
  17.       this.name = name;
  18.     }
  19. // ---------------------------------------------------------------------------    
  20.     /** Implementation of the cellLayout method. */
  21.     public void CellLayout(
  22.         PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
  23.     {
  24.       writer.DirectContent.LocalDestination(
  25.         name,
  26.         new PdfDestination(PdfDestination.FITH, position.Top)
  27.       );
  28.     }
  29. // ===========================================================================
  30.     }
  31. }
MovieAnnotation.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Text;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  15.   public class MovieAnnotation : IWriter {
  16. // ===========================================================================
  17.     /** One of the resources. */
  18.     public readonly String RESOURCE = Path.Combine(
  19.       Utility.ResourceImage, "foxdog.mpg"
  20.     );
  21. // ---------------------------------------------------------------------------
  22.     public void Write(Stream stream) {
  23.       // step 1
  24.       using (Document document = new Document()) {
  25.         // step 2
  26.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  27.         // step 3
  28.         document.Open();
  29.         // step 4
  30.         PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
  31.           writer, RESOURCE, "foxdog.mpg", null
  32.         );
  33.         writer.AddAnnotation(PdfAnnotation.CreateScreen(
  34.           writer,
  35.           new Rectangle(200f, 700f, 400f, 800f),
  36.           "Fox and Dog", fs,
  37.           "video/mpeg", true
  38.         ));        
  39.       }
  40.     }
  41. // ===========================================================================
  42.     }
  43. }
Pdf3D.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Text;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  15.   public class Pdf3D : IWriter {
  16. // ===========================================================================
  17.     public readonly String RESOURCE = Path.Combine(
  18.       Utility.ResourceImage, "teapot.u3d"
  19.     );
  20. // ---------------------------------------------------------------------------
  21.     public void Write(Stream stream) {
  22.       // step 1
  23.       using (Document document = new Document()) {
  24.         // step 2
  25.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  26.         // step 3
  27.         document.Open();
  28.         // step 4
  29.         Rectangle rect = new Rectangle(100, 400, 500, 800);
  30.         rect.Border = Rectangle.BOX;
  31.         rect.BorderWidth = 0.5f;
  32.         rect.BorderColor = new BaseColor(0xFF, 0x00, 0x00);
  33.         document.Add(rect);
  34.  
  35.         PdfIndirectObject streamObject = null;
  36.         using (FileStream fs =
  37.           new FileStream(RESOURCE, FileMode.Open, FileAccess.Read))
  38.         {
  39.           PdfStream stream3D = new PdfStream(fs, writer);
  40.          
  41.           stream3D.Put(PdfName.TYPE, new PdfName("3D"));
  42.           stream3D.Put(PdfName.SUBTYPE, new PdfName("U3D"));
  43.           stream3D.FlateCompress();
  44.           streamObject = writer.AddToBody(stream3D);
  45.           stream3D.WriteLength();
  46.         }
  47.            
  48.         PdfDictionary dict3D = new PdfDictionary();
  49.         dict3D.Put(PdfName.TYPE, new PdfName("3DView"));
  50.         dict3D.Put(new PdfName("XN"), new PdfString("Default"));
  51.         dict3D.Put(new PdfName("IN"), new PdfString("Unnamed"));
  52.         dict3D.Put(new PdfName("MS"), PdfName.M);
  53.         dict3D.Put(
  54.           new PdfName("C2W"),
  55.           new PdfArray(
  56.             new float[] { 1, 0, 0, 0, 0, -1, 0, 1, 0, 3, -235, 28 }
  57.           )
  58.         );
  59.         dict3D.Put(PdfName.CO, new PdfNumber(235));
  60.  
  61.         PdfIndirectObject dictObject = writer.AddToBody(dict3D);
  62.            
  63.         PdfAnnotation annot = new PdfAnnotation(writer, rect);
  64.         annot.Put(PdfName.CONTENTS, new PdfString("3D Model"));
  65.         annot.Put(PdfName.SUBTYPE, new PdfName("3D"));
  66.         annot.Put(PdfName.TYPE, PdfName.ANNOT);
  67.         annot.Put(new PdfName("3DD"), streamObject.IndirectReference);
  68.         annot.Put(new PdfName("3DV"), dictObject.IndirectReference);
  69.         PdfAppearance ap = writer.DirectContent.CreateAppearance(
  70.           rect.Width, rect.Height
  71.         );
  72.         annot.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, ap);
  73.         annot.SetPage();
  74.  
  75.         writer.AddAnnotation(annot);      
  76.       }
  77.     }
  78. // ===========================================================================
  79.     }
  80. }
FestivalCalendar1.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.richmedia;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  17.   public class FestivalCalendar1 : IWriter {
  18. // ===========================================================================
  19.     /** The path to a Flash application. */
  20.     public readonly String RESOURCE = Path.Combine(
  21.       Utility.ResourceSwf, "FestivalCalendar1.swf"
  22.     );
  23. // ---------------------------------------------------------------------------
  24.     public void Write(Stream stream) {
  25.       // step 1
  26.       using (Document document = new Document()) {
  27.         // step 2
  28.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  29.         writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
  30.         writer.AddDeveloperExtension(
  31.           PdfDeveloperExtension.ADOBE_1_7_EXTENSIONLEVEL3
  32.         );
  33.         // step 3
  34.         document.Open();
  35.         // step 4
  36.         // we prepare a RichMediaAnnotation
  37.         RichMediaAnnotation richMedia = new RichMediaAnnotation(
  38.           writer, new Rectangle(36, 400, 559,806)
  39.         );
  40.         // we embed the swf file
  41.         PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
  42.           writer, RESOURCE, "FestivalCalendar1.swf", null
  43.         );
  44.         // we declare the swf file as an asset
  45.         PdfIndirectReference asset = richMedia.AddAsset(
  46.           "FestivalCalendar1.swf", fs
  47.         );
  48.         // we create a configuration
  49.         RichMediaConfiguration configuration = new RichMediaConfiguration(
  50.           PdfName.FLASH
  51.         );
  52.         RichMediaInstance instance = new RichMediaInstance(PdfName.FLASH);
  53.         RichMediaParams flashVars = new RichMediaParams();
  54.         String vars = "&day=2011-10-13";
  55.         flashVars.FlashVars = vars;
  56.         instance.Params = flashVars;
  57.         instance.Asset = asset;
  58.         configuration.AddInstance(instance);
  59.         // we add the configuration to the annotation
  60.         PdfIndirectReference configurationRef = richMedia.AddConfiguration(
  61.           configuration
  62.         );
  63.         // activation of the rich media
  64.         RichMediaActivation activation = new RichMediaActivation();
  65.         activation.Configuration = configurationRef;
  66.         richMedia.Activation = activation;
  67.         // we add the annotation
  68.         PdfAnnotation richMediaAnnotation = richMedia.CreateAnnotation();
  69.         richMediaAnnotation.Flags = PdfAnnotation.FLAGS_PRINT;
  70.         writer.AddAnnotation(richMediaAnnotation);
  71.       }
  72.     }
  73. // ===========================================================================
  74.     }
  75. }
FestivalCalendar2.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.richmedia;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter16 {
  17.   public class FestivalCalendar2 : IWriter {
  18. // ===========================================================================
  19.     /** The path to a Flash application. */
  20.     public readonly String RESOURCE = Path.Combine(
  21.       Utility.ResourceSwf, "FestivalCalendar2.swf"
  22.     );
  23.     /** The path to a JavaScript file. */
  24.     public readonly String JS = Path.Combine(
  25.       Utility.ResourceJavaScript, "show_date.js"
  26.     );
  27. // ---------------------------------------------------------------------------
  28.     public void Write(Stream stream) {
  29.       // step 1
  30.       using (Document document = new Document()) {
  31.         // step 2
  32.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  33.         writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
  34.         writer.AddDeveloperExtension(
  35.           PdfDeveloperExtension.ADOBE_1_7_EXTENSIONLEVEL3
  36.         );
  37.         // step 3
  38.         document.Open();
  39.         // step 4
  40.         writer.AddJavaScript(File.ReadAllText(JS));
  41.  
  42.         // we prepare a RichMediaAnnotation
  43.         RichMediaAnnotation richMedia = new RichMediaAnnotation(
  44.           writer, new Rectangle(36, 560, 561, 760)
  45.         );
  46.         // we embed the swf file
  47.         PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
  48.           writer, RESOURCE, "FestivalCalendar2.swf", null
  49.         );
  50.         // we declare the swf file as an asset
  51.         PdfIndirectReference asset = richMedia.AddAsset(
  52.           "FestivalCalendar2.swf", fs
  53.         );
  54.         // we create a configuration
  55.         RichMediaConfiguration configuration = new RichMediaConfiguration(
  56.           PdfName.FLASH
  57.         );
  58.         RichMediaInstance instance = new RichMediaInstance(PdfName.FLASH);
  59.         instance.Asset = asset;
  60.         configuration.AddInstance(instance);
  61.         // we add the configuration to the annotation
  62.         PdfIndirectReference configurationRef = richMedia.AddConfiguration(
  63.           configuration
  64.         );
  65.         // activation of the rich media
  66.         RichMediaActivation activation = new RichMediaActivation();
  67.         activation.Configuration = configurationRef;
  68.         richMedia.Activation = activation;
  69.         // we add the annotation
  70.         PdfAnnotation richMediaAnnotation = richMedia.CreateAnnotation();
  71.         richMediaAnnotation.Flags = PdfAnnotation.FLAGS_PRINT;
  72.         writer.AddAnnotation(richMediaAnnotation);
  73.        
  74.         String[] days = new String[] {
  75.           "2011-10-12", "2011-10-13", "2011-10-14", "2011-10-15",
  76.           "2011-10-16", "2011-10-17", "2011-10-18", "2011-10-19"
  77.         };
  78.         for (int i = 0; i < days.Length; i++) {
  79.           Rectangle rect = new Rectangle(36 + (65 * i), 765, 100 + (65 * i), 780);
  80.           PushbuttonField button = new PushbuttonField(writer, rect, "button" + i);
  81.           button.BackgroundColor = new GrayColor(0.75f);
  82.           button.BorderStyle = PdfBorderDictionary.STYLE_BEVELED;
  83.           button.TextColor = GrayColor.GRAYBLACK;
  84.           button.FontSize = 12;
  85.           button.Text = days[i];
  86.           button.Layout = PushbuttonField.LAYOUT_ICON_LEFT_LABEL_RIGHT;
  87.           button.ScaleIcon = PushbuttonField.SCALE_ICON_ALWAYS;
  88.           button.ProportionalIcon = true;
  89.           button.IconHorizontalAdjustment = 0;
  90.           PdfFormField field = button.Field;
  91.           RichMediaCommand command = new RichMediaCommand(
  92.             new PdfString("getDateInfo")
  93.           );
  94.           command.Arguments = new PdfString(days[i]);
  95.           RichMediaExecuteAction action = new RichMediaExecuteAction(
  96.             richMediaAnnotation.IndirectReference, command
  97.           );
  98.           field.Action = action;
  99.           writer.AddAnnotation(field);
  100.         }
  101.         TextField text = new TextField(
  102.           writer, new Rectangle(36, 785, 559, 806), "date"
  103.         );
  104.         text.Options = TextField.READ_ONLY;
  105.         writer.AddAnnotation(text.GetTextField());
  106.       }
  107.     }
  108. // ===========================================================================
  109.     }
  110. }
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