Chapter 6: Working with existing PDFs

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

10th October 2015
admin-marketing

Switch code for this example

PageInformation.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.PrintWriter;
  13.  
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.Rectangle;
  16. import com.itextpdf.text.pdf.PdfReader;
  17.  
  18. import part1.chapter01.HelloWorldLandscape1;
  19. import part1.chapter01.HelloWorldLandscape2;
  20. import part1.chapter03.MovieTemplates;
  21. import part1.chapter05.Hero1;
  22.  
  23. public class PageInformation {
  24.  
  25.     /** The resulting text file with info about a PDF. */
  26.     public static final String RESULT
  27.         = "results/part2/chapter06/page_info.txt";
  28.    
  29.     /**
  30.      * Main method.
  31.      * @param args no arguments needed
  32.      * @throws DocumentException
  33.      * @throws IOException
  34.      */
  35.     public static void main(String[] args)
  36.         throws DocumentException, IOException {
  37.         // Use old examples to create PDFs
  38.         HelloWorldLandscape1.main(args);
  39.         HelloWorldLandscape2.main(args);
  40.         MovieTemplates.main(args);
  41.         Hero1.main(args);
  42.         // Inspecting PDFs
  43.         PrintWriter writer = new PrintWriter(new FileOutputStream(RESULT));
  44.         inspect(writer, HelloWorldLandscape1.RESULT);
  45.         inspect(writer, HelloWorldLandscape2.RESULT);
  46.         inspect(writer, MovieTemplates.RESULT);
  47.         inspect(writer, Hero1.RESULT);
  48.         writer.close();
  49.     }
  50.    
  51.     /**
  52.      * Inspect a PDF file and write the info to a txt file
  53.      * @param writer Writer to a text file
  54.      * @param filename Path to the PDF file
  55.      * @throws IOException
  56.      */
  57.     public static void inspect(PrintWriter writer, String filename)
  58.         throws IOException {
  59.         PdfReader reader = new PdfReader(filename);
  60.         writer.println(filename);
  61.         writer.print("Number of pages: ");
  62.         writer.println(reader.getNumberOfPages());
  63.         Rectangle mediabox = reader.getPageSize(1);
  64.         writer.print("Size of page 1: [");
  65.         writer.print(mediabox.getLeft());
  66.         writer.print(',');
  67.         writer.print(mediabox.getBottom());
  68.         writer.print(',');
  69.         writer.print(mediabox.getRight());
  70.         writer.print(',');
  71.         writer.print(mediabox.getTop());
  72.         writer.println("]");
  73.         writer.print("Rotation of page 1: ");
  74.         writer.println(reader.getPageRotation(1));
  75.         writer.print("Page size with rotation of page 1: ");
  76.         writer.println(reader.getPageSizeWithRotation(1));
  77.         writer.print("Is rebuilt? ");
  78.         writer.println(reader.isRebuilt());
  79.         writer.print("Is encrypted? ");
  80.         writer.println(reader.isEncrypted());
  81.         writer.println();
  82.         writer.flush();
  83.         reader.close();
  84.     }
  85. }
MemoryInfo.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import com.itextpdf.text.DocumentException;
  11. import com.itextpdf.text.pdf.PdfReader;
  12. import com.itextpdf.text.pdf.RandomAccessFileOrArray;
  13. import part1.chapter03.MovieTemplates;
  14.  
  15. import java.io.FileOutputStream;
  16. import java.io.IOException;
  17. import java.io.PrintWriter;
  18.  
  19. public class MemoryInfo {
  20.  
  21.     /** The resulting PDF file. */
  22.     public static final String RESULT
  23.         = "results/part2/chapter06/memory_info.txt";
  24.    
  25.     /**
  26.      * Main method.
  27.      * @param args no arguments needed
  28.      * @throws DocumentException
  29.      * @throws IOException
  30.      */
  31.     public static void main(String[] args)
  32.         throws IOException, DocumentException {
  33.         // Use a previous example to create a PDF
  34.         MovieTemplates.main(args);
  35.         // Create a writer for a report file
  36.         PrintWriter writer
  37.             = new PrintWriter(new FileOutputStream(RESULT));
  38.         garbageCollect();
  39.         // Do a full read
  40.         fullRead(writer, MovieTemplates.RESULT);
  41.         // Do a partial read
  42.         partialRead(writer, MovieTemplates.RESULT);
  43.         // Close the text file writer
  44.         writer.close();
  45.     }
  46.    
  47.     /**
  48.      * Do a full read of a PDF file
  49.      * @param writer a writer to a report file
  50.      * @param filename the file to read
  51.      * @throws IOException
  52.      */
  53.     public static void fullRead(PrintWriter writer, String filename)
  54.         throws IOException {
  55.         long before = getMemoryUse();
  56.         PdfReader reader = new PdfReader(filename);
  57.         reader.getNumberOfPages();
  58.         writer.println(String.format("Memory used by full read: %d",
  59.                     getMemoryUse() - before));
  60.         writer.flush();
  61.         reader.close();
  62.     }
  63.    
  64.     /**
  65.      * Do a partial read of a PDF file
  66.      * @param writer a writer to a report file
  67.      * @param filename the file to read
  68.      * @throws IOException
  69.      */
  70.     public static void partialRead(PrintWriter writer, String filename)
  71.         throws IOException {
  72.         long before = getMemoryUse();
  73.         PdfReader reader = new PdfReader(
  74.                 new RandomAccessFileOrArray(filename), null);
  75.         reader.getNumberOfPages();
  76.         writer.println(String.format("Memory used by partial read: %d",
  77.                     getMemoryUse() - before));
  78.         writer.flush();
  79.         reader.close();
  80.     }
  81.  
  82.     /**
  83.      * Returns the current memory use.
  84.      *
  85.      * @return the current memory use
  86.      */
  87.     public static long getMemoryUse() {
  88.         garbageCollect();
  89.         garbageCollect();
  90.         garbageCollect();
  91.         garbageCollect();
  92.         long totalMemory = Runtime.getRuntime().totalMemory();
  93.         garbageCollect();
  94.         garbageCollect();
  95.         long freeMemory = Runtime.getRuntime().freeMemory();
  96.         return (totalMemory - freeMemory);
  97.     }
  98.  
  99.     /**
  100.      * Makes sure all garbage is cleared from the memory.
  101.      */
  102.     public static void garbageCollect() {
  103.         try {
  104.             System.gc();
  105.             Thread.sleep(200);
  106.             System.runFinalization();
  107.             Thread.sleep(200);
  108.             System.gc();
  109.             Thread.sleep(200);
  110.             System.runFinalization();
  111.             Thread.sleep(200);
  112.         } catch (InterruptedException ex) {
  113.             ex.printStackTrace();
  114.         }
  115.     }
  116. }
SelectPages.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import part1.chapter03.MovieTemplates;
  14.  
  15. import com.itextpdf.text.Document;
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.pdf.PdfCopy;
  18. import com.itextpdf.text.pdf.PdfReader;
  19. import com.itextpdf.text.pdf.PdfStamper;
  20.  
  21. public class SelectPages {
  22.  
  23.     /** A resulting PDF file. */
  24.     public static final String RESULT1 = "results/part2/chapter06/timetable_stamper.pdf";
  25.     /** A resulting PDF file. */
  26.     public static final String RESULT2 = "results/part2/chapter06/timetable_copy.pdf";
  27.    
  28.     /**
  29.      * Main method.
  30.      * @param args no arguments needed
  31.      * @throws DocumentException
  32.      * @throws IOException
  33.      */
  34.     public static void main(String[] args) throws IOException, DocumentException {
  35.         new MovieTemplates().createPdf(MovieTemplates.RESULT);
  36.         PdfReader reader = new PdfReader(MovieTemplates.RESULT);
  37.         reader.selectPages("4-8");
  38.         manipulateWithStamper(reader);
  39.         manipulateWithCopy(reader);
  40.         reader.close();
  41.     }
  42.  
  43.     /**
  44.      * Creates a new PDF based on the one in the reader
  45.      * @param reader a reader with a PDF file
  46.      * @throws IOException
  47.      * @throws DocumentException
  48.      */
  49.     private static void manipulateWithStamper(PdfReader reader)
  50.         throws IOException, DocumentException {
  51.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT1));
  52.         stamper.close();
  53.     }
  54.  
  55.     /**
  56.      * Creates a new PDF based on the one in the reader
  57.      * @param reader a reader with a PDF file
  58.      * @throws IOException
  59.      * @throws DocumentException
  60.      */
  61.     private static void manipulateWithCopy(PdfReader reader)
  62.         throws IOException, DocumentException {
  63.         int n = reader.getNumberOfPages();
  64.         Document document = new Document();
  65.         PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT2));
  66.         document.open();
  67.         for (int i = 0; i < n;) {
  68.             copy.addPage(copy.getImportedPage(reader, ++i));
  69.         }
  70.         document.close();
  71.     }
  72.    
  73.    
  74. }
