Chapter 10: Brightening up your PDF with color and images

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

10th October 2015
admin-marketing

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

DeviceColor.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
/*
 * 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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.CMYKColor;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;
 
public class DeviceColor {
 
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter10/device_color.pdf";
    
    /**
     * Draws a colored rectangle.
     * @param canvas the canvas to draw on
     * @param color the Color
     * @param x the X coordinate
     * @param y the Y coordinate
     * @param width the width of the rectangle
     * @param height the height of the rectangle
     */
    public void colorRectangle(PdfContentByte canvas,
        BaseColor color, float x, float y, float width, float height) {
        canvas.saveState();
        canvas.setColorFill(color);
        canvas.rectangle(x, y, width, height);
        canvas.fillStroke();
        canvas.restoreState();
    }
 
    /**
     * 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
        PdfContentByte canvas = writer.getDirectContent();
        // RGB Colors
        colorRectangle(canvas, new BaseColor(0x00, 0x00, 0x00), 36, 770, 36, 36);
        colorRectangle(canvas, new BaseColor(0x00, 0x00, 0xFF), 90, 770, 36, 36);
        colorRectangle(canvas, new BaseColor(0x00, 0xFF, 0x00), 144, 770, 36, 36);
        colorRectangle(canvas, new BaseColor(0xFF, 0x00, 0x00), 198, 770, 36, 36);
        colorRectangle(canvas, new BaseColor(0f, 1f, 1f), 252, 770, 36, 36);
        colorRectangle(canvas, new BaseColor(1f, 0f, 1f), 306, 770, 36, 36);
        colorRectangle(canvas, new BaseColor(1f, 1f, 0f), 360, 770, 36, 36);
        colorRectangle(canvas, BaseColor.BLACK, 416, 770, 36, 36);
        colorRectangle(canvas, BaseColor.LIGHT_GRAY, 470, 770, 36, 36);
        // CMYK Colors
        colorRectangle(canvas, new CMYKColor(0x00, 0x00, 0x00, 0x00), 36, 716, 36, 36);
        colorRectangle(canvas, new CMYKColor(0x00, 0x00, 0xFF, 0x00), 90, 716, 36, 36);
        colorRectangle(canvas, new CMYKColor(0x00, 0x00, 0xFF, 0xFF), 144, 716, 36, 36);
        colorRectangle(canvas, new CMYKColor(0x00, 0xFF, 0x00, 0x00), 198, 716, 36, 36);
        colorRectangle(canvas, new CMYKColor(0f, 1f, 0f, 0.5f), 252, 716, 36, 36);
        colorRectangle(canvas, new CMYKColor(1f, 0f, 0f, 0f), 306, 716, 36, 36);
        colorRectangle(canvas, new CMYKColor(1f, 0f, 0f, 0.5f), 360, 716, 36, 36);
        colorRectangle(canvas, new CMYKColor(1f, 0f, 0f, 1f), 416, 716, 36, 36);
        colorRectangle(canvas, new CMYKColor(0f, 0f, 0f, 1f), 470, 716, 36, 36);
        // Gray color
        colorRectangle(canvas, new GrayColor(0x20), 36, 662, 36, 36);
        colorRectangle(canvas, new GrayColor(0x40), 90, 662, 36, 36);
        colorRectangle(canvas, new GrayColor(0x60), 144, 662, 36, 36);
        colorRectangle(canvas, new GrayColor(0.5f), 198, 662, 36, 36);
        colorRectangle(canvas, new GrayColor(0.625f), 252, 662, 36, 36);
        colorRectangle(canvas, new GrayColor(0.75f), 306, 662, 36, 36);
        colorRectangle(canvas, new GrayColor(0.825f), 360, 662, 36, 36);
        colorRectangle(canvas, GrayColor.GRAYBLACK, 416, 662, 36, 36);
        colorRectangle(canvas, GrayColor.GRAYWHITE, 470, 662, 36, 36);
        // Alternative ways to color the rectangle
        canvas.setRGBColorFill(0x00, 0x80, 0x80);
        canvas.rectangle(36, 608, 36, 36);
        canvas.fillStroke();
        canvas.setRGBColorFillF(0.5f, 0.25f, 0.60f);
        canvas.rectangle(90, 608, 36, 36);
        canvas.fillStroke();
        canvas.setGrayFill(0.5f);
        canvas.rectangle(144, 608, 36, 36);
        canvas.fillStroke();
        canvas.setCMYKColorFill(0xFF, 0xFF, 0x00, 0x80);
        canvas.rectangle(198, 608, 36, 36);
        canvas.fillStroke();
        canvas.setCMYKColorFillF(0f, 1f, 1f, 0.5f);
        canvas.rectangle(252, 608, 36, 36);
        canvas.fillStroke();
 
        // step 5
        document.close();
    }
 
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new DeviceColor().createPdf(RESULT);
    }
}
SeparationColor.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
/*
 * 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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.CMYKColor;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfSpotColor;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.SpotColor;
 
public class SeparationColor extends DeviceColor {
    
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter10/separation_color.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
        PdfContentByte canvas = writer.getDirectContent();
        PdfSpotColor psc_g = new PdfSpotColor(
            "iTextSpotColorGray", new GrayColor(0.9f));
        PdfSpotColor psc_rgb = new PdfSpotColor(
            "iTextSpotColorRGB", new BaseColor(0x64, 0x95, 0xed));
        PdfSpotColor psc_cmyk = new PdfSpotColor(
            "iTextSpotColorCMYK", new CMYKColor(0.3f, .9f, .3f, .1f));
 
        colorRectangle(canvas, new SpotColor(psc_g, 0.5f), 36, 770, 36, 36);
        colorRectangle(canvas, new SpotColor(psc_rgb, 0.1f), 90, 770, 36, 36);
        colorRectangle(canvas, new SpotColor(psc_rgb, 0.2f), 144, 770, 36, 36); 
        colorRectangle(canvas, new SpotColor(psc_rgb, 0.3f), 198, 770, 36, 36); 
        colorRectangle(canvas, new SpotColor(psc_rgb, 0.4f), 252, 770, 36, 36); 
        colorRectangle(canvas, new SpotColor(psc_rgb, 0.5f), 306, 770, 36, 36); 
        colorRectangle(canvas, new SpotColor(psc_rgb, 0.6f), 360, 770, 36, 36); 
        colorRectangle(canvas, new SpotColor(psc_rgb, 0.7f), 416, 770, 36, 36); 
        colorRectangle(canvas, new SpotColor(psc_cmyk, 0.25f), 470, 770, 36, 36);
        
        canvas.setColorFill(psc_g, 0.5f);
        canvas.rectangle(36, 716, 36, 36);
        canvas.fillStroke();
        canvas.setColorFill(psc_g, 0.9f);
        canvas.rectangle(90, 716, 36, 36);
        canvas.fillStroke();
        canvas.setColorFill(psc_rgb, 0.5f);
        canvas.rectangle(144, 716, 36, 36);
        canvas.fillStroke();
        canvas.setColorFill(psc_rgb, 0.9f);
        canvas.rectangle(198, 716, 36, 36);
        canvas.fillStroke();
        canvas.setColorFill(psc_cmyk, 0.5f);
        canvas.rectangle(252, 716, 36, 36);
        canvas.fillStroke();
        canvas.setColorFill(psc_cmyk, 0.9f);
        canvas.rectangle(306, 716, 36, 36);
        canvas.fillStroke();
 
        // step 5
        document.close();
    }
 
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new SeparationColor().createPdf(RESULT);
    }
}
TilingPatternColor.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
/*
 * 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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PatternColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPatternPainter;
import com.itextpdf.text.pdf.PdfWriter;
 
public class TilingPatternColor extends DeviceColor {
 
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter10/tiling_pattern.pdf";
 
    /** An image that will be used for a pattern color. */
    public static final String RESOURCE
        = "resources/img/info.png";
 
    /**
     * 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
        PdfContentByte canvas = writer.getDirectContent();
        PdfPatternPainter square
            = canvas.createPattern(15, 15);
        square.setColorFill(new BaseColor(0xFF, 0xFF, 0x00));
        square.setColorStroke(new BaseColor(0xFF, 0x00, 0x00));
        square.rectangle(5, 5, 5, 5);
        square.fillStroke();
        
        PdfPatternPainter ellipse
            = canvas.createPattern(15, 10, 20, 25);
        ellipse.setColorFill(new BaseColor(0xFF, 0xFF, 0x00));
        ellipse.setColorStroke(new BaseColor(0xFF, 0x00, 0x00));
        ellipse.ellipse(2f, 2f, 13f, 8f);
        ellipse.fillStroke();
        
        PdfPatternPainter circle
            = canvas.createPattern(15, 15, 10, 20, BaseColor.BLUE);
        circle.circle(7.5f, 7.5f, 2.5f);
        circle.fill();
        
        PdfPatternPainter line
            = canvas.createPattern(5, 10, null);
        line.setLineWidth(1);
        line.moveTo(3, -1);
        line.lineTo(3, 11);
        line.stroke();
        
        Image img = Image.getInstance(RESOURCE);
        img.scaleAbsolute(20, 20);
        img.setAbsolutePosition(0, 0);
        PdfPatternPainter img_pattern
            = canvas.createPattern(20, 20, 20, 20);
        img_pattern.addImage(img);
        img_pattern.setPatternMatrix(-0.5f, 0f, 0f, 0.5f, 0f, 0f);
        
        colorRectangle(canvas, new PatternColor(square), 36, 696, 126, 126);
        colorRectangle(canvas, new PatternColor(ellipse), 180, 696, 126, 126);
        colorRectangle(canvas, new PatternColor(circle), 324, 696, 126, 126);
        colorRectangle(canvas, new PatternColor(line), 36, 552, 126, 126);
        colorRectangle(canvas, new PatternColor(img_pattern), 36, 408, 126, 126);
 
        canvas.setPatternFill(line, BaseColor.RED);
        canvas.ellipse(180, 552, 306, 678);
        canvas.fillStroke();
        canvas.setPatternFill(circle, BaseColor.GREEN);
        canvas.ellipse(324, 552, 450, 678);
        canvas.fillStroke();
        
        canvas.setPatternFill(img_pattern);
        canvas.ellipse(180, 408, 450, 534);
        canvas.fillStroke();
 
        // step 5
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new TilingPatternColor().createPdf(RESULT);
    }
}
ShadingPatternColor.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
/*
 * 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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfShading;
import com.itextpdf.text.pdf.PdfShadingPattern;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.ShadingColor;
 
public class ShadingPatternColor extends DeviceColor {
 
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter10/shading_pattern.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
        PdfContentByte canvas = writer.getDirectContent();
        PdfShading axial = PdfShading.simpleAxial(writer, 36, 716, 396,
                788, BaseColor.ORANGE, BaseColor.BLUE);
        canvas.paintShading(axial);
        document.newPage();
        PdfShading radial = PdfShading.simpleRadial(writer,
            200, 700, 50, 300, 700, 100,
            new BaseColor(0xFF, 0xF7, 0x94),
            new BaseColor(0xF7, 0x8A, 0x6B),
            false, false);
        canvas.paintShading(radial);
 
        PdfShadingPattern shading = new PdfShadingPattern(axial);
        colorRectangle(canvas, new ShadingColor(shading), 150, 420, 126, 126);
        canvas.setShadingFill(shading);
        canvas.rectangle(300, 420, 126, 126);
        canvas.fillStroke();
        // step 5
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new ShadingPatternColor().createPdf(RESULT);
    }
}
Transparency1.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
/*
 * 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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfTransparencyGroup;
import com.itextpdf.text.pdf.PdfWriter;
 
public class Transparency1 {
 
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter10/transparency1.pdf";
    
    public static void main(String[] args) {
        // step 1
        Document document = new Document();
        try {
            // step 2
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
            // step 3
            document.open();
            // step 4
            PdfContentByte cb = writer.getDirectContent();
            float gap = (document.getPageSize().getWidth() - 400) / 3;
 
            pictureBackdrop(gap, 500, cb);
            pictureBackdrop(200 + 2 * gap, 500, cb);
            pictureBackdrop(gap, 500 - 200 - gap, cb);
            pictureBackdrop(200 + 2 * gap, 500 - 200 - gap, cb);
 
            pictureCircles(gap, 500, cb);
            cb.saveState();
            PdfGState gs1 = new PdfGState();
            gs1.setFillOpacity(0.5f);
            cb.setGState(gs1);
            pictureCircles(200 + 2 * gap, 500, cb);
            cb.restoreState();
 
            cb.saveState();
            PdfTemplate tp = cb.createTemplate(200, 200);
            PdfTransparencyGroup group = new PdfTransparencyGroup();
            tp.setGroup(group);
            pictureCircles(0, 0, tp);
            cb.setGState(gs1);
            cb.addTemplate(tp, gap, 500 - 200 - gap);
            cb.restoreState();
 
            cb.saveState();
            tp = cb.createTemplate(200, 200);
            tp.setGroup(group);
            PdfGState gs2 = new PdfGState();
            gs2.setFillOpacity(0.5f);
            gs2.setBlendMode(PdfGState.BM_HARDLIGHT);
            tp.setGState(gs2);
            pictureCircles(0, 0, tp);
            cb.addTemplate(tp, 200 + 2 * gap, 500 - 200 - gap);
            cb.restoreState();
 
            cb.resetRGBColorFill();
            ColumnText ct = new ColumnText(cb);
            Phrase ph = new Phrase("Ungrouped objects\nObject opacity = 1.0");
            ct.setSimpleColumn(ph, gap, 0, gap + 200, 500, 18, Element.ALIGN_CENTER);
            ct.go();
 
            ph = new Phrase("Ungrouped objects\nObject opacity = 0.5");
            ct.setSimpleColumn(ph, 200 + 2 * gap, 0, 200 + 2 * gap + 200, 500,
                18, Element.ALIGN_CENTER);
            ct.go();
 
            ph = new Phrase(
                "Transparency group\nObject opacity = 1.0\nGroup opacity = 0.5\nBlend mode = Normal");
            ct.setSimpleColumn(ph, gap, 0, gap + 200, 500 - 200 - gap, 18, Element.ALIGN_CENTER);
            ct.go();
 
            ph = new Phrase(
                "Transparency group\nObject opacity = 0.5\nGroup opacity = 1.0\nBlend mode = HardLight");
            ct.setSimpleColumn(ph, 200 + 2 * gap, 0, 200 + 2 * gap + 200, 500 - 200 - gap,
                18, Element.ALIGN_CENTER);
            ct.go();
        } catch (DocumentException de) {
            System.err.println(de.getMessage());
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
        }
 
        // step 5: we close the document
        document.close();
    }
 
    /**
     * Prints a square and fills half of it with a gray rectangle.
     * 
     * @param x
     * @param y
     * @param cb
     * @throws Exception
     */
    public static void pictureBackdrop(float x, float y, PdfContentByte cb) {
        cb.setColorStroke(GrayColor.GRAYBLACK);
        cb.setColorFill(new GrayColor(0.8f));
        cb.rectangle(x, y, 100, 200);
        cb.fill();
        cb.setLineWidth(2);
        cb.rectangle(x, y, 200, 200);
        cb.stroke();
    }
 
    /**
     * Prints 3 circles in different colors that intersect with eachother.
     * 
     * @param x
     * @param y
     * @param cb
     * @throws Exception
     */
    public static void pictureCircles(float x, float y, PdfContentByte cb) {
        cb.setColorFill(BaseColor.RED);
        cb.circle(x + 70, y + 70, 50);
        cb.fill();
        cb.setColorFill(BaseColor.YELLOW);
        cb.circle(x + 100, y + 130, 50);
        cb.fill();
        cb.setColorFill(BaseColor.BLUE);
        cb.circle(x + 130, y + 70, 50);
        cb.fill();
    }
 
}
Transparency2.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
/*
 * 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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.CMYKColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfShading;
import com.itextpdf.text.pdf.PdfShadingPattern;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfTransparencyGroup;
import com.itextpdf.text.pdf.PdfWriter;
 
public class Transparency2 {
 
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter10/transparency2.pdf";
    
    public static void main(String[] args) {
        // step 1
        Document document = new Document();
        try {
            // step 2
            PdfWriter writer = PdfWriter.getInstance(
                    document,
                    new FileOutputStream(RESULT));
            // step 3
            document.open();
            // step 4
            PdfContentByte cb = writer.getDirectContent();
            float gap = (document.getPageSize().getWidth() - 400) / 3;
 
            pictureBackdrop(gap, 500, cb, writer);
            pictureBackdrop(200 + 2 * gap, 500, cb, writer);
            pictureBackdrop(gap, 500 - 200 - gap, cb, writer);
            pictureBackdrop(200 + 2 * gap, 500 - 200 - gap, cb, writer);
            PdfTemplate tp;
            PdfTransparencyGroup group;
 
            tp = cb.createTemplate(200, 200);
            pictureCircles(0, 0, tp);
            group = new PdfTransparencyGroup();
            group.setIsolated(true);
            group.setKnockout(true);
            tp.setGroup(group);
            cb.addTemplate(tp, gap, 500);
 
            tp = cb.createTemplate(200, 200);
            pictureCircles(0, 0, tp);
            group = new PdfTransparencyGroup();
            group.setIsolated(true);
            group.setKnockout(false);
            tp.setGroup(group);
            cb.addTemplate(tp, 200 + 2 * gap, 500);
 
            tp = cb.createTemplate(200, 200);
            pictureCircles(0, 0, tp);
            group = new PdfTransparencyGroup();
            group.setIsolated(false);
            group.setKnockout(true);
            tp.setGroup(group);
            cb.addTemplate(tp, gap, 500 - 200 - gap);
 
            tp = cb.createTemplate(200, 200);
            pictureCircles(0, 0, tp);
            group = new PdfTransparencyGroup();
            group.setIsolated(false);
            group.setKnockout(false);
            tp.setGroup(group);
            cb.addTemplate(tp, 200 + 2 * gap, 500 - 200 - gap);
        } catch (DocumentException de) {
            System.err.println(de.getMessage());
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
        }
 
        // step 5: we close the document
        document.close();
    }
 
    /**
     * Prints a square and fills half of it with a gray rectangle.
     * 
     * @param x
     * @param y
     * @param cb
     * @throws Exception
     */
    public static void pictureBackdrop(float x, float y, PdfContentByte cb,
            PdfWriter writer) {
        PdfShading axial = PdfShading.simpleAxial(writer, x, y, x + 200, y,
                BaseColor.YELLOW, BaseColor.RED);
        PdfShadingPattern axialPattern = new PdfShadingPattern(axial);
        cb.setShadingFill(axialPattern);
        cb.setColorStroke(BaseColor.BLACK);
        cb.setLineWidth(2);
        cb.rectangle(x, y, 200, 200);
        cb.fillStroke();
    }
 
    /**
     * Prints 3 circles in different colors that intersect with eachother.
     * 
     * @param x
     * @param y
     * @param cb
     * @throws Exception
     */
    public static void pictureCircles(float x, float y, PdfContentByte cb) {
        PdfGState gs = new PdfGState();
        gs.setBlendMode(PdfGState.BM_MULTIPLY);
        gs.setFillOpacity(1f);
        cb.setGState(gs);
        cb.setColorFill(new CMYKColor(0f, 0f, 0f, 0.15f));
        cb.circle(x + 75, y + 75, 70);
        cb.fill();
        cb.circle(x + 75, y + 125, 70);
        cb.fill();
        cb.circle(x + 125, y + 75, 70);
        cb.fill();
        cb.circle(x + 125, y + 125, 70);
        cb.fill();
    }
 
}
ImageTypes.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
/*
 * 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 part3.chapter10;
 
import java.awt.Toolkit;
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.Barcode;
import com.itextpdf.text.pdf.BarcodeEAN;
import com.itextpdf.text.pdf.BarcodePDF417;
import com.itextpdf.text.pdf.PdfWriter;
 
public class ImageTypes {
 
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter10/image_types.pdf";
    /** Paths to images. */
    public static final String[] RESOURCES = {
        "bruno_ingeborg.jpg",
        "map.jp2",
        "info.png",
        "close.bmp",
        "movie.gif",
        "butterfly.wmf",
        "animated_fox_dog.gif",
        "marbles.tif",
        "amb.jb2"
    };
    /** Path to an image. */
    public static final String RESOURCE = "resources/img/hitchcock.png";
 
    /**
     * 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
        // Adding a series of images
        Image img;
        for (int i = 0; i < RESOURCES.length; i++) {
            img = Image.getInstance(String.format("resources/img/%s", RESOURCES[i]));
            if (img.getScaledWidth() > 300 || img.getScaledHeight() > 300) {
                img.scaleToFit(300, 300);
            }
            document.add(new Paragraph(
                    String.format("%s is an image of type %s", RESOURCES[i], img.getClass().getName())));
            document.add(img);
        }
        // Adding a java.awt.Image
        java.awt.Image awtImage = Toolkit.getDefaultToolkit().createImage(RESOURCE);
        img = com.itextpdf.text.Image.getInstance(awtImage, null);
        document.add(new Paragraph(
                String.format("%s is an image of type %s", "java.awt.Image", img.getClass().getName())));
        document.add(img);
        // Adding a barcode
        BarcodeEAN codeEAN = new BarcodeEAN();
        codeEAN.setCodeType(Barcode.EAN13);
        codeEAN.setCode("9781935182610");
        img = codeEAN.createImageWithBarcode(writer.getDirectContent(), null, null);
        document.add(new Paragraph(
                String.format("%s is an image of type %s", "barcode", img.getClass().getName())));
        document.add(img);
        // Adding a matrix code
        BarcodePDF417 pdf417 = new BarcodePDF417();
        String text = "iText in Action, a book by Bruno Lowagie.";
        pdf417.setText(text);
        img = pdf417.getImage();
        document.add(new Paragraph(
                String.format("%s is an image of type %s", "barcode", img.getClass().getName())));
        document.add(img);
 
        // step 5
        document.close();
    }
 
 
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new ImageTypes().createPdf(RESULT);
    }
}
RawImage.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
/*
 * 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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
 
public class RawImage {
 
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter10/gradient.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.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        // Image in color space DeviceGray
        byte gradient[] = new byte[256];
        for (int i = 0; i < 256; i++)
            gradient[i] = (byte) i;
        Image img1 = Image.getInstance(256, 1, 1, 8, gradient);
        img1.scaleAbsolute(256, 50);
        document.add(img1);
        // Image in color space RGB
        byte cgradient[] = new byte[256 * 3];
        for (int i = 0; i < 256; i++) {
            cgradient[i * 3] = (byte) (255 - i);
            cgradient[i * 3 + 1] = (byte) (255 - i);
            cgradient[i * 3 + 2] = (byte) i;
        }
        Image img2 = Image.getInstance(256, 1, 3, 8, cgradient);
        img2.scaleAbsolute(256, 50);
        document.add(img2);
        Image img3 = Image.getInstance(16, 16, 3, 8, cgradient);
        img3.scaleAbsolute(64, 64);
        document.add(img3);
        // step 5
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new RawImage().createPdf(RESULT);
    }
}
Barcodes.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/*
 * 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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.Barcode;
import com.itextpdf.text.pdf.Barcode128;
import com.itextpdf.text.pdf.Barcode39;
import com.itextpdf.text.pdf.BarcodeCodabar;
import com.itextpdf.text.pdf.BarcodeDatamatrix;
import com.itextpdf.text.pdf.BarcodeEAN;
import com.itextpdf.text.pdf.BarcodeEANSUPP;
import com.itextpdf.text.pdf.BarcodeInter25;
import com.itextpdf.text.pdf.BarcodePDF417;
import com.itextpdf.text.pdf.BarcodePostnet;
import com.itextpdf.text.pdf.BarcodeQRCode;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;
 
public class Barcodes {
 
    /** The resulting PDF. */
    private static final String RESULT = "results/part3/chapter10/barcodes.pdf";
 
    /**
     * Generates a PDF file with different types of barcodes.
     * 
     * @param args
     *            no arguments needed here
     * @throws DocumentException
     * @throws IOException
     */
    public static void main(String[] args) throws IOException,
            DocumentException {
        new Barcodes().createPdf(RESULT);
    }
 
    /**
     * 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(new Rectangle(340, 842));
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();
 
        // EAN 13
        document.add(new Paragraph("Barcode EAN.UCC-13"));
        BarcodeEAN codeEAN = new BarcodeEAN();
        codeEAN.setCode("4512345678906");
        document.add(new Paragraph("default:"));
        document.add(codeEAN.createImageWithBarcode(cb, null, null));
        codeEAN.setGuardBars(false);
        document.add(new Paragraph("without guard bars:"));
        document.add(codeEAN.createImageWithBarcode(cb, null, null));
        codeEAN.setBaseline(-1f);
        codeEAN.setGuardBars(true);
        document.add(new Paragraph("text above:"));
        document.add(codeEAN.createImageWithBarcode(cb, null, null));
        codeEAN.setBaseline(codeEAN.getSize());
 
        // UPC A
        document.add(new Paragraph("Barcode UCC-12 (UPC-A)"));
        codeEAN.setCodeType(Barcode.UPCA);
        codeEAN.setCode("785342304749");
        document.add(codeEAN.createImageWithBarcode(cb, null, null));
 
        // EAN 8
        document.add(new Paragraph("Barcode EAN.UCC-8"));
        codeEAN.setCodeType(Barcode.EAN8);
        codeEAN.setBarHeight(codeEAN.getSize() * 1.5f);
        codeEAN.setCode("34569870");
        document.add(codeEAN.createImageWithBarcode(cb, null, null));
 
        // UPC E
        document.add(new Paragraph("Barcode UPC-E"));
        codeEAN.setCodeType(Barcode.UPCE);
        codeEAN.setCode("03456781");
        document.add(codeEAN.createImageWithBarcode(cb, null, null));
        codeEAN.setBarHeight(codeEAN.getSize() * 3f);
 
        // EANSUPP
        document.add(new Paragraph("Bookland"));
        document.add(new Paragraph("ISBN 0-321-30474-8"));
        codeEAN.setCodeType(Barcode.EAN13);
        codeEAN.setCode("9781935182610");
        BarcodeEAN codeSUPP = new BarcodeEAN();
        codeSUPP.setCodeType(Barcode.SUPP5);
        codeSUPP.setCode("55999");
        codeSUPP.setBaseline(-2);
        BarcodeEANSUPP eanSupp = new BarcodeEANSUPP(codeEAN, codeSUPP);
        document.add(eanSupp.createImageWithBarcode(cb, null, BaseColor.BLUE));
 
        // CODE 128
        document.add(new Paragraph("Barcode 128"));
        Barcode128 code128 = new Barcode128();
        code128.setCode("0123456789 hello");
        document.add(code128.createImageWithBarcode(cb, null, null));
        code128.setCode("0123456789\uffffMy Raw Barcode (0 - 9)");
        code128.setCodeType(Barcode.CODE128_RAW);
        document.add(code128.createImageWithBarcode(cb, null, null));
 
        // Data for the barcode :
        String code402 = "24132399420058289";
        String code90 = "3700000050";
        String code421 = "422356";
        StringBuffer data = new StringBuffer(code402);
        data.append(Barcode128.FNC1);
        data.append(code90);
        data.append(Barcode128.FNC1);
        data.append(code421);
        Barcode128 shipBarCode = new Barcode128();
        shipBarCode.setX(0.75f);
        shipBarCode.setN(1.5f);
        shipBarCode.setSize(10f);
        shipBarCode.setTextAlignment(Element.ALIGN_CENTER);
        shipBarCode.setBaseline(10f);
        shipBarCode.setBarHeight(50f);
        shipBarCode.setCode(data.toString());
        document.add(shipBarCode.createImageWithBarcode(cb, BaseColor.BLACK,
                BaseColor.BLUE));
 
        // it is composed of 3 blocks whith AI 01, 3101 and 10
        Barcode128 uccEan128 = new Barcode128();
        uccEan128.setCodeType(Barcode.CODE128_UCC);
        uccEan128.setCode("(01)00000090311314(10)ABC123(15)060916");
        document.add(uccEan128.createImageWithBarcode(cb, BaseColor.BLUE,
                BaseColor.BLACK));
        uccEan128.setCode("0191234567890121310100035510ABC123");
        document.add(uccEan128.createImageWithBarcode(cb, BaseColor.BLUE,
                BaseColor.RED));
        uccEan128.setCode("(01)28880123456788");
        document.add(uccEan128.createImageWithBarcode(cb, BaseColor.BLUE,
                BaseColor.BLACK));
 
        // INTER25
        document.add(new Paragraph("Barcode Interleaved 2 of 5"));
        BarcodeInter25 code25 = new BarcodeInter25();
        code25.setGenerateChecksum(true);
        code25.setCode("41-1200076041-001");
        document.add(code25.createImageWithBarcode(cb, null, null));
        code25.setCode("411200076041001");
        document.add(code25.createImageWithBarcode(cb, null, null));
        code25.setCode("0611012345678");
        code25.setChecksumText(true);
        document.add(code25.createImageWithBarcode(cb, null, null));
 
        // POSTNET
        document.add(new Paragraph("Barcode Postnet"));
        BarcodePostnet codePost = new BarcodePostnet();
        document.add(new Paragraph("ZIP"));
        codePost.setCode("01234");
        document.add(codePost.createImageWithBarcode(cb, null, null));
        document.add(new Paragraph("ZIP+4"));
        codePost.setCode("012345678");
        document.add(codePost.createImageWithBarcode(cb, null, null));
        document.add(new Paragraph("ZIP+4 and dp"));
        codePost.setCode("01234567890");
        document.add(codePost.createImageWithBarcode(cb, null, null));
 
        document.add(new Paragraph("Barcode Planet"));
        BarcodePostnet codePlanet = new BarcodePostnet();
        codePlanet.setCode("01234567890");
        codePlanet.setCodeType(Barcode.PLANET);
        document.add(codePlanet.createImageWithBarcode(cb, null, null));
 
        // CODE 39
        document.add(new Paragraph("Barcode 3 of 9"));
        Barcode39 code39 = new Barcode39();
        code39.setCode("ITEXT IN ACTION");
        document.add(code39.createImageWithBarcode(cb, null, null));
 
        document.add(new Paragraph("Barcode 3 of 9 extended"));
        Barcode39 code39ext = new Barcode39();
        code39ext.setCode("iText in Action");
        code39ext.setStartStopText(false);
        code39ext.setExtended(true);
        document.add(code39ext.createImageWithBarcode(cb, null, null));
 
        // CODABAR
        document.add(new Paragraph("Codabar"));
        BarcodeCodabar codabar = new BarcodeCodabar();
        codabar.setCode("A123A");
        codabar.setStartStopText(true);
        document.add(codabar.createImageWithBarcode(cb, null, null));
 
        // PDF417
        document.add(new Paragraph("Barcode PDF417"));
        BarcodePDF417 pdf417 = new BarcodePDF417();
        String text = "Call me Ishmael. Some years ago--never mind how long "
            + "precisely --having little or no money in my purse, and nothing "
            + "particular to interest me on shore, I thought I would sail about "
            + "a little and see the watery part of the world.";
        pdf417.setText(text);
        Image img = pdf417.getImage();
        img.scalePercent(50, 50 * pdf417.getYHeight());
        document.add(img);
 
        document.add(new Paragraph("Barcode Datamatrix"));
        BarcodeDatamatrix datamatrix = new BarcodeDatamatrix();
        datamatrix.generate(text);
        img = datamatrix.createImage();
        document.add(img);
 
        document.add(new Paragraph("Barcode QRCode"));
        BarcodeQRCode qrcode = new BarcodeQRCode("Moby Dick by Herman Melville", 1, 1, null);
        img = qrcode.getImage();
        document.add(img);
        
        // step 5
        document.close();
    }
}
CompressImage.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
/*
 * 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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
 
public class CompressImage {
 
    /** The resulting PDF file. */
    public static final String RESULT1
        = "results/part3/chapter10/uncompressed.pdf";
    /** The resulting PDF file. */
    public static final String RESULT2
        = "results/part3/chapter10/compressed.pdf";
    /** One of the resources. */
    public static final String RESOURCE
        = "resources/img/butterfly.bmp";
 
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename, boolean compress) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        Image img = Image.getInstance(RESOURCE);
        if (compress)
            img.setCompressionLevel(9);
        document.add(img);
        // step 5
        document.close();
    }
 
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new CompressImage().createPdf(RESULT1, false);
        new CompressImage().createPdf(RESULT2, true);
    }
}
CompressAwt.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
/*
 * 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 part3.chapter10;
 
import java.awt.Toolkit;
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
 
public class CompressAwt {
 
    /** The resulting PDF file. */
    public static final String RESULT1
        = "results/part3/chapter10/hitchcock100.pdf";
    /** The resulting PDF file. */
    public static final String RESULT2
        = "results/part3/chapter10/hitchcock20.pdf";
    /** The resulting PDF file. */
    public static final String RESULT3
        = "results/part3/chapter10/hitchcock10.pdf";
    /** One of the resources. */
    public static final String RESOURCE
        = "resources/img/hitchcock.png";
 
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename, float quality) throws IOException, DocumentException {
        // step 1
        Document document = new Document(new Rectangle(200, 280));
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        java.awt.Image awtImage = Toolkit.getDefaultToolkit().createImage(RESOURCE);
        Image img = Image.getInstance(writer, awtImage, quality);
        img.setAbsolutePosition(15, 15);
        document.add(img);
        // step 5
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new CompressAwt().createPdf(RESULT1, 1);
        new CompressAwt().createPdf(RESULT2, 0.2f);
        new CompressAwt().createPdf(RESULT3, 0.1f);
    }
}
PagedImages.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
/*
 * 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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.RandomAccessFileOrArray;
import com.itextpdf.text.pdf.codec.GifImage;
import com.itextpdf.text.pdf.codec.JBIG2Image;
import com.itextpdf.text.pdf.codec.TiffImage;
 
public class PagedImages {
    
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter10/tiff_jbig2_gif.pdf";
    /** One of the resources. */
    public static final String RESOURCE1
        = "resources/img/marbles.tif";
    /** One of the resources. */
    public static final String RESOURCE2
        = "resources/img/amb.jb2";
    /** One of the resources. */
    public static final String RESOURCE3
        = "resources/img/animated_fox_dog.gif";
 
    /**
     * 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.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        addTif(document, RESOURCE1);
        document.newPage();
        addJBIG2(document, RESOURCE2);
        document.newPage();
        addGif(document, RESOURCE3);
        // step 5
        document.close();
    }
    
    /**
     * Adds the different pages inside a single TIFF file to a document.
     * @param document the document to which the pages have to be added
     * @param path     the path to the TIFF file
     * @throws DocumentException
     * @throws IOException
     */
    public static void addTif(Document document, String path) throws DocumentException, IOException {
        RandomAccessFileOrArray ra = new RandomAccessFileOrArray(path);
        int n = TiffImage.getNumberOfPages(ra);
        Image img;
        for (int i = 1; i <= n; i++) {
            img = TiffImage.getTiffImage(ra, i);
            img.scaleToFit(523, 350);
            document.add(img);
        }
    }
    
    /**
     * Adds the different pages inside a JBIG2 file to a document.
     * @param document the document to which the pages have to be added
     * @param path     the path to the JBIG2 file
     * @throws IOException
     * @throws DocumentException
     */
    public static void addJBIG2(Document document, String path) throws IOException, DocumentException {
        RandomAccessFileOrArray ra = new RandomAccessFileOrArray(path);
        int n = JBIG2Image.getNumberOfPages(ra);
        Image img;
        for (int i = 1; i <= n; i++) {
            img = JBIG2Image.getJbig2Image(ra, i);
            img.scaleToFit(523, 350);
            document.add(img);
        }
    }
    
    /**
     * Adds the different frames inside an animated GIF to a document.
     * @param document the document to which the frames have to be added
     * @param path     the path to the GIF file
     * @throws IOException
     * @throws DocumentException
     */
    public static void addGif(Document document, String path) throws IOException, DocumentException {
        GifImage img = new GifImage(path);
        int n = img.getFrameCount();
        for (int i = 1; i <= n; i++) {
            document.add(img.getImage(i));
        }
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new PagedImages().createPdf(RESULT);
    }
}
TransparentImage.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
/*
 * 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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
 
public class TransparentImage {
 
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter10/transparent_image.pdf";
    /** One of the resources. */
    public static final String RESOURCE1
        = "resources/img/bruno.jpg";
    /** One of the resources. */
    public static final String RESOURCE2
        = "resources/img/info.png";
    /** One of the resources. */
    public static final String RESOURCE3
        = "resources/img/1t3xt.gif";
    /** One of the resources. */
    public static final String RESOURCE4
        = "resources/img/logo.gif";
 
 
    /**
     * 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 {
        Image img1 = Image.getInstance(RESOURCE1);
        // step 1
        Document document = new Document(img1);
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        img1.setAbsolutePosition(0, 0);
        document.add(img1);
        Image img2 = Image.getInstance(RESOURCE2);
        img2.setAbsolutePosition(0, 260);
        document.add(img2);
        Image img3 = Image.getInstance(RESOURCE3);
        img3.setTransparency(new int[]{ 0x00, 0x10 });
        img3.setAbsolutePosition(0, 0);
        document.add(img3);
        Image img4 = Image.getInstance(RESOURCE4);
        img4.setTransparency(new int[]{ 0xF0, 0xFF });
        img4.setAbsolutePosition(50, 50);
        document.add(img4);
 
        // step 5
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new TransparentImage().createPdf(RESULT);
    }
}
TransparentAwt.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
/*
 * 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 part3.chapter10;
 
import java.awt.Color;
import java.awt.Toolkit;
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfWriter;
 
public class TransparentAwt {
 
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter10/transparent_hitchcock.pdf";
    /** One of the resources. */
    public static final String RESOURCE
        = "resources/img/hitchcock.gif";
 
    /**
     * 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
        Rectangle r = new Rectangle(PageSize.A4);
        r.setBackgroundColor(new GrayColor(0.8f));
        Document document = new Document(r);
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        java.awt.Image awtImage = Toolkit.getDefaultToolkit().createImage(RESOURCE);
        document.add(new Paragraph("Hitchcock in Red."));
        Image img1 = Image.getInstance(awtImage, null);
        document.add(img1);
        document.add(new Paragraph("Hitchcock in Black and White."));
        Image img2 = Image.getInstance(awtImage, null, true);
        document.add(img2);
        document.newPage();
        document.add(new Paragraph("Hitchcock in Red and Yellow."));
        Image img3 = Image.getInstance(awtImage, new Color(0xFF, 0xFF, 0x00));
        document.add(img3);
        document.add(new Paragraph("Hitchcock in Black and White."));
        Image img4 = Image.getInstance(awtImage, new Color(0xFF, 0xFF, 0x00), true);
        document.add(img4);
        // step 5
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new TransparentAwt().createPdf(RESULT);
    }
}
ImageMask.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
/*
 * 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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
 
public class ImageMask {
 
    /** The resulting PDF file. */
    public static final String RESULT1
        = "results/part3/chapter10/hardmask.pdf";
    /** The resulting PDF file. */
    public static final String RESULT2
        = "results/part3/chapter10/softmask.pdf";
    /** One of the resources. */
    public static final String RESOURCE
        = "resources/img/bruno.jpg";
 
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename, Image mask) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        Image img = Image.getInstance(RESOURCE);
        img.setImageMask(mask);
        document.add(img);
        // step 5
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        byte circledata[] = { (byte) 0x3c, (byte) 0x7e, (byte) 0xff,
                (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x7e,
                (byte) 0x3c };
        Image mask = Image.getInstance(8, 8, 1, 1, circledata);
        mask.makeMask();
        mask.setInverted(true);
        new ImageMask().createPdf(RESULT1, mask);
        byte gradient[] = new byte[256];
        for (int i = 0; i < 256; i++)
            gradient[i] = (byte) i;
        mask = Image.getInstance(256, 1, 1, 8, gradient);
        mask.makeMask();
        new ImageMask().createPdf(RESULT2, mask);
    }
}
TemplateClip.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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
 
