Chapter 13: PDFs inside-out

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

10th October 2015
admin-marketing

Switch code for this example

PdfXPdfA.java
  1. /* in_action/chapterF/HelloWorldPdfX.java */
  2.  
  3. package part4.chapter13;
  4.  
  5. import java.io.FileInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8.  
  9. import com.itextpdf.text.Document;
  10. import com.itextpdf.text.DocumentException;
  11. import com.itextpdf.text.Font;
  12. import com.itextpdf.text.FontFactory;
  13. import com.itextpdf.text.Paragraph;
  14. import com.itextpdf.text.pdf.BaseFont;
  15. import com.itextpdf.text.pdf.CMYKColor;
  16. import com.itextpdf.text.pdf.ICC_Profile;
  17. import com.itextpdf.text.pdf.PdfAConformanceLevel;
  18. import com.itextpdf.text.pdf.PdfAWriter;
  19. import com.itextpdf.text.pdf.PdfWriter;
  20.  
  21. public class PdfXPdfA {
  22.  
  23.     /** The resulting PDF file. */
  24.     public static final String RESULT1 = "results/part4/chapter13/x.pdf";
  25.     /** The resulting PDF file. */
  26.     public static final String RESULT2 = "results/part4/chapter13/a.pdf";
  27.  
  28.     /** A font program that is used. */
  29.     public static final String FONT = "c:/windows/fonts/arial.ttf";
  30.     /** A color profile that is used. */
  31.     public static final String PROFILE = "resources/img/sRGB.profile";
  32.    
  33.     /**
  34.      * Creates a PDF document.
  35.      * @param filename the path to the new PDF document
  36.      * @throws DocumentException
  37.      * @throws IOException
  38.      */
  39.     public void createPdfX(String filename) throws IOException, DocumentException {
  40.         // step 1
  41.         Document document = new Document();
  42.         // step 2
  43.         PdfWriter writer = PdfWriter.getInstance(document,
  44.             new FileOutputStream(filename));
  45.         writer.setPDFXConformance(PdfWriter.PDFX1A2001);
  46.         // step 3
  47.         document.open();
  48.         // step 4
  49.         Font font = FontFactory.getFont(
  50.             FONT, BaseFont.CP1252, BaseFont.EMBEDDED, Font.UNDEFINED,
  51.             Font.UNDEFINED, new CMYKColor(255, 255, 0, 0));
  52.         document.add(new Paragraph("Hello World", font));
  53.         // step 5
  54.         document.close();
  55.     }
  56.  
  57.     /**
  58.      * Creates a PDF document.
  59.      * @param filename the path to the new PDF document
  60.      * @throws DocumentException
  61.      * @throws IOException
  62.      */
  63.     public void createPdfA(String filename) throws IOException, DocumentException {
  64.         // step 1
  65.         Document document = new Document();
  66.         // step 2
  67.         PdfAWriter writer = PdfAWriter.getInstance(document,
  68.             new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_1B);
  69.         writer.createXmpMetadata();
  70.         // step 3
  71.         document.open();
  72.         // step 4
  73.         Font font = FontFactory.getFont(FONT, BaseFont.CP1252, BaseFont.EMBEDDED);
  74.         document.add(new Paragraph("Hello World", font));
  75.         ICC_Profile icc = ICC_Profile.getInstance(new FileInputStream(PROFILE));
  76.         writer.setOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
  77.         // step 5
  78.         document.close();
  79.     }
  80.    
  81.     /**
  82.      * Main method.
  83.      *
  84.      * @param    args    no arguments needed
  85.      * @throws DocumentException
  86.      * @throws IOException
  87.      */
  88.     public static void main(String[] args) throws IOException, DocumentException {
  89.         PdfXPdfA example = new PdfXPdfA();
  90.         example.createPdfX(RESULT1);
  91.         example.createPdfA(RESULT2);
  92.     }
  93. }
AppendMode.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter13;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import part1.chapter01.HelloWorld;
  14.  
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.Element;
  17. import com.itextpdf.text.pdf.BaseFont;
  18. import com.itextpdf.text.pdf.PdfContentByte;
  19. import com.itextpdf.text.pdf.PdfReader;
  20. import com.itextpdf.text.pdf.PdfStamper;
  21.  
  22. public class AppendMode {
  23.     /** The resulting PDF. */
  24.     public static final String RESULT
  25.         = "results/part4/chapter13/appended.pdf";
  26.  
  27.     /**
  28.      * Manipulates a PDF file src with the file dest as result
  29.      * @param src the original PDF
  30.      * @param dest the resulting PDF
  31.      * @throws IOException
  32.      * @throws DocumentException
  33.      */
  34.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  35.         PdfReader reader = new PdfReader(src);
  36.         PdfStamper stamper =
  37.             new PdfStamper(reader, new FileOutputStream(dest), '\0', true);
  38.         PdfContentByte cb = stamper.getUnderContent(1);
  39.         cb.beginText();
  40.         cb.setFontAndSize(BaseFont.createFont(), 12);
  41.         cb.showTextAligned(Element.ALIGN_LEFT, "Hello People!", 36, 770, 0);
  42.         cb.endText();
  43.         stamper.close();
  44.         reader.close();
  45.     }
  46.    
  47.     /**
  48.      * Main method.
  49.      *
  50.      * @param    args    no arguments needed
  51.      * @throws DocumentException
  52.      * @throws IOException
  53.      */
  54.     public static void main(String[] args) throws IOException, DocumentException {
  55.         new HelloWorld().createPdf(HelloWorld.RESULT);
  56.         new AppendMode().manipulatePdf(HelloWorld.RESULT, RESULT);
  57.     }
  58. }
PageLayoutExample.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter13;
  8.  
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.sql.SQLException;
  12. import java.util.List;
  13.  
  14. import part1.chapter02.MovieParagraphs1;
  15.  
  16. import com.itextpdf.text.Document;
  17. import com.itextpdf.text.DocumentException;
  18. import com.itextpdf.text.Element;
  19. import com.itextpdf.text.Paragraph;
  20. import com.itextpdf.text.pdf.PdfWriter;
  21. import com.lowagie.database.DatabaseConnection;
  22. import com.lowagie.database.HsqldbConnection;
  23. import com.lowagie.filmfestival.Movie;
  24. import com.lowagie.filmfestival.PojoFactory;
  25.  
  26. public class PageLayoutExample extends MovieParagraphs1 {
  27.  
  28.     /** The resulting PDF file. */
  29.     public static final String RESULT1
  30.         = "results/part4/chapter13/page_layout_single.pdf";
  31.     /** The resulting PDF file. */
  32.     public static final String RESULT2
  33.         = "results/part4/chapter13/page_layout_column.pdf";
  34.     /** The resulting PDF file. */
  35.     public static final String RESULT3
  36.         = "results/part4/chapter13/page_layout_columns_l.pdf";
  37.     /** The resulting PDF file. */
  38.     public static final String RESULT4
  39.         = "results/part4/chapter13/page_layout_columns_r.pdf";
  40.     /** The resulting PDF file. */
  41.     public static final String RESULT5
  42.         = "results/part4/chapter13/page_layout_pages_l.pdf";
  43.     /** The resulting PDF file. */
  44.     public static final String RESULT6
  45.         = "results/part4/chapter13/page_layout_pages_r.pdf";
  46.  
  47.     /**
  48.      * Creates a PDF with information about the movies
  49.      * @param filename the name of the PDF file that will be created.
  50.      * @param pagelayout the value for the viewerpreferences
  51.      * @throws    DocumentException
  52.      * @throws    IOException
  53.      * @throws    SQLException
  54.      */
  55.     public void createPdf(String filename, int viewerpreference)
  56.         throws IOException, DocumentException, SQLException {
  57.         // Create a database connection
  58.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  59.         // step 1
  60.         Document document = new Document();
  61.         // step 2
  62.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  63.         writer.setPdfVersion(PdfWriter.VERSION_1_5);
  64.         writer.setViewerPreferences(viewerpreference);
  65.         // step 3
  66.         document.open();
  67.         // step 4
  68.         List movies = PojoFactory.getMovies(connection);
  69.         for (Movie movie : movies) {
  70.             Paragraph p = createMovieInformation(movie);
  71.             p.setAlignment(Element.ALIGN_JUSTIFIED);
  72.             p.setIndentationLeft(18);
  73.             p.setFirstLineIndent(-18);
  74.             document.add(p);
  75.         }
  76.         // step 5
  77.         document.close();
  78.         // Close the database connection
  79.         connection.close();
  80.     }
  81.  
  82.     /**
  83.      * Main method.
  84.      *
  85.      * @param    args    no arguments needed
  86.      * @throws DocumentException
  87.      * @throws IOException
  88.      * @throws SQLException
  89.      */
  90.     public static void main(String[] args)
  91.         throws IOException, DocumentException, SQLException {
  92.         PageLayoutExample example = new PageLayoutExample();
  93.         example.createPdf(RESULT1, PdfWriter.PageLayoutSinglePage);
  94.         example.createPdf(RESULT2, PdfWriter.PageLayoutOneColumn);
  95.         example.createPdf(RESULT3, PdfWriter.PageLayoutTwoColumnLeft);
  96.         example.createPdf(RESULT4, PdfWriter.PageLayoutTwoColumnRight);
  97.         example.createPdf(RESULT5, PdfWriter.PageLayoutTwoPageLeft);
  98.         example.createPdf(RESULT6, PdfWriter.PageLayoutTwoPageRight);
  99.     }
  100. }
ViewerPreferencesExample.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter13;
  8.  
  9. import java.io.IOException;
  10. import java.sql.SQLException;
  11.  
  12. import com.itextpdf.text.DocumentException;
  13. import com.itextpdf.text.pdf.PdfWriter;
  14.  
  15. public class ViewerPreferencesExample extends PageLayoutExample {
  16.  
  17.     /** The resulting PDF file. */
  18.     public static final String RESULT1
  19.         = "results/part4/chapter13/viewerpreferences1.pdf";
  20.     /** The resulting PDF file. */
  21.     public static final String RESULT2
  22.         = "results/part4/chapter13/viewerpreferences2.pdf";
  23.     /** The resulting PDF file. */
  24.     public static final String RESULT3
  25.         = "results/part4/chapter13/viewerpreferences3.pdf";
  26.     /** The resulting PDF file. */
  27.     public static final String RESULT4
  28.         = "results/part4/chapter13/viewerpreferences4.pdf";
  29.     /** The resulting PDF file. */
  30.     public static final String RESULT5
  31.         = "results/part4/chapter13/viewerpreferences5.pdf";
  32.     /** The resulting PDF file. */
  33.     public static final String RESULT6
  34.         = "results/part4/chapter13/viewerpreferences6.pdf";
  35.  
  36.     /**
  37.      * Main method.
  38.      *
  39.      * @param    args    no arguments needed
  40.      * @throws DocumentException
  41.      * @throws IOException
  42.      * @throws SQLException
  43.      */
  44.     public static void main(String[] args)
  45.         throws IOException, DocumentException, SQLException {
  46.         ViewerPreferencesExample example = new ViewerPreferencesExample();
  47.         example.createPdf(RESULT1,
  48.             PdfWriter.PageModeFullScreen);
  49.         example.createPdf(RESULT2,
  50.             PdfWriter.PageModeUseThumbs);
  51.         example.createPdf(RESULT3,
  52.             PdfWriter.PageLayoutTwoColumnRight | PdfWriter.PageModeUseThumbs);
  53.         example.createPdf(RESULT4,
  54.             PdfWriter.PageModeFullScreen | PdfWriter.NonFullScreenPageModeUseOutlines);
  55.         example.createPdf(RESULT5,
  56.             PdfWriter.FitWindow | PdfWriter.HideToolbar);
  57.         example.createPdf(RESULT6,
  58.             PdfWriter.HideWindowUI);
  59.     }
  60. }
