iText pdf library
Website search

Chapter 13: PDFs inside-out

These examples were written in the context of Chapter 13 of the book "iText in Action - Second Edition".

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


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