public class TemplateClip {
 
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter10/template_clip.pdf";
    /** One of the resources. */
    public static final String RESOURCE
        = "resources/img/bruno_ingeborg.jpg";
    
    /**
     * 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
        Image img = Image.getInstance(RESOURCE);
        float w = img.getScaledWidth();
        float h = img.getScaledHeight();
        PdfTemplate t = writer.getDirectContent().createTemplate(850, 600);
        t.addImage(img, w, 0, 0, h, 0, -600);
        Image clipped = Image.getInstance(t);
        clipped.scalePercent(50);
        document.add(clipped);
        // step 5
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new TemplateClip().createPdf(RESULT);
    }
}
ClippingPath.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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
 
public class ClippingPath {
 
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter10/clipping_path.pdf";
    /** One of the resources. */
    public static final String RESOURCE
        = "resources/img/bruno_ingeborg.jpg";
    
    /**
     * 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
        Image img = Image.getInstance(RESOURCE);
        float w = img.getScaledWidth();
        float h = img.getScaledHeight();
        PdfTemplate t = writer.getDirectContent().createTemplate(850, 600);
        t.ellipse(0, 0, 850, 600);
        t.clip();
        t.newPath();
        t.addImage(img, w, 0, 0, h, 0, -600);
        Image clipped = Image.getInstance(t);
        clipped.scalePercent(50);
        document.add(clipped);
        // step 5
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new ClippingPath().createPdf(RESULT);
    }
}
TransparentOverlay.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
/*
 * 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 part3.chapter10;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfTransparencyGroup;
import com.itextpdf.text.pdf.PdfWriter;
 
public class TransparentOverlay {
 
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter10/transparent_overlay.pdf";
    /** One of the resources. */
    public static final String RESOURCE
        = "resources/img/bruno_ingeborg.jpg";
    