PrintPreferencesExample.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter13;
  8.  
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11.  
  12. import com.itextpdf.text.Document;
  13. import com.itextpdf.text.DocumentException;
  14. import com.itextpdf.text.Paragraph;
  15. import com.itextpdf.text.pdf.PdfBoolean;
  16. import com.itextpdf.text.pdf.PdfName;
  17. import com.itextpdf.text.pdf.PdfNumber;
  18. import com.itextpdf.text.pdf.PdfWriter;
  19.  
  20. public class PrintPreferencesExample {
  21.  
  22.     /** The resulting PDF file. */
  23.     public static final String RESULT
  24.         = "results/part4/chapter13/printpreferences.pdf";
  25.  
  26.     /**
  27.      * Creates a PDF with information about the movies
  28.      * @param filename the name of the PDF file that will be created.
  29.      * @param pagelayout the value for the viewerpreferences
  30.      * @throws    DocumentException
  31.      * @throws    IOException
  32.      */
  33.     public void createPdf(String filename)
  34.         throws IOException, DocumentException {
  35.         // step 1
  36.         Document document = new Document();
  37.         // step 2
  38.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  39.         writer.setPdfVersion(PdfWriter.VERSION_1_5);
  40.         writer.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
  41.         writer.addViewerPreference(PdfName.NUMCOPIES, new PdfNumber(3));
  42.         writer.addViewerPreference(PdfName.PICKTRAYBYPDFSIZE, PdfBoolean.PDFTRUE);
  43.         // step 3
  44.         document.open();
  45.         // step 4
  46.         document.add(new Paragraph("Hello World"));
  47.         // step 5
  48.         document.close();
  49.     }
  50.     /**
  51.      * Main method.
  52.      *
  53.      * @param    args    no arguments needed
  54.      * @throws DocumentException
  55.      * @throws IOException
  56.      */
  57.     public static void main(String[] args)
  58.         throws IOException, DocumentException {
  59.         new PrintPreferencesExample().createPdf(RESULT);
  60.     }
  61. }