ImportingPages1.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import part1.chapter03.MovieTemplates;
  14.  
  15. import com.itextpdf.text.Document;
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.Image;
  18. import com.itextpdf.text.pdf.PdfImportedPage;
  19. import com.itextpdf.text.pdf.PdfPTable;
  20. import com.itextpdf.text.pdf.PdfReader;
  21. import com.itextpdf.text.pdf.PdfWriter;
  22.  
  23. public class ImportingPages1 {
  24.  
  25.     /** The resulting PDF file. */
  26.     public static final String RESULT
  27.         = "results/part2/chapter06/time_table_imported1.pdf";
  28.    
  29.     /**
  30.      * Main method.
  31.      * @param args no arguments needed
  32.      * @throws DocumentException
  33.      * @throws IOException
  34.      */
  35.     public static void main(String[] args)
  36.         throws IOException, DocumentException {
  37.         // Use old example to create PDF
  38.         new MovieTemplates().createPdf(MovieTemplates.RESULT);
  39.         // step 1
  40.         Document document = new Document();
  41.         // step 2
  42.         PdfWriter writer
  43.             = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  44.         // step 3
  45.         document.open();
  46.         // step 4
  47.         PdfPTable table = new PdfPTable(2);
  48.         PdfReader reader = new PdfReader(MovieTemplates.RESULT);
  49.         int n = reader.getNumberOfPages();
  50.         PdfImportedPage page;
  51.         for (int i = 1; i
ImportingPages2.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import part1.chapter03.MovieTemplates;
  14.  
  15. import com.itextpdf.text.Document;
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.Image;
  18. import com.itextpdf.text.pdf.PdfImportedPage;
  19. import com.itextpdf.text.pdf.PdfPTable;
  20. import com.itextpdf.text.pdf.PdfReader;
  21. import com.itextpdf.text.pdf.PdfWriter;
  22.  
  23. public class ImportingPages2 {
  24.  
  25.     /** The resulting PDF file. */
  26.     public static final String RESULT
  27.         = "results/part2/chapter06/time_table_imported2.pdf";
  28.    
  29.     /**
  30.      * Main method.
  31.      * @param args no arguments needed
  32.      * @throws DocumentException
  33.      * @throws IOException
  34.      */
  35.     public static void main(String[] args)
  36.         throws IOException, DocumentException {
  37.         // use old example to create PDF
  38.         new MovieTemplates().createPdf(MovieTemplates.RESULT);
  39.         // step 1
  40.         Document document = new Document();
  41.         // step 2
  42.         PdfWriter writer
  43.             = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  44.         // step 3
  45.         document.open();
  46.         // step 4
  47.         PdfReader reader = new PdfReader(MovieTemplates.RESULT);
  48.         int n = reader.getNumberOfPages();
  49.         PdfImportedPage page;
  50.         PdfPTable table = new PdfPTable(2);
  51.         for (int i = 1; i
Layers.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.Document;
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.Element;
  16. import com.itextpdf.text.Font;
  17. import com.itextpdf.text.Image;
  18. import com.itextpdf.text.PageSize;
  19. import com.itextpdf.text.Paragraph;
  20. import com.itextpdf.text.Font.FontFamily;
  21. import com.itextpdf.text.pdf.BaseFont;
  22. import com.itextpdf.text.pdf.PdfContentByte;
  23. import com.itextpdf.text.pdf.PdfGState;
  24. import com.itextpdf.text.pdf.PdfImportedPage;
  25. import com.itextpdf.text.pdf.PdfReader;
  26. import com.itextpdf.text.pdf.PdfWriter;
  27.  
  28. public class Layers {
  29.  
  30.     /** The resulting PDF. */
  31.     public static final String SOURCE
  32.         = "results/part2/chapter06/layers_orig.pdf";
  33.     /** The resulting PDF. */
  34.     public static final String RESULT
  35.         = "results/part2/chapter06/layers.pdf";
  36.     /** The movie poster. */
  37.     public static final String RESOURCE
  38.         = "resources/img/loa.jpg";
  39.    
  40.     /**
  41.      * Main method.
  42.      * @param args no arguments needed
  43.      * @throws DocumentException
  44.      * @throws IOException
  45.      */
  46.     public static void main(String[] args)
  47.         throws IOException, DocumentException {
  48.         new Layers().createPdf(SOURCE);
  49.         // Create a reader
  50.         PdfReader reader = new PdfReader(SOURCE);
  51.         // step 1
  52.         Document document = new Document(PageSize.A5.rotate());
  53.         // step 2
  54.         PdfWriter writer
  55.             = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  56.         // step 3
  57.         document.open();
  58.         // step 4
  59.         PdfContentByte canvas = writer.getDirectContent();
  60.         PdfImportedPage page;
  61.         BaseFont bf
  62.             = BaseFont.createFont(BaseFont.ZAPFDINGBATS, "", BaseFont.EMBEDDED);
  63.         for (int i = 0; i < reader.getNumberOfPages(); ) {
  64.             page = writer.getImportedPage(reader, ++i);
  65.             canvas.addTemplate(page, 1f, 0, 0.4f, 0.4f, 72, 50 * i);
  66.             canvas.beginText();
  67.             canvas.setFontAndSize(bf, 20);
  68.             canvas.showTextAligned(Element.ALIGN_CENTER,
  69.                 String.valueOf((char)(181 + i)), 496, 150 + 50 * i, 0);
  70.             canvas.endText();
  71.         }
  72.         // step 5
  73.         document.close();
  74.         reader.close();
  75.     }
  76.  
  77.     /**
  78.      * Creates a PDF document.
  79.      * @param filename the path to the new PDF document
  80.      * @throws    DocumentException
  81.      * @throws    IOException
  82.      */
  83.     public void createPdf(String filename)
  84.         throws IOException, DocumentException {
  85.         // step 1
  86.         Document document = new Document(PageSize.POSTCARD, 30, 30, 30, 30);
  87.         // step 2
  88.         PdfWriter writer = PdfWriter.getInstance(document,
  89.                 new FileOutputStream(filename));
  90.         // step 3
  91.         document.open();
  92.         // step 4
  93.         PdfContentByte under = writer.getDirectContentUnder();
  94.         // Page 1: a rectangle
  95.         drawRectangle(under, PageSize.POSTCARD.getWidth(), PageSize.POSTCARD.getHeight());
  96.         under.setRGBColorFill(0xFF, 0xD7, 0x00);
  97.         under.rectangle(5, 5, PageSize.POSTCARD.getWidth() - 10, PageSize.POSTCARD.getHeight() - 10);
  98.         under.fill();
  99.         document.newPage();
  100.         // Page 2: an image
  101.         drawRectangle(under, PageSize.POSTCARD.getWidth(), PageSize.POSTCARD.getHeight());
  102.         Image img = Image.getInstance(RESOURCE);
  103.         img.setAbsolutePosition((PageSize.POSTCARD.getWidth() - img.getScaledWidth()) / 2,
  104.                 (PageSize.POSTCARD.getHeight() - img.getScaledHeight()) / 2);
  105.         document.add(img);
  106.         document.newPage();
  107.         // Page 3: the words "Foobar Film Festival"
  108.         drawRectangle(under, PageSize.POSTCARD.getWidth(), PageSize.POSTCARD.getHeight());;
  109.         Paragraph p = new Paragraph("Foobar Film Festival", new Font(FontFamily.HELVETICA, 22));
  110.         p.setAlignment(Element.ALIGN_CENTER);
  111.         document.add(p);
  112.         document.newPage();
  113.         // Page 4: the words "SOLD OUT"
  114.         drawRectangle(under, PageSize.POSTCARD.getWidth(), PageSize.POSTCARD.getHeight());
  115.         PdfContentByte over = writer.getDirectContent();
  116.         over.saveState();
  117.         float sinus = (float)Math.sin(Math.PI / 60);
  118.         float cosinus = (float)Math.cos(Math.PI / 60);
  119.         BaseFont bf = BaseFont.createFont();
  120.         over.beginText();
  121.         over.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
  122.         over.setLineWidth(1.5f);
  123.         over.setRGBColorStroke(0xFF, 0x00, 0x00);
  124.         over.setRGBColorFill(0xFF, 0xFF, 0xFF);
  125.         over.setFontAndSize(bf, 36);
  126.         over.setTextMatrix(cosinus, sinus, -sinus, cosinus, 50, 324);
  127.         over.showText("SOLD OUT");
  128.         over.setTextMatrix(0, 0);
  129.         over.endText();
  130.         over.restoreState();
  131.         // step 5
  132.         document.close();
  133.     }
  134.    
  135.     /**
  136.      * Draws a rectangle
  137.      * @param content the direct content layer
  138.      * @param width the width of the rectangle
  139.      * @param height the height of the rectangle
  140.      */
  141.     public static void drawRectangle(PdfContentByte content, float width, float height) {
  142.         content.saveState();
  143.         PdfGState state = new PdfGState();
  144.         state.setFillOpacity(0.6f);
  145.         content.setGState(state);
  146.         content.setRGBColorFill(0xFF, 0xFF, 0xFF);
  147.         content.setLineWidth(3);
  148.         content.rectangle(0, 0, width, height);
  149.         content.fillStroke();
  150.         content.restoreState();
  151.     }
  152. }
Superimposing.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.Document;
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.Element;
  16. import com.itextpdf.text.Font;
  17. import com.itextpdf.text.Image;
  18. import com.itextpdf.text.PageSize;
  19. import com.itextpdf.text.Paragraph;
  20. import com.itextpdf.text.Font.FontFamily;
  21. import com.itextpdf.text.pdf.BaseFont;
  22. import com.itextpdf.text.pdf.PdfContentByte;
  23. import com.itextpdf.text.pdf.PdfImportedPage;
  24. import com.itextpdf.text.pdf.PdfReader;
  25. import com.itextpdf.text.pdf.PdfWriter;
  26.  
  27. public class Superimposing {
  28.  
  29.     /** The resulting PDF. */
  30.     public static final String SOURCE
  31.         = "results/part2/chapter06/opening.pdf";
  32.     /** The resulting PDF. */
  33.     public static final String RESULT
  34.         = "results/part2/chapter06/festival_opening.pdf";
  35.     /** The movie poster. */
  36.     public static final String RESOURCE
  37.         = "resources/img/loa.jpg";
  38.  
  39.     /**
  40.      * Main method.
  41.      * @param    args    no arguments needed
  42.      * @throws DocumentException
  43.      * @throws IOException
  44.      */
  45.     public static void main(String[] args)
  46.         throws IOException, DocumentException {
  47.         new Superimposing().createPdf(SOURCE);
  48.         // Create a reader object
  49.         PdfReader reader = new PdfReader(SOURCE);
  50.         // step 1
  51.         Document document = new Document(PageSize.POSTCARD);
  52.         // step 2
  53.         PdfWriter writer
  54.             = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  55.         // step 3
  56.         document.open();
  57.         // step 4
  58.         PdfContentByte canvas = writer.getDirectContent();
  59.         PdfImportedPage page;
  60.         for (int i = 1; i
Stationery.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15. import java.util.Set;
  16. import java.util.TreeSet;
  17.  
  18. import com.lowagie.database.DatabaseConnection;
  19. import com.lowagie.database.HsqldbConnection;
  20. import com.lowagie.filmfestival.FilmFonts;
  21. import com.lowagie.filmfestival.Movie;
  22. import com.lowagie.filmfestival.MovieComparator;
  23. import com.lowagie.filmfestival.PojoFactory;
  24. import com.lowagie.filmfestival.PojoToElementFactory;
  25. import com.itextpdf.text.Chunk;
  26. import com.itextpdf.text.Document;
  27. import com.itextpdf.text.DocumentException;
  28. import com.itextpdf.text.Element;
  29. import com.itextpdf.text.Font;
  30. import com.itextpdf.text.PageSize;
  31. import com.itextpdf.text.Paragraph;
  32. import com.itextpdf.text.Phrase;
  33. import com.itextpdf.text.Font.FontFamily;
  34. import com.itextpdf.text.pdf.ColumnText;
  35. import com.itextpdf.text.pdf.GrayColor;
  36. import com.itextpdf.text.pdf.PdfImportedPage;
  37. import com.itextpdf.text.pdf.PdfPTable;
  38. import com.itextpdf.text.pdf.PdfPageEventHelper;
  39. import com.itextpdf.text.pdf.PdfReader;
  40. import com.itextpdf.text.pdf.PdfWriter;
  41.  
  42. public class Stationery extends PdfPageEventHelper {
  43.  
  44.     /** The original PDF. */
  45.     public static final String STATIONERY
  46.         = "results/part2/chapter06/stationery.pdf";
  47.     /** The resulting PDF. */
  48.     public static final String RESULT
  49.         = "results/part2/chapter06/text_on_stationery.pdf";
  50.    
  51.     /**
  52.      * Main method.
  53.      * @param args no arguments needed
  54.      * @throws DocumentException
  55.      * @throws IOException
  56.      * @throws SQLException
  57.      */
  58.     public static void main(String[] args)
  59.         throws IOException, DocumentException, SQLException {
  60.         Stationery stationary = new Stationery();
  61.         createStationary(STATIONERY);
  62.         stationary.createPdf(RESULT);
  63.     }
  64.  
  65.     /**
  66.      * Creates a PDF document.
  67.      * @param filename the path to the new PDF document
  68.      * @throws    DocumentException
  69.      * @throws    IOException
  70.      * @throws    SQLException
  71.      */
  72.     public void createPdf(String filename)
  73.         throws SQLException, IOException, DocumentException {
  74.         // Create the database connection
  75.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  76.         // step 1
  77.         Document document = new Document(PageSize.A4, 36, 36, 72, 36);
  78.         // step 2
  79.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  80.         useStationary(writer);
  81.         // step 3
  82.         document.open();
  83.         // step 4
  84.         Statement stm = connection.createStatement();
  85.         ResultSet rs = stm.executeQuery(
  86.             "SELECT country, id FROM film_country ORDER BY country");
  87.         while (rs.next()) {
  88.             document.add(new Paragraph(rs.getString("country"), FilmFonts.BOLD));
  89.             document.add(Chunk.NEWLINE);
  90.             Set movies =
  91.                 new TreeSet(new MovieComparator(MovieComparator.BY_YEAR));
  92.             movies.addAll(PojoFactory.getMovies(connection, rs.getString("id")));
  93.             for(Movie movie : movies) {
  94.                 document.add(new Paragraph(movie.getMovieTitle(), FilmFonts.BOLD));
  95.                 if (movie.getOriginalTitle() != null)
  96.                     document.add(new Paragraph(movie.getOriginalTitle(), FilmFonts.ITALIC));
  97.                 document.add(new Paragraph(
  98.                     String.format("Year: %d; run length: %d minutes",
  99.                     movie.getYear(), movie.getDuration()), FilmFonts.NORMAL));
  100.                 document.add(PojoToElementFactory.getDirectorList(movie));
  101.             }
  102.             document.newPage();
  103.         }
  104.         // step 5
  105.         document.close();
  106.         // Close the database connection
  107.         connection.close();
  108.     }
  109.    
  110.     /** Imported page with the stationery. */
  111.     protected PdfImportedPage page;
  112.  
  113.     /**
  114.      * Initialize the imported page.
  115.      * @param writer The PdfWriter
  116.      * @throws IOException
  117.      */
  118.     public void useStationary(PdfWriter writer) throws IOException {
  119.         writer.setPageEvent(this);
  120.         PdfReader reader = new PdfReader(STATIONERY);
  121.         page = writer.getImportedPage(reader, 1);
  122.     }
  123.    
  124.     /**
  125.      * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
  126.      *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  127.      */
  128.     public void onEndPage(PdfWriter writer, Document document) {
  129.         writer.getDirectContentUnder().addTemplate(page, 0, 0);
  130.     }
  131.  
  132.     /**
  133.      * Creates a PDF document.
  134.      * @param filename the path to the new PDF document
  135.      * @throws    DocumentException
  136.      * @throws    IOException
  137.      * @throws    SQLException
  138.      */
  139.     public static void createStationary(String filename)
  140.         throws IOException, DocumentException {
  141.         // step 1
  142.         Document document = new Document();
  143.         // step 2
  144.         PdfWriter writer
  145.             = PdfWriter.getInstance(document, new FileOutputStream(filename));
  146.         // step 3
  147.         document.open();
  148.         // step 4
  149.         PdfPTable table = new PdfPTable(1);
  150.         table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
  151.         table.addCell(new Phrase("FOOBAR FILM FESTIVAL", FilmFonts.BOLD));
  152.         document.add(table);
  153.         Font font = new Font(FontFamily.HELVETICA, 52, Font.BOLD, new GrayColor(0.75f));
  154.         ColumnText.showTextAligned(writer.getDirectContentUnder(),
  155.                 Element.ALIGN_CENTER, new Phrase("FOOBAR FILM FESTIVAL", font),
  156.                 297.5f, 421, 45);
  157.         // step 5
  158.         document.close();
  159.     }
  160. }
NUpTool.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13.  
  14. import com.itextpdf.text.Document;
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.Rectangle;
  17. import com.itextpdf.text.pdf.PdfContentByte;
  18. import com.itextpdf.text.pdf.PdfImportedPage;
  19. import com.itextpdf.text.pdf.PdfReader;
  20. import com.itextpdf.text.pdf.PdfWriter;
  21.  
  22. public class NUpTool {
  23.  
  24.     /** Format of the resulting PDF files. */
  25.     public static final String RESULT
  26.         = "results/part2/chapter06/result%dup.pdf";
  27.    
  28.     /**
  29.      * Manipulates a PDF file src with the file dest as result
  30.      * @param src the original PDF
  31.      * @param dest the resulting PDF
  32.      * @param pow the PDF will be N-upped with N = Math.pow(2, pow);
  33.      * @throws IOException
  34.      * @throws DocumentException
  35.      * @throws SQLException
  36.      */
  37.     public void manipulatePdf(String src, String dest, int pow)
  38.         throws IOException, DocumentException {
  39.         // reader for the src file
  40.         PdfReader reader = new PdfReader(src);
  41.         // initializations
  42.         Rectangle pageSize = reader.getPageSize(1);
  43.         Rectangle newSize = (pow % 2) == 0 ?
  44.             new Rectangle(pageSize.getWidth(), pageSize.getHeight()) :
  45.             new Rectangle(pageSize.getHeight(), pageSize.getWidth());
  46.         Rectangle unitSize = new Rectangle(pageSize.getWidth(), pageSize.getHeight());
  47.         for (int i = 0; i < pow; i++) {
  48.             unitSize = new Rectangle(unitSize.getHeight() / 2, unitSize.getWidth());
  49.         }
  50.         int n = (int)Math.pow(2, pow);
  51.         int r = (int)Math.pow(2, pow / 2);
  52.         int c = n / r;
  53.         // step 1
  54.         Document document = new Document(newSize, 0, 0, 0, 0);
  55.         // step 2
  56.         PdfWriter writer
  57.            = PdfWriter.getInstance(document, new FileOutputStream(String.format(dest, n)));
  58.         // step 3
  59.         document.open();
  60.         // step 4
  61.         PdfContentByte cb = writer.getDirectContent();
  62.         PdfImportedPage page;
  63.         Rectangle currentSize;
  64.         float offsetX, offsetY, factor;
  65.         int total = reader.getNumberOfPages();
  66.         for (int i = 0; i < total; ) {
  67.             if (i % n == 0) {
  68.                 document.newPage();
  69.             }
  70.             currentSize = reader.getPageSize(++i);
  71.             factor = Math.min(
  72.                 unitSize.getWidth() / currentSize.getWidth(),
  73.                 unitSize.getHeight() / currentSize.getHeight());
  74.             offsetX = unitSize.getWidth() * ((i % n) % c)
  75.               + (unitSize.getWidth() - (currentSize.getWidth() * factor)) / 2f;
  76.             offsetY = newSize.getHeight() - (unitSize.getHeight() * (((i % n) / c) + 1))
  77.               + (unitSize.getHeight() - (currentSize.getHeight() * factor)) / 2f;
  78.             page = writer.getImportedPage(reader, i);
  79.             cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
  80.         }
  81.         // step 5
  82.         document.close();
  83.         reader.close();
  84.     }
  85.    
  86.     /**
  87.      * Main method.
  88.      * @param args no arguments needed
  89.      * @throws DocumentException
  90.      * @throws IOException
  91.      * @throws SQLException
  92.      */
  93.     public static void main(String[] args)
  94.         throws IOException, DocumentException, SQLException {
  95.         Stationery.main(args);
  96.         new NUpTool().manipulatePdf(Stationery.RESULT, RESULT, 1);
  97.         new NUpTool().manipulatePdf(Stationery.RESULT, RESULT, 2);
  98.         new NUpTool().manipulatePdf(Stationery.RESULT, RESULT, 3);
  99.         new NUpTool().manipulatePdf(Stationery.RESULT, RESULT, 4);
  100.     }
  101. }
TilingHero.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  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.PdfContentByte;
  17. import com.itextpdf.text.pdf.PdfImportedPage;
  18. import com.itextpdf.text.pdf.PdfReader;
  19. import com.itextpdf.text.pdf.PdfWriter;
  20.  
  21. public class TilingHero {
  22.  
  23.     /** The original PDF file. */
  24.     public static final String RESOURCE
  25.         = "resources/pdfs/hero.pdf";
  26.  
  27.     /** The resulting PDF file. */
  28.     public static final String RESULT
  29.         = "results/part2/chapter06/superman.pdf";
  30.    
  31.     /**
  32.      * Manipulates a PDF file src with the file dest as result
  33.      * @param src the original PDF
  34.      * @param dest the resulting PDF
  35.      * @throws IOException
  36.      * @throws DocumentException
  37.      */
  38.     public void manipulatePdf(String src, String dest)
  39.         throws IOException, DocumentException {
  40.         // Creating a reader
  41.         PdfReader reader = new PdfReader(src);
  42.         Rectangle pagesize = reader.getPageSizeWithRotation(1);
  43.         // step 1
  44.         Document document = new Document(pagesize);
  45.         // step 2
  46.         PdfWriter writer
  47.             = PdfWriter.getInstance(document, new FileOutputStream(dest));
  48.         // step 3
  49.         document.open();
  50.         // step 4
  51.         PdfContentByte content = writer.getDirectContent();
  52.         PdfImportedPage page = writer.getImportedPage(reader, 1);
  53.         // adding the same page 16 times with a different offset
  54.         float x, y;
  55.         for (int i = 0; i < 16; i++) {
  56.             x = -pagesize.getWidth() * (i % 4);
  57.             y = pagesize.getHeight() * (i / 4 - 3);
  58.             content.addTemplate(page, 4, 0, 0, 4, x, y);
  59.             document.newPage();
  60.         }
  61.         // step 4
  62.         document.close();
  63.         reader.close();
  64.     }
  65.  
  66.     /**
  67.      * Main method.
  68.      * @param    args    no arguments needed
  69.      * @throws DocumentException
  70.      * @throws IOException
  71.      */
  72.     public static void main(String[] args)
  73.         throws IOException, DocumentException {
  74.         new TilingHero().manipulatePdf(RESOURCE, RESULT);
  75.     }
  76. }
StampText.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.DocumentException;
  14. import com.itextpdf.text.Element;
  15. import com.itextpdf.text.Phrase;
  16. import com.itextpdf.text.pdf.ColumnText;
  17. import com.itextpdf.text.pdf.PdfContentByte;
  18. import com.itextpdf.text.pdf.PdfReader;
  19. import com.itextpdf.text.pdf.PdfStamper;
  20.  
  21. import part1.chapter01.HelloWorldLandscape1;
  22. import part1.chapter01.HelloWorldLandscape2;
  23.  
  24. public class StampText {
  25.     /** A resulting PDF file. */
  26.     public static final String RESULT1
  27.         = "results/part2/chapter06/hello1.pdf";
  28.     /** A resulting PDF file. */
  29.     public static final String RESULT2
  30.         = "results/part2/chapter06/hello2.pdf";
  31.     /** A resulting PDF file. */
  32.     public static final String RESULT3
  33.         = "results/part2/chapter06/hello3.pdf";
  34.    
  35.     /**
  36.      * Main method.
  37.      * @param args no arguments needed
  38.      * @throws DocumentException
  39.      * @throws IOException
  40.      */
  41.     public static void main(String[] args)
  42.         throws DocumentException, IOException {
  43.         HelloWorldLandscape1.main(args);
  44.         HelloWorldLandscape2.main(args);
  45.         stamp(HelloWorldLandscape1.RESULT, RESULT1);
  46.         stampIgnoreRotation(HelloWorldLandscape1.RESULT, RESULT2);
  47.         stamp(HelloWorldLandscape2.RESULT, RESULT3);
  48.        
  49.     }
  50.  
  51.     /**
  52.      * Manipulates a PDF file src with the file dest as result
  53.      * @param src the original PDF
  54.      * @param dest the resulting PDF
  55.      * @throws IOException
  56.      * @throws DocumentException
  57.      */
  58.     public static void stamp(String src, String dest)
  59.         throws IOException, DocumentException {
  60.         PdfReader reader = new PdfReader(src);
  61.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  62.         PdfContentByte canvas = stamper.getOverContent(1);
  63.         ColumnText.showTextAligned(canvas,
  64.                 Element.ALIGN_LEFT, new Phrase("Hello people!"), 36, 540, 0);
  65.         stamper.close();
  66.         reader.close();
  67.     }
  68.  
  69.     /**
  70.      * Manipulates a PDF file src with the file dest as result
  71.      * @param src the original PDF
  72.      * @param dest the resulting PDF
  73.      * @throws IOException
  74.      * @throws DocumentException
  75.      */
  76.     public static void stampIgnoreRotation(String src, String dest)
  77.         throws IOException, DocumentException {
  78.         PdfReader reader = new PdfReader(src);
  79.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  80.         stamper.setRotateContents(false);
  81.         PdfContentByte canvas = stamper.getOverContent(1);
  82.         ColumnText.showTextAligned(canvas,
  83.                 Element.ALIGN_LEFT, new Phrase("Hello people!"), 36, 540, 0);
  84.         stamper.close();
  85.         reader.close();
  86.     }
  87. }
TwoPasses.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.ByteArrayOutputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.sql.ResultSet;
  14. import java.sql.SQLException;
  15. import java.sql.Statement;
  16. import java.util.Set;
  17. import java.util.TreeSet;
  18.  
  19. import com.lowagie.database.DatabaseConnection;
  20. import com.lowagie.database.HsqldbConnection;
  21. import com.lowagie.filmfestival.FilmFonts;
  22. import com.lowagie.filmfestival.Movie;
  23. import com.lowagie.filmfestival.MovieComparator;
  24. import com.lowagie.filmfestival.PojoFactory;
  25. import com.lowagie.filmfestival.PojoToElementFactory;
  26. import com.itextpdf.text.Chunk;
  27. import com.itextpdf.text.Document;
  28. import com.itextpdf.text.DocumentException;
  29. import com.itextpdf.text.Element;
  30. import com.itextpdf.text.PageSize;
  31. import com.itextpdf.text.Paragraph;
  32. import com.itextpdf.text.Rectangle;
  33. import com.itextpdf.text.pdf.PdfPTable;
  34. import com.itextpdf.text.pdf.PdfReader;
  35. import com.itextpdf.text.pdf.PdfStamper;
  36. import com.itextpdf.text.pdf.PdfWriter;
  37.  
  38. public class TwoPasses {
  39.  
  40.     /** The resulting PDF file. */
  41.     public static final String RESULT
  42.         = "results/part2/chapter06/page_x_of_y.pdf";
  43.  
  44.     /**
  45.      * Main method.
  46.      * @param    args    no arguments needed
  47.      * @throws DocumentException
  48.      * @throws IOException
  49.      * @throws SQLException
  50.      * @throws SQLException
  51.      */
  52.     public static void main(String[] args)
  53.         throws SQLException, DocumentException, IOException {
  54.        
  55.         // FIRST PASS, CREATE THE PDF WITHOUT HEADER
  56.        
  57.         // Create a database connection
  58.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  59.         // step 1
  60.         Document document = new Document(PageSize.A4, 36, 36, 54, 36);
  61.         // step 2
  62.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  63.         PdfWriter.getInstance(document, baos);
  64.         // step 3
  65.         document.open();
  66.         // step 4
  67.         Statement stm = connection.createStatement();
  68.         ResultSet rs = stm.executeQuery(
  69.             "SELECT country, id FROM film_country ORDER BY country");
  70.         while (rs.next()) {
  71.             document.add(new Paragraph(rs.getString("country"), FilmFonts.BOLD));
  72.             document.add(Chunk.NEWLINE);
  73.             Set movies =
  74.                 new TreeSet(new MovieComparator(MovieComparator.BY_YEAR));
  75.             movies.addAll(PojoFactory.getMovies(connection, rs.getString("id")));
  76.             for(Movie movie : movies) {
  77.                 document.add(new Paragraph(movie.getMovieTitle(), FilmFonts.BOLD));
  78.                 if (movie.getOriginalTitle() != null)
  79.                     document.add(
  80.                         new Paragraph(movie.getOriginalTitle(), FilmFonts.ITALIC));
  81.                 document.add(new Paragraph(
  82.                     String.format("Year: %d; run length: %d minutes",
  83.                     movie.getYear(), movie.getDuration()), FilmFonts.NORMAL));
  84.                 document.add(PojoToElementFactory.getDirectorList(movie));
  85.             }
  86.             document.newPage();
  87.         }
  88.         // step 5
  89.         document.close();
  90.         // Close the database connection
  91.         connection.close();
  92.        
  93.         // SECOND PASS, ADD THE HEADER
  94.        
  95.         // Create a reader
  96.         PdfReader reader = new PdfReader(baos.toByteArray());
  97.         // Create a stamper
  98.         PdfStamper stamper
  99.             = new PdfStamper(reader, new FileOutputStream(RESULT));
  100.         // Loop over the pages and add a header to each page
  101.         int n = reader.getNumberOfPages();
  102.         for (int i = 1; i
StampStationery.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15. import java.util.Set;
  16. import java.util.TreeSet;
  17.  
  18. import com.lowagie.database.DatabaseConnection;
  19. import com.lowagie.database.HsqldbConnection;
  20. import com.lowagie.filmfestival.FilmFonts;
  21. import com.lowagie.filmfestival.Movie;
  22. import com.lowagie.filmfestival.MovieComparator;
  23. import com.lowagie.filmfestival.PojoFactory;
  24. import com.lowagie.filmfestival.PojoToElementFactory;
  25. import com.itextpdf.text.Chunk;
  26. import com.itextpdf.text.Document;
  27. import com.itextpdf.text.DocumentException;
  28. import com.itextpdf.text.PageSize;
  29. import com.itextpdf.text.Paragraph;
  30. import com.itextpdf.text.pdf.PdfContentByte;
  31. import com.itextpdf.text.pdf.PdfImportedPage;
  32. import com.itextpdf.text.pdf.PdfReader;
  33. import com.itextpdf.text.pdf.PdfStamper;
  34. import com.itextpdf.text.pdf.PdfWriter;
  35.  
  36. public class StampStationery {
  37.     /** The original PDF file. */
  38.     public static final String ORIGINAL
  39.         = "results/part2/chapter06/original.pdf";
  40.     /** The resulting PDF. */
  41.     public static final String RESULT
  42.         = "results/part2/chapter06/stamped_stationary.pdf";
  43.    
  44.     /**
  45.      * Main method.
  46.      * @param args no arguments needed
  47.      * @throws DocumentException
  48.      * @throws IOException
  49.      * @throws SQLException
  50.      */
  51.     public static void main(String[] args)
  52.         throws IOException, DocumentException, SQLException {
  53.         Stationery.createStationary(Stationery.STATIONERY);
  54.         StampStationery stationary = new StampStationery();
  55.         stationary.createPdf(ORIGINAL);
  56.         stationary.manipulatePdf(ORIGINAL, Stationery.STATIONERY, RESULT);
  57.     }
  58.    
  59.     /**
  60.      * Manipulates a PDF file src with the file dest as result
  61.      * @param src the original PDF
  62.      * @param stationery a PDF that will be added as background
  63.      * @param dest the resulting PDF
  64.      * @throws IOException
  65.      * @throws DocumentException
  66.      */
  67.     public void manipulatePdf(String src, String stationery, String dest)
  68.         throws IOException, DocumentException {
  69.         // Create readers
  70.         PdfReader reader = new PdfReader(src);
  71.         PdfReader s_reader = new PdfReader(stationery);
  72.         // Create the stamper
  73.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  74.         // Add the stationery to each page
  75.         PdfImportedPage page = stamper.getImportedPage(s_reader, 1);
  76.         int n = reader.getNumberOfPages();
  77.         PdfContentByte background;
  78.         for (int i = 1; i
InsertPages.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15.  
  16. import com.lowagie.database.DatabaseConnection;
  17. import com.lowagie.database.HsqldbConnection;
  18. import com.itextpdf.text.Chunk;
  19. import com.itextpdf.text.DocumentException;
  20. import com.itextpdf.text.Paragraph;
  21. import com.itextpdf.text.pdf.ColumnText;
  22. import com.itextpdf.text.pdf.PdfImportedPage;
  23. import com.itextpdf.text.pdf.PdfReader;
  24. import com.itextpdf.text.pdf.PdfStamper;
  25.  
  26. public class InsertPages {
  27.     /** A resulting PDF. */
  28.     public static final String RESULT1
  29.         = "results/part2/chapter06/inserted_pages.pdf";
  30.     /** A resulting PDF. */
  31.     public static final String RESULT2
  32.         = "results/part2/chapter06/reordered.pdf";
  33.    
  34.     /**
  35.      * Main method.
  36.      * @param args no arguments needed
  37.      * @throws DocumentException
  38.      * @throws IOException
  39.      * @throws SQLException
  40.      */
  41.     public static void main(String[] args)
  42.         throws IOException, DocumentException, SQLException {
  43.         // use a previous example to create a PDF
  44.         StampStationery.main(args);
  45.         // manipulate the PDF
  46.         new InsertPages().manipulatePdf(StampStationery.RESULT, RESULT1);
  47.         // reorder the pages in the PDF
  48.         PdfReader reader = new PdfReader(RESULT1);
  49.         reader.selectPages("3-41,1-2");
  50.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT2));
  51.         stamper.close();
  52.         reader.close();
  53.     }
  54.    
  55.     /**
  56.      * Manipulates a PDF file src with the file dest as result
  57.      * @param src the original PDF
  58.      * @param dest the resulting PDF
  59.      * @throws IOException
  60.      * @throws DocumentException
  61.      * @throws SQLException
  62.      */
  63.     public void manipulatePdf(String src, String dest)
  64.         throws IOException, DocumentException, SQLException {
  65.         // Create a database connection and statement
  66.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  67.         Statement stm = connection.createStatement();
  68.         // Fill a ColumnText object with data
  69.         ResultSet rs = stm.executeQuery(
  70.             "SELECT country, id FROM film_country ORDER BY country");
  71.         ColumnText ct = new ColumnText(null);
  72.         while (rs.next()) {
  73.             ct.addElement(new Paragraph(24, new Chunk(rs.getString("country"))));
  74.         }
  75.         // Close the statement and database connection
  76.         stm.close();
  77.         connection.close();
  78.        
  79.         // Create a reader for the original document and for the stationery
  80.         PdfReader reader = new PdfReader(src);
  81.         PdfReader stationery = new PdfReader(Stationery.STATIONERY);
  82.         // Create a stamper
  83.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  84.         // Create an imported page for the stationery
  85.         PdfImportedPage page = stamper.getImportedPage(stationery, 1);
  86.         int i = 0;
  87.         // Add the content of the ColumnText object
  88.         while(true) {
  89.             // Add a new page
  90.             stamper.insertPage(++i, reader.getPageSize(1));
  91.             // Add the stationary to the new page
  92.             stamper.getUnderContent(i).addTemplate(page, 0, 0);
  93.             // Add as much content of the column as possible
  94.             ct.setCanvas(stamper.getOverContent(i));
  95.             ct.setSimpleColumn(36, 36, 559, 770);
  96.             if (!ColumnText.hasMoreText(ct.go()))
  97.                 break;
  98.         }
  99.         // Close the stamper
  100.         stamper.close();
  101.         reader.close();
  102.         stationery.close();
  103.     }
  104. }
FormInformation.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.PrintWriter;
  13. import java.util.Set;
  14.  
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.pdf.AcroFields;
  17. import com.itextpdf.text.pdf.PdfReader;
  18.  
  19. public class FormInformation {
  20.  
  21.     /** The original PDF file. */
  22.     public static final String DATASHEET
  23.         = "resources/pdfs/datasheet.pdf";
  24.     /** The resulting text file with the field info. */
  25.     public static final String RESULT
  26.         = "results/part2/chapter06/form_info.txt";    
  27.    
  28.     /**
  29.      * Main method.
  30.      * @param args no arguments needed
  31.      * @throws DocumentException
  32.      * @throws IOException
  33.      */
  34.     public static void main(String[] args)
  35.         throws DocumentException, IOException {
  36.         // Create a writer for the report file
  37.         PrintWriter writer
  38.             = new PrintWriter(new FileOutputStream(RESULT));
  39.         // Create a reader to extract info
  40.         PdfReader reader = new PdfReader(DATASHEET);
  41.         // Get the fields from the reader (read-only!!!)
  42.         AcroFields form = reader.getAcroFields();
  43.         // Loop over the fields and get info about them
  44.         Set fields = form.getFields().keySet();
  45.         for (String key : fields) {
  46.             writer.print(key + ": ");
  47.             switch (form.getFieldType(key)) {
  48.             case AcroFields.FIELD_TYPE_CHECKBOX:
  49.                 writer.println("Checkbox");
  50.                 break;
  51.             case AcroFields.FIELD_TYPE_COMBO:
  52.                 writer.println("Combobox");
  53.                 break;
  54.             case AcroFields.FIELD_TYPE_LIST:
  55.                 writer.println("List");
  56.                 break;
  57.             case AcroFields.FIELD_TYPE_NONE:
  58.                 writer.println("None");
  59.                 break;
  60.             case AcroFields.FIELD_TYPE_PUSHBUTTON:
  61.                 writer.println("Pushbutton");
  62.                 break;
  63.             case AcroFields.FIELD_TYPE_RADIOBUTTON:
  64.                 writer.println("Radiobutton");
  65.                 break;
  66.             case AcroFields.FIELD_TYPE_SIGNATURE:
  67.                 writer.println("Signature");
  68.                 break;
  69.             case AcroFields.FIELD_TYPE_TEXT:
  70.                 writer.println("Text");
  71.                 break;
  72.             default:
  73.                 writer.println("?");
  74.             }
  75.         }
  76.         // Get possible values for field "CP_1"
  77.         writer.println("Possible values for CP_1:");
  78.         String[] states = form.getAppearanceStates("CP_1");
  79.         for (int i = 0; i < states.length; i++) {
  80.             writer.print(" - ");
  81.             writer.println(states[i]);
  82.         }
  83.         // Get possible values for field "category"
  84.         writer.println("Possible values for category:");
  85.         states = form.getAppearanceStates("category");
  86.         for (int i = 0; i < states.length - 1; i++) {
  87.             writer.print(states[i]);
  88.             writer.print(", ");
  89.         }
  90.         writer.println(states[states.length - 1]);
  91.         // flush and close the report file
  92.         writer.flush();
  93.         writer.close();
  94.         reader.close();
  95.     }
  96.  
  97. }
FillDataSheet.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13. import java.util.List;
  14.  
  15. import com.lowagie.database.DatabaseConnection;
  16. import com.lowagie.database.HsqldbConnection;
  17. import com.lowagie.filmfestival.Director;
  18. import com.lowagie.filmfestival.Movie;
  19. import com.lowagie.filmfestival.PojoFactory;
  20. import com.lowagie.filmfestival.Screening;
  21. import com.itextpdf.text.DocumentException;
  22. import com.itextpdf.text.pdf.AcroFields;
  23. import com.itextpdf.text.pdf.PdfReader;
  24. import com.itextpdf.text.pdf.PdfStamper;
  25.  
  26. public class FillDataSheet {
  27.  
  28.     /** The original PDF file. */
  29.     public static final String DATASHEET
  30.         = "resources/pdfs/datasheet.pdf";
  31.     /** The resulting PDF file. */
  32.     public static final String RESULT
  33.         = "results/part2/chapter06/imdb%s.pdf";
  34.    
  35.     /**
  36.      * Main method.
  37.      * @param args no arguments needed
  38.      * @throws DocumentException
  39.      * @throws IOException
  40.      * @throws SQLException
  41.      */
  42.     public static void main(String[] args)
  43.         throws SQLException, IOException, DocumentException {
  44.         // Create a database connection
  45.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  46.         // Get the movies
  47.         List movies = PojoFactory.getMovies(connection);
  48.         PdfReader reader;
  49.         PdfStamper stamper;
  50.         // Fill out the data sheet form with data
  51.         for (Movie movie : movies) {
  52.             if (movie.getYear() < 2007)
  53.                 continue;
  54.             reader = new PdfReader(DATASHEET);
  55.             stamper = new PdfStamper(reader,
  56.                     new FileOutputStream(String.format(RESULT, movie.getImdb())));
  57.             AcroFields fields = stamper.getAcroFields();
  58.             fields.setGenerateAppearances(true);
  59.             fill(fields, movie);
  60.             if (movie.getYear() == 2007)
  61.                 stamper.setFormFlattening(true);
  62.             stamper.close();
  63.             reader.close();
  64.         }
  65.         // Close the database connection
  66.         connection.close();
  67.     }
  68.    
  69.     /**
  70.      * Fill out the fields using info from a Movie object.
  71.      * @param form The form object
  72.      * @param movie A movie POJO
  73.      * @throws IOException
  74.      * @throws DocumentException
  75.      */
  76.     public static void fill(AcroFields form, Movie movie)
  77.         throws IOException, DocumentException {
  78.         form.setField("title", movie.getMovieTitle());
  79.         form.setField("director", getDirectors(movie));
  80.         form.setField("year", String.valueOf(movie.getYear()));
  81.         form.setField("duration", String.valueOf(movie.getDuration()));
  82.         form.setField("category", movie.getEntry().getCategory().getKeyword());
  83.         for (Screening screening : movie.getEntry().getScreenings()) {
  84.             form.setField(screening.getLocation().replace('.', '_'), "Yes");
  85.         }
  86.     }
  87.    
  88.     /**
  89.      * Gets the directors from a Movie object,
  90.      * and concatenates them in a String.
  91.      * @param movie a Movie object
  92.      * @return a String containing director names
  93.      */
  94.     public static String getDirectors(Movie movie) {
  95.         List directors = movie.getDirectors();
  96.         StringBuffer buf = new StringBuffer();
  97.         for (Director director : directors) {
  98.             buf.append(director.getGivenName());
  99.             buf.append(' ');
  100.             buf.append(director.getName());
  101.             buf.append(',');
  102.             buf.append(' ');
  103.         }
  104.         int i = buf.length();
  105.         if (i > 0)
  106.             buf.delete(i - 2, i);
  107.         return buf.toString();
  108.     }
  109. }
Concatenate.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13.  
  14. import com.itextpdf.text.Document;
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.pdf.PdfCopy;
  17. import com.itextpdf.text.pdf.PdfReader;
  18.  
  19. import part1.chapter02.MovieHistory;
  20. import part1.chapter02.MovieLinks1;
  21.  
  22. public class Concatenate {
  23.  
  24.     /** The resulting PDF file. */
  25.     public static final String RESULT
  26.         = "results/part2/chapter06/concatenated.pdf";
  27.  
  28.     /**
  29.      * Main method.
  30.      * @param    args    no arguments needed
  31.      * @throws DocumentException
  32.      * @throws IOException
  33.      * @throws SQLException
  34.      */
  35.     public static void main(String[] args)
  36.         throws IOException, DocumentException, SQLException {
  37.         // using previous examples to create PDFs
  38.         MovieLinks1.main(args);
  39.         MovieHistory.main(args);
  40.         String[] files = { MovieLinks1.RESULT, MovieHistory.RESULT };
  41.         // step 1
  42.         Document document = new Document();
  43.         // step 2
  44.         PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));
  45.         // step 3
  46.         document.open();
  47.         // step 4
  48.         PdfReader reader;
  49.         int n;
  50.         // loop over the documents you want to concatenate
  51.         for (int i = 0; i < files.length; i++) {
  52.             reader = new PdfReader(files[i]);
  53.             // loop over the pages in that document
  54.             n = reader.getNumberOfPages();
  55.             for (int page = 0; page < n; ) {
  56.                 copy.addPage(copy.getImportedPage(reader, ++page));
  57.             }
  58.             copy.freeReader(reader);
  59.             reader.close();
  60.         }
  61.         // step 5
  62.         document.close();
  63.     }
  64. }
ConcatenateStamp.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13.  
  14. import com.itextpdf.text.Document;
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.Element;
  17. import com.itextpdf.text.Phrase;
  18. import com.itextpdf.text.pdf.ColumnText;
  19. import com.itextpdf.text.pdf.PdfCopy;
  20. import com.itextpdf.text.pdf.PdfImportedPage;
  21. import com.itextpdf.text.pdf.PdfReader;
  22.  
  23. import part1.chapter02.MovieHistory;
  24. import part1.chapter02.MovieLinks1;
  25.  
  26. public class ConcatenateStamp {
  27.  
  28.     /** The resulting PDF file. */
  29.     public static final String RESULT
  30.         = "results/part2/chapter06/concatenated_stamped.pdf";
  31.    
  32.     /**
  33.      * Main method.
  34.      * @param args no arguments needed
  35.      * @throws DocumentException
  36.      * @throws IOException
  37.      * @throws SQLException
  38.      */
  39.     public static void main(String[] args)
  40.         throws IOException, DocumentException, SQLException {
  41.         // use old examples to create PDFs
  42.         MovieLinks1.main(args);
  43.         MovieHistory.main(args);
  44.         // step 1
  45.         Document document = new Document();
  46.         // step 2
  47.         PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));
  48.         // step 3
  49.         document.open();
  50.         // step 4
  51.         // reader for document 1
  52.         PdfReader reader1 = new PdfReader(MovieLinks1.RESULT);
  53.         int n1 = reader1.getNumberOfPages();
  54.         // reader for document 2
  55.         PdfReader reader2 = new PdfReader(MovieHistory.RESULT);
  56.         int n2 = reader2.getNumberOfPages();
  57.         // initializations
  58.         PdfImportedPage page;
  59.         PdfCopy.PageStamp stamp;
  60.         // Loop over the pages of document 1
  61.         for (int i = 0; i < n1; ) {
  62.             page = copy.getImportedPage(reader1, ++i);
  63.             stamp = copy.createPageStamp(page);
  64.             // add page numbers
  65.             ColumnText.showTextAligned(
  66.                     stamp.getUnderContent(), Element.ALIGN_CENTER,
  67.                     new Phrase(String.format("page %d of %d", i, n1 + n2)),
  68.                     297.5f, 28, 0);
  69.             stamp.alterContents();
  70.             copy.addPage(page);
  71.         }
  72.         // Loop over the pages of document 2
  73.         for (int i = 0; i < n2; ) {
  74.             page = copy.getImportedPage(reader2, ++i);
  75.             stamp = copy.createPageStamp(page);
  76.             // add page numbers
  77.             ColumnText.showTextAligned(
  78.                     stamp.getUnderContent(), Element.ALIGN_CENTER,
  79.                     new Phrase(String.format("page %d of %d", n1 + i, n1 + n2)),
  80.                     297.5f, 28, 0);
  81.             stamp.alterContents();
  82.             copy.addPage(page);
  83.         }
  84.         // step 5
  85.         document.close();
  86.         reader1.close();
  87.         reader2.close();
  88.     }
  89. }
Burst.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import part1.chapter03.MovieTemplates;
  14.  
  15. import com.itextpdf.text.Document;
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.pdf.PdfCopy;
  18. import com.itextpdf.text.pdf.PdfReader;
  19.  
  20. public class Burst {
  21.  
  22.     /** Format of the resulting PDF files. */
  23.     public static final String RESULT
  24.         = "results/part2/chapter06/timetable_p%d.pdf";
  25.  
  26.     /**
  27.      * Main method.
  28.      * @param    args    no arguments needed
  29.      * @throws DocumentException
  30.      * @throws IOException
  31.      */
  32.     public static void main(String[] args)
  33.         throws IOException, DocumentException {
  34.         // use one of the previous examples to create a PDF
  35.         new MovieTemplates().createPdf(MovieTemplates.RESULT);
  36.         // Create a reader
  37.         PdfReader reader = new PdfReader(MovieTemplates.RESULT);
  38.         // We'll create as many new PDFs as there are pages
  39.         Document document;
  40.         PdfCopy copy;
  41.         // loop over all the pages in the original PDF
  42.         int n = reader.getNumberOfPages();
  43.         for (int i = 0; i < n; ) {
  44.             // step 1
  45.             document = new Document();
  46.             // step 2
  47.             copy = new PdfCopy(document,
  48.                 new FileOutputStream(String.format(RESULT, ++i)));
  49.             // step 3
  50.             document.open();
  51.             // step 4
  52.             copy.addPage(copy.getImportedPage(reader, i));
  53.             // step 5
  54.             document.close();
  55.         }
  56.         reader.close();
  57.     }
  58.    
  59.    
  60. }
DataSheets1.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.ByteArrayOutputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.sql.SQLException;
  14. import java.util.List;
  15.  
  16. import com.lowagie.database.DatabaseConnection;
  17. import com.lowagie.database.HsqldbConnection;
  18. import com.lowagie.filmfestival.Movie;
  19. import com.lowagie.filmfestival.PojoFactory;
  20. import com.itextpdf.text.Document;
  21. import com.itextpdf.text.DocumentException;
  22. import com.itextpdf.text.pdf.AcroFields;
  23. import com.itextpdf.text.pdf.PdfCopy;
  24. import com.itextpdf.text.pdf.PdfReader;
  25. import com.itextpdf.text.pdf.PdfStamper;
  26.  
  27. public class DataSheets1 extends FillDataSheet {
  28.  
  29.     /** The resulting PDF file. */
  30.     public static final String RESULT
  31.         = "results/part2/chapter06/datasheets1.pdf";
  32.    
  33.     /**
  34.      * Main method.
  35.      * @param args no arguments needed
  36.      * @throws DocumentException
  37.      * @throws IOException
  38.      * @throws SQLException
  39.      */
  40.     public static void main(String[] args)
  41.         throws IOException, SQLException, DocumentException {
  42.         new DataSheets1().createPdf(RESULT);
  43.     }
  44.  
  45.     /**
  46.      * Creates a PDF document.
  47.      * @param filename the path to the new PDF document
  48.      * @throws    DocumentException
  49.      * @throws    IOException
  50.      * @throws    SQLException
  51.      */
  52.     public void createPdf(String filename)
  53.         throws IOException, DocumentException, SQLException {
  54.         // step 1
  55.         Document document = new Document();
  56.         // step 2
  57.         PdfCopy copy
  58.             = new PdfCopy(document, new FileOutputStream(filename));
  59.         // step 3
  60.         document.open();
  61.         // step 4
  62.         addDataSheets(copy);
  63.         // step 5
  64.         document.close();
  65.     }
  66.    
  67.     /**
  68.      * Fills out a data sheet, flattens it, and adds it to a combined PDF.
  69.      * @param copy the PdfCopy instance (can also be PdfSmartCopy)
  70.      * @throws SQLException
  71.      * @throws IOException
  72.      * @throws DocumentException
  73.      */
  74.     public void addDataSheets(PdfCopy copy)
  75.         throws SQLException, IOException, DocumentException {
  76.         // Create a database connection
  77.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  78.         List movies = PojoFactory.getMovies(connection);
  79.         PdfReader reader;
  80.         PdfStamper stamper;
  81.         ByteArrayOutputStream baos;
  82.         // Loop over all the movies and fill out the data sheet
  83.         for (Movie movie : movies) {
  84.             reader = new PdfReader(DATASHEET);
  85.             baos = new ByteArrayOutputStream();
  86.             stamper = new PdfStamper(reader, baos);
  87.             AcroFields fields = stamper.getAcroFields();
  88.             fields.setGenerateAppearances(true);
  89.             fill(fields, movie);
  90.             stamper.setFormFlattening(true);
  91.             stamper.close();
  92.             reader.close();
  93.            
  94.             reader = new PdfReader(baos.toByteArray());
  95.             copy.addPage(copy.getImportedPage(reader, 1));
  96.             copy.freeReader(reader);
  97.             reader.close();
  98.         }
  99.         // Close the database connection
  100.         connection.close();
  101.     }
  102. }
DataSheets2.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13.  
  14. import com.itextpdf.text.Document;
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.pdf.PdfSmartCopy;
  17.  
  18. public class DataSheets2 extends DataSheets1 {
  19.  
  20.     /** The resulting PDF file. */
  21.     public static final String RESULT
  22.         = "results/part2/chapter06/datasheets2.pdf";
  23.    
  24.     /**
  25.      * Main method.
  26.      * @param args no arguments needed
  27.      * @throws DocumentException
  28.      * @throws IOException
  29.      * @throws SQLException
  30.      */
  31.     public static void main(String[] args)
  32.         throws IOException, SQLException, DocumentException {
  33.         new DataSheets2().createPdf(RESULT);
  34.     }
  35.  
  36.     /**
  37.      * Creates a PDF document.
  38.      * @param filename the path to the new PDF document
  39.      * @throws    DocumentException
  40.      * @throws    IOException
  41.      * @throws    SQLException
  42.      */
  43.     public void createPdf(String filename)
  44.         throws IOException, DocumentException, SQLException {
  45.         // step 1
  46.         Document document = new Document();
  47.         // step 2
  48.         PdfSmartCopy copy
  49.             = new PdfSmartCopy(document, new FileOutputStream(filename));
  50.         // step 3
  51.         document.open();
  52.         // step 4
  53.         addDataSheets(copy);
  54.         // step 5
  55.         document.close();
  56.     }
  57. }
ConcatenateForms1.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.DocumentException;
  14. import com.itextpdf.text.pdf.PdfCopyFields;
  15. import com.itextpdf.text.pdf.PdfReader;
  16.  
  17. public class ConcatenateForms1 {
  18.  
  19.     /** The original PDF file. */
  20.     public static final String DATASHEET
  21.         = "resources/pdfs/datasheet.pdf";
  22.     /** The resulting PDF file. */
  23.     public static final String RESULT
  24.         = "results/part2/chapter06/concatenated_forms1.pdf";
  25.    
  26.     /**
  27.      * Main method.
  28.      * @param args no arguments needed
  29.      * @throws DocumentException
  30.      * @throws IOException
  31.      */
  32.     public static void main(String[] args)
  33.         throws IOException, DocumentException {
  34.         // Create a PdfCopyFields object
  35.         PdfCopyFields copy
  36.             = new PdfCopyFields(new FileOutputStream(RESULT));
  37.         // add a document
  38.         PdfReader reader1 = new PdfReader(DATASHEET);
  39.         copy.addDocument(reader1);
  40.         // add a document
  41.         PdfReader reader2 = new PdfReader(DATASHEET);
  42.         copy.addDocument(reader2);
  43.         // close the PdfCopyFields object
  44.         copy.close();
  45.         reader1.close();
  46.         reader2.close();
  47.     }
  48. }
ConcatenateForms2.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part2.chapter06;
  9.  
  10. import java.io.ByteArrayOutputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.util.HashSet;
  14. import java.util.Set;
  15.  
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.pdf.AcroFields;
  18. import com.itextpdf.text.pdf.PdfCopyFields;
  19. import com.itextpdf.text.pdf.PdfReader;
  20. import com.itextpdf.text.pdf.PdfStamper;
  21.  
  22. public class ConcatenateForms2 {
  23.  
  24.     /** The original PDF file. */
  25.     public static final String DATASHEET
  26.         = "resources/pdfs/datasheet.pdf";
  27.     /** The resulting PDF file. */
  28.     public static final String RESULT
  29.         = "results/part2/chapter06/concatenated_forms2.pdf";
  30.    
  31.     /**
  32.      * Main method.
  33.      * @param    args    no arguments needed
  34.      * @throws DocumentException
  35.      * @throws IOException
  36.      */
  37.     public static void main(String[] args)
  38.         throws IOException, DocumentException {
  39.         // Create a PdfCopyFields object
  40.         PdfCopyFields copy
  41.             = new PdfCopyFields(new FileOutputStream(RESULT));
  42.         // add a document
  43.         PdfReader reader1 = new PdfReader(renameFieldsIn(DATASHEET, 1));
  44.         copy.addDocument(reader1);
  45.         // add a document
  46.         PdfReader reader2 = new PdfReader(renameFieldsIn(DATASHEET, 2));
  47.         copy.addDocument(reader2);
  48.         // Close the PdfCopyFields object
  49.         copy.close();
  50.         reader1.close();
  51.         reader2.close();
  52.     }
  53.    
  54.     /**
  55.      * Renames the fields in an interactive form.
  56.      * @param datasheet the path to the original form
  57.      * @param i a number that needs to be appended to the field names
  58.      * @return a byte[] containing an altered PDF file
  59.      * @throws IOException
  60.      * @throws DocumentException
  61.      */
  62.     private static byte[] renameFieldsIn(String datasheet, int i)
  63.         throws IOException, DocumentException {
  64.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  65.         // Create the stamper
  66.         PdfStamper stamper = new PdfStamper(new PdfReader(datasheet), baos);
  67.         // Get the fields
  68.         AcroFields form = stamper.getAcroFields();
  69.         // Loop over the fields
  70.         Set keys = new HashSet(form.getFields().keySet());
  71.         for (String key : keys) {
  72.             // rename the fields
  73.             form.renameField(key, String.format("%s_%d", key, i));
  74.         }
  75.         // close the stamper
  76.         stamper.close();
  77.         return baos.toByteArray();
  78.     }
  79. }
PageInformation.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.Text;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using Ionic.Zip;
  13. using kuujinbo.iTextInAction2Ed.Chapter01;
  14. using kuujinbo.iTextInAction2Ed.Chapter03;
  15. using kuujinbo.iTextInAction2Ed.Chapter05;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  18.   public class PageInformation : IWriter {
  19. // ===========================================================================
  20.     public const string RESULT = "page_info.txt";
  21.     public void Write(Stream stream) {
  22.       IWriter[] iw = {
  23.         new HelloWorldLandscape1(), new HelloWorldLandscape2(),
  24.         new MovieTemplates(), new Hero1()
  25.       };
  26.       StringBuilder sb = new StringBuilder();      
  27.       using (ZipFile zip = new ZipFile()) {
  28.         foreach (IWriter w in iw) {
  29.           // Create a reader
  30.           byte[] pdf = Utility.PdfBytes(w);
  31.           string fileName = Utility.ResultFileName(w.ToString() + ".pdf");
  32.           Inspect(sb, pdf, fileName);
  33.           zip.AddEntry(fileName, pdf);  
  34.         }
  35.         zip.AddEntry(RESULT, sb.ToString());
  36.         zip.Save(stream);
  37.       }          
  38.     }  
  39. // ---------------------------------------------------------------------------
  40.     /**
  41.      * Inspect a PDF file and write the info to a txt file
  42.      * @param writer StringBuilder
  43.      * @param pdf PDF file bytes
  44.      * @param fileName PDF filename
  45.      */
  46.     public static void Inspect(StringBuilder sb, byte[] pdf, string fileName) {
  47.       PdfReader reader = new PdfReader(pdf);
  48.       sb.Append(fileName);
  49.       sb.Append(Environment.NewLine);
  50.       sb.Append("Number of pages: ");
  51.       sb.Append(reader.NumberOfPages);
  52.       sb.Append(Environment.NewLine);
  53.       Rectangle mediabox = reader.GetPageSize(1);
  54.       sb.Append("Size of page 1: [");
  55.       sb.Append(mediabox.Left);
  56.       sb.Append(',');
  57.       sb.Append(mediabox.Bottom);
  58.       sb.Append(',');
  59.       sb.Append(mediabox.Right);
  60.       sb.Append(',');
  61.       sb.Append(mediabox.Top);
  62.       sb.Append("]");
  63.       sb.Append(Environment.NewLine);
  64.       sb.Append("Rotation of page 1: ");
  65.       sb.Append(reader.GetPageRotation(1));
  66.       sb.Append(Environment.NewLine);
  67.       sb.Append("Page size with rotation of page 1: ");
  68.       sb.Append(reader.GetPageSizeWithRotation(1));
  69.       sb.Append(Environment.NewLine);
  70.       sb.Append("Is rebuilt? ");
  71.       sb.Append(reader.IsRebuilt().ToString());
  72.       sb.Append(Environment.NewLine);
  73.       sb.Append("Is encrypted? ");
  74.       sb.Append(reader.IsEncrypted().ToString());
  75.       sb.Append(Environment.NewLine);
  76.       sb.Append(Environment.NewLine);
  77.     }    
  78. // ===========================================================================
  79.   }
  80. }
MemoryInfo.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.Diagnostics;
  9. using System.IO;
  10. using System.Text;
  11. using System.Threading;
  12. using Ionic.Zip;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using kuujinbo.iTextInAction2Ed.Chapter03;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  18.   public class MemoryInfo : IWriter {
  19.  
  20.     /** The resulting PDF file. */
  21.     public static readonly String RESULT
  22.         = "memory_info.txt";
  23.     public static readonly String RESULT0
  24.         = "MovieTemplates.pdf";
  25.    
  26.     /**
  27.      * Do a full read of a PDF file
  28.      * @param writer a writer to a report file
  29.      * @param filename the file to read
  30.      * @throws IOException
  31.      */
  32.     public static void fullRead(StreamWriter writer, byte[] file){
  33.         long before = GC.GetTotalMemory(true);
  34.         PdfReader reader = new PdfReader(file);
  35.         int num = reader.NumberOfPages;
  36.         writer.WriteLine(String.Format("Number of pages: {0}", num));
  37.         writer.WriteLine(String.Format("Memory used by full read: {0}",
  38.                     GC.GetTotalMemory(true) - before));
  39.         writer.Flush();
  40.         reader.Close();
  41.     }
  42.    
  43.     /**
  44.      * Do a partial read of a PDF file
  45.      * @param writer a writer to a report file
  46.      * @param filename the file to read
  47.      * @throws IOException
  48.      */
  49.     public static void partialRead(StreamWriter writer, byte[] file) {
  50.         long before = GC.GetTotalMemory(true);
  51.         PdfReader reader = new PdfReader(
  52.                 new RandomAccessFileOrArray(file), null);
  53.         int num = reader.NumberOfPages;
  54.         writer.WriteLine(String.Format("Number of pages: {0}", num));
  55.         writer.WriteLine(String.Format("Memory used by partial read: {0}",
  56.                     GC.GetTotalMemory(true) - before));
  57.         writer.Flush();
  58.         reader.Close();
  59.     }
  60.      
  61.  
  62.     /**
  63.      * Makes sure all garbage is cleared from the memory.
  64.      */
  65.     private static void GarbageCollect()
  66.     {
  67.         try
  68.         {
  69.             GC.Collect();
  70.             Thread.Sleep(200);
  71.             GC.WaitForPendingFinalizers();
  72.             Thread.Sleep(200);
  73.             GC.Collect();
  74.             Thread.Sleep(200);
  75.             GC.WaitForPendingFinalizers();
  76.             Thread.Sleep(200);
  77.         }
  78.         catch (Exception ex)
  79.         {
  80.             Console.WriteLine(ex.StackTrace);
  81.         }
  82.     }
  83. // ===========================================================================
  84.     public void Write(Stream stream) {
  85.         try
  86.         {
  87.             using (ZipFile zip = new ZipFile())
  88.             {
  89.                 using (MemoryStream resultStream = new MemoryStream())
  90.                 {
  91.                     using (StreamWriter sw = new StreamWriter(resultStream))
  92.                     {
  93.                         using (MemoryStream movies = new MemoryStream())
  94.                         {
  95.                             // step 1
  96.                             MovieTemplates mt = new MovieTemplates();
  97.                             mt.Write(movies);
  98.                             zip.AddEntry(RESULT0, movies.ToArray());
  99.  
  100.                             // step 2
  101.                             GarbageCollect();
  102.                             // Do a full read
  103.                             fullRead(sw, movies.ToArray());
  104.                             // Do a partial read
  105.                             partialRead(sw, movies.ToArray());
  106.                             zip.AddEntry(RESULT, resultStream.ToArray());
  107.                         }
  108.                     }
  109.                 }
  110.                 zip.Save(stream);
  111.             }
  112.         }
  113.         catch(Exception ex)
  114.         {
  115.             Console.WriteLine(ex.StackTrace);
  116.         }
  117.     }    
  118. // ===========================================================================
  119.   }
  120. }
SelectPages.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using iTextSharp.text;
  10. using iTextSharp.text.pdf;
  11. using Ionic.Zip;
  12. using kuujinbo.iTextInAction2Ed.Chapter03;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  15.   public class SelectPages : IWriter {
  16. // ===========================================================================
  17.     /** A resulting PDF file. */
  18.     public const String RESULT1 = "timetable_stamper.pdf";
  19.     /** A resulting PDF file. */
  20.     public const String RESULT2 = "timetable_copy.pdf";
  21. // ---------------------------------------------------------------------------
  22.     public void Write(Stream stream) {
  23.       MovieTemplates mt = new MovieTemplates();
  24.       byte[] pdf = Utility.PdfBytes(mt);
  25.       PdfReader reader = new PdfReader(pdf);
  26.       using (ZipFile zip = new ZipFile()) {
  27.         reader.SelectPages("4-8");
  28.         zip.AddEntry(RESULT1, ManipulateWithStamper(reader));
  29. /*
  30.  * can't figure out __WHY__, but if i don't reset the reader the example
  31.  * will __NOT__ work!
  32.  */
  33.         reader = new PdfReader(pdf);
  34.         reader.SelectPages("4-8");
  35.         zip.AddEntry(RESULT2, ManipulateWithCopy(reader));      
  36.         zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf);
  37.         zip.Save(stream);
  38.       }
  39.     }
  40. // ---------------------------------------------------------------------------
  41.     /**
  42.      * Creates a new PDF based on the one in the reader
  43.      * @param reader a reader with a PDF file
  44.      */
  45.     private byte[] ManipulateWithStamper(PdfReader reader) {
  46.       using (MemoryStream ms = new MemoryStream()) {
  47.         using ( PdfStamper stamper = new PdfStamper(reader, ms) ) {
  48.         }
  49.         return ms.ToArray();
  50.       }    
  51.     }
  52. // ---------------------------------------------------------------------------
  53.     /**
  54.      * Creates a new PDF based on the one in the reader
  55.      * @param reader a reader with a PDF file
  56.      */
  57.     private byte[] ManipulateWithCopy(PdfReader reader) {
  58.       using (MemoryStream ms = new MemoryStream()) {
  59.         int n = reader.NumberOfPages;
  60.         using (Document document = new Document()) {
  61.           using (PdfCopy copy = new PdfCopy(document, ms)) {
  62.             document.Open();
  63.             for (int i = 0; i < n;) {
  64.               copy.AddPage(copy.GetImportedPage(reader, ++i));
  65.             }
  66.           }
  67.         }
  68.         return ms.ToArray();
  69.       }
  70.     }    
  71. // ===========================================================================
  72.   }
  73. }
ImportingPages1.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using kuujinbo.iTextInAction2Ed.Chapter03;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  15.   public class ImportingPages1 : IWriter {
  16. // ===========================================================================
  17.     public const string RESULT = "time_table_imported1.pdf";
  18. // ---------------------------------------------------------------------------
  19.     public void Write(Stream stream) {
  20.       // Use old example to create PDF
  21.       MovieTemplates mt = new MovieTemplates();
  22.       byte[] pdf = Utility.PdfBytes(mt);
  23.       using (ZipFile zip = new ZipFile()) {
  24.         using (MemoryStream ms = new MemoryStream()) {
  25.           // step 1
  26.           using (Document document = new Document()) {
  27.             // step 2
  28.             PdfWriter writer = PdfWriter.GetInstance(document, ms);
  29.             // step 3
  30.             document.Open();
  31.             // step 4
  32.             PdfPTable table = new PdfPTable(2);
  33.             PdfReader reader = new PdfReader(pdf);
  34.             int n = reader.NumberOfPages;
  35.             PdfImportedPage page;
  36.             for (int i = 1; i
ImportingPages2.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using kuujinbo.iTextInAction2Ed.Chapter03;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  15.   public class ImportingPages2 : IWriter {
  16. // ===========================================================================
  17.     public const string RESULT = "time_table_imported2.pdf";
  18. // ---------------------------------------------------------------------------
  19.     public void Write(Stream stream) {
  20.       // Use old example to create PDF
  21.       MovieTemplates mt = new MovieTemplates();
  22.       byte[] pdf = Utility.PdfBytes(mt);
  23.       using (ZipFile zip = new ZipFile()) {
  24.         using (MemoryStream ms = new MemoryStream()) {
  25.           // step 1
  26.           using (Document document = new Document()) {
  27.             // step 2
  28.             PdfWriter writer = PdfWriter.GetInstance(document, ms);
  29.             // step 3
  30.             document.Open();
  31.             // step 4
  32.             PdfPTable table = new PdfPTable(2);
  33.             PdfReader reader = new PdfReader(pdf);
  34.             int n = reader.NumberOfPages;
  35.             PdfImportedPage page;
  36.             for (int i = 1; i
Layers.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12.  
  13. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  14.   public class Layers : IWriter {
  15. // ===========================================================================
  16.     /** The resulting PDF. */
  17.     public const string SOURCE = "layers_orig.pdf";
  18.     /** The resulting PDF. */
  19.     public const string RESULT = "layers.pdf";    
  20. // ---------------------------------------------------------------------------        
  21.     public void Write(Stream stream) {
  22.       using (ZipFile zip = new ZipFile()) {
  23.         byte[] pdf = new Layers().CreatePdf();        
  24.  
  25.         // Create a reader
  26.         PdfReader reader = new PdfReader(pdf);
  27.         // step 1
  28.         using (MemoryStream ms = new MemoryStream()) {
  29.           using (Document document = new Document(PageSize.A5.Rotate())) {
  30.             // step 2
  31.             PdfWriter writer = PdfWriter.GetInstance(document, ms);
  32.             // step 3
  33.             document.Open();
  34.             // step 4
  35.             PdfContentByte canvas = writer.DirectContent;
  36.             PdfImportedPage page;
  37.             BaseFont bf = BaseFont.CreateFont(
  38.               BaseFont.ZAPFDINGBATS, "", BaseFont.EMBEDDED
  39.             );
  40.             for (int i = 0; i < reader.NumberOfPages; ) {
  41.               page = writer.GetImportedPage(reader, ++i);
  42.               canvas.AddTemplate(page, 1f, 0, 0.4f, 0.4f, 72, 50 * i);
  43.               canvas.BeginText();
  44.               canvas.SetFontAndSize(bf, 20);
  45.               canvas.ShowTextAligned(
  46.                 Element.ALIGN_CENTER,
  47.                 ((char)(181 + i)).ToString(),
  48.                 496, 150 + 50 * i, 0
  49.               );
  50.               canvas.EndText();
  51.             }
  52.           }        
  53.           zip.AddEntry(RESULT, ms.ToArray());
  54.         }
  55.         zip.AddEntry(SOURCE, pdf);
  56.         zip.Save(stream);
  57.       }  
  58.     }
  59. // ---------------------------------------------------------------------------    
  60.     /**
  61.      * Creates a PDF document for PdfReader.
  62.      */
  63.     public byte[] CreatePdf() {
  64.       // step 1
  65.       using (MemoryStream ms = new MemoryStream()) {
  66.         using (Document document = new Document(PageSize.POSTCARD, 30, 30, 30, 30)) {
  67.         // step 2
  68.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  69.           // step 3
  70.           document.Open();
  71.           // step 4
  72.           PdfContentByte under = writer.DirectContentUnder;
  73.           // Page 1: a rectangle
  74.           DrawRectangle(
  75.             under, PageSize.POSTCARD.Width, PageSize.POSTCARD.Height
  76.           );
  77.           under.SetRGBColorFill(0xFF, 0xD7, 0x00);
  78.           under.Rectangle(
  79.             5, 5, PageSize.POSTCARD.Width - 10, PageSize.POSTCARD.Height - 10
  80.           );
  81.           under.Fill();
  82.           document.NewPage();
  83.           // Page 2: an image
  84.           DrawRectangle(
  85.             under, PageSize.POSTCARD.Width, PageSize.POSTCARD.Height
  86.           );
  87.           Image img = Image.GetInstance(Path.Combine(
  88.             Utility.ResourceImage, "loa.jpg"
  89.           ));
  90.           img.SetAbsolutePosition(
  91.             (PageSize.POSTCARD.Width - img.ScaledWidth) / 2,
  92.             (PageSize.POSTCARD.Height - img.ScaledHeight) / 2
  93.           );
  94.           document.Add(img);
  95.           document.NewPage();
  96.           // Page 3: the words "Foobar Film Festival"
  97.           DrawRectangle(
  98.             under, PageSize.POSTCARD.Width, PageSize.POSTCARD.Height
  99.           );
  100.           Paragraph p = new Paragraph(
  101.             "Foobar Film Festival", new Font(Font.FontFamily.HELVETICA, 22)
  102.           );
  103.           p.Alignment = Element.ALIGN_CENTER;
  104.           document.Add(p);
  105.           document.NewPage();
  106.           // Page 4: the words "SOLD OUT"
  107.           DrawRectangle(under, PageSize.POSTCARD.Width, PageSize.POSTCARD.Height);
  108.           PdfContentByte over = writer.DirectContent;
  109.           over.SaveState();
  110.           float sinus = (float)Math.Sin(Math.PI / 60);
  111.           float cosinus = (float)Math.Cos(Math.PI / 60);
  112.           BaseFont bf = BaseFont.CreateFont();
  113.           over.BeginText();
  114.           over.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
  115.           over.SetLineWidth(1.5f);
  116.           over.SetRGBColorStroke(0xFF, 0x00, 0x00);
  117.           over.SetRGBColorFill(0xFF, 0xFF, 0xFF);
  118.           over.SetFontAndSize(bf, 36);
  119.           over.SetTextMatrix(cosinus, sinus, -sinus, cosinus, 50, 324);
  120.           over.ShowText("SOLD OUT");
  121.           over.SetTextMatrix(0, 0);
  122.           over.EndText();
  123.           over.RestoreState();
  124.         }
  125.         return ms.ToArray();
  126.       }
  127.     }
  128. // ---------------------------------------------------------------------------    
  129.     /**
  130.      * Draws a rectangle
  131.      * @param content the direct content layer
  132.      * @param width the width of the rectangle
  133.      * @param height the height of the rectangle
  134.      */
  135.     public static void DrawRectangle(
  136.       PdfContentByte content, float width, float height)
  137.     {
  138.       content.SaveState();
  139.       PdfGState state = new PdfGState();
  140.       state.FillOpacity = 0.6f;
  141.       content.SetGState(state);
  142.       content.SetRGBColorFill(0xFF, 0xFF, 0xFF);
  143.       content.SetLineWidth(3);
  144.       content.Rectangle(0, 0, width, height);
  145.       content.FillStroke();
  146.       content.RestoreState();
  147.     }  
  148. // ===========================================================================
  149.   }
  150. }
Superimposing.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.Com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12.  
  13. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  14.   public class Superimposing : IWriter {
  15. // ===========================================================================
  16.     /** The resulting PDF. */
  17.     public const string SOURCE = "opening.pdf";
  18.     /** The resulting PDF. */
  19.     public const string RESULT = "festival_opening.pdf";    
  20. // ---------------------------------------------------------------------------        
  21.     public void Write(Stream stream) {
  22.       using (ZipFile zip = new ZipFile()) {
  23.         byte[] pdf = new Superimposing().CreatePdf();
  24.         // Create a reader
  25.         PdfReader reader = new PdfReader(pdf);
  26.         using (MemoryStream ms = new MemoryStream()) {    
  27.           // step 1
  28.           using (Document document = new Document(PageSize.POSTCARD)) {
  29.             // step 2
  30.             PdfWriter writer = PdfWriter.GetInstance(document, ms);
  31.             // step 3
  32.             document.Open();
  33.             // step 4
  34.             PdfContentByte canvas = writer.DirectContent;
  35.             PdfImportedPage page;
  36.             for (int i = 1; i
Stationery.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.Com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Data;
  10. using System.Data.Common;
  11. using Ionic.Zip;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  17.   public class Stationery : IWriter {
  18. // ===========================================================================
  19.     /** The original PDF. */
  20.     public const string STATIONERY = "stationery.pdf";
  21.     /** The resulting PDF. */
  22.     public const string RESULT = "text_on_stationery.pdf";
  23. // ---------------------------------------------------------------------------
  24.     public void Write(Stream stream) {
  25.       using (ZipFile zip = new ZipFile()) {
  26. // create first PDF        
  27.         byte[] stationary  = CreateStationary();
  28.         zip.AddEntry(STATIONERY, stationary);
  29.         zip.AddEntry(RESULT, CreatePdf(stationary));
  30.         zip.Save(stream);
  31.       }
  32.     }
  33. // ---------------------------------------------------------------------------
  34.     /**
  35.      * Creates a PDF document.
  36.      * @param stationary byte array of the new PDF document
  37.      */  
  38.     public byte[] CreatePdf(byte[] stationary) {
  39.       using (MemoryStream ms = new MemoryStream()) {
  40.         // step 1
  41.         using (Document document = new Document(PageSize.A4, 36, 36, 72, 36)) {
  42.           // step 2
  43.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  44.           //writer.CloseStream = false;
  45.           UseStationary(writer, stationary);
  46.           // step 3
  47.           document.Open();
  48.           // step 4
  49.           string SQL = "SELECT country, id FROM film_country ORDER BY country";
  50.           using (var c =  AdoDB.Provider.CreateConnection()) {
  51.             c.ConnectionString = AdoDB.CS;
  52.             using (DbCommand cmd = c.CreateCommand()) {
  53.               cmd.CommandText = SQL;        
  54.               c.Open();
  55.               using (var r = cmd.ExecuteReader()) {
  56.                 while (r.Read()) {
  57.                   document.Add(new Paragraph(
  58.                     r["country"].ToString(), FilmFonts.BOLD
  59.                   ));
  60.                   document.Add(Chunk.NEWLINE);          
  61.                   string id = r["id"].ToString();
  62.                   foreach (Movie movie in PojoFactory.GetMovies(id, true)) {
  63.                     document.Add(new Paragraph(
  64.                       movie.MovieTitle, FilmFonts.BOLD
  65.                     ));
  66.                     if (!string.IsNullOrEmpty(movie.OriginalTitle)) {
  67.                       document.Add(new Paragraph(
  68.                         movie.OriginalTitle, FilmFonts.ITALIC
  69.                       ));
  70.                     }
  71.                     document.Add(new Paragraph(
  72.                       string.Format(
  73.                         "Year: {0}; run length: {0} minutes",
  74.                         movie.Year, movie.Duration
  75.                       ),
  76.                       FilmFonts.NORMAL
  77.                     ));
  78.                     document.Add(PojoToElementFactory.GetDirectorList(movie));
  79.                   }
  80.                   document.NewPage();              
  81.                 }
  82.               }
  83.             }
  84.           }
  85.         }
  86.         return ms.ToArray();
  87.       }
  88.     }
  89. // ---------------------------------------------------------------------------    
  90.     /** Imported page with the stationery. */
  91.     private PdfImportedPage page;
  92.  
  93.     /**
  94.      * Initialize the imported page.
  95.      * @param writer The PdfWriter
  96.      */
  97.     public void UseStationary(PdfWriter writer, byte[] stationary) {
  98.       writer.PageEvent = new TemplateHelper(this);
  99.       PdfReader reader = new PdfReader(stationary);
  100.       page = writer.GetImportedPage(reader, 1);
  101.     }
  102. /*
  103.  * ###########################################################################
  104.  * Inner class to add template
  105.  * ###########################################################################
  106. */
  107.     class TemplateHelper : PdfPageEventHelper {
  108.       private Stationery instance;
  109.       public TemplateHelper() { }
  110.       public TemplateHelper(Stationery instance) {
  111.         this.instance = instance;
  112.       }
  113.       /**
  114.        * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
  115.        *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  116.        */
  117.       public override void OnEndPage(PdfWriter writer, Document document) {
  118.         writer.DirectContentUnder.AddTemplate(instance.page, 0, 0);
  119.       }
  120.     }
  121. // ---------------------------------------------------------------------------    
  122.     /**
  123.      * Creates a PDF document.
  124.      */
  125.     public byte[] CreateStationary() {
  126.       using (MemoryStream ms = new MemoryStream()) {
  127.         // step 1
  128.         using (Document document = new Document()) {
  129.           // step 2
  130.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  131.           writer.CloseStream = false;
  132.           // step 3
  133.           document.Open();
  134.           // step 4
  135.           PdfPTable table = new PdfPTable(1);
  136.           table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
  137.           table.AddCell(new Phrase("FOOBAR FILM FESTIVAL", FilmFonts.BOLD));
  138.           document.Add(table);
  139.           Font font = new Font(
  140.             Font.FontFamily.HELVETICA, 52, Font.BOLD, new GrayColor(0.75f)
  141.           );
  142.           ColumnText.ShowTextAligned(
  143.             writer.DirectContentUnder,
  144.             Element.ALIGN_CENTER, new Phrase("FOOBAR FILM FESTIVAL", font),
  145.             297.5f, 421, 45
  146.           );
  147.         }
  148.         return ms.ToArray();
  149.       }      
  150.     }    
  151. // ===========================================================================
  152.   }
  153. }
NUpTool.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.Com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12.  
  13. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  14.   public class NUpTool : IWriter {
  15. // ===========================================================================
  16.     public const String RESULT = "result{0}up.pdf";
  17. // ---------------------------------------------------------------------------    
  18.     public void Write(Stream stream) {
  19.       using (ZipFile zip = new ZipFile()) {
  20.         // previous example
  21.         Stationery s = new Stationery();
  22.         byte[] stationary  = s.CreatePdf(s.CreateStationary());
  23.         // reader for the src file
  24.         PdfReader reader = new PdfReader(stationary);
  25.         // initializations
  26.         int pow = 1;
  27.                
  28.         do {
  29.           Rectangle pageSize = reader.GetPageSize(1);
  30.           Rectangle newSize = (pow % 2) == 0
  31.             ? new Rectangle(pageSize.Width, pageSize.Height)
  32.             : new Rectangle(pageSize.Height, pageSize.Width)
  33.           ;
  34.           Rectangle unitSize = new Rectangle(pageSize.Width, pageSize.Height);
  35.           for (int i = 0; i < pow; i++) {
  36.             unitSize = new Rectangle(unitSize.Height / 2, unitSize.Width);
  37.           }
  38.           int n = (int)Math.Pow(2, pow);
  39.           int r = (int)Math.Pow(2, pow / 2);
  40.           int c = n / r;          
  41.          
  42.           using (MemoryStream ms = new MemoryStream()) {
  43.             // step 1
  44.             using (Document document = new Document(newSize, 0, 0, 0, 0)) {
  45.               // step 2
  46.               PdfWriter writer = PdfWriter.GetInstance(document, ms);
  47.               // step 3
  48.               document.Open();
  49.               // step 4
  50.               PdfContentByte cb = writer.DirectContent;
  51.               PdfImportedPage page;
  52.               Rectangle currentSize;
  53.               float offsetX, offsetY, factor;
  54.               int total = reader.NumberOfPages;
  55.              
  56.               for (int i = 0; i < total; ) {
  57.                 if (i % n == 0) {
  58.                   document.NewPage();
  59.                 }
  60.                 currentSize = reader.GetPageSize(++i);
  61.                 factor = Math.Min(
  62.                     unitSize.Width / currentSize.Width,
  63.                     unitSize.Height / currentSize.Height
  64.                 );
  65.                 offsetX = unitSize.Width * ((i % n) % c)
  66.                   + (unitSize.Width - (currentSize.Width * factor)) / 2f
  67.                 ;
  68.                 offsetY = newSize.Height
  69.                   - (unitSize.Height * (((i % n) / c) + 1))
  70.                   + (unitSize.Height - (currentSize.Height * factor)) / 2f
  71.                 ;
  72.                 page = writer.GetImportedPage(reader, i);
  73.                 cb.AddTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
  74.               }
  75.             }
  76.             zip.AddEntry(string.Format(RESULT, n), ms.ToArray());
  77.             ++pow;
  78.           }
  79.         } while (pow < 5);
  80.         zip.AddEntry(Utility.ResultFileName(s.ToString() + ".pdf"), stationary);
  81.         zip.Save(stream);
  82.       }
  83.     }
  84. // ===========================================================================
  85.   }
  86. }
TilingHero.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12.  
  13. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  14.   public class TilingHero : IWriter {
  15. // ===========================================================================
  16.     public const String RESOURCE = "Hero.pdf";
  17.     public const String RESULT = "superman.pdf";
  18. // ---------------------------------------------------------------------------        
  19.     public void Write(Stream stream) {
  20.       // Creating a reader
  21.       string resource = Path.Combine(Utility.ResourcePdf, RESOURCE);
  22.       PdfReader reader = new PdfReader(resource);
  23.       Rectangle pagesize = reader.GetPageSizeWithRotation(1);
  24.       using (ZipFile zip = new ZipFile()) {
  25.         // step 1
  26.         using (MemoryStream ms = new MemoryStream()) {
  27.           using (Document document = new Document(pagesize)) {
  28.             // step 2
  29.             PdfWriter writer = PdfWriter.GetInstance(document, ms);
  30.             // step 3
  31.             document.Open();
  32.             // step 4
  33.             PdfContentByte content = writer.DirectContent;
  34.             PdfImportedPage page = writer.GetImportedPage(reader, 1);
  35.             // adding the same page 16 times with a different offset
  36.             float x, y;
  37.             for (int i = 0; i < 16; i++) {
  38.               x = -pagesize.Width * (i % 4);
  39.               y = pagesize.Height * (i / 4 - 3);
  40.               content.AddTemplate(page, 4, 0, 0, 4, x, y);
  41.               document.NewPage();
  42.             }
  43.           }
  44.           zip.AddEntry(RESULT, ms.ToArray());
  45.         }
  46.         zip.AddFile(resource, "");
  47.         zip.Save(stream);
  48.       }
  49.     }
  50. // ===========================================================================
  51.   }
  52. }
StampText.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using kuujinbo.iTextInAction2Ed.Chapter01;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  15.   public class StampText : IWriter {
  16. // ===========================================================================
  17.   /** A resulting PDF file. */
  18.     public const string RESULT1 = "hello1.pdf";
  19.   /** A resulting PDF file. */
  20.     public const string RESULT2 = "hello2.pdf";
  21.   /** A resulting PDF file. */
  22.     public const string RESULT3 = "hello3.pdf";
  23. // ---------------------------------------------------------------------------        
  24.     public void Write(Stream stream) {
  25.       HelloWorldLandscape1 h1 = new HelloWorldLandscape1();
  26.       byte[] h1b = Utility.PdfBytes(h1);
  27.       HelloWorldLandscape2 h2 = new HelloWorldLandscape2();
  28.       byte[] h2b = Utility.PdfBytes(h2);
  29.  
  30.       using (ZipFile zip = new ZipFile()) {
  31.         zip.AddEntry(RESULT1, Stamp(h1b));
  32.         zip.AddEntry(RESULT2, StampIgnoreRotation(h1b));
  33.         zip.AddEntry(RESULT3, Stamp(h2b));
  34.  
  35.         zip.AddEntry(Utility.ResultFileName(h1.ToString() + ".pdf"), h1b);
  36.         zip.AddEntry(Utility.ResultFileName(h2.ToString() + ".pdf"), h2b);
  37.         zip.Save(stream);
  38.       }
  39.     }
  40. // ---------------------------------------------------------------------------
  41.     /**
  42.      * Manipulates a PDF file src with the file dest as result
  43.      * @param resource the original PDF
  44.      */
  45.     public static byte[] Stamp(byte[] resource) {
  46.       PdfReader reader = new PdfReader(resource);
  47.       using (var ms = new MemoryStream()) {
  48.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  49.           PdfContentByte canvas = stamper.GetOverContent(1);
  50.           ColumnText.ShowTextAligned(
  51.             canvas,
  52.             Element.ALIGN_LEFT,
  53.             new Phrase("Hello people!"),
  54.             36, 540, 0
  55.           );
  56.         }
  57.         return ms.ToArray();
  58.       }
  59.     }
  60.  
  61.     /**
  62.      * Manipulates a PDF file
  63.      * @param resource the original PDF
  64.      */
  65.     public static byte[] StampIgnoreRotation(byte[] resource) {
  66.       PdfReader reader = new PdfReader(resource);
  67.       using (var ms = new MemoryStream()) {
  68.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  69.           stamper.RotateContents = false;
  70.           PdfContentByte canvas = stamper.GetOverContent(1);
  71.           ColumnText.ShowTextAligned(
  72.             canvas,
  73.             Element.ALIGN_LEFT,
  74.             new Phrase("Hello people!"),
  75.             36, 540, 0
  76.           );
  77.         }
  78.         return ms.ToArray();
  79.       }    
  80.     }    
  81. // ===========================================================================
  82.   }
  83. }
TwoPasses.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using System.Data;
  11. using System.Data.Common;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  17.   public class TwoPasses : IWriter {
  18. // ===========================================================================
  19.     /** The resulting PDF file. */
  20.     public const String RESULT = "page_x_of_y.pdf";
  21. // ---------------------------------------------------------------------------        
  22.     public void Write(Stream stream) {
  23.       string SQL = "SELECT country, id FROM film_country ORDER BY country";
  24.       using (ZipFile zip = new ZipFile()) {
  25.         using (var ms = new MemoryStream()) {
  26.           // FIRST PASS, CREATE THE PDF WITHOUT HEADER
  27.           // step 1
  28.           using (Document document = new Document(PageSize.A4, 36, 36, 54, 36)) {
  29.             // step 2
  30.             PdfWriter.GetInstance(document, ms);
  31.             // step 3
  32.             document.Open();
  33.             // step 4
  34.             using (var c =  AdoDB.Provider.CreateConnection()) {
  35.               c.ConnectionString = AdoDB.CS;
  36.               using (DbCommand cmd = c.CreateCommand()) {
  37.                 cmd.CommandText = SQL;          
  38.                 c.Open();
  39.                 using (var r = cmd.ExecuteReader()) {
  40.                   while (r.Read()) {
  41.                     document.Add(new Paragraph(
  42.                       r["country"].ToString(), FilmFonts.BOLD
  43.                     ));
  44.                     document.Add(Chunk.NEWLINE);          
  45.                     string id = r["id"].ToString();
  46.                     foreach (Movie movie in PojoFactory.GetMovies(id, true)) {
  47.                       document.Add(new Paragraph(
  48.                         movie.MovieTitle, FilmFonts.BOLD
  49.                       ));
  50.                       if (!string.IsNullOrEmpty(movie.OriginalTitle)) {
  51.                         document.Add(new Paragraph(
  52.                           movie.OriginalTitle, FilmFonts.ITALIC
  53.                         ));
  54.                       }
  55.                       document.Add(new Paragraph(string.Format(
  56.                           "Year: {0}; run length: {0} minutes",
  57.                           movie.Year, movie.Duration
  58.                         ),
  59.                         FilmFonts.NORMAL
  60.                       ));
  61.                       document.Add(PojoToElementFactory.GetDirectorList(movie));
  62.                     }
  63.                     document.NewPage();              
  64.                   }
  65.                 }
  66.               }
  67.             }
  68.           }
  69.           byte[] firstPass = ms.ToArray();
  70.           zip.AddEntry("first-pass.pdf", firstPass);
  71.  
  72.           // SECOND PASS, ADD THE HEADER
  73.           // Create a reader
  74.           PdfReader reader = new PdfReader(firstPass);
  75.           using (MemoryStream ms2 = new MemoryStream()) {
  76.             // Create a stamper
  77.             using (PdfStamper stamper = new PdfStamper(reader, ms2)) {
  78.               // Loop over the pages and add a header to each page
  79.               int n = reader.NumberOfPages;
  80.               for (int i = 1; i
InsertPages.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Data;
  10. using System.Data.Common;
  11. using Ionic.Zip;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  17.   public class InsertPages : IWriter {
  18. // ===========================================================================
  19.     public const string RESULT1 = "inserted_pages.pdf";
  20.     public const string RESULT2 = "reordered.pdf";
  21. // ---------------------------------------------------------------------------
  22.     public void Write(Stream stream) {
  23.       using (ZipFile zip = new ZipFile()) {
  24.         Stationery s = new Stationery();
  25.         StampStationery ss = new StampStationery();
  26.         byte[] stationery  = s.CreateStationary();
  27.         byte[] sStationery = ss.ManipulatePdf(
  28.           ss.CreatePdf(), stationery
  29.         );
  30.         byte[] insertPages = ManipulatePdf(sStationery, stationery);
  31.         zip.AddEntry(RESULT1, insertPages);
  32.         // reorder the pages in the PDF
  33.         PdfReader reader = new PdfReader(insertPages);
  34.         reader.SelectPages("3-41,1-2");
  35.         using (MemoryStream ms = new MemoryStream()) {
  36.           using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  37.           }
  38.           zip.AddEntry(RESULT2, ms.ToArray());
  39.         }
  40.         zip.AddEntry(Utility.ResultFileName(s.ToString() + ".pdf"), stationery);
  41.         zip.AddEntry(Utility.ResultFileName(ss.ToString() + ".pdf"), sStationery);
  42.         zip.Save(stream);          
  43.       }
  44.     }
  45. // ---------------------------------------------------------------------------
  46.     /**
  47.      * Manipulates a PDF file src
  48.      * @param src the original PDF
  49.      * @param stationery the resulting PDF
  50.      */
  51.     public byte[] ManipulatePdf(byte[] src, byte[] stationery) {
  52.       ColumnText ct = new ColumnText(null);
  53.       string SQL =
  54. @"SELECT country, id FROM film_country
  55. ORDER BY country
  56. ";        
  57.       using (var c =  AdoDB.Provider.CreateConnection()) {
  58.         c.ConnectionString = AdoDB.CS;
  59.         using (DbCommand cmd = c.CreateCommand()) {
  60.           cmd.CommandText = SQL;
  61.           c.Open();
  62.           using (var r = cmd.ExecuteReader()) {
  63.             while (r.Read()) {
  64.               ct.AddElement(new Paragraph(
  65.                 24, new Chunk(r["country"].ToString())
  66.               ));
  67.             }
  68.           }
  69.         }
  70.       }
  71.       // Create a reader for the original document and for the stationery
  72.       PdfReader reader = new PdfReader(src);
  73.       PdfReader rStationery = new PdfReader(stationery);
  74.       using (MemoryStream ms = new MemoryStream()) {
  75.         // Create a stamper
  76.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  77.           // Create an imported page for the stationery
  78.           PdfImportedPage page = stamper.GetImportedPage(rStationery, 1);
  79.           int i = 0;
  80.           // Add the content of the ColumnText object
  81.           while(true) {
  82.           // Add a new page
  83.             stamper.InsertPage(++i, reader.GetPageSize(1));
  84.             // Add the stationary to the new page
  85.             stamper.GetUnderContent(i).AddTemplate(page, 0, 0);
  86.             // Add as much content of the column as possible
  87.             ct.Canvas = stamper.GetOverContent(i);
  88.             ct.SetSimpleColumn(36, 36, 559, 770);
  89.             if (!ColumnText.HasMoreText(ct.Go()))
  90.                 break;
  91.           }
  92.         }
  93.         return ms.ToArray();    
  94.       }
  95.     }    
  96. // ===========================================================================
  97.   }
  98. }
FormInformation.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.Text;
  10. using Ionic.Zip;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  15.   public class FormInformation : IWriter {
  16. // ===========================================================================
  17.     public const string RESULT = "form_info.txt";
  18. // ---------------------------------------------------------------------------
  19.     public void Write(Stream stream) {
  20.       string datasheet = Path.Combine(Utility.ResourcePdf, "datasheet.pdf");
  21.       using (ZipFile zip = new ZipFile()) {
  22.         // Create a reader to extract info
  23.         PdfReader reader = new PdfReader(datasheet);
  24.         // Get the fields from the reader (read-only!!!)
  25.         AcroFields form = reader.AcroFields;
  26.         // Loop over the fields and get info about them
  27.         StringBuilder sb = new StringBuilder();      
  28.         foreach (string key in form.Fields.Keys) {
  29.           sb.Append(key);
  30.           sb.Append(": ");
  31.           switch (form.GetFieldType(key)) {
  32.             case AcroFields.FIELD_TYPE_CHECKBOX:
  33.               sb.Append("Checkbox");
  34.               break;
  35.             case AcroFields.FIELD_TYPE_COMBO:
  36.               sb.Append("Combobox");
  37.               break;
  38.             case AcroFields.FIELD_TYPE_LIST:
  39.               sb.Append("List");
  40.               break;
  41.             case AcroFields.FIELD_TYPE_NONE:
  42.               sb.Append("None");
  43.               break;
  44.             case AcroFields.FIELD_TYPE_PUSHBUTTON:
  45.               sb.Append("Pushbutton");
  46.               break;
  47.             case AcroFields.FIELD_TYPE_RADIOBUTTON:
  48.               sb.Append("Radiobutton");
  49.               break;
  50.             case AcroFields.FIELD_TYPE_SIGNATURE:
  51.               sb.Append("Signature");
  52.               break;
  53.             case AcroFields.FIELD_TYPE_TEXT:
  54.               sb.Append("Text");
  55.               break;
  56.             default:
  57.               sb.Append("?");
  58.               break;
  59.           }
  60.           sb.Append(Environment.NewLine);
  61.         }
  62.        
  63.         // Get possible values for field "CP_1"
  64.         sb.Append("Possible values for CP_1:");
  65.         sb.Append(Environment.NewLine);
  66.         string[] states = form.GetAppearanceStates("CP_1");
  67.         for (int i = 0; i < states.Length; i++) {
  68.           sb.Append(" - ");
  69.           sb.Append(states[i]);
  70.           sb.Append(Environment.NewLine);
  71.         }
  72.  
  73.         // Get possible values for field "category"
  74.         sb.Append("Possible values for category:");
  75.         sb.Append(Environment.NewLine);
  76.         states = form.GetAppearanceStates("category");
  77.         for (int i = 0; i < states.Length - 1; i++) {
  78.           sb.Append(states[i]);
  79.           sb.Append(", ");
  80.         }
  81.         sb.Append(states[states.Length - 1]);
  82.        
  83.         zip.AddEntry(RESULT, sb.ToString());
  84.         zip.AddFile(datasheet, "");
  85.         zip.Save(stream);
  86.       }      
  87.     }
  88. // ===========================================================================
  89.   }
  90. }
FillDataSheet.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Text;
  12. using Ionic.Zip;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  16. /*
  17.  * only run on localhost; requires write permissions
  18.  * to the specified directory on a real web server
  19. */
  20. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  21.   public class FillDataSheet : IWriter {
  22. // ===========================================================================
  23. /** The original PDF file. */
  24.     public const string DATASHEET = "datasheet.pdf";
  25. /** Format for resulting PDF files. */
  26.     public const string RESULT = "imdb{0}.pdf";    
  27. // ---------------------------------------------------------------------------    
  28.     public virtual void Write(Stream stream) {  
  29.       using (ZipFile zip = new ZipFile()) {
  30.         // Get the movies
  31.         IEnumerable movies = PojoFactory.GetMovies();
  32.         string datasheet = Path.Combine(Utility.ResourcePdf, DATASHEET);
  33.         string className = this.ToString();            
  34.         // Fill out the data sheet form with data
  35.         foreach (Movie movie in movies) {
  36.           if (movie.Year < 2007) continue;
  37.           PdfReader reader = new PdfReader(datasheet);          
  38.           string dest = string.Format(RESULT, movie.Imdb);
  39.           using (MemoryStream ms = new MemoryStream()) {
  40.             using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  41.               AcroFields fields = stamper.AcroFields;
  42.               fields.GenerateAppearances = true;
  43.               Fill(fields, movie);
  44.               if (movie.Year == 2007) stamper.FormFlattening = true;
  45.             }
  46.             zip.AddEntry(dest, ms.ToArray());
  47.           }        
  48.         }
  49.         zip.AddFile(datasheet, "");
  50.         zip.Save(stream);
  51.       }              
  52.     }
  53. // ---------------------------------------------------------------------------    
  54.     /**
  55.      * Fill out the fields using info from a Movie object.
  56.      * @param form The form object
  57.      * @param movie A movie POJO
  58.      */
  59.     public static void Fill(AcroFields form, Movie movie) {
  60.       form.SetField("title", movie.MovieTitle);
  61.       form.SetField("director", GetDirectors(movie));
  62.       form.SetField("year", movie.Year.ToString());
  63.       form.SetField("duration", movie.Duration.ToString());
  64.       form.SetField("category", movie.entry.category.Keyword);
  65.       foreach (Screening screening in movie.entry.Screenings) {
  66.         form.SetField(screening.Location.Replace('.', '_'), "Yes");
  67.       }
  68.     }
  69. // ---------------------------------------------------------------------------    
  70.     /**
  71.      * Gets the directors from a Movie object,
  72.      * and concatenates them in a String.
  73.      * @param movie a Movie object
  74.      * @return a String containing director names
  75.      */
  76.     public static String GetDirectors(Movie movie) {
  77.       List directors = movie.Directors;
  78.       StringBuilder buf = new StringBuilder();
  79.       foreach (Director director in directors) {
  80.         buf.Append(director.GivenName);
  81.         buf.Append(' ');
  82.         buf.Append(director.Name);
  83.         buf.Append(',');
  84.         buf.Append(' ');
  85.       }
  86.       int i = buf.Length;
  87.       if (i > 0) buf.Length = i - 2;
  88.       return buf.ToString();
  89.     }    
  90. // ===========================================================================
  91.   }
  92. }
Concatenate.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 iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12. using Ionic.Zip;
  13. using kuujinbo.iTextInAction2Ed.Chapter02;
  14. using kuujinbo.iTextInAction2Ed.Chapter05;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  17.   public class Concatenate : IWriter {
  18. // ===========================================================================
  19.     public const string RESULT = "concatenated.pdf";
  20. // ---------------------------------------------------------------------------
  21.     public void Write(Stream stream) {
  22.       MovieLinks1 ml = new MovieLinks1();
  23.       MovieHistory mh = new MovieHistory();
  24.       List pdf = new List() {
  25.         Utility.PdfBytes(ml),
  26.         Utility.PdfBytes(mh)
  27.       };
  28.       string[] names = {ml.ToString(), mh.ToString()};
  29.       using (ZipFile zip = new ZipFile()) {
  30.         using (MemoryStream ms = new MemoryStream()) {
  31.           // step 1
  32.           using (Document document = new Document()) {
  33.             // step 2
  34.             using (PdfCopy copy = new PdfCopy(document, ms)) {
  35.               // step 3
  36.               document.Open();
  37.               // step 4
  38.               for (int i = 0; i < pdf.Count; ++i) {
  39.                 zip.AddEntry(Utility.ResultFileName(names[i] + ".pdf"), pdf[i]);
  40.                 PdfReader reader = new PdfReader(pdf[i]);
  41.                 // loop over the pages in that document
  42.                 int n = reader.NumberOfPages;
  43.                 for (int page = 0; page < n; ) {
  44.                   copy.AddPage(copy.GetImportedPage(reader, ++page));
  45.                 }
  46.               }
  47.             }
  48.           }
  49.           zip.AddEntry(RESULT, ms.ToArray());
  50.         }
  51.         zip.Save(stream);    
  52.       }
  53.     }
  54. // ===========================================================================
  55.   }
  56. }
ConcatenateStamp.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. using kuujinbo.iTextInAction2Ed.Chapter02;
  14. using kuujinbo.iTextInAction2Ed.Chapter05;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  17.   public class ConcatenateStamp : IWriter {
  18. // ===========================================================================
  19.     /** The resulting PDF file. */
  20.     public const string RESULT = "concatenated_stamped.pdf";
  21. // ---------------------------------------------------------------------------    
  22.     public void Write(Stream stream) {  
  23.       using (ZipFile zip = new ZipFile()) {
  24.         MovieLinks1 ml = new MovieLinks1();
  25.         byte[] r1 = Utility.PdfBytes(ml);
  26.         MovieHistory mh = new MovieHistory();
  27.         byte[] r2 = Utility.PdfBytes(mh);
  28.         using (MemoryStream ms = new MemoryStream()) {
  29.           // step 1
  30.           using (Document document = new Document()) {
  31.             // step 2
  32.             using (PdfCopy copy = new PdfCopy(document, ms)) {
  33.               // step 3
  34.               document.Open();
  35.               // step 4
  36.               // reader for document 1
  37.               PdfReader reader1 = new PdfReader(r1);
  38.               int n1 = reader1.NumberOfPages;
  39.               // reader for document 2
  40.               PdfReader reader2 = new PdfReader(r2);
  41.               int n2 = reader2.NumberOfPages;
  42.               // initializations
  43.               PdfImportedPage page;
  44.               PdfCopy.PageStamp stamp;
  45.               // Loop over the pages of document 1
  46.               for (int i = 0; i < n1; ) {
  47.                 page = copy.GetImportedPage(reader1, ++i);
  48.                 stamp = copy.CreatePageStamp(page);
  49.                 // add page numbers
  50.                 ColumnText.ShowTextAligned(
  51.                   stamp.GetUnderContent(), Element.ALIGN_CENTER,
  52.                   new Phrase(string.Format("page {0} of {1}", i, n1 + n2)),
  53.                   297.5f, 28, 0
  54.                 );
  55.                 stamp.AlterContents();
  56.                 copy.AddPage(page);
  57.               }
  58.  
  59.               // Loop over the pages of document 2
  60.               for (int i = 0; i < n2; ) {
  61.                 page = copy.GetImportedPage(reader2, ++i);
  62.                 stamp = copy.CreatePageStamp(page);
  63.                 // add page numbers
  64.                 ColumnText.ShowTextAligned(
  65.                   stamp.GetUnderContent(), Element.ALIGN_CENTER,
  66.                   new Phrase(string.Format("page {0} of {1}", n1 + i, n1 + n2)),
  67.                   297.5f, 28, 0
  68.                 );
  69.                 stamp.AlterContents();
  70.                 copy.AddPage(page);
  71.               }  
  72.             }  
  73.           }
  74.           zip.AddEntry(RESULT, ms.ToArray());          
  75.           zip.AddEntry(Utility.ResultFileName(ml.ToString() + ".pdf"), r1);      
  76.           zip.AddEntry(Utility.ResultFileName(mh.ToString()+ ".pdf"), r2);
  77.         }
  78.         zip.Save(stream);
  79.       }      
  80.     }
  81. // ===========================================================================
  82.   }
  83. }
Burst.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using iTextSharp.text;
  10. using iTextSharp.text.pdf;
  11. using Ionic.Zip;
  12. using kuujinbo.iTextInAction2Ed.Chapter03;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  15.   public class Burst : IWriter {
  16. // ===========================================================================
  17. /** Format of the resulting PDF files. */
  18.     public const string RESULT = "timetable_p{0}.pdf";
  19. // ---------------------------------------------------------------------------
  20.     public void Write(Stream stream) {
  21.       // use one of the previous examples to create a PDF
  22.       MovieTemplates mt = new MovieTemplates();
  23.       // Create a reader
  24.       byte[] pdf = Utility.PdfBytes(mt);
  25.       PdfReader reader = new PdfReader(pdf);
  26.       // loop over all the pages in the original PDF
  27.       int n = reader.NumberOfPages;      
  28.       using (ZipFile zip = new ZipFile()) {
  29.         for (int i = 0; i < n; ) {
  30.           string dest = string.Format(RESULT, ++i);
  31.           using (MemoryStream ms = new MemoryStream()) {
  32. // We'll create as many new PDFs as there are pages
  33.             // step 1
  34.             using (Document document = new Document()) {
  35.               // step 2
  36.               using (PdfCopy copy = new PdfCopy(document, ms)) {
  37.                 // step 3
  38.                 document.Open();
  39.                 // step 4
  40.                 copy.AddPage(copy.GetImportedPage(reader, i));
  41.               }
  42.             }
  43.             zip.AddEntry(dest, ms.ToArray());
  44.           }
  45.         }
  46.         zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf);
  47.         zip.Save(stream);      
  48.       }
  49.     }
  50. // ===========================================================================
  51.   }
  52. }
DataSheets1.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. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  16.   public class DataSheets1 : FillDataSheet {
  17. // ===========================================================================
  18.     public new const string RESULT = "datasheets1.pdf";
  19.     public readonly string DATASHEET_PATH = Path.Combine(Utility.ResourcePdf, DATASHEET);
  20. // ---------------------------------------------------------------------------
  21.     public override void Write(Stream stream) {
  22.       using (ZipFile zip = new ZipFile()) {
  23.         using (MemoryStream ms = new MemoryStream()) {
  24.           // step 1
  25.           using (Document document = new Document()) {
  26.             // step 2
  27.             using (PdfCopy copy = new PdfCopy(document, ms)) {
  28.               // step 3
  29.               document.Open();
  30.               // step 4
  31.               AddDataSheets(copy);
  32.             }
  33.           }
  34.           zip.AddEntry(RESULT, ms.ToArray());        
  35.         }
  36.         zip.AddFile(DATASHEET_PATH, "");
  37.         zip.Save(stream);
  38.       }
  39.     }
  40. // ---------------------------------------------------------------------------
  41.     /**
  42.      * Fills out a data sheet, flattens it, and adds it to a combined PDF.
  43.      * @param copy the PdfCopy instance (can also be PdfSmartCopy)
  44.      */
  45.     public void AddDataSheets(PdfCopy copy) {
  46.       IEnumerable movies = PojoFactory.GetMovies();
  47.       // Loop over all the movies and fill out the data sheet
  48.       foreach (Movie movie in movies) {
  49.         PdfReader reader = new PdfReader(DATASHEET_PATH);
  50.         using (var ms = new MemoryStream()) {
  51.           using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  52.             Fill(stamper.AcroFields, movie);
  53.             stamper.FormFlattening = true;
  54.           }
  55.           reader = new PdfReader(ms.ToArray());
  56.           copy.AddPage(copy.GetImportedPage(reader, 1));
  57.         }
  58.       }
  59.     }    
  60. // ===========================================================================
  61.   }
  62. }
DataSheets2.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.  * this creates a bit of overhead, so we only run on localhost;
  15. */
  16. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  17.   public class DataSheets2 : DataSheets1 {
  18. // ===========================================================================
  19.     public new const string RESULT = "datasheets2.pdf";
  20. // ---------------------------------------------------------------------------
  21.     public override void Write(Stream stream) {
  22.       using (ZipFile zip = new ZipFile()) {
  23.         using (MemoryStream ms = new MemoryStream()) {
  24.           // step 1
  25.           using (Document document = new Document()) {
  26.             // step 2
  27.             using (PdfSmartCopy copy = new PdfSmartCopy(document, ms)) {
  28.               // step 3
  29.               document.Open();
  30.               // step 4
  31.               AddDataSheets(copy);
  32.             }
  33.           }
  34.           zip.AddEntry(RESULT, ms.ToArray());        
  35.         }
  36.         zip.AddFile(DATASHEET_PATH, "");
  37.         zip.Save(stream);
  38.       }    
  39.     }
  40. // ===========================================================================
  41.   }
  42. }
ConcatenateForms1.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12.  
  13. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  14.   public class ConcatenateForms1 : IWriter {
  15. // ===========================================================================
  16.     public const string RESULT = "concatenated_forms1.pdf";
  17.     /** The original PDF file. */
  18.     public const string copyName = "datasheet.pdf";
  19.     public readonly string DATASHEET = Path.Combine(
  20.       Utility.ResourcePdf, copyName
  21.     );
  22. // ---------------------------------------------------------------------------    
  23.     public void Write(Stream stream) {
  24.       using (ZipFile zip = new ZipFile()) {
  25.         using (MemoryStream ms = new MemoryStream()) {
  26.           // Create a PdfCopyFields object
  27.           PdfCopyFields copy = new PdfCopyFields(ms);
  28.           // add a document
  29.           copy.AddDocument(new PdfReader(DATASHEET));
  30.           // add a document
  31.           copy.AddDocument(new PdfReader(DATASHEET));
  32.           // close the PdfCopyFields object
  33.           copy.Close();
  34.           zip.AddEntry(RESULT, ms.ToArray());
  35.         }
  36.         zip.AddFile(DATASHEET, "");
  37.         zip.Save(stream);
  38.       }
  39.     }
  40. // ===========================================================================
  41.   }
  42. }
ConcatenateForms2.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.Chapter06 {
  15.   public class ConcatenateForms2 : IWriter {
  16. // ===========================================================================
  17.     public const string RESULT = "concatenated_forms2.pdf";
  18. /** The original PDF file. */
  19.     public const string copyName = "datasheet.pdf";
  20.     public readonly string DATASHEET = Path.Combine(
  21.       Utility.ResourcePdf, copyName
  22.     );
  23. // ---------------------------------------------------------------------------    
  24.     public void Write(Stream stream) {  
  25.       using (ZipFile zip = new ZipFile()) {
  26.         using (MemoryStream ms = new MemoryStream()) {
  27.           // Create a PdfCopyFields object
  28.           PdfCopyFields copy = new PdfCopyFields(ms);
  29.           // add a document
  30.           copy.AddDocument(new PdfReader(RenameFieldsIn(
  31.             DATASHEET, 1
  32.           )));
  33.           // add a document
  34.           copy.AddDocument(new PdfReader(RenameFieldsIn(
  35.             DATASHEET, 2
  36.           )));
  37.           // close the PdfCopyFields object
  38.           copy.Close();
  39.           zip.AddEntry(RESULT, ms.ToArray());            
  40.         }
  41.         zip.AddFile(DATASHEET, "");
  42.         zip.Save(stream);        
  43.       }    
  44.     }
  45. // ---------------------------------------------------------------------------    
  46.     /**
  47.      * Renames the fields in an interactive form.
  48.      * @param datasheet the path to the original form
  49.      * @param i a number that needs to be appended to the field names
  50.      * @return a byte[] containing an altered PDF file
  51.      */
  52.     private static byte[] RenameFieldsIn(string datasheet, int i) {
  53.       List form_keys = new List();
  54.       using (var ms = new MemoryStream()) {
  55.         // Create the stamper
  56.         using (PdfStamper stamper = new PdfStamper(
  57.           new PdfReader(datasheet), ms))
  58.         {
  59.           // Get the fields
  60.           AcroFields form = stamper.AcroFields;
  61.           // so we aren't hit with 'Collection was modified' exception
  62.           foreach (string k in stamper.AcroFields.Fields.Keys) {
  63.             form_keys.Add(k);
  64.           }
  65.           // Loop over the fields
  66.           foreach (string key in form_keys) {
  67.             // rename the fields
  68.             form.RenameField(key, string.Format("{0}_{1}", key, i));
  69.           }
  70.         }
  71.         return ms.ToArray();
  72.       }
  73.     }    
  74. // ===========================================================================
  75.   }
  76. }
StampStationery.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Data;
  11. using System.Data.Common;
  12. using System.Linq;
  13. using Ionic.Zip;
  14. using iTextSharp.text;
  15. using iTextSharp.text.pdf;
  16. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  17.  
  18. namespace kuujinbo.iTextInAction2Ed.Chapter06 {
  19.   public class StampStationery : IWriter {
  20. // ===========================================================================
  21.     /** The original PDF file. */
  22.     public const string ORIGINAL = "original.pdf";
  23.     /** The resulting PDF. */
  24.     public const string RESULT = "stamped_stationary.pdf";    
  25. // ---------------------------------------------------------------------------
  26.     public void Write(Stream stream) {
  27.       using (ZipFile zip = new ZipFile()) {
  28.         // previous example
  29.         Stationery s = new Stationery();
  30.         StampStationery ss = new StampStationery();
  31.         byte[] stationery  = s.CreateStationary();
  32.         byte[] sStationery = ss.CreatePdf();
  33.        
  34.         zip.AddEntry(RESULT, ManipulatePdf(sStationery, stationery));
  35.         zip.AddEntry(ORIGINAL, sStationery);
  36.         zip.AddEntry(Utility.ResultFileName(s.ToString() + ".pdf"), stationery);
  37.         zip.Save(stream);
  38.       }      
  39.     }
  40. // ---------------------------------------------------------------------------
  41.     /**
  42.      * Manipulates a PDF file src with the file dest as result
  43.      * @param src the original PDF
  44.      * @param stationery a PDF that will be added as background
  45.      */
  46.     public byte[] ManipulatePdf(byte[] src, byte[] stationery) {
  47.       // Create readers
  48.       PdfReader reader = new PdfReader(src);
  49.       PdfReader s_reader = new PdfReader(stationery);
  50.       using (MemoryStream ms = new MemoryStream()) {
  51.         // Create the stamper
  52.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  53.           // Add the stationery to each page
  54.           PdfImportedPage page = stamper.GetImportedPage(s_reader, 1);
  55.           int n = reader.NumberOfPages;
  56.           PdfContentByte background;
  57.           for (int i = 1; i
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