    /**
     * 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(new Rectangle(850, 600));
        // step 2
        PdfWriter writer
          = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte canvas = writer.getDirectContent();
        
        // add the clipped image
        Image img = Image.getInstance(RESOURCE);
        float w = img.getScaledWidth();
        float h = img.getScaledHeight();
        canvas.ellipse(1, 1, 848, 598);
        canvas.clip();
        canvas.newPath();
        canvas.addImage(img, w, 0, 0, h, 0, -600);
 
        // Create a transparent PdfTemplate
        PdfTemplate t2 = writer.getDirectContent().createTemplate(850, 600);
        PdfTransparencyGroup transGroup = new PdfTransparencyGroup();
        transGroup.put( PdfName.CS, PdfName.DEVICEGRAY);
        transGroup.setIsolated(true);
        transGroup.setKnockout(false);
        t2.setGroup(transGroup);
 
        // Add transparent ellipses to the template
        int gradationStep = 30;
        float[] gradationRatioList = new float[gradationStep];
        for(int i = 0; i < gradationStep; i++) {
            gradationRatioList[i] = 1 - (float)Math.sin(Math.toRadians(90.0f / gradationStep * (i + 1)));
        }
        for(int i = 1; i < gradationStep + 1; i++) {
            t2.setLineWidth(5 * (gradationStep + 1 - i));
            t2.setGrayStroke(gradationRatioList[gradationStep - i]);
            t2.ellipse(0, 0, 850, 600);
            t2.stroke();
        }
        
        // Create an image mask for the direct content
        PdfDictionary maskDict = new PdfDictionary();
        maskDict.put(PdfName.TYPE, PdfName.MASK );
        maskDict.put(PdfName.S, new PdfName("Luminosity"));
        maskDict.put(new PdfName("G"), t2.getIndirectReference());
        PdfGState gState = new PdfGState();
        gState.put(PdfName.SMASK, maskDict );
        canvas.setGState(gState);
        
        canvas.addTemplate(t2, 0, 0);
 
        // 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 TransparentOverlay().createPdf(RESULT);
    }
}
DeviceColor.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class DeviceColor : IWriter {
// ===========================================================================
    public virtual void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        PdfContentByte canvas = writer.DirectContent;
        // RGB Colors
        ColorRectangle(canvas, new BaseColor(0x00, 0x00, 0x00), 
          36, 770, 36, 36
        );
        ColorRectangle(canvas, new BaseColor(0x00, 0x00, 0xFF), 
          90, 770, 36, 36
        );
        ColorRectangle(canvas, new BaseColor(0x00, 0xFF, 0x00), 
          144, 770, 36, 36
        );
        ColorRectangle(canvas, new BaseColor(0xFF, 0x00, 0x00), 
          198, 770, 36, 36
        );
        ColorRectangle(canvas, new BaseColor(0f, 1f, 1f), 252, 770, 36, 36);
        ColorRectangle(canvas, new BaseColor(1f, 0f, 1f), 306, 770, 36, 36);
        ColorRectangle(canvas, new BaseColor(1f, 1f, 0f), 360, 770, 36, 36);
        ColorRectangle(canvas, BaseColor.BLACK, 416, 770, 36, 36);
        ColorRectangle(canvas, BaseColor.LIGHT_GRAY, 470, 770, 36, 36);
        // CMYK Colors
        ColorRectangle(canvas, new CMYKColor(0x00, 0x00, 0x00, 0x00), 
          36, 716, 36, 36
        );
        ColorRectangle(canvas, new CMYKColor(0x00, 0x00, 0xFF, 0x00), 
          90, 716, 36, 36
        );
        ColorRectangle(canvas, new CMYKColor(0x00, 0x00, 0xFF, 0xFF), 
          144, 716, 36, 36
        );
        ColorRectangle(canvas, new CMYKColor(0x00, 0xFF, 0x00, 0x00), 
          198, 716, 36, 36
        );
        ColorRectangle(canvas, new CMYKColor(0f, 1f, 0f, 0.5f), 
          252, 716, 36, 36
        );
        ColorRectangle(canvas, new CMYKColor(1f, 0f, 0f, 0f), 
          306, 716, 36, 36
        );
        ColorRectangle(canvas, new CMYKColor(1f, 0f, 0f, 0.5f), 
          360, 716, 36, 36
        );
        ColorRectangle(canvas, new CMYKColor(1f, 0f, 0f, 1f), 
          416, 716, 36, 36
        );
        ColorRectangle(canvas, new CMYKColor(0f, 0f, 0f, 1f), 
          470, 716, 36, 36
        );
        // Gray color
        ColorRectangle(canvas, new GrayColor(0x20), 36, 662, 36, 36);
        ColorRectangle(canvas, new GrayColor(0x40), 90, 662, 36, 36);
        ColorRectangle(canvas, new GrayColor(0x60), 144, 662, 36, 36);
        ColorRectangle(canvas, new GrayColor(0.5f), 198, 662, 36, 36);
        ColorRectangle(canvas, new GrayColor(0.625f), 252, 662, 36, 36);
        ColorRectangle(canvas, new GrayColor(0.75f), 306, 662, 36, 36);
        ColorRectangle(canvas, new GrayColor(0.825f), 360, 662, 36, 36);
        ColorRectangle(canvas, GrayColor.GRAYBLACK, 416, 662, 36, 36);
        ColorRectangle(canvas, GrayColor.GRAYWHITE, 470, 662, 36, 36);
        // Alternative ways to color the rectangle
        canvas.SetRGBColorFill(0x00, 0x80, 0x80);
        canvas.Rectangle(36, 608, 36, 36);
        canvas.FillStroke();
        canvas.SetRGBColorFillF(0.5f, 0.25f, 0.60f);
        canvas.Rectangle(90, 608, 36, 36);
        canvas.FillStroke();
        canvas.SetGrayFill(0.5f);
        canvas.Rectangle(144, 608, 36, 36);
        canvas.FillStroke();
        canvas.SetCMYKColorFill(0xFF, 0xFF, 0x00, 0x80);
        canvas.Rectangle(198, 608, 36, 36);
        canvas.FillStroke();
        canvas.SetCMYKColorFillF(0f, 1f, 1f, 0.5f);
        canvas.Rectangle(252, 608, 36, 36);
        canvas.FillStroke();
      }
    }
// ---------------------------------------------------------------------------    
    /**
     * Draws a colored rectangle.
     * @param canvas the canvas to draw on
     * @param color the Color
     * @param x the X coordinate
     * @param y the Y coordinate
     * @param width the width of the rectangle
     * @param height the height of the rectangle
     */
    public void ColorRectangle(PdfContentByte canvas, BaseColor color, 
        float x, float y, float width, float height) 
    {
      canvas.SaveState();
      canvas.SetColorFill(color);
      canvas.Rectangle(x, y, width, height);
      canvas.FillStroke();
      canvas.RestoreState();
    }
// ===========================================================================
  }
}
SeparationColor.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class SeparationColor : DeviceColor {
// ===========================================================================
    public override void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        PdfContentByte canvas = writer.DirectContent;
        PdfSpotColor psc_g = new PdfSpotColor(
          "iTextSpotColorGray", new GrayColor(0.9f)
        );
        PdfSpotColor psc_rgb = new PdfSpotColor(
          "iTextSpotColorRGB", new BaseColor(0x64, 0x95, 0xed)
        );
        PdfSpotColor psc_cmyk = new PdfSpotColor(
          "iTextSpotColorCMYK", new CMYKColor(0.3f, .9f, .3f, .1f)
        );
        ColorRectangle(canvas, new SpotColor(psc_g, 0.5f), 
          36, 770, 36, 36
        );
        ColorRectangle(canvas, new SpotColor(psc_rgb, 0.1f), 
          90, 770, 36, 36
        );
        ColorRectangle(canvas, new SpotColor(psc_rgb, 0.2f), 
          144, 770, 36, 36
        ); 
        ColorRectangle(canvas, new SpotColor(psc_rgb, 0.3f), 
          198, 770, 36, 36
        ); 
        ColorRectangle(canvas, new SpotColor(psc_rgb, 0.4f), 
          252, 770, 36, 36
        ); 
        ColorRectangle(canvas, new SpotColor(psc_rgb, 0.5f), 
          306, 770, 36, 36
        ); 
        ColorRectangle(canvas, new SpotColor(psc_rgb, 0.6f), 
          360, 770, 36, 36
        ); 
        ColorRectangle(canvas, new SpotColor(psc_rgb, 0.7f), 
          416, 770, 36, 36
        ); 
        ColorRectangle(canvas, new SpotColor(psc_cmyk, 0.25f), 
          470, 770, 36, 36
        );
        canvas.SetColorFill(psc_g, 0.5f);
        canvas.Rectangle(36, 716, 36, 36);
        canvas.FillStroke();
        canvas.SetColorFill(psc_g, 0.9f);
        canvas.Rectangle(90, 716, 36, 36);
        canvas.FillStroke();
        canvas.SetColorFill(psc_rgb, 0.5f);
        canvas.Rectangle(144, 716, 36, 36);
        canvas.FillStroke();
        canvas.SetColorFill(psc_rgb, 0.9f);
        canvas.Rectangle(198, 716, 36, 36);
        canvas.FillStroke();
        canvas.SetColorFill(psc_cmyk, 0.5f);
        canvas.Rectangle(252, 716, 36, 36);
        canvas.FillStroke();
        canvas.SetColorFill(psc_cmyk, 0.9f);
        canvas.Rectangle(306, 716, 36, 36);
        canvas.FillStroke();
      }
    }