CropPages.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter13;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import part1.chapter03.MovieTemplates;
  14.  
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.pdf.PdfDictionary;
  17. import com.itextpdf.text.pdf.PdfName;
  18. import com.itextpdf.text.pdf.PdfReader;
  19. import com.itextpdf.text.pdf.PdfRectangle;
  20. import com.itextpdf.text.pdf.PdfStamper;
  21.  
  22. public class CropPages {
  23.  
  24.     /** The resulting PDF. */
  25.     public static final String RESULT
  26.         = "results/part4/chapter13/timetable_cropped.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.      * @throws IOException
  33.      * @throws DocumentException
  34.      */
  35.     public void manipulatePdf(String src, String dest)
  36.         throws IOException, DocumentException {
  37.         PdfReader reader = new PdfReader(src);
  38.         int n = reader.getNumberOfPages();
  39.         PdfDictionary pageDict;
  40.         PdfRectangle rect = new PdfRectangle(55, 76, 560, 816);
  41.         for (int i = 1; i
RotatePages.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter13;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import part1.chapter03.MovieTemplates;
  14.  
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.pdf.PdfDictionary;
  17. import com.itextpdf.text.pdf.PdfName;
  18. import com.itextpdf.text.pdf.PdfNumber;
  19. import com.itextpdf.text.pdf.PdfReader;
  20. import com.itextpdf.text.pdf.PdfStamper;
  21.  
  22. public class RotatePages {
  23.  
  24.     /** The resulting PDF. */
  25.     public static final String RESULT
  26.         = "results/part4/chapter13/timetable_rotated.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.      * @throws IOException
  33.      * @throws DocumentException
  34.      */
  35.     public void manipulatePdf(String src, String dest)
  36.         throws IOException, DocumentException {
  37.         PdfReader reader = new PdfReader(MovieTemplates.RESULT);
  38.         int n = reader.getNumberOfPages();
  39.         int rot;
  40.         PdfDictionary pageDict;
  41.         for (int i = 1; i
RemoveLaunchActions.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter13;
  8.  
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11.  
  12. import part2.chapter07.LaunchAction;
  13.  
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.pdf.PdfDictionary;
  16. import com.itextpdf.text.pdf.PdfName;
  17. import com.itextpdf.text.pdf.PdfObject;
  18. import com.itextpdf.text.pdf.PdfReader;
  19. import com.itextpdf.text.pdf.PdfStamper;
  20. import com.itextpdf.text.pdf.PdfString;
  21.  
  22. public class RemoveLaunchActions {
  23.     /** The resulting PDF. */
  24.     public static final String RESULT
  25.         = "results/part4/chapter13/launch_removed.pdf";
  26.    
  27.     /**
  28.      * Manipulates a PDF file src with the file dest as result
  29.      * @param src the original PDF
  30.      * @param dest the resulting PDF
  31.      * @throws IOException
  32.      * @throws DocumentException
  33.      */
  34.     public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
  35.         PdfReader reader = new PdfReader(src);
  36.         PdfObject object;
  37.         PdfDictionary action;
  38.         for (int i = 1; i < reader.getXrefSize(); i++) {
  39.             object = reader.getPdfObject(i);
  40.             if (object instanceof PdfDictionary) {
  41.                 action = ((PdfDictionary)object).getAsDict(PdfName.A);
  42.                 if (action == null) continue;
  43.                 if (PdfName.LAUNCH.equals(action.getAsName(PdfName.S))) {
  44.                     action.remove(PdfName.F);
  45.                     action.remove(PdfName.WIN);
  46.                     action.put(PdfName.S, PdfName.JAVASCRIPT);
  47.                     action.put(PdfName.JS,
  48.                         new PdfString("app.alert('Launch Application Action removed by iText');\r"));
  49.                 }
  50.             }
  51.         }
  52.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  53.         stamper.close();
  54.         reader.close();
  55.     }
  56.     /**
  57.      * Main method creating the PDF.
  58.      * @param    args    no arguments needed
  59.      * @throws DocumentException
  60.      * @throws IOException
  61.      */
  62.     public static void main(String[] args)
  63.         throws IOException, DocumentException {
  64.         new LaunchAction().createPdf(LaunchAction.RESULT);
  65.         new RemoveLaunchActions().manipulatePdf(LaunchAction.RESULT, RESULT);
  66.     }
  67. }
PageLabelExample.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter13;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.PrintStream;
  13. import java.sql.ResultSet;
  14. import java.sql.SQLException;
  15. import java.sql.Statement;
  16.  
  17. import com.itextpdf.text.Document;
  18. import com.itextpdf.text.DocumentException;
  19. import com.itextpdf.text.PageSize;
  20. import com.itextpdf.text.Paragraph;
  21. import com.itextpdf.text.pdf.PdfArray;
  22. import com.itextpdf.text.pdf.PdfDictionary;
  23. import com.itextpdf.text.pdf.PdfName;
  24. import com.itextpdf.text.pdf.PdfPageLabels;
  25. import com.itextpdf.text.pdf.PdfReader;
  26. import com.itextpdf.text.pdf.PdfStamper;
  27. import com.itextpdf.text.pdf.PdfString;
  28. import com.itextpdf.text.pdf.PdfWriter;
  29. import com.lowagie.database.DatabaseConnection;
  30. import com.lowagie.database.HsqldbConnection;
  31.  
  32. public class PageLabelExample {
  33.    
  34.     /** The resulting PDF file. */
  35.     public static final String RESULT
  36.         = "results/part4/chapter13/page_labels.pdf";
  37.     /** The resulting PDF file. */
  38.     public static final String RESULT2
  39.         = "results/part4/chapter13/page_labels_changed.pdf";
  40.     /** A text file containing page numbers and labels. */
  41.     public static final String LABELS
  42.         = "results/part4/chapter13/page_labels.txt";
  43.     /** SQL statements */
  44.     public static final String[] SQL = {
  45.         "SELECT country FROM film_country ORDER BY country",
  46.         "SELECT name FROM film_director ORDER BY name",
  47.         "SELECT title FROM film_movietitle ORDER BY title"
  48.     };
  49.     /** SQL statements */
  50.     public static final String[] FIELD = { "country", "name", "title" };
  51.    
  52.     /**
  53.      * Creates a PDF document.
  54.      * @param filename the path to the new PDF document
  55.      * @throws    DocumentException
  56.      * @throws    IOException
  57.      * @throws    SQLException
  58.      */
  59.     public void createPdf(String filename)
  60.         throws IOException, DocumentException, SQLException{
  61.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  62.         // step 1
  63.         Document document = new Document(PageSize.A5);
  64.         // step 2
  65.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  66.         // step 3
  67.         document.open();
  68.         // step 4
  69.         int[] start = new int[3];
  70.         for (int i = 0; i < 3; i++) {
  71.             start[i] = writer.getPageNumber();
  72.             addParagraphs(document, connection, SQL[i], FIELD[i]);
  73.             document.newPage();
  74.         }
  75.         PdfPageLabels labels = new PdfPageLabels();
  76.         labels.addPageLabel(start[0], PdfPageLabels.UPPERCASE_LETTERS);
  77.         labels.addPageLabel(start[1], PdfPageLabels.DECIMAL_ARABIC_NUMERALS);
  78.         labels.addPageLabel(start[2],
  79.             PdfPageLabels.DECIMAL_ARABIC_NUMERALS, "Movies-", start[2] - start[1] + 1);
  80.         writer.setPageLabels(labels);
  81.         // step 5
  82.         document.close();
  83.         connection.close();
  84.        
  85.     }
  86.    
  87.     /**
  88.      * Performs an SQL query and writes the results to a PDF using the Paragraph object.
  89.      * @param document    The document to which the paragraphs have to be added
  90.      * @param connection  The database connection that has to be used
  91.      * @param sql         The SQL statement
  92.      * @param field       The name of the field that has to be shown
  93.      * @throws SQLException
  94.      * @throws DocumentException
  95.      * @throws IOException
  96.      */
  97.     public void addParagraphs(Document document, DatabaseConnection connection, String sql, String field)
  98.         throws SQLException, DocumentException, IOException {
  99.         Statement stm = connection.createStatement();
  100.         ResultSet rs = stm.executeQuery(sql);
  101.         while (rs.next()) {
  102.             document.add(new Paragraph(new String(rs.getBytes(field), "UTF-8")));
  103.         }
  104.     }
  105.    
  106.     /**
  107.      * Reads the page labels from an existing PDF
  108.      * @param src  the path to an existing PDF
  109.      * @param dest the path to the resulting text file
  110.      * @throws IOException
  111.      */
  112.     public void listPageLabels(String src, String dest) throws IOException {
  113.         // no PDF, just a text file
  114.         PrintStream out = new PrintStream(new FileOutputStream(dest));
  115.         PdfReader reader = new PdfReader(src);
  116.         String[] labels = PdfPageLabels.getPageLabels(reader);
  117.         for (int i = 0; i < labels.length; i++) {
  118.             out.println(labels[i]);
  119.         }
  120.         out.flush();
  121.         out.close();
  122.         reader.close();
  123.     }
  124.    
  125.     /**
  126.      * Manipulates the page labels at the lowest PDF level.
  127.      * @param src  The path to the source file
  128.      * @param dest The path to the changed PDF
  129.      * @throws IOException
  130.      * @throws DocumentException
  131.      */
  132.     public void manipulatePageLabel(String src, String dest) throws IOException, DocumentException {
  133.         PdfReader reader = new PdfReader(src);
  134.         PdfDictionary root = reader.getCatalog();
  135.         PdfDictionary labels = root.getAsDict(PdfName.PAGELABELS);
  136.         PdfArray nums = labels.getAsArray(PdfName.NUMS);
  137.         int n;
  138.         PdfDictionary pagelabel;
  139.         for (int i = 0; i < nums.size(); i++) {
  140.             n = nums.getAsNumber(i).intValue();
  141.             i++;
  142.             if (n == 5) {
  143.                 pagelabel = nums.getAsDict(i);
  144.                 pagelabel.remove(PdfName.ST);
  145.                 pagelabel.put(PdfName.P, new PdfString("Film-"));
  146.             }
  147.         }
  148.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  149.         stamper.close();
  150.         reader.close();
  151.     }
  152.    
  153.     /**
  154.      * Main method.
  155.      *
  156.      * @param    args    no arguments needed
  157.      * @throws DocumentException
  158.      * @throws IOException
  159.      * @throws SQLException
  160.      */
  161.     public static void main(String[] args)
  162.         throws IOException, DocumentException, SQLException {
  163.         PageLabelExample labels = new PageLabelExample();
  164.         labels.createPdf(RESULT);
  165.         labels.listPageLabels(RESULT, LABELS);
  166.         labels.manipulatePageLabel(RESULT, RESULT2);
  167.     }
  168. }
Bookmarks2NamedDestinations.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter13;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.SQLException;
  13. import java.util.Set;
  14. import java.util.TreeSet;
  15.  
  16. import part2.chapter07.LinkActions;
  17.  
  18. import com.itextpdf.text.Chapter;
  19. import com.itextpdf.text.Document;
  20. import com.itextpdf.text.DocumentException;
  21. import com.itextpdf.text.Font;
  22. import com.itextpdf.text.Paragraph;
  23. import com.itextpdf.text.Section;
  24. import com.itextpdf.text.Font.FontFamily;
  25. import com.itextpdf.text.pdf.PdfArray;
  26. import com.itextpdf.text.pdf.PdfDictionary;
  27. import com.itextpdf.text.pdf.PdfIndirectReference;
  28. import com.itextpdf.text.pdf.PdfName;
  29. import com.itextpdf.text.pdf.PdfReader;
  30. import com.itextpdf.text.pdf.PdfStamper;
  31. import com.itextpdf.text.pdf.PdfWriter;
  32. import com.lowagie.database.DatabaseConnection;
  33. import com.lowagie.database.HsqldbConnection;
  34. import com.lowagie.filmfestival.Movie;
  35. import com.lowagie.filmfestival.MovieComparator;
  36. import com.lowagie.filmfestival.PojoFactory;
  37. import com.lowagie.filmfestival.PojoToElementFactory;
  38.  
  39. public class Bookmarks2NamedDestinations {
  40.  
  41.     /** The resulting PDF file. */
  42.     public static final String RESULT1 = "results/part4/chapter13/bookmarks.pdf";
  43.     /** The resulting PDF file. */
  44.     public static final String RESULT2 = "results/part4/chapter13/named_destinations.pdf";
  45.     /** The resulting PDF file. */
  46.     public static final String RESULT3 = "results/part4/chapter13/named_destinations.xml";
  47.    
  48.     /** The different epochs. */
  49.     public static final String[] EPOCH =
  50.         { "Forties", "Fifties", "Sixties", "Seventies", "Eighties",
  51.           "Nineties", "Twenty-first Century" };
  52.     /** The fonts for the title. */
  53.     public static final Font[] FONT = new Font[4];
  54.     static {
  55.         FONT[0] = new Font(FontFamily.HELVETICA, 24);
  56.         FONT[1] = new Font(FontFamily.HELVETICA, 18);
  57.         FONT[2] = new Font(FontFamily.HELVETICA, 14);
  58.         FONT[3] = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
  59.     }
  60.    
  61.     /**
  62.      * Creates a PDF document.
  63.      * @param filename the path to the new PDF document
  64.      * @throws DocumentException
  65.      * @throws IOException
  66.      * @throws    DocumentException
  67.      * @throws    IOException
  68.      * @throws SQLException
  69.      */
  70.     public void createPdf(String filename) throws IOException, DocumentException, SQLException {
  71.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  72.         // step 1
  73.         Document document = new Document();
  74.         // step 2
  75.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  76.         // step 3
  77.         document.open();
  78.         // step 4
  79.         Set movies =
  80.             new TreeSet(new MovieComparator(MovieComparator.BY_YEAR));
  81.         movies.addAll(PojoFactory.getMovies(connection));
  82.         int epoch = -1;
  83.         int currentYear = 0;
  84.         Paragraph title = null;
  85.         Chapter chapter = null;
  86.         Section section = null;
  87.  
  88.         for (Movie movie : movies) {
  89.             // add the chapter if we're in a new epoch
  90.             if (epoch < (movie.getYear() - 1940) / 10) {
  91.                 epoch = (movie.getYear() - 1940) / 10;
  92.                 if (chapter != null) {
  93.                     document.add(chapter);
  94.                 }
  95.                 title = new Paragraph(EPOCH[epoch], FONT[0]);
  96.                 chapter = new Chapter(title, epoch + 1);
  97.                 chapter.setBookmarkTitle(EPOCH[epoch]);
  98.             }
  99.             // switch to a new year
  100.             if (currentYear < movie.getYear()) {
  101.                 currentYear = movie.getYear();
  102.                 title = new Paragraph(
  103.                     String.format("The year %d", movie.getYear()), FONT[1]);
  104.                 section = chapter.addSection(title);
  105.                 section.setBookmarkTitle(String.valueOf(movie.getYear()));
  106.                 section.setIndentation(30);
  107.                 section.setBookmarkOpen(false);
  108.                 section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
  109.                 section.add(new Paragraph(
  110.                     String.format("Movies from the year %d:", movie.getYear())));
  111.             }
  112.             title = new Paragraph(movie.getMovieTitle(), FONT[2]);
  113.             section.add(title);
  114.             section.add(new Paragraph("Duration: " + movie.getDuration(), FONT[3]));
  115.             section.add(new Paragraph("Director(s):", FONT[3]));
  116.             section.add(PojoToElementFactory.getDirectorList(movie));
  117.             section.add(new Paragraph("Countries:", FONT[3]));
  118.             section.add(PojoToElementFactory.getCountryList(movie));
  119.         }
  120.         document.add(chapter);
  121.         // step 5
  122.         document.close();
  123.         connection.close();
  124.     }
  125.     /**
  126.      * Manipulates a PDF file src with the file dest as result
  127.      * @param src the original PDF
  128.      * @param dest the resulting PDF
  129.      * @throws IOException
  130.      * @throws DocumentException
  131.      */
  132.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  133.         PdfReader reader = new PdfReader(src);
  134.         PdfDictionary root = reader.getCatalog();
  135.         PdfDictionary outlines = root.getAsDict(PdfName.OUTLINES);
  136.         if (outlines == null)
  137.             return;
  138.         PdfArray dests = new PdfArray();
  139.         addKids(dests, outlines.getAsDict(PdfName.FIRST));
  140.         if (dests.size() == 0)
  141.             return;
  142.         PdfIndirectReference ref = reader.addPdfObject(dests);
  143.         PdfDictionary nametree = new PdfDictionary();
  144.         nametree.put(PdfName.NAMES, ref);
  145.         PdfDictionary names = new PdfDictionary();
  146.         names.put(PdfName.DESTS, nametree);
  147.         root.put(PdfName.NAMES, names);
  148.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  149.         stamper.close();
  150.         reader.close();
  151.     }
  152.    
  153.     /**
  154.      * Adds Outline dictionaries to an array of destinations.
  155.      * @param dests
  156.      * @param outline
  157.      */
  158.     public static void addKids(PdfArray dests, PdfDictionary outline) {
  159.         while (outline != null) {
  160.             dests.add(outline.getAsString(PdfName.TITLE));
  161.             dests.add(outline.getAsArray(PdfName.DEST));
  162.             addKids(dests, outline.getAsDict(PdfName.FIRST));
  163.             outline = outline.getAsDict(PdfName.NEXT);
  164.         }
  165.     }
  166.    
  167.     /**
  168.      * Main method.
  169.      *
  170.      * @param    args    no arguments needed
  171.      * @throws DocumentException
  172.      * @throws IOException
  173.      * @throws SQLException
  174.      */
  175.     public static void main(String[] args) throws IOException, DocumentException, SQLException {
  176.         Bookmarks2NamedDestinations example = new Bookmarks2NamedDestinations();
  177.         example.createPdf(RESULT1);
  178.         example.manipulatePdf(RESULT1, RESULT2);
  179.         new LinkActions().createXml(RESULT2, RESULT3);
  180.     }
  181. }
FixBrokenForm.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter13;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.DocumentException;
  14. import com.itextpdf.text.pdf.AcroFields;
  15. import com.itextpdf.text.pdf.PdfArray;
  16. import com.itextpdf.text.pdf.PdfDictionary;
  17. import com.itextpdf.text.pdf.PdfName;
  18. import com.itextpdf.text.pdf.PdfReader;
  19. import com.itextpdf.text.pdf.PdfStamper;
  20.  
  21. public class FixBrokenForm {
  22.  
  23.     /** The original PDF file. */
  24.     public static final String ORIGINAL = "resources/pdfs/broken_form.pdf";
  25.     /** The resulting PDF file. */
  26.     public static final String FIXED = "results/part4/chapter13/fixed_form.pdf";
  27.  
  28.     /** The original PDF file that couldn't be filled out. */
  29.     public static final String RESULT1 = "results/part4/chapter13/broken_form.pdf";
  30.     /** The fixed PDF file that was correctly filled out. */
  31.     public static final String RESULT2 = "results/part4/chapter13/filled_form.pdf";
  32.    
  33.     /**
  34.      * Manipulates a PDF file src with the file dest as result
  35.      * @param src the original PDF
  36.      * @param dest the resulting PDF
  37.      * @throws IOException
  38.      * @throws DocumentException
  39.      */
  40.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  41.         PdfReader reader = new PdfReader(src);
  42.         PdfDictionary root = reader.getCatalog();
  43.         PdfDictionary form = root.getAsDict(PdfName.ACROFORM);
  44.         PdfArray fields = form.getAsArray(PdfName.FIELDS);
  45.  
  46.         PdfDictionary page;
  47.         PdfArray annots;
  48.         for (int i = 1; i
InspectForm.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter13;
  8.  
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.io.OutputStreamWriter;
  12. import java.util.Map;
  13.  
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.pdf.AcroFields;
  16. import com.itextpdf.text.pdf.BaseField;
  17. import com.itextpdf.text.pdf.PdfDictionary;
  18. import com.itextpdf.text.pdf.PdfName;
  19. import com.itextpdf.text.pdf.PdfReader;
  20.  
  21. import part2.chapter08.Subscribe;
  22.  
  23. public class InspectForm {
  24.  
  25.     /** A text file containing information about a form. */
  26.     public static final String RESULTTXT = "results/part4/chapter13/fieldflags.txt";
  27.  
  28.     /**
  29.      * Inspects a PDF file src with the file dest as result
  30.      * @param src the original PDF
  31.      * @param dest the resulting PDF
  32.      * @throws IOException
  33.      * @throws DocumentException
  34.      */
  35.     public void inspectPdf(String src, String dest)
  36.         throws IOException, DocumentException {
  37.         OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(dest));
  38.         PdfReader reader = new PdfReader(src);
  39.         AcroFields form = reader.getAcroFields();
  40.         Map fields = form.getFields();
  41.         AcroFields.Item item;
  42.         PdfDictionary dict;
  43.         int flags;
  44.         for (Map.Entry entry : fields.entrySet()) {
  45.             out.write(entry.getKey());
  46.             item = entry.getValue();
  47.             dict = item.getMerged(0);
  48.             flags = dict.getAsNumber(PdfName.FF).intValue();
  49.             if ((flags & BaseField.PASSWORD) > 0)
  50.                 out.write(" -> password");
  51.             if ((flags & BaseField.MULTILINE) > 0)
  52.                 out.write(" -> multiline");
  53.             out.write('\n');
  54.         }
  55.         out.flush();
  56.         out.close();
  57.         reader.close();
  58.     }
  59.    
  60.     /**
  61.      * Inspects a form.
  62.      * @param args no arguments needed
  63.      * @throws IOException
  64.      * @throws DocumentException
  65.      */
  66.     public static void main(String[] args) throws IOException, DocumentException {
  67.         new Subscribe().createPdf(Subscribe.RESULT);
  68.         new InspectForm().inspectPdf(Subscribe.RESULT, RESULTTXT);
  69.     }
  70. }
AddJavaScriptToForm.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter13;
  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.Rectangle;
  18. import com.itextpdf.text.Utilities;
  19. import com.itextpdf.text.pdf.AcroFields;
  20. import com.itextpdf.text.pdf.BaseFont;
  21. import com.itextpdf.text.pdf.GrayColor;
  22. import com.itextpdf.text.pdf.PdfAction;
  23. import com.itextpdf.text.pdf.PdfContentByte;
  24. import com.itextpdf.text.pdf.PdfDictionary;
  25. import com.itextpdf.text.pdf.PdfFormField;
  26. import com.itextpdf.text.pdf.PdfName;
  27. import com.itextpdf.text.pdf.PdfReader;
  28. import com.itextpdf.text.pdf.PdfStamper;
  29. import com.itextpdf.text.pdf.PdfWriter;
  30. import com.itextpdf.text.pdf.PushbuttonField;
  31. import com.itextpdf.text.pdf.RadioCheckField;
  32. import com.itextpdf.text.pdf.TextField;
  33.  
  34. public class AddJavaScriptToForm {
  35.     /** The resulting PDF file. */
  36.     public static final String ORIGINAL
  37.         = "results/part4/chapter13/form_without_js.pdf";
  38.     /** The resulting PDF file. */
  39.     public static final String RESULT
  40.         = "results/part4/chapter13/form_with_js.pdf";
  41.     /** Path to the resources. */
  42.     public static final String RESOURCE
  43.         = "resources/js/extra.js";
  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) throws IOException, DocumentException {
  53.         // step 1
  54.         Document document = new Document();
  55.         // step 2
  56.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  57.         // step 3
  58.         document.open();
  59.         // step 4
  60.         BaseFont bf = BaseFont.createFont();
  61.         PdfContentByte directcontent = writer.getDirectContent();
  62.         directcontent.beginText();
  63.         directcontent.setFontAndSize(bf, 12);
  64.         directcontent.showTextAligned(Element.ALIGN_LEFT, "Married?", 36, 770, 0);
  65.         directcontent.showTextAligned(Element.ALIGN_LEFT, "YES", 58, 750, 0);
  66.         directcontent.showTextAligned(Element.ALIGN_LEFT, "NO", 102, 750, 0);
  67.         directcontent.showTextAligned(Element.ALIGN_LEFT, "Name partner?", 36, 730, 0);
  68.         directcontent.endText();
  69.         // create a radio button field
  70.         PdfFormField married = PdfFormField.createRadioButton(writer, true);
  71.         married.setFieldName("married");
  72.         married.setValueAsName("Yes");
  73.         Rectangle rectYes = new Rectangle(40, 766, 56, 744);
  74.         RadioCheckField yes = new RadioCheckField(writer, rectYes, null, "Yes");
  75.         yes.setChecked(true);
  76.         married.addKid(yes.getRadioField());
  77.         Rectangle rectNo = new Rectangle(84, 766, 100, 744);
  78.         RadioCheckField no = new RadioCheckField(writer, rectNo, null, "No");
  79.         no.setChecked(false);
  80.         married.addKid(no.getRadioField());
  81.         writer.addAnnotation(married);
  82.         // create a text field
  83.         Rectangle rect = new Rectangle(40, 710, 200, 726);
  84.         TextField partner = new TextField(writer, rect, "partner");
  85.         partner.setBorderColor(GrayColor.GRAYBLACK);
  86.         partner.setBorderWidth(0.5f);
  87.         writer.addAnnotation(partner.getTextField());
  88.         // step 5
  89.         document.close();
  90.     }
  91.    
  92.     /**
  93.      * Manipulates a PDF file src with the file dest as result
  94.      * @param src the original PDF
  95.      * @param dest the resulting PDF
  96.      * @throws IOException
  97.      * @throws DocumentException
  98.      */
  99.     public void manipulatePdf(String src, String dest)
  100.         throws IOException, DocumentException {
  101.         // Create a reader and a stamper
  102.         PdfReader reader = new PdfReader(src);
  103.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  104.         // Get the writer from the stamper
  105.         PdfWriter writer = stamper.getWriter();
  106.         // Add JavaScript
  107.         writer.addJavaScript(Utilities.readFileToString(RESOURCE));
  108.         // get the form fields
  109.         AcroFields form = stamper.getAcroFields();
  110.         AcroFields.Item fd = form.getFieldItem("married");
  111.         // Get the PDF dictionary of the YES radio button and add an additional action
  112.         PdfDictionary dictYes =
  113.             (PdfDictionary) PdfReader.getPdfObject(fd.getWidgetRef(0));
  114.         PdfDictionary yesAction = dictYes.getAsDict(PdfName.AA);
  115.         if (yesAction == null) yesAction = new PdfDictionary();
  116.         yesAction.put(new PdfName("Fo"),
  117.                 PdfAction.javaScript("setReadOnly(false);", stamper.getWriter()));
  118.         dictYes.put(PdfName.AA, yesAction);
  119.         // Get the PDF dictionary of the NO radio button and add an additional action
  120.         PdfDictionary dictNo =
  121.             (PdfDictionary) PdfReader.getPdfObject(fd.getWidgetRef(1));
  122.         PdfDictionary noAction = dictNo.getAsDict(PdfName.AA);
  123.         if (noAction == null) noAction = new PdfDictionary();
  124.         noAction.put(new PdfName("Fo"),
  125.                 PdfAction.javaScript("setReadOnly(true);", stamper.getWriter()));
  126.         dictNo.put(PdfName.AA, noAction);
  127.         // Create a submit button and add it to the stamper
  128.         PushbuttonField button = new PushbuttonField(writer,
  129.                 new Rectangle(40, 690, 200, 710), "submit");
  130.         button.setText("validate and submit");
  131.         button.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
  132.         PdfFormField validateAndSubmit = button.getField();
  133.         validateAndSubmit.setAction(PdfAction.javaScript("validate();", stamper.getWriter()));
  134.         stamper.addAnnotation(validateAndSubmit, 1);
  135.         // close the stamper
  136.         stamper.close();
  137.         reader.close();
  138.     }
  139.    
  140.     /**
  141.      * Main method.
  142.      *
  143.      * @param    args    no arguments needed
  144.      * @throws DocumentException
  145.      * @throws IOException
  146.      * @throws SQLException
  147.      */
  148.     public static void main(String[] args)
  149.         throws IOException, DocumentException {
  150.         AddJavaScriptToForm example = new AddJavaScriptToForm();
  151.         example.createPdf(ORIGINAL);
  152.         example.manipulatePdf(ORIGINAL, RESULT);
  153.     }
  154. }
ReplaceURL.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter13;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import part2.chapter08.ChildFieldEvent;
  14.  
  15. import com.itextpdf.text.Document;
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.Rectangle;
  18. import com.itextpdf.text.pdf.AcroFields;
  19. import com.itextpdf.text.pdf.GrayColor;
  20. import com.itextpdf.text.pdf.PdfAction;
  21. import com.itextpdf.text.pdf.PdfDictionary;
  22. import com.itextpdf.text.pdf.PdfFormField;
  23. import com.itextpdf.text.pdf.PdfName;
  24. import com.itextpdf.text.pdf.PdfPCell;
  25. import com.itextpdf.text.pdf.PdfPTable;
  26. import com.itextpdf.text.pdf.PdfReader;
  27. import com.itextpdf.text.pdf.PdfStamper;
  28. import com.itextpdf.text.pdf.PdfString;
  29. import com.itextpdf.text.pdf.PdfWriter;
  30. import com.itextpdf.text.pdf.PushbuttonField;
  31. import com.itextpdf.text.pdf.TextField;
  32.  
  33. public class ReplaceURL {
  34.  
  35.     /** The resulting PDF file. */
  36.     public static final String RESULT1
  37.         = "results/part4/chapter13/submit1.pdf";
  38.     /** The resulting PDF file. */
  39.     public static final String RESULT2
  40.         = "results/part4/chapter13/submit2.pdf";
  41.  
  42.     /**
  43.      * Creates a PDF document.
  44.      * @param filename the path to the new PDF document
  45.      * @throws    DocumentException
  46.      * @throws    IOException
  47.      */
  48.     public void createPdf(String filename) throws IOException, DocumentException {
  49.         // step 1
  50.         Document document = new Document();
  51.         // step 2
  52.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  53.         // step 3
  54.         document.open();
  55.         // step 4
  56.         PdfFormField personal = PdfFormField.createEmpty(writer);
  57.         personal.setFieldName("personal");
  58.         PdfPTable table = new PdfPTable(3);
  59.         PdfPCell cell;
  60.        
  61.         table.addCell("Your name:");
  62.         cell = new PdfPCell();
  63.         cell.setColspan(2);
  64.         TextField field = new TextField(writer, new Rectangle(0, 0), "name");
  65.         field.setFontSize(12);
  66.         cell.setCellEvent(new ChildFieldEvent(personal, field.getTextField(), 1));
  67.         table.addCell(cell);
  68.         table.addCell("Login:");
  69.         cell = new PdfPCell();
  70.         field = new TextField(writer, new Rectangle(0, 0), "loginname");
  71.         field.setFontSize(12);
  72.         cell.setCellEvent(new ChildFieldEvent(personal, field.getTextField(), 1));
  73.         table.addCell(cell);
  74.         cell = new PdfPCell();
  75.         field = new TextField(writer, new Rectangle(0, 0), "password");
  76.         field.setOptions(TextField.PASSWORD);
  77.         field.setFontSize(12);
  78.         cell.setCellEvent(new ChildFieldEvent(personal, field.getTextField(), 1));
  79.         table.addCell(cell);
  80.         table.addCell("Your motivation:");
  81.         cell = new PdfPCell();
  82.         cell.setColspan(2);
  83.         cell.setFixedHeight(60);
  84.         field = new TextField(writer, new Rectangle(0, 0), "reason");
  85.         field.setOptions(TextField.MULTILINE);
  86.         field.setFontSize(12);
  87.         cell.setCellEvent(new ChildFieldEvent(personal, field.getTextField(), 1));
  88.         table.addCell(cell);
  89.         document.add(table);
  90.         writer.addAnnotation(personal);
  91.        
  92.         PushbuttonField button1 = new PushbuttonField(
  93.             writer, new Rectangle(90, 660, 140, 690), "post");
  94.         button1.setText("POST");
  95.         button1.setBackgroundColor(new GrayColor(0.7f));
  96.         button1.setVisibility(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
  97.         PdfFormField submit1 = button1.getField();
  98.         submit1.setAction(PdfAction.createSubmitForm("/book/request", null,
  99.             PdfAction.SUBMIT_HTML_FORMAT | PdfAction.SUBMIT_COORDINATES));
  100.         writer.addAnnotation(submit1);
  101.         // step 5
  102.         document.close();
  103.     }
  104.    
  105.     /**
  106.      * Manipulates a PDF file src with the file dest as result
  107.      * @param src the original PDF
  108.      * @param dest the resulting PDF
  109.      * @throws IOException
  110.      * @throws DocumentException
  111.      */
  112.     public void manipulatePdf(String src, String dest)
  113.         throws IOException, DocumentException {
  114.         PdfReader reader = new PdfReader(src);
  115.         AcroFields form = reader.getAcroFields();
  116.         AcroFields.Item item = form.getFieldItem("post");
  117.         PdfDictionary field = item.getMerged(0);
  118.         PdfDictionary action = field.getAsDict(PdfName.A);
  119.         PdfDictionary f = action.getAsDict(PdfName.F);
  120.         f.put(PdfName.F, new PdfString("http://itextpdf.com:8080/book/request"));
  121.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  122.         stamper.close();
  123.         reader.close();
  124.     }
  125.    
  126.     /**
  127.      * Main method.
  128.      *
  129.      * @param    args    no arguments needed
  130.      * @throws DocumentException
  131.      * @throws IOException
  132.      */
  133.     public static void main(String[] args)
  134.         throws IOException, DocumentException {
  135.         ReplaceURL form = new ReplaceURL();
  136.         form.createPdf(RESULT1);
  137.         form.manipulatePdf(RESULT1, RESULT2);
  138.     }
  139. }
PdfXPdfA.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter13 {
  16.   public class PdfXPdfA : IWriter {
  17. // ===========================================================================
  18.     public const string RESULT1 = "x.pdf";
  19.     public const string RESULT2 = "a.pdf";
  20.     public const string FONT = "c:/windows/fonts/arial.ttf";
  21.     public static string PROFILE = Path.Combine(
  22.       Utility.ResourceImage, "sRGB.profile"
  23.     );
  24. // ---------------------------------------------------------------------------
  25.     public void Write(Stream stream) {
  26.       using (ZipFile zip = new ZipFile()) {
  27.         PdfXPdfA example = new PdfXPdfA();
  28.         zip.AddEntry(RESULT1, example.CreatePdfX());      
  29.         zip.AddEntry(RESULT2, example.CreatePdfA());      
  30.         zip.Save(stream);            
  31.       }
  32.     }    
  33. // ---------------------------------------------------------------------------
  34.   /**
  35.    * Creates a PDF document.
  36.    */      
  37.     public byte[] CreatePdfX() {
  38.       using (MemoryStream ms = new MemoryStream()) {
  39.         // step 1
  40.         using (Document document = new Document()) {
  41.         // step 2
  42.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  43.           writer.PDFXConformance = PdfWriter.PDFX1A2001;
  44.           // step 3
  45.           document.Open();
  46.           // step 4
  47.           Font font = FontFactory.GetFont(
  48.             FONT, BaseFont.CP1252, BaseFont.EMBEDDED, Font.UNDEFINED,
  49.             Font.UNDEFINED, new CMYKColor(255, 255, 0, 0)
  50.           );
  51.           document.Add(new Paragraph("Hello World", font));
  52.         }
  53.         return ms.ToArray();
  54.       }
  55.     }
  56. // ---------------------------------------------------------------------------
  57.     /**
  58.      * Creates a PDF document.
  59.      */
  60.     public byte[] CreatePdfA() {
  61.       using (MemoryStream ms = new MemoryStream()) {
  62.       // step 1
  63.         using (Document document = new Document()) {
  64.           // step 2
  65.           PdfAWriter writer = PdfAWriter.GetInstance(document, ms, PdfAConformanceLevel.PDF_A_1B);
  66.           writer.CreateXmpMetadata();    
  67.           // step 3
  68.           document.Open();
  69.           // step 4
  70.           Font font = FontFactory.GetFont(FONT, BaseFont.CP1252, BaseFont.EMBEDDED);
  71.           document.Add(new Paragraph("Hello World", font));
  72.           using (FileStream fs2 = new FileStream(
  73.               PROFILE, FileMode.Open, FileAccess.Read, FileShare.Read
  74.           ))
  75.           {
  76.             ICC_Profile icc = ICC_Profile.GetInstance(fs2);
  77.             writer.SetOutputIntents(
  78.               "Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc
  79.             );
  80.           }
  81.         }
  82.         return ms.ToArray();  
  83.       }  
  84.     }
  85. // ===========================================================================
  86.   }
  87. }
AppendMode.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Chapter01;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter13 {
  17.   public class AppendMode : IWriter {
  18. // ===========================================================================
  19.     /** The resulting PDF. */
  20.     public const String RESULT = "appended.pdf";
  21. // ---------------------------------------------------------------------------
  22.     public void Write(Stream stream) {
  23.       using (ZipFile zip = new ZipFile()) {
  24.         HelloWorld h = new HelloWorld();
  25.         byte[] pdf = Utility.PdfBytes(h);
  26.         zip.AddEntry(Utility.ResultFileName(h.ToString() + ".pdf"), pdf);      
  27.         AppendMode a = new AppendMode();      
  28.         zip.AddEntry(RESULT, a.ManipulatePdf(pdf));      
  29.         zip.Save(stream);            
  30.       }
  31.     }
  32. // ---------------------------------------------------------------------------
  33.     /**
  34.      * Manipulates a PDF file src with the file dest as result
  35.      * @param src the original PDF
  36.      * @throws DocumentException
  37.      */
  38.     public byte[] ManipulatePdf(byte[] src) {
  39.         PdfReader reader = new PdfReader(src);
  40.       using (MemoryStream ms = new MemoryStream()) {
  41.           using (PdfStamper stamper = new PdfStamper(reader, ms, '\0', true)) {
  42.             PdfContentByte cb = stamper.GetUnderContent(1);
  43.             cb.BeginText();
  44.             cb.SetFontAndSize(BaseFont.CreateFont(), 12);
  45.             cb.ShowTextAligned(Element.ALIGN_LEFT, "Hello People!", 36, 770, 0);
  46.             cb.EndText();
  47.         }
  48.         return ms.ToArray();
  49.         }
  50.     }
  51. // ===========================================================================
  52.   }
  53. }
PageLayoutExample.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  15. using kuujinbo.iTextInAction2Ed.Chapter02;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter13 {
  18.   public class PageLayoutExample : MovieParagraphs1 {
  19. // ===========================================================================
  20.     /** The resulting PDF file. */
  21.     public const string RESULT1 = "page_layout_single.pdf";
  22.     /** The resulting PDF file. */
  23.     public const string RESULT2 = "page_layout_column.pdf";
  24.     /** The resulting PDF file. */
  25.     public const string RESULT3 = "page_layout_columns_l.pdf";
  26.     /** The resulting PDF file. */
  27.     public const string RESULT4 = "page_layout_columns_r.pdf";
  28.     /** The resulting PDF file. */
  29.     public const string RESULT5 = "page_layout_pages_l.pdf";
  30.     /** The resulting PDF file. */
  31.     public const string RESULT6 = "page_layout_pages_r.pdf";
  32. // ---------------------------------------------------------------------------
  33.     public override void Write(Stream stream) {
  34.       using (ZipFile zip = new ZipFile()) {
  35.         PageLayoutExample example = new PageLayoutExample();
  36.         zip.AddEntry(RESULT1, example.CreatePdf(PdfWriter.PageLayoutSinglePage));
  37.         zip.AddEntry(RESULT2, example.CreatePdf(PdfWriter.PageLayoutOneColumn));
  38.         zip.AddEntry(RESULT3, example.CreatePdf(PdfWriter.PageLayoutTwoColumnLeft));
  39.         zip.AddEntry(RESULT4, example.CreatePdf(PdfWriter.PageLayoutTwoColumnRight));
  40.         zip.AddEntry(RESULT5, example.CreatePdf(PdfWriter.PageLayoutTwoPageLeft));
  41.         zip.AddEntry(RESULT6, example.CreatePdf(PdfWriter.PageLayoutTwoPageRight));      
  42.         zip.Save(stream);            
  43.       }
  44.     }
  45. // ---------------------------------------------------------------------------        
  46.     /**
  47.      * Creates a PDF with information about the movies
  48.      * @param pagelayout the value for the viewerpreferences
  49.      */
  50.     public byte[] CreatePdf(int viewerpreference) {
  51.       using (MemoryStream ms = new MemoryStream()) {
  52.         // step 1
  53.         using (Document document = new Document()) {
  54.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  55.           writer.PdfVersion = PdfWriter.VERSION_1_5;
  56.           writer.ViewerPreferences = viewerpreference;
  57.           // step 3
  58.           document.Open();
  59.           // step 4
  60.           foreach (Movie movie in PojoFactory.GetMovies()) {
  61.             Paragraph p = CreateMovieInformation(movie);
  62.             p.Alignment = Element.ALIGN_JUSTIFIED;
  63.             p.IndentationLeft = 18;
  64.             p.FirstLineIndent = -18;
  65.             document.Add(p);
  66.           }
  67.         }
  68.         return ms.ToArray();
  69.       }
  70.     }
  71. // ===========================================================================
  72.   }
  73. }
ViewerPreferencesExample.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter13 {
  16.   public class ViewerPreferencesExample : PageLayoutExample {
  17. // ===========================================================================
  18.     /** The resulting PDF file. */
  19.     public new const string RESULT1 = "viewerpreferences1.pdf";
  20.     /** The resulting PDF file. */
  21.     public new const string RESULT2 = "viewerpreferences2.pdf";
  22.     /** The resulting PDF file. */
  23.     public new const string RESULT3 = "viewerpreferences3.pdf";
  24.     /** The resulting PDF file. */
  25.     public new const string RESULT4 = "viewerpreferences4.pdf";
  26.     /** The resulting PDF file. */
  27.     public new const string RESULT5 = "viewerpreferences5.pdf";
  28.     /** The resulting PDF file. */
  29.     public new const string RESULT6 = "viewerpreferences6.pdf";
  30. // ---------------------------------------------------------------------------
  31.     public override void Write(Stream stream) {
  32.       using (ZipFile zip = new ZipFile()) {
  33.         ViewerPreferencesExample example = new ViewerPreferencesExample();
  34.         zip.AddEntry(RESULT1, example.CreatePdf(PdfWriter.PageModeFullScreen));
  35.         zip.AddEntry(RESULT2, example.CreatePdf(PdfWriter.PageModeUseThumbs));
  36.         zip.AddEntry(RESULT3, example.CreatePdf(
  37.           PdfWriter.PageLayoutTwoColumnRight | PdfWriter.PageModeUseThumbs
  38.         ));
  39.         zip.AddEntry(RESULT4, example.CreatePdf(
  40.           PdfWriter.PageModeFullScreen | PdfWriter.NonFullScreenPageModeUseOutlines
  41.         ));
  42.         zip.AddEntry(RESULT5, example.CreatePdf(
  43.           PdfWriter.FitWindow | PdfWriter.HideToolbar
  44.         ));
  45.         zip.AddEntry(RESULT6, example.CreatePdf(PdfWriter.HideWindowUI));      
  46.         zip.Save(stream);            
  47.       }
  48.     }
  49. // ===========================================================================
  50.   }
  51. }
PrintPreferencesExample.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter13 {
  16.   public class PrintPreferencesExample : IWriter {
  17. // ===========================================================================
  18.     public void Write(Stream stream) {
  19.       // step 1
  20.       using (Document document = new Document()) {
  21.         // step 2
  22.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  23.         writer.PdfVersion = PdfWriter.VERSION_1_5;
  24.         writer.AddViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
  25.         writer.AddViewerPreference(PdfName.NUMCOPIES, new PdfNumber(3));
  26.         writer.AddViewerPreference(PdfName.PICKTRAYBYPDFSIZE, PdfBoolean.PDFTRUE);        
  27.         // step 3
  28.         document.Open();
  29.         // step 4
  30.         document.Add(new Paragraph("Hello World!"));
  31.       }
  32.     }
  33. // ===========================================================================
  34.   }
  35. }
CropPages.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Chapter03;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter13 {
  17.   public class CropPages : IWriter {
  18. // ===========================================================================
  19.     /** The resulting PDF. */
  20.     public const String RESULT = "timetable_cropped.pdf";
  21. // ---------------------------------------------------------------------------
  22.     public void Write(Stream stream) {
  23.       using (ZipFile zip = new ZipFile()) {
  24.         MovieTemplates m = new MovieTemplates();
  25.         byte[] pdf = Utility.PdfBytes(m);
  26.         zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdf);
  27.         CropPages c = new CropPages();      
  28.         zip.AddEntry(RESULT, c.ManipulatePdf(pdf));      
  29.         zip.Save(stream);            
  30.       }
  31.     }
  32. // ---------------------------------------------------------------------------
  33.     /**
  34.      * Manipulates a PDF file src with the file dest as result
  35.      * @param src the original PDF
  36.      */
  37.     public byte[] ManipulatePdf(byte[] src) {
  38.       PdfReader reader = new PdfReader(src);
  39.       int n = reader.NumberOfPages;
  40.       PdfDictionary pageDict;
  41.       PdfRectangle rect = new PdfRectangle(55, 76, 560, 816);
  42.       for (int i = 1; i
RotatePages.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Chapter03;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter13 {
  17.   public class RotatePages : IWriter {
  18. // ===========================================================================
  19.     /** The resulting PDF. */
  20.     public const String RESULT = "timetable_rotated.pdf";
  21. // ---------------------------------------------------------------------------
  22.     public void Write(Stream stream) {
  23.       using (ZipFile zip = new ZipFile()) {
  24.         MovieTemplates m = new MovieTemplates();
  25.         byte[] pdf = Utility.PdfBytes(m);
  26.         zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdf);
  27.         RotatePages r = new RotatePages();      
  28.         zip.AddEntry(RESULT, r.ManipulatePdf(pdf));      
  29.         zip.Save(stream);            
  30.       }
  31.     }
  32. // ---------------------------------------------------------------------------
  33.     /**
  34.      * Manipulates a PDF file src
  35.      * @param src the original PDF
  36.      */
  37.     public byte[] ManipulatePdf(byte[] src) {
  38.       PdfReader reader = new PdfReader(src);
  39.       int n = reader.NumberOfPages;
  40.       int rot;
  41.       PdfDictionary pageDict;
  42.       for (int i = 1; i
RemoveLaunchActions.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Chapter07;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter13 {
  17.   public class RemoveLaunchActions : IWriter {
  18. // ===========================================================================
  19.     /** The resulting PDF. */
  20.     public const String RESULT = "launch_removed.pdf";
  21. // ---------------------------------------------------------------------------
  22.     public void Write(Stream stream) {
  23.       using (ZipFile zip = new ZipFile()) {
  24.         LaunchAction l = new LaunchAction();
  25.         byte[] pdf = Utility.PdfBytes(l);
  26.         zip.AddEntry(Utility.ResultFileName(l.ToString() + ".pdf"), pdf);
  27.         RemoveLaunchActions r = new RemoveLaunchActions();      
  28.         zip.AddEntry(RESULT, r.ManipulatePdf(pdf));      
  29.         zip.Save(stream);            
  30.       }
  31.     }    
  32. // ---------------------------------------------------------------------------
  33.     /**
  34.      * Manipulates a PDF file src
  35.      * @param src the original PDF
  36.      */
  37.     public byte[] ManipulatePdf(byte[] src) {
  38.       PdfReader reader = new PdfReader(src);
  39.       PdfObject obj;
  40.       PdfDictionary action;
  41.       for (int i = 1; i < reader.XrefSize; i++) {
  42.         obj = reader.GetPdfObject(i);
  43.         if (obj is PdfDictionary) {
  44.             action = ((PdfDictionary)obj).GetAsDict(PdfName.A);
  45.             if (action == null) continue;
  46.             if (PdfName.LAUNCH.Equals(action.GetAsName(PdfName.S))) {
  47.                 action.Remove(PdfName.F);
  48.                 action.Remove(PdfName.WIN);
  49.                 action.Put(PdfName.S, PdfName.JAVASCRIPT);
  50.                 action.Put(PdfName.JS, new PdfString(
  51.                   "app.alert('Launch Application Action removed by iText');\r"
  52.                 ));
  53.             }
  54.         }
  55.       }        
  56.       using (MemoryStream ms = new MemoryStream()) {
  57.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  58.         }
  59.         return ms.ToArray();
  60.       }
  61.     }
  62. // ===========================================================================
  63.   }
  64. }
PageLabelExample.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.Data;
  9. using System.Data.Common;
  10. using System.IO;
  11. using Ionic.Zip;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14. using System.Text;
  15. using iTextSharp.text;
  16. using iTextSharp.text.pdf;
  17. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  18.  
  19. namespace kuujinbo.iTextInAction2Ed.Chapter13 {
  20.   public class PageLabelExample : IWriter {
  21. // ===========================================================================
  22.     /** The resulting PDF file. */
  23.     public const string RESULT = "page_labels.pdf";
  24.     /** The resulting PDF file. */
  25.     public const string RESULT2 = "page_labels_changed.pdf";
  26.     /** A text file containing page numbers and labels. */
  27.     public const string LABELS = "page_labels.txt";
  28.     /** SQL statements */
  29.     public readonly string[] SQL = {
  30.       "SELECT country FROM film_country ORDER BY country",
  31.       "SELECT name FROM film_director ORDER BY name",
  32.       "SELECT title FROM film_movietitle ORDER BY title"
  33.     };
  34.     /** SQL statements */
  35.     public readonly string[] FIELD = { "country", "name", "title" };
  36. // ---------------------------------------------------------------------------
  37.     public void Write(Stream stream) {
  38.       using (ZipFile zip = new ZipFile()) {
  39.         PageLabelExample labels = new PageLabelExample();
  40.         byte[] pdf = labels.CreatePdf();
  41.         zip.AddEntry(RESULT, pdf);          
  42.         zip.AddEntry(LABELS, labels.ListPageLabels(pdf));          
  43.         zip.AddEntry(RESULT2, labels.ManipulatePageLabel(pdf));          
  44.         zip.Save(stream);            
  45.       }
  46.     }        
  47. // ---------------------------------------------------------------------------    
  48.     /**
  49.      * Creates a PDF document.
  50.      */
  51.     public byte[] CreatePdf() {
  52.       using (MemoryStream ms = new MemoryStream()) {
  53.         using (var c =  AdoDB.Provider.CreateConnection()) {
  54.           c.ConnectionString = AdoDB.CS;
  55.           c.Open();
  56.           // step 1
  57.           using (Document document = new Document(PageSize.A5)) {
  58.             // step 2
  59.             PdfWriter writer = PdfWriter.GetInstance(document, ms);
  60.             // step 3
  61.             document.Open();
  62.             // step 4
  63.             int[] start = new int[3];
  64.             for (int i = 0; i < 3; i++) {
  65.               start[i] = writer.PageNumber;
  66.               AddParagraphs(document, c, SQL[i], FIELD[i]);
  67.               document.NewPage();
  68.             }
  69.             PdfPageLabels labels = new PdfPageLabels();
  70.             labels.AddPageLabel(start[0], PdfPageLabels.UPPERCASE_LETTERS);
  71.             labels.AddPageLabel(start[1], PdfPageLabels.DECIMAL_ARABIC_NUMERALS);
  72.             labels.AddPageLabel(
  73.               start[2], PdfPageLabels.DECIMAL_ARABIC_NUMERALS,
  74.               "Movies-", start[2] - start[1] + 1
  75.             );
  76.             writer.PageLabels = labels;
  77.           }
  78.           return ms.ToArray();
  79.         }
  80.       }
  81.     }
  82. // ---------------------------------------------------------------------------    
  83.     public void AddParagraphs(
  84.         Document document, DbConnection connection, String sql, String field)
  85.     {
  86.       using (DbCommand cmd = connection.CreateCommand()) {
  87.         cmd.CommandText = sql;  
  88.         using (var r = cmd.ExecuteReader()) {
  89.           while (r.Read()) {
  90.             document.Add(new Paragraph(r[field].ToString()));
  91.           }
  92.         }
  93.       }
  94.     }
  95. // ---------------------------------------------------------------------------
  96.     /**
  97.      * Reads the page labels from an existing PDF
  98.      * @param src the existing PDF
  99.      */  
  100.     public string ListPageLabels(byte[] src) {
  101.       StringBuilder sb = new StringBuilder();
  102.       String[] labels = PdfPageLabels.GetPageLabels(new PdfReader(src));
  103.       for (int i = 0; i < labels.Length; i++) {
  104.         sb.Append(labels[i]);
  105.         sb.AppendLine();
  106.       }
  107.       return sb.ToString();
  108.     }
  109. // ---------------------------------------------------------------------------
  110.     /**
  111.      * Manipulates the page labels at the lowest PDF level.
  112.      * @param src  the source file
  113.      */  
  114.     public byte[] ManipulatePageLabel(byte[] src) {
  115.       PdfReader reader = new PdfReader(src);
  116.       PdfDictionary root = reader.Catalog;
  117.       PdfDictionary labels = root.GetAsDict(PdfName.PAGELABELS);
  118.       PdfArray nums = labels.GetAsArray(PdfName.NUMS);
  119.       int n;
  120.       PdfDictionary pagelabel;
  121.       for (int i = 0; i < nums.Size; i++) {
  122.         n = nums.GetAsNumber(i).IntValue;
  123.         i++;
  124.         if (n == 5) {
  125.           pagelabel = nums.GetAsDict(i);
  126.           pagelabel.Remove(PdfName.ST);
  127.           pagelabel.Put(PdfName.P, new PdfString("Film-"));
  128.         }
  129.       }
  130.       using (MemoryStream ms = new MemoryStream()) {
  131.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  132.         }
  133.         return ms.ToArray();
  134.       }
  135.     }    
  136. // ===========================================================================
  137.   }
  138. }
Bookmarks2NamedDestinations.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  15. using kuujinbo.iTextInAction2Ed.Chapter07;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter13 {
  18.   public class Bookmarks2NamedDestinations : IWriter {
  19. // ===========================================================================
  20.     /** The resulting PDF file. */
  21.     public const string RESULT1 = "bookmarks.pdf";
  22.     /** The resulting PDF file. */
  23.     public const string RESULT2 = "named_destinations.pdf";
  24.     /** The resulting PDF file. */
  25.     public const string RESULT3 = "named_destinations.xml";
  26.    
  27.     /** The different epochs. */
  28.     public readonly string[] EPOCH = {
  29.       "Forties", "Fifties", "Sixties", "Seventies", "Eighties",
  30.       "Nineties", "Twenty-first Century"
  31.     };
  32.     /** The fonts for the title. */
  33.     public readonly Font[] FONT = {
  34.       new Font(Font.FontFamily.HELVETICA, 24),
  35.       new Font(Font.FontFamily.HELVETICA, 18),
  36.       new Font(Font.FontFamily.HELVETICA, 14),
  37.       new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD)
  38.     };
  39. // ---------------------------------------------------------------------------
  40.     public void Write(Stream stream) {
  41.       using (ZipFile zip = new ZipFile()) {
  42.         Bookmarks2NamedDestinations example = new Bookmarks2NamedDestinations();
  43.         byte[] pdf = example.CreatePdf();
  44.         zip.AddEntry(RESULT1, pdf);
  45.         pdf = example.ManipulatePdf(pdf);
  46.         zip.AddEntry(RESULT2, pdf);
  47.         zip.AddEntry(RESULT3, new LinkActions().CreateXml(pdf));
  48.         zip.Save(stream);            
  49.       }
  50.     }
  51. // ---------------------------------------------------------------------------    
  52.     /**
  53.      * Creates a PDF document.
  54.      */
  55.     public byte[] CreatePdf() {
  56.       using (MemoryStream ms = new MemoryStream()) {
  57.         // step 1
  58.         using (Document document = new Document()) {
  59.           // step 2
  60.           PdfWriter.GetInstance(document, ms);
  61.           // step 3
  62.           document.Open();
  63.           // step 4
  64.           int epoch = -1;
  65.           int currentYear = 0;
  66.           Paragraph title = null;
  67.           Chapter chapter = null;
  68.           Section section = null;
  69.           bool sortByYear = true;
  70.           foreach (Movie movie in PojoFactory.GetMovies(sortByYear)) {
  71.             // add the chapter if we're in a new epoch
  72.             if (epoch < (movie.Year - 1940) / 10) {
  73.               epoch = (movie.Year - 1940) / 10;
  74.               if (chapter != null) {
  75.                 document.Add(chapter);
  76.               }
  77.               title = new Paragraph(EPOCH[epoch], FONT[0]);
  78.               chapter = new Chapter(title, epoch + 1);
  79.               chapter.BookmarkTitle = EPOCH[epoch];
  80.             }
  81.             // switch to a new year
  82.             if (currentYear < movie.Year) {
  83.               currentYear = movie.Year;
  84.               title = new Paragraph(
  85.                 String.Format("The year {0}", movie.Year), FONT[1]
  86.               );
  87.               section = chapter.AddSection(title);
  88.               section.BookmarkTitle = movie.Year.ToString();
  89.               section.Indentation = 30;
  90.               section.BookmarkOpen = false;
  91.               section.NumberStyle = Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT;
  92.               section.Add(new Paragraph(
  93.                 String.Format("Movies from the year {0}:", movie.Year)
  94.               ));
  95.             }
  96.             title = new Paragraph(movie.MovieTitle, FONT[2]);
  97.             section.Add(title);
  98.             section.Add(new Paragraph(
  99.               "Duration: " + movie.Duration.ToString(), FONT[3]
  100.             ));
  101.             section.Add(new Paragraph("Director(s):", FONT[3]));
  102.             section.Add(PojoToElementFactory.GetDirectorList(movie));
  103.             section.Add(new Paragraph("Countries:", FONT[3]));
  104.             section.Add(PojoToElementFactory.GetCountryList(movie));
  105.           }
  106.           document.Add(chapter);
  107.         }
  108.         return ms.ToArray();
  109.       }      
  110.     }
  111. // ---------------------------------------------------------------------------  
  112.     /**
  113.      * Manipulates a PDF file src with the file dest as result
  114.      * @param src the original PDF
  115.      */
  116.     public byte[] ManipulatePdf(byte[] src) {
  117.       PdfReader reader = new PdfReader(src);
  118.       PdfDictionary root = reader.Catalog;
  119.       PdfDictionary outlines = root.GetAsDict(PdfName.OUTLINES);
  120.       if (outlines == null) return null;
  121.      
  122.       PdfArray dests = new PdfArray();
  123.       AddKids(dests, outlines.GetAsDict(PdfName.FIRST));
  124.       if (dests.Size == 0) return null;
  125.      
  126.       PdfIndirectReference pir = reader.AddPdfObject(dests);
  127.       PdfDictionary nametree = new PdfDictionary();
  128.       nametree.Put(PdfName.NAMES, pir);
  129.       PdfDictionary names = new PdfDictionary();
  130.       names.Put(PdfName.DESTS, nametree);
  131.       root.Put(PdfName.NAMES, names);
  132.       using (MemoryStream ms = new MemoryStream()) {
  133.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  134.         }
  135.         return ms.ToArray();
  136.       }
  137.     }
  138. // ---------------------------------------------------------------------------    
  139.     public void AddKids(PdfArray dests, PdfDictionary outline) {
  140.       while (outline != null) {
  141.         dests.Add(outline.GetAsString(PdfName.TITLE));
  142.         dests.Add(outline.GetAsArray(PdfName.DEST));
  143.         AddKids(dests, outline.GetAsDict(PdfName.FIRST));
  144.         outline = outline.GetAsDict(PdfName.NEXT);
  145.       }
  146.     }    
  147. // ===========================================================================
  148.   }
  149. }
FixBrokenForm.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter13 {
  16.   public class FixBrokenForm : IWriter {
  17. // ===========================================================================
  18.     /** The resulting PDF file. */
  19.     public readonly string ORIGINAL = Path.Combine(
  20.       Utility.ResourcePdf, "broken_form.pdf"
  21.     );
  22.     /** The resulting PDF file. */
  23.     public const string FIXED = "fixed_form.pdf";
  24.     /* NAME DIFFERENT FROM THE EXAMPLE FOR IMPROVED CLARITY */
  25.     public const string RESULT1 = "broken_form_not_filled.pdf";
  26.     public const string RESULT2 = "filled_form.pdf";
  27. // ---------------------------------------------------------------------------
  28.     public void Write(Stream stream) {
  29.       using (ZipFile zip = new ZipFile()) {
  30.         zip.AddFile(ORIGINAL, "");
  31.         FixBrokenForm example = new FixBrokenForm();
  32.         byte[] pdf = example.ManipulatePdf(ORIGINAL);
  33.         zip.AddEntry(FIXED, pdf);
  34.         zip.AddEntry(RESULT1, example.FillData(new PdfReader(ORIGINAL)));
  35.         zip.AddEntry(RESULT2, example.FillData(new PdfReader(pdf)));
  36.         zip.Save(stream);            
  37.       }
  38.     }    
  39. // ---------------------------------------------------------------------------
  40.     /**
  41.      * Manipulates a PDF file src with the file dest as result
  42.      * @param src the original PDF
  43.      */
  44.     public byte[] ManipulatePdf(string src) {
  45.       PdfReader reader = new PdfReader(src);
  46.       PdfDictionary root = reader.Catalog;
  47.       PdfDictionary form = root.GetAsDict(PdfName.ACROFORM);
  48.       PdfArray fields = form.GetAsArray(PdfName.FIELDS);
  49.       PdfDictionary page;
  50.       PdfArray annots;
  51.       for (int i = 1; i
InspectForm.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Text;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using kuujinbo.iTextInAction2Ed.Chapter08;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter13 {
  18.   public class InspectForm : IWriter {
  19. // ===========================================================================
  20.     /** A text file containing information about a form. */
  21.     public const String RESULTTXT = "fieldflags.txt";
  22. // ---------------------------------------------------------------------------
  23.     public void Write(Stream stream) {
  24.       using (ZipFile zip = new ZipFile()) {
  25.         Subscribe s = new Subscribe();
  26.         byte[] pdf = s.CreatePdf();
  27.         zip.AddEntry(Utility.ResultFileName(s.ToString() + ".pdf"), pdf);
  28.         InspectForm i = new InspectForm();
  29.         zip.AddEntry(RESULTTXT, i.InspectPdf(pdf));            
  30.         zip.Save(stream);            
  31.       }
  32.     }    
  33. // ---------------------------------------------------------------------------
  34.     /**
  35.      * Inspects a PDF file src with the file dest as result
  36.      * @param src the original PDF
  37.      */
  38.     public string InspectPdf(byte[] src) {
  39.       PdfReader reader = new PdfReader(src);
  40.       AcroFields form = reader.AcroFields;
  41.       IDictionary fields = form.Fields;
  42.       AcroFields.Item item;
  43.       PdfDictionary dict;
  44.       int flags;
  45.       StringBuilder sb = new StringBuilder();
  46.       foreach (string key in fields.Keys) {
  47.           sb.Append(key);
  48.           item = fields[key];
  49.           dict = item.GetMerged(0);
  50.           flags = dict.GetAsNumber(PdfName.FF).IntValue;
  51.           if ((flags & BaseField.PASSWORD) > 0)
  52.               sb.Append(" -> password");
  53.           if ((flags & BaseField.MULTILINE) > 0)
  54.               sb.Append(" -> multiline");
  55.           sb.Append(Environment.NewLine);
  56.       }        
  57.       return sb.ToString();
  58.     }
  59. // ===========================================================================
  60.   }
  61. }
AddJavaScriptToForm.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter13 {
  16.   public class AddJavaScriptToForm : IWriter {
  17. // ===========================================================================
  18.     /** The resulting PDF file. */
  19.     public const string ORIGINAL = "form_without_js.pdf";
  20.     /** The resulting PDF file. */
  21.     public const string RESULT = "form_with_js.pdf";
  22.     /** Path to the resources. */
  23.     public readonly string RESOURCE = Path.Combine(
  24.       Utility.ResourceJavaScript, "extra.js"
  25.     );
  26. // ---------------------------------------------------------------------------
  27.     public void Write(Stream stream) {
  28.       using (ZipFile zip = new ZipFile()) {
  29.         zip.AddFile(RESOURCE, "");
  30.           AddJavaScriptToForm example = new AddJavaScriptToForm();
  31.           byte[] pdf = example.CreatePdf();
  32.         zip.AddEntry(ORIGINAL, pdf);
  33.         zip.AddEntry(RESULT, example.ManipulatePdf(pdf));        
  34.         zip.Save(stream);            
  35.       }
  36.     }    
  37. // ---------------------------------------------------------------------------    
  38.     /**
  39.      * Creates a PDF document.
  40.      */
  41.       public byte[] CreatePdf() {
  42.           using (MemoryStream ms = new MemoryStream()) {
  43.             using (Document document = new Document()) {
  44.               PdfWriter writer = PdfWriter.GetInstance(document, ms);
  45.               document.Open();
  46.        
  47.               BaseFont bf = BaseFont.CreateFont();
  48.               PdfContentByte directcontent = writer.DirectContent;
  49.               directcontent.BeginText();
  50.               directcontent.SetFontAndSize(bf, 12);
  51.               directcontent.ShowTextAligned(Element.ALIGN_LEFT, "Married?", 36, 770, 0);
  52.               directcontent.ShowTextAligned(Element.ALIGN_LEFT, "YES", 58, 750, 0);
  53.               directcontent.ShowTextAligned(Element.ALIGN_LEFT, "NO", 102, 750, 0);
  54.               directcontent.ShowTextAligned(
  55.                 Element.ALIGN_LEFT, "Name partner?", 36, 730, 0
  56.               );
  57.               directcontent.EndText();
  58.        
  59.               PdfFormField married = PdfFormField.CreateRadioButton(writer, true);
  60.               married.FieldName = "married";
  61.               married.ValueAsName = "yes";
  62.               Rectangle rectYes = new Rectangle(40, 766, 56, 744);
  63.               RadioCheckField yes = new RadioCheckField(writer, rectYes, null, "yes");
  64.               yes.Checked = true;
  65.               married.AddKid(yes.RadioField);
  66.               Rectangle rectNo = new Rectangle(84, 766, 100, 744);
  67.               RadioCheckField no = new RadioCheckField(writer, rectNo, null, "no");
  68.               no.Checked = false;
  69.               married.AddKid(no.RadioField);
  70.               writer.AddAnnotation(married);
  71.        
  72.               Rectangle rect = new Rectangle(40, 710, 200, 726);
  73.               TextField partner = new TextField(writer, rect, "partner");
  74.               partner.BorderColor = GrayColor.GRAYBLACK;
  75.               partner.BorderWidth = 0.5f;
  76.               writer.AddAnnotation(partner.GetTextField());
  77.             }
  78.         return ms.ToArray();
  79.           }
  80.       }
  81. // ---------------------------------------------------------------------------          
  82.     /**
  83.      * Manipulates a PDF file src with the file dest as result
  84.      * @param src the original PDF
  85.      */
  86.     public byte[] ManipulatePdf(byte[] src) {
  87.         PdfReader reader = new PdfReader(src);
  88.       using (MemoryStream ms = new MemoryStream()) {
  89.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  90.           stamper.Writer.AddJavaScript(File.ReadAllText(RESOURCE));
  91.           AcroFields form = stamper.AcroFields;
  92.           AcroFields.Item fd = form.GetFieldItem("married");
  93.    
  94.           PdfDictionary dictYes =
  95.               (PdfDictionary) PdfReader.GetPdfObject(fd.GetWidgetRef(0));
  96.           PdfDictionary yesAction = dictYes.GetAsDict(PdfName.AA);
  97.           if (yesAction == null) yesAction = new PdfDictionary();
  98.           yesAction.Put(
  99.             new PdfName("Fo"),
  100.               PdfAction.JavaScript("ReadOnly = false);", stamper.Writer)
  101.           );
  102.           dictYes.Put(PdfName.AA, yesAction);
  103.    
  104.           PdfDictionary dictNo =
  105.               (PdfDictionary) PdfReader.GetPdfObject(fd.GetWidgetRef(1));
  106.           PdfDictionary noAction = dictNo.GetAsDict(PdfName.AA);
  107.           if (noAction == null) noAction = new PdfDictionary();
  108.           noAction.Put(
  109.             new PdfName("Fo"),
  110.               PdfAction.JavaScript("ReadOnly = true);", stamper.Writer)
  111.           );
  112.           dictNo.Put(PdfName.AA, noAction);
  113.    
  114.               PdfWriter writer = stamper.Writer;
  115.               PushbuttonField button = new PushbuttonField(
  116.                 writer, new Rectangle(40, 690, 200, 710), "submit"
  117.                   );
  118.               button.Text = "validate and submit";
  119.               button.Options = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT;
  120.               PdfFormField validateAndSubmit = button.Field;
  121.               validateAndSubmit.Action = PdfAction.JavaScript(
  122.                 "validate();", stamper.Writer
  123.               );
  124.               stamper.AddAnnotation(validateAndSubmit, 1);
  125.             }
  126.             return ms.ToArray();
  127.           }
  128.     }    
  129. // ===========================================================================
  130.   }
  131. }
ReplaceURL.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using Ionic.Zip;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using kuujinbo.iTextInAction2Ed.Chapter08;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter13 {
  17.   public class ReplaceURL : IWriter {
  18. // ===========================================================================
  19.     /** The resulting PDF file. */
  20.     public const string RESULT1 = "submit1.pdf";
  21.     /** The resulting PDF file. */
  22.     public const string RESULT2 = "submit2.pdf";
  23. // ---------------------------------------------------------------------------
  24.     public void Write(Stream stream) {
  25.       using (ZipFile zip = new ZipFile()) {
  26.         ReplaceURL form = new ReplaceURL();
  27.           byte[] pdf = form.CreatePdf();
  28.         zip.AddEntry(RESULT1, pdf);
  29.         zip.AddEntry(RESULT2, form.ManipulatePdf(pdf));        
  30.         zip.Save(stream);            
  31.       }
  32.     }    
  33. // ---------------------------------------------------------------------------    
  34.     /**
  35.      * Creates a PDF document.
  36.      */
  37.     public byte[] CreatePdf() {
  38.           using (MemoryStream ms = new MemoryStream()) {
  39.             using (Document document = new Document()) {
  40.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  41.           document.Open();
  42.           PdfFormField personal = PdfFormField.CreateEmpty(writer);
  43.           personal.FieldName = "personal";
  44.           PdfPTable table = new PdfPTable(3);
  45.           PdfPCell cell;
  46.          
  47.           table.AddCell("Your name:");
  48.           cell = new PdfPCell();
  49.           cell.Colspan = 2;
  50.           TextField field = new TextField(writer, new Rectangle(0, 0), "name");
  51.           field.FontSize = 12;
  52.           cell.CellEvent = new ChildFieldEvent(
  53.             personal, field.GetTextField(), 1
  54.           );
  55.           table.AddCell(cell);
  56.           table.AddCell("Login:");
  57.           cell = new PdfPCell();
  58.           field = new TextField(writer, new Rectangle(0, 0), "loginname");
  59.           field.FontSize = 12;
  60.           cell.CellEvent = new ChildFieldEvent(
  61.             personal, field.GetTextField(), 1
  62.           );
  63.           table.AddCell(cell);
  64.           cell = new PdfPCell();
  65.           field = new TextField(writer, new Rectangle(0, 0), "password");
  66.           field.Options = TextField.PASSWORD;
  67.           field.FontSize = 12;
  68.           cell.CellEvent = new ChildFieldEvent(
  69.             personal, field.GetTextField(), 1
  70.           );
  71.           table.AddCell(cell);
  72.           table.AddCell("Your motivation:");
  73.           cell = new PdfPCell();
  74.           cell.Colspan = 2;
  75.           cell.FixedHeight = 60;
  76.           field = new TextField(writer, new Rectangle(0, 0), "reason");
  77.           field.Options = TextField.MULTILINE;
  78.           field.FontSize = 12;
  79.           cell.CellEvent = new ChildFieldEvent(
  80.             personal, field.GetTextField(), 1
  81.           );
  82.           table.AddCell(cell);
  83.           document.Add(table);
  84.           writer.AddAnnotation(personal);
  85.          
  86.           PushbuttonField button1 = new PushbuttonField(
  87.               writer, new Rectangle(90, 660, 140, 690), "post");
  88.           button1.Text = "POST";
  89.           button1.BackgroundColor = new GrayColor(0.7f);
  90.           button1.Visibility = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT;
  91.           PdfFormField submit1 = button1.Field;
  92.           submit1.Action = PdfAction.CreateSubmitForm(
  93.             "/book/request", null,
  94.             PdfAction.SUBMIT_HTML_FORMAT | PdfAction.SUBMIT_COORDINATES
  95.           );
  96.           writer.AddAnnotation(submit1);
  97.         }
  98.         return ms.ToArray();
  99.       }
  100.     }
  101. // ---------------------------------------------------------------------------
  102.     /**
  103.      * Manipulates a PDF file src with the file dest as result
  104.      * @param src the original PDF
  105.      */
  106.     public byte[] ManipulatePdf(byte[] src) {
  107.         PdfReader reader = new PdfReader(src);
  108.         AcroFields form = reader.AcroFields;
  109.         AcroFields.Item item = form.GetFieldItem("post");
  110.         PdfDictionary field = item.GetMerged(0);
  111.         PdfDictionary action = field.GetAsDict(PdfName.A);
  112.         PdfDictionary f = action.GetAsDict(PdfName.F);
  113.         f.Put(PdfName.F, new PdfString("http://NON-EXISTENT-DOMAIN.invalid/"));
  114.           using (MemoryStream ms = new MemoryStream()) {
  115.           using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  116.           }
  117.           return ms.ToArray();
  118.       }
  119.     }
  120. // ===========================================================================
  121.   }
  122. }
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