// ===========================================================================
  }
}
TilingPatternColor.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class TilingPatternColor : DeviceColor {
// ===========================================================================
    /** The resulting PDF file. */
    public const string RESULT = "tiling_pattern.pdf";
    /** An image that will be used for a pattern color. */
    public static string RESOURCE = Path.Combine(Utility.ResourceImage, "info.png");
// --------------------------------------------------------------------------- 
    public override void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        TilingPatternColor t = new TilingPatternColor();
        zip.AddEntry(RESULT, t.CreatePdf());
        zip.AddFile(RESOURCE, "");
        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 writer = PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
          PdfContentByte canvas = writer.DirectContent;
          PdfPatternPainter square
              = canvas.CreatePattern(15, 15);
          square.SetColorFill(new BaseColor(0xFF, 0xFF, 0x00));
          square.SetColorStroke(new BaseColor(0xFF, 0x00, 0x00));
          square.Rectangle(5, 5, 5, 5);
          square.FillStroke();
          
          PdfPatternPainter ellipse
              = canvas.CreatePattern(15, 10, 20, 25);
          ellipse.SetColorFill(new BaseColor(0xFF, 0xFF, 0x00));
          ellipse.SetColorStroke(new BaseColor(0xFF, 0x00, 0x00));
          ellipse.Ellipse(2f, 2f, 13f, 8f);
          ellipse.FillStroke();
          
          PdfPatternPainter circle
              = canvas.CreatePattern(15, 15, 10, 20, BaseColor.BLUE);
          circle.Circle(7.5f, 7.5f, 2.5f);
          circle.Fill();
          
          PdfPatternPainter line
              = canvas.CreatePattern(5, 10, null);
          line.SetLineWidth(1);
          line.MoveTo(3, -1);
          line.LineTo(3, 11);
          line.Stroke();
          
          Image img = Image.GetInstance(RESOURCE);
          img.ScaleAbsolute(20, 20);
          img.SetAbsolutePosition(0, 0);
          PdfPatternPainter img_pattern
              = canvas.CreatePattern(20, 20, 20, 20);
          img_pattern.AddImage(img);
          img_pattern.SetPatternMatrix(-0.5f, 0f, 0f, 0.5f, 0f, 0f);
          
          ColorRectangle(canvas, new PatternColor(square), 36, 696, 126, 126);
          ColorRectangle(canvas, new PatternColor(ellipse), 180, 696, 126, 126);
          ColorRectangle(canvas, new PatternColor(circle), 324, 696, 126, 126);
          ColorRectangle(canvas, new PatternColor(line), 36, 552, 126, 126);
          ColorRectangle(canvas, new PatternColor(img_pattern), 36, 408, 126, 126);
 
          canvas.SetPatternFill(line, BaseColor.RED);
          canvas.Ellipse(180, 552, 306, 678);
          canvas.FillStroke();
          canvas.SetPatternFill(circle, BaseColor.GREEN);
          canvas.Ellipse(324, 552, 450, 678);
          canvas.FillStroke();
          
          canvas.SetPatternFill(img_pattern);
          canvas.Ellipse(180, 408, 450, 534);
          canvas.FillStroke();
        }
        return ms.ToArray();
      }
    }
// ===========================================================================
  }
}
ShadingPatternColor.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class ShadingPatternColor : DeviceColor {
// ===========================================================================
    public override void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        PdfContentByte canvas = writer.DirectContent;
        PdfShading axial = PdfShading.SimpleAxial(writer, 36, 716, 396,
          788, BaseColor.ORANGE, BaseColor.BLUE
        );
        canvas.PaintShading(axial);
        document.NewPage();
        PdfShading radial = PdfShading.SimpleRadial(writer,
          200, 700, 50, 300, 700, 100,
          new BaseColor(0xFF, 0xF7, 0x94),
          new BaseColor(0xF7, 0x8A, 0x6B),
          false, false
        );
        canvas.PaintShading(radial);
 
        PdfShadingPattern shading = new PdfShadingPattern(axial);
        ColorRectangle(canvas, new ShadingColor(shading), 150, 420, 126, 126);
        canvas.SetShadingFill(shading);
        canvas.Rectangle(300, 420, 126, 126);
        canvas.FillStroke();
      }
    }
// ===========================================================================
  }
}
Transparency1.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class Transparency1 : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        PdfContentByte cb = writer.DirectContent;
        float gap = (document.PageSize.Width - 400) / 3;
 
        PictureBackdrop(gap, 500, cb);
        PictureBackdrop(200 + 2 * gap, 500, cb);
        PictureBackdrop(gap, 500 - 200 - gap, cb);
        PictureBackdrop(200 + 2 * gap, 500 - 200 - gap, cb);
 
        PictureCircles(gap, 500, cb);
        cb.SaveState();
        PdfGState gs1 = new PdfGState();
        gs1.FillOpacity = 0.5f;
        cb.SetGState(gs1);
        PictureCircles(200 + 2 * gap, 500, cb);
        cb.RestoreState();
 
        cb.SaveState();
        PdfTemplate tp = cb.CreateTemplate(200, 200);
        PdfTransparencyGroup group = new PdfTransparencyGroup();
        tp.Group = group;
        PictureCircles(0, 0, tp);
        cb.SetGState(gs1);
        cb.AddTemplate(tp, gap, 500 - 200 - gap);
        cb.RestoreState();
 
        cb.SaveState();
        tp = cb.CreateTemplate(200, 200);
        tp.Group = group;
        PdfGState gs2 = new PdfGState();
        gs2.FillOpacity = 0.5f;
        gs2.BlendMode = PdfGState.BM_HARDLIGHT;
        tp.SetGState(gs2);
        PictureCircles(0, 0, tp);
        cb.AddTemplate(tp, 200 + 2 * gap, 500 - 200 - gap);
        cb.RestoreState();
 
        cb.ResetRGBColorFill();
        ColumnText ct = new ColumnText(cb);
        Phrase ph = new Phrase("Ungrouped objects\nObject opacity = 1.0");
        ct.SetSimpleColumn(ph, gap, 0, gap + 200, 500, 18,
          Element.ALIGN_CENTER
        );
        ct.Go();
 
        ph = new Phrase("Ungrouped objects\nObject opacity = 0.5");
        ct.SetSimpleColumn(ph, 200 + 2 * gap, 0, 200 + 2 * gap + 200, 500,
          18, Element.ALIGN_CENTER
        );
        ct.Go();
 
        ph = new Phrase(
          "Transparency group\nObject opacity = 1.0\nGroup opacity = 0.5\nBlend mode = Normal"
        );
        ct.SetSimpleColumn(ph, gap, 0, gap + 200, 500 - 200 - gap, 18,
          Element.ALIGN_CENTER
        );
        ct.Go();
 
        ph = new Phrase(
          "Transparency group\nObject opacity = 0.5\nGroup opacity = 1.0\nBlend mode = HardLight"
        );
        ct.SetSimpleColumn(ph, 200 + 2 * gap, 0, 200 + 2 * gap + 200,
          500 - 200 - gap, 18, Element.ALIGN_CENTER
        );
        ct.Go();
      }
    }
// ---------------------------------------------------------------------------
    /**
     * Prints a square and fills half of it with a gray rectangle.
     * 
     * @param x
     * @param y
     * @param cb
     * @throws Exception
     */
    public static void PictureBackdrop(float x, float y, PdfContentByte cb) {
      cb.SetColorStroke(GrayColor.GRAYBLACK);
      cb.SetColorFill(new GrayColor(0.8f));
      cb.Rectangle(x, y, 100, 200);
      cb.Fill();
      cb.SetLineWidth(2);
      cb.Rectangle(x, y, 200, 200);
      cb.Stroke();
    }
// ---------------------------------------------------------------------------
    /**
     * Prints 3 circles in different colors that intersect with eachother.
     * 
     * @param x
     * @param y
     * @param cb
     * @throws Exception
     */
    public static void PictureCircles(float x, float y, PdfContentByte cb) {
      cb.SetColorFill(BaseColor.RED);
      cb.Circle(x + 70, y + 70, 50);
      cb.Fill();
      cb.SetColorFill(BaseColor.YELLOW);
      cb.Circle(x + 100, y + 130, 50);
      cb.Fill();
      cb.SetColorFill(BaseColor.BLUE);
      cb.Circle(x + 130, y + 70, 50);
      cb.Fill();
    }
// ===========================================================================
  }
}
Transparency2.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class Transparency2 : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        PdfContentByte cb = writer.DirectContent;
        float gap = (document.PageSize.Width - 400) / 3;
 
        PictureBackdrop(gap, 500, cb, writer);
        PictureBackdrop(200 + 2 * gap, 500, cb, writer);
        PictureBackdrop(gap, 500 - 200 - gap, cb, writer);
        PictureBackdrop(200 + 2 * gap, 500 - 200 - gap, cb, writer);
        PdfTemplate tp;
        PdfTransparencyGroup group;
 
        tp = cb.CreateTemplate(200, 200);
        PictureCircles(0, 0, tp);
        group = new PdfTransparencyGroup();
        group.Isolated = true;
        group.Knockout = true;
        tp.Group = group;
        cb.AddTemplate(tp, gap, 500);
 
        tp = cb.CreateTemplate(200, 200);
        PictureCircles(0, 0, tp);
        group = new PdfTransparencyGroup();
        group.Isolated  = true;
        group.Knockout = false;
        tp.Group = group;
        cb.AddTemplate(tp, 200 + 2 * gap, 500);
 
        tp = cb.CreateTemplate(200, 200);
        PictureCircles(0, 0, tp);
        group = new PdfTransparencyGroup();
        group.Isolated = false;
        group.Knockout = true;
        tp.Group = group;
        cb.AddTemplate(tp, gap, 500 - 200 - gap);
 
        tp = cb.CreateTemplate(200, 200);
        PictureCircles(0, 0, tp);
        group = new PdfTransparencyGroup();
        group.Isolated = false;
        group.Knockout = false;
        tp.Group = group;
        cb.AddTemplate(tp, 200 + 2 * gap, 500 - 200 - gap);
      }
    }
// ---------------------------------------------------------------------------
    /**
     * Prints a square and fills half of it with a gray rectangle.
     * 
     * @param x
     * @param y
     * @param cb
     * @throws Exception
     */
    public static void PictureBackdrop(float x, float y, PdfContentByte cb,
        PdfWriter writer) 
    {
      PdfShading axial = PdfShading.SimpleAxial(writer, x, y, x + 200, y,
        BaseColor.YELLOW, BaseColor.RED
      );
      PdfShadingPattern axialPattern = new PdfShadingPattern(axial);
      cb.SetShadingFill(axialPattern);
      cb.SetColorStroke(BaseColor.BLACK);
      cb.SetLineWidth(2);
      cb.Rectangle(x, y, 200, 200);
      cb.FillStroke();
    }    
// ---------------------------------------------------------------------------
    /**
     * Prints 3 circles in different colors that intersect with eachother.
     * 
     * @param x
     * @param y
     * @param cb
     * @throws Exception
     */
    public static void PictureCircles(float x, float y, PdfContentByte cb) {
      PdfGState gs = new PdfGState();
      gs.BlendMode = PdfGState.BM_MULTIPLY;
      gs.FillOpacity = 1f;
      cb.SetGState(gs);
      cb.SetColorFill(new CMYKColor(0f, 0f, 0f, 0.15f));
      cb.Circle(x + 75, y + 75, 70);
      cb.Fill();
      cb.Circle(x + 75, y + 125, 70);
      cb.Fill();
      cb.Circle(x + 125, y + 75, 70);
      cb.Fill();
      cb.Circle(x + 125, y + 125, 70);
      cb.Fill();
    }
// ===========================================================================
  }
}
ImageTypes.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class ImageTypes : IWriter {
// ===========================================================================
    /** The resulting PDF file. */
    public const String RESULT = "image_types.pdf";
    /** Paths to images. */
    public string[] RESOURCES = {
      "bruno_ingeborg.jpg",
      "map.jp2",
      "info.png",
      "close.bmp",
      "movie.gif",
      "butterfly.wmf",
      "animated_fox_dog.gif",
      "marbles.tif",
      "amb.jb2"
    };
    /** Path to an image. */
    public const string RESOURCE = "hitchcock.png";
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        ImageTypes it = new ImageTypes();
        zip.AddEntry(RESULT, it.CreatePdf());
/* 
 * uncomment if you want to see the image files in the zip archive;
 * some of them are semi-large files
 * 
        for (int i = 0; i < RESOURCES.Length; i++) {
          zip.AddFile(Path.Combine(Utility.ResourceImage, RESOURCES[i]), "");
        }
        zip.AddFile(Path.Combine(Utility.ResourceImage, RESOURCE), "");
 */
        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();
          Image img = null;
          for (int i = 0; i < RESOURCES.Length; i++) {
            img = Image.GetInstance(Path.Combine(Utility.ResourceImage, RESOURCES[i]));
            if (img.ScaledWidth > 300 || img.ScaledHeight > 300) {
              img.ScaleToFit(300, 300);
            }
            document.Add(new Paragraph(String.Format(
              "{0} is an image of type {1}", RESOURCES[i], img.GetType())
            ));
            document.Add(img);
          }
/*
* you DO NOT want to use classes within the System.Drawing namespace to
* manipulate image files in ASP.NET applications, see the warning here:
* http://msdn.microsoft.com/en-us/library/system.drawing.aspx
*/
          using (System.Drawing.Image dotnet_img = 
            System.Drawing.Image.FromFile(
              Path.Combine(Utility.ResourceImage, RESOURCE)
            )) 
          {
            img = Image.GetInstance(
              dotnet_img, System.Drawing.Imaging.ImageFormat.Png
            );
            document.Add(new Paragraph(String.Format(
              "{0} is an image of type {1}", "System.Drawing.Image", img.GetType())
            ));
            document.Add(img);
          }
 
          BarcodeEAN codeEAN = new BarcodeEAN();
          codeEAN.CodeType = Barcode.EAN13;
          codeEAN.Code = "9781935182610";
          img = codeEAN.CreateImageWithBarcode(writer.DirectContent, null, null);
          document.Add(new Paragraph(String.Format(
            "{0} is an image of type {1}", "barcode", img.GetType())
          ));
          document.Add(img);
 
          BarcodePDF417 pdf417 = new BarcodePDF417();
          string text = "iText in Action, a book by Bruno Lowagie.";
          pdf417.SetText(text);
          img = pdf417.GetImage();
          document.Add(new Paragraph(String.Format(
            "{0} is an image of type {1}", "barcode", img.GetType())
          ));
          document.Add(img);
        }
        return ms.ToArray();
      }
    }
// ===========================================================================
  }
}
RawImage.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class RawImage : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        // Image in colorspace DeviceGray
        byte[] gradient = new byte[256];
        for (int i = 0; i < 256; i++) {
          gradient[i] = (byte) i;
        }
        Image img1 = Image.GetInstance(256, 1, 1, 8, gradient);
        img1.ScaleAbsolute(256, 50);
        document.Add(img1);
        // Image in colorspace RGB
        byte[] cgradient = new byte[256 * 3];
        for (int i = 0; i < 256; i++) {
          cgradient[i * 3] = (byte) (255 - i);
          cgradient[i * 3 + 1] = (byte) (255 - i);
          cgradient[i * 3 + 2] = (byte) i;
        }
        Image img2 = Image.GetInstance(256, 1, 3, 8, cgradient);
        img2.ScaleAbsolute(256, 50);
        document.Add(img2);
        Image img3 = Image.GetInstance(16, 16, 3, 8, cgradient);
        img3.ScaleAbsolute(64, 64);
        document.Add(img3);
      }
    }
// ===========================================================================
  }
}
Barcodes.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
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/*
 * 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 System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class Barcodes : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document(new Rectangle(340, 842))) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        PdfContentByte cb = writer.DirectContent;
 
        // EAN 13
        document.Add(new Paragraph("Barcode EAN.UCC-13"));
        BarcodeEAN codeEAN = new BarcodeEAN();
        codeEAN.Code = "4512345678906";
        document.Add(new Paragraph("default:"));
        document.Add(codeEAN.CreateImageWithBarcode(cb, null, null));
        codeEAN.GuardBars = false;
        document.Add(new Paragraph("without guard bars:"));
        document.Add(codeEAN.CreateImageWithBarcode(cb, null, null));
        codeEAN.Baseline = -1f;
        codeEAN.GuardBars = true;
        document.Add(new Paragraph("text above:"));
        document.Add(codeEAN.CreateImageWithBarcode(cb, null, null));
        codeEAN.Baseline = codeEAN.Size;
 
        // UPC A
        document.Add(new Paragraph("Barcode UCC-12 (UPC-A)"));
        codeEAN.CodeType = Barcode.UPCA;
        codeEAN.Code = "785342304749";
        document.Add(codeEAN.CreateImageWithBarcode(cb, null, null));
 
        // EAN 8
        document.Add(new Paragraph("Barcode EAN.UCC-8"));
        codeEAN.CodeType = Barcode.EAN8;
        codeEAN.BarHeight = codeEAN.Size * 1.5f;
        codeEAN.Code = "34569870";
        document.Add(codeEAN.CreateImageWithBarcode(cb, null, null));
 
        // UPC E
        document.Add(new Paragraph("Barcode UPC-E"));
        codeEAN.CodeType = Barcode.UPCE;
        codeEAN.Code = "03456781";
        document.Add(codeEAN.CreateImageWithBarcode(cb, null, null));
        codeEAN.BarHeight = codeEAN.Size * 3f;
 
        // EANSUPP
        document.Add(new Paragraph("Bookland"));
        document.Add(new Paragraph("ISBN 0-321-30474-8"));
        codeEAN.CodeType = Barcode.EAN13;
        codeEAN.Code = "9781935182610";
        BarcodeEAN codeSUPP = new BarcodeEAN();
        codeSUPP.CodeType = Barcode.SUPP5;
        codeSUPP.Code = "55999";
        codeSUPP.Baseline = -2;
        BarcodeEANSUPP eanSupp = new BarcodeEANSUPP(codeEAN, codeSUPP);
        document.Add(eanSupp.CreateImageWithBarcode(cb, null, BaseColor.BLUE));
 
        // CODE 128
        document.Add(new Paragraph("Barcode 128"));
        Barcode128 code128 = new Barcode128();
        code128.Code = "0123456789 hello";
        document.Add(code128.CreateImageWithBarcode(cb, null, null));
        code128.Code = "0123456789\uffffMy Raw Barcode (0 - 9)";
        code128.CodeType = Barcode.CODE128_RAW;
        document.Add(code128.CreateImageWithBarcode(cb, null, null));
 
        // Data for the barcode :
        String code402 = "24132399420058289";
        String code90 = "3700000050";
        String code421 = "422356";
        StringBuilder data = new StringBuilder(code402);
        data.Append(Barcode128.FNC1);
        data.Append(code90);
        data.Append(Barcode128.FNC1);
        data.Append(code421);
        Barcode128 shipBarCode = new Barcode128();
        shipBarCode.X = 0.75f;
        shipBarCode.N = 1.5f;
        shipBarCode.Size = 10f;
        shipBarCode.TextAlignment = Element.ALIGN_CENTER;
        shipBarCode.Baseline = 10f;
        shipBarCode.BarHeight = 50f;
        shipBarCode.Code = data.ToString();
        document.Add(shipBarCode.CreateImageWithBarcode(
          cb, BaseColor.BLACK, BaseColor.BLUE
        ));
 
        // it is composed of 3 blocks whith AI 01, 3101 and 10
        Barcode128 uccEan128 = new Barcode128();
        uccEan128.CodeType = Barcode.CODE128_UCC;
        uccEan128.Code = "(01)00000090311314(10)ABC123(15)060916";
        document.Add(uccEan128.CreateImageWithBarcode(
          cb, BaseColor.BLUE, BaseColor.BLACK
        ));
        uccEan128.Code = "0191234567890121310100035510ABC123";
        document.Add(uccEan128.CreateImageWithBarcode(
          cb, BaseColor.BLUE, BaseColor.RED
        ));
        uccEan128.Code = "(01)28880123456788";
        document.Add(uccEan128.CreateImageWithBarcode(
          cb, BaseColor.BLUE, BaseColor.BLACK
        ));
 
        // INTER25
        document.Add(new Paragraph("Barcode Interleaved 2 of 5"));
        BarcodeInter25 code25 = new BarcodeInter25();
        code25.GenerateChecksum = true;
        code25.Code = "41-1200076041-001";
        document.Add(code25.CreateImageWithBarcode(cb, null, null));
        code25.Code = "411200076041001";
        document.Add(code25.CreateImageWithBarcode(cb, null, null));
        code25.Code = "0611012345678";
        code25.ChecksumText = true;
        document.Add(code25.CreateImageWithBarcode(cb, null, null));
 
        // POSTNET
        document.Add(new Paragraph("Barcode Postnet"));
        BarcodePostnet codePost = new BarcodePostnet();
        document.Add(new Paragraph("ZIP"));
        codePost.Code = "01234";
        document.Add(codePost.CreateImageWithBarcode(cb, null, null));
        document.Add(new Paragraph("ZIP+4"));
        codePost.Code = "012345678";
        document.Add(codePost.CreateImageWithBarcode(cb, null, null));
        document.Add(new Paragraph("ZIP+4 and dp"));
        codePost.Code = "01234567890";
        document.Add(codePost.CreateImageWithBarcode(cb, null, null));
 
        document.Add(new Paragraph("Barcode Planet"));
        BarcodePostnet codePlanet = new BarcodePostnet();
        codePlanet.Code = "01234567890";
        codePlanet.CodeType = Barcode.PLANET;
        document.Add(codePlanet.CreateImageWithBarcode(cb, null, null));
 
        // CODE 39
        document.Add(new Paragraph("Barcode 3 of 9"));
        Barcode39 code39 = new Barcode39();
        code39.Code = "ITEXT IN ACTION";
        document.Add(code39.CreateImageWithBarcode(cb, null, null));
 
        document.Add(new Paragraph("Barcode 3 of 9 extended"));
        Barcode39 code39ext = new Barcode39();
        code39ext.Code = "iText in Action";
        code39ext.StartStopText = false;
        code39ext.Extended = true;
        document.Add(code39ext.CreateImageWithBarcode(cb, null, null));
 
        // CODABAR
        document.Add(new Paragraph("Codabar"));
        BarcodeCodabar codabar = new BarcodeCodabar();
        codabar.Code = "A123A";
        codabar.StartStopText = true;
        document.Add(codabar.CreateImageWithBarcode(cb, null, null));
 
        // PDF417
        document.Add(new Paragraph("Barcode PDF417"));
        BarcodePDF417 pdf417 = new BarcodePDF417();
        String text = "Call me Ishmael. Some years ago--never mind how long "
        + "precisely --having little or no money in my purse, and nothing "
              + "particular to interest me on shore, I thought I would sail about "
              + "a little and see the watery part of the world."
            ;
        pdf417.SetText(text);
        Image img = pdf417.GetImage();
        img.ScalePercent(50, 50 * pdf417.YHeight);
        document.Add(img);
 
        document.Add(new Paragraph("Barcode Datamatrix"));
        BarcodeDatamatrix datamatrix = new BarcodeDatamatrix();
        datamatrix.Generate(text);
        img = datamatrix.CreateImage();
        document.Add(img);
 
        document.Add(new Paragraph("Barcode QRCode"));
        BarcodeQRCode qrcode = new BarcodeQRCode(
          "Moby Dick by Herman Melville", 1, 1, null
        );
        img = qrcode.GetImage();
        document.Add(img);        
      }
    }
// ===========================================================================
  }
}
CompressImage.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class CompressImage : IWriter {
// ===========================================================================
    /** The resulting PDF file. */
    public const string RESULT1 = "uncompressed.pdf";
    /** The resulting PDF file. */
    public const string RESULT2 = "compressed.pdf";
    /** One of the resources. */
    public const string RESOURCE = "butterfly.bmp";
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        CompressImage c = new CompressImage();
        zip.AddEntry(RESULT1, c.CreatePdf(false));
        zip.AddEntry(RESULT2, c.CreatePdf(true));
        zip.AddFile(Path.Combine(Utility.ResourceImage, RESOURCE), "");
        zip.Save(stream);             
      }
    }
// ---------------------------------------------------------------------------
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     */    
    public byte[] CreatePdf(bool compress)  {
      using (MemoryStream ms = new MemoryStream()) {
      // step 1
        using (Document document = new Document()) {
          // step 2
          PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
          Image img = Image.GetInstance(
            Path.Combine(Utility.ResourceImage, RESOURCE)
          );
          if (compress) img.CompressionLevel = 9;
          document.Add(img);
        }
        return ms.ToArray();
      }
    }    
// ===========================================================================
  }
}
CompressAwt.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class CompressAwt : IWriter {
// ===========================================================================
    /** The resulting PDF file. */
    public const string RESULT1 = "hitchcock100.pdf";
    /** The resulting PDF file. */
    public const string RESULT2 = "hitchcock20.pdf";
    /** The resulting PDF file. */
    public const string RESULT3 = "hitchcock10.pdf";
    /** One of the resources. */
    public static string RESOURCE = Path.Combine(
      Utility.ResourceImage, "hitchcock.png"
    );
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        CompressAwt c = new CompressAwt();
        zip.AddEntry(RESULT1, c.CreatePdf(100L));
        zip.AddEntry(RESULT2, c.CreatePdf(20L));
        zip.AddEntry(RESULT3, c.CreatePdf(10L));
        zip.AddFile(RESOURCE, "");
        zip.Save(stream);             
      }
    }
// ---------------------------------------------------------------------------
/*
 * you DO NOT want to use classes within the System.Drawing namespace to
 * manipulate image files in ASP.NET applications, see the warning here:
 * http://msdn.microsoft.com/en-us/library/system.drawing.aspx
*/
    public byte[] CreatePdf(long quality) {
      using (MemoryStream msDoc = new MemoryStream()) {
        Image img = null;
        using (System.Drawing.Bitmap dotnetImg = 
            new System.Drawing.Bitmap(RESOURCE)) 
        {
          // set codec to jpeg type => jpeg index codec is "1"
          System.Drawing.Imaging.ImageCodecInfo codec = 
          System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
          // set parameters for image quality
          System.Drawing.Imaging.EncoderParameters eParams = 
            new System.Drawing.Imaging.EncoderParameters(1);
          eParams.Param[0] = 
            new System.Drawing.Imaging.EncoderParameter(
              System.Drawing.Imaging.Encoder.Quality, quality
          );
          using (MemoryStream msImg = new MemoryStream()) {
            dotnetImg.Save(msImg, codec, eParams);
            msImg.Position = 0;
            img = Image.GetInstance(msImg);
            img.SetAbsolutePosition(15, 15);
            // step 1
            using (Document document = new Document()) {
              // step 2
              PdfWriter.GetInstance(document, msDoc);
              // step 3
              document.Open();
              // step 4
              document.Add(img);
            }
          }
        }
        return msDoc.ToArray();
      }
    }
// ===========================================================================
  }
}
PagedImages.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.codec;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class PagedImages : IWriter {
// ===========================================================================
    /** The resulting PDF file. */
    public const String RESULT = "tiff_jbig2_gif.pdf";
    /** One of the resources. */
    public static string RESOURCE1 = Path.Combine(Utility.ResourceImage, "marbles.tif");
    /** One of the resources. */
    public static string RESOURCE2 = Path.Combine(Utility.ResourceImage, "amb.jb2");
    /** One of the resources. */
    public static string RESOURCE3 = Path.Combine(Utility.ResourceImage, "animated_fox_dog.gif");
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        PagedImages p = new PagedImages();
        zip.AddEntry(RESULT, p.CreatePdf());
        zip.AddFile(RESOURCE1, "");
        zip.AddFile(RESOURCE2, "");
        zip.AddFile(RESOURCE3, "");
        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
          AddTif(document, RESOURCE1);
          document.NewPage();
          AddJBIG2(document, RESOURCE2);
          document.NewPage();
          AddGif(document, RESOURCE3);
        }
        return ms.ToArray();
      }
    }
// ---------------------------------------------------------------------------    
    public void AddTif(Document document, String path) {
      RandomAccessFileOrArray ra = new RandomAccessFileOrArray(path);
      int n = TiffImage.GetNumberOfPages(ra);
      Image img;
      for (int i = 1; i <= n; i++) {
        img = TiffImage.GetTiffImage(ra, i);
        img.ScaleToFit(523, 350);
        document.Add(img);
      }
    }
// ---------------------------------------------------------------------------    
    public void AddJBIG2(Document document, String path) {
      RandomAccessFileOrArray ra = new RandomAccessFileOrArray(path);
      int n = JBIG2Image.GetNumberOfPages(ra);
      Image img;
      for (int i = 1; i <= n; i++) {
        img = JBIG2Image.GetJbig2Image(ra, i);
        img.ScaleToFit(523, 350);
        document.Add(img);
      }
    }
// ---------------------------------------------------------------------------    
    public void AddGif(Document document, String path) {
      GifImage img = new GifImage(path);
      int n = img.GetFrameCount();
      for (int i = 1; i <= n; i++) {
        document.Add(img.GetImage(i));
      }
    }    
// ===========================================================================
  }
}
TransparentImage.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class TransparentImage : IWriter {
// ===========================================================================
    /** The resulting PDF file. */
    public const String RESULT = "transparant_image.pdf";
    /** One of the resources. */
    public static string RESOURCE1 = Path.Combine(Utility.ResourceImage, "bruno.jpg");
    /** One of the resources. */
    public static string RESOURCE2 = Path.Combine(Utility.ResourceImage, "info.png");
    /** One of the resources. */
    public static string RESOURCE3 = Path.Combine(Utility.ResourceImage, "1t3xt.gif");
    /** One of the resources. */
    public static string RESOURCE4 = Path.Combine(Utility.ResourceImage, "logo.gif");
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        TransparentImage t = new TransparentImage();
        zip.AddEntry(RESULT, t.CreatePdf());
        zip.AddFile(RESOURCE1, "");
        zip.AddFile(RESOURCE2, "");
        zip.AddFile(RESOURCE3, "");
        zip.AddFile(RESOURCE4, "");
        zip.Save(stream);             
      }
    }
// --------------------------------------------------------------------------- 
    /**
     * Creates a PDF document.
     */
    public byte[] CreatePdf() {
      using (MemoryStream ms = new MemoryStream()) {
        Image img1 = Image.GetInstance(
          Path.Combine(Utility.ResourceImage, RESOURCE1)
        );
        // step 1
        using (Document document = new Document()) {
          // step 2
          PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
          img1.SetAbsolutePosition(0, 0);
          document.Add(img1);
          Image img2 = Image.GetInstance(
            Path.Combine(Utility.ResourceImage, RESOURCE2)
          );
          img2.SetAbsolutePosition(0, 260);
          document.Add(img2);
          Image img3 = Image.GetInstance(
            Path.Combine(Utility.ResourceImage,RESOURCE3)
          );
          img3.Transparency = new int[]{ 0x00, 0x10 };
          img3.SetAbsolutePosition(0, 0);
          document.Add(img3);
          Image img4 = Image.GetInstance(
            Path.Combine(Utility.ResourceImage,RESOURCE4)
          );
          img4.Transparency = new int[]{ 0xF0, 0xFF };
          img4.SetAbsolutePosition(50, 50);
          document.Add(img4);
        }
        return ms.ToArray();
      }
    }
// ===========================================================================
  }
}
TransparentAwt.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class TransparentAwt : IWriter {
// ===========================================================================
    /** The resulting PDF file. */
    public const String RESULT = "transparant_hitchcock.pdf";
    /** One of the resources. */
    public static string RESOURCE = Path.Combine(
      Utility.ResourceImage, "hitchcock.gif"
    );
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        TransparentAwt t = new TransparentAwt();
        zip.AddEntry(RESULT, t.CreatePdf());
        zip.AddFile(RESOURCE, "");
        zip.Save(stream);             
      }
    }
// --------------------------------------------------------------------------- 
    /**
     * Creates a PDF document.
     */ 
    public byte[] CreatePdf() {
      using (MemoryStream ms = new MemoryStream()) {
        // step 1
        Rectangle r = new Rectangle(PageSize.A4);
        r.BackgroundColor = new GrayColor(0.8f);
        using (Document document = new Document(r)) {
          // step 2
          PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
/*
* you DO NOT want to use classes within the System.Drawing namespace to
* manipulate image files in ASP.NET applications, see the warning here:
* http://msdn.microsoft.com/en-us/library/system.drawing.aspx
*/
          using (System.Drawing.Image dotnet_img = 
            System.Drawing.Image.FromFile(
              Path.Combine(Utility.ResourceImage, RESOURCE)
            )) 
          {
            document.Add(new Paragraph("Hitchcock in Red."));
            Image img1 = Image.GetInstance(
              dotnet_img, System.Drawing.Imaging.ImageFormat.Gif
            );
            document.Add(img1);
            document.Add(new Paragraph("Hitchcock in Black and White."));
            Image img2 = Image.GetInstance(dotnet_img, null, true);
            document.Add(img2);
            document.NewPage();
            document.Add(new Paragraph("Hitchcock in Red and Yellow."));
            Image img3 = Image.GetInstance(
              dotnet_img, new BaseColor(0xFF, 0xFF, 0x00)
            );
            document.Add(img3);
            document.Add(new Paragraph("Hitchcock in Black and White."));
            Image img4 = Image.GetInstance(
              dotnet_img, new BaseColor(0xFF, 0xFF, 0x00), true
            );
            document.Add(img4);
          }
        }
        return ms.ToArray();
      }
    }
// ===========================================================================
  }
}
ImageMask.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class ImageMask : IWriter {
// ===========================================================================
    /** The resulting PDF file. */
    public const String RESULT1 = "hardmask.pdf";
    /** The resulting PDF file. */
    public const String RESULT2 = "softmask.pdf";
    /** One of the resources. */
    public static string RESOURCE = Path.Combine(Utility.ResourceImage, "bruno.jpg");
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {    
      using (ZipFile zip = new ZipFile()) {
        byte[] circledata = { 
          (byte) 0x3c, (byte) 0x7e, (byte) 0xff, (byte) 0xff, 
          (byte) 0xff, (byte) 0xff, (byte) 0x7e, (byte) 0x3c 
        };
        Image mask = Image.GetInstance(8, 8, 1, 1, circledata);
        mask.MakeMask();
        mask.Inverted = true;
        
        ImageMask im = new ImageMask();
        zip.AddEntry(RESULT1, im.CreatePdf(mask));
        
        byte[] gradient = new byte[256];
        for (int i = 0; i < 256; i++) {
          gradient[i] = (byte) i;
        }
        mask = Image.GetInstance(256, 1, 1, 8, gradient);
        mask.MakeMask();
        im = new ImageMask();
        zip.AddEntry(RESULT2, im.CreatePdf(mask));
 
        zip.AddFile(RESOURCE, "");
        zip.Save(stream);             
      }
    }
// --------------------------------------------------------------------------- 
    /**
     * Creates a PDF document.
     */ 
    public byte[] CreatePdf(Image mask) {
      using (MemoryStream ms = new MemoryStream()) {
        // step 1
        using (Document document = new Document()) {
          // step 2
          PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
          Image img = Image.GetInstance(RESOURCE);
          img.ImageMask = mask;
          document.Add(img);
        }
        return ms.ToArray();
      }
    }
// ===========================================================================
  }
}
TemplateClip.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class TemplateClip : IWriter {
// ===========================================================================
    /** The resulting PDF file. */
    public const String RESULT = "template_clip.pdf";
    /** One of the resources. */
    public static string RESOURCE = Path.Combine(
      Utility.ResourceImage, "bruno_ingeborg.jpg"
    );
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        TemplateClip t = new TemplateClip();
        zip.AddEntry(RESULT, t.CreatePdf());
        zip.AddFile(RESOURCE, "");
        zip.Save(stream);             
      }
    }
// ---------------------------------------------------------------------------
    public byte[] CreatePdf() {
      using (MemoryStream ms = new MemoryStream()) {    
        // step 1
        using (Document document = new Document()) {
          // step 2
          PdfWriter writer = PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
          Image img = Image.GetInstance(
            Path.Combine(Utility.ResourceImage, RESOURCE)
          );
          float w = img.ScaledWidth;
          float h = img.ScaledHeight;
          PdfTemplate t = writer.DirectContent.CreateTemplate(850, 600);
          t.AddImage(img, w, 0, 0, h, 0, -600);
          Image clipped = Image.GetInstance(t);
          clipped.ScalePercent(50);
          document.Add(clipped);
        }
        return ms.ToArray();
      }
    }
// ===========================================================================
  }
}
ClippingPath.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class ClippingPath : IWriter {
// ===========================================================================
    /** The resulting PDF file. */
    public const String RESULT = "clipping_path.pdf";
    /** One of the resources. */
    public static string RESOURCE = Path.Combine(
      Utility.ResourceImage, "bruno_ingeborg.jpg"
    );
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        ClippingPath c = new ClippingPath();
        zip.AddEntry(RESULT, c.CreatePdf());
        zip.AddFile(RESOURCE, "");
        zip.Save(stream);             
      }
    }
// ---------------------------------------------------------------------------
    public byte[] CreatePdf() {
      using (MemoryStream ms = new MemoryStream()) {    
        // step 1
        using (Document document = new Document()) {
          // step 2
          PdfWriter writer = PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
          Image img = Image.GetInstance(
            Path.Combine(Utility.ResourceImage, RESOURCE)
          );
          float w = img.ScaledWidth;
          float h = img.ScaledHeight;
          PdfTemplate t = writer.DirectContent.CreateTemplate(850, 600);
          t.Ellipse(0, 0, 850, 600);
          t.Clip();
          t.NewPath();
          t.AddImage(img, w, 0, 0, h, 0, -600);
          Image clipped = Image.GetInstance(t);
          clipped.ScalePercent(50);
          document.Add(clipped);        
        }
        return ms.ToArray();
      }
    }
// ===========================================================================
  }
}
TransparentOverlay.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
/*
 * 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.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
namespace kuujinbo.iTextInAction2Ed.Chapter10 {
  public class TransparentOverlay : IWriter {
// ===========================================================================
    /** The resulting PDF file. */
    public const String RESULT = "transparent_overlay.pdf";
    /** One of the resources. */
    public static string RESOURCE = Path.Combine(
      Utility.ResourceImage, "bruno_ingeborg.jpg"
    );
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        TransparentOverlay t = new TransparentOverlay();
        zip.AddEntry(RESULT, t.CreatePdf());
        zip.AddFile(RESOURCE, "");
        zip.Save(stream);             
      }
    }
// ---------------------------------------------------------------------------
    public byte[] CreatePdf() {
      using (MemoryStream ms = new MemoryStream()) {    
        // step 1
        using (Document document = new Document(new Rectangle(850, 600))) {
          // step 2
          PdfWriter writer = PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
          PdfContentByte canvas = writer.DirectContent;
          // add the clipped image
          Image img = Image.GetInstance(
            Path.Combine(Utility.ResourceImage, RESOURCE)
          );
          float w = img.ScaledWidth;
          float h = img.ScaledHeight;
          canvas.Ellipse(1, 1, 848, 598);
          canvas.Clip();
          canvas.NewPath();
          canvas.AddImage(img, w, 0, 0, h, 0, -600);
 
          // Create a transparent PdfTemplate
          PdfTemplate t2 = writer.DirectContent.CreateTemplate(850, 600);
          PdfTransparencyGroup transGroup = new PdfTransparencyGroup();
          transGroup.Put( PdfName.CS, PdfName.DEVICEGRAY);
          transGroup.Isolated = true;
          transGroup.Knockout = false;
          t2.Group = transGroup;
 
          // Add transparent ellipses to the template
          int gradationStep = 30;
          float[] gradationRatioList = new float[gradationStep];
          for(int i = 0; i < gradationStep; i++) {
/*
* gotta love .NET, guess they forgot to copy java.lang.Math.toRadians
*/
            double radians = (Math.PI / 180) * 90.0f / gradationStep * (i + 1);
            gradationRatioList[i] = 1 - (float) Math.Sin(radians);
          }
          for(int i = 1; i < gradationStep + 1; i++) {
              t2.SetLineWidth(5 * (gradationStep + 1 - i));
              t2.SetGrayStroke(gradationRatioList[gradationStep - i]);
              t2.Ellipse(0, 0, 850, 600);
              t2.Stroke();
          }
          
          // Create an image mask for the direct content
          PdfDictionary maskDict = new PdfDictionary();
          maskDict.Put(PdfName.TYPE, PdfName.MASK);
          maskDict.Put(PdfName.S, new PdfName("Luminosity"));
          maskDict.Put(new PdfName("G"), t2.IndirectReference);
          PdfGState gState = new PdfGState();
          gState.Put(PdfName.SMASK, maskDict );
          canvas.SetGState(gState);
          
          canvas.AddTemplate(t2, 0, 0);        
        }
        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