Chapter 15: Page content and structure

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

10th October 2015
admin-marketing

Switch code for this example

PeekABoo.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter15;
  8.  
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11.  
  12. import com.itextpdf.text.Document;
  13. import com.itextpdf.text.DocumentException;
  14. import com.itextpdf.text.Element;
  15. import com.itextpdf.text.pdf.BaseFont;
  16. import com.itextpdf.text.pdf.PdfContentByte;
  17. import com.itextpdf.text.pdf.PdfLayer;
  18. import com.itextpdf.text.pdf.PdfWriter;
  19.  
  20. /**
  21.  * This example was written by Bruno Lowagie. It is part of the book 'iText in
  22.  * Action' by Manning Publications.
  23.  * ISBN: 1932394796
  24.  * http://www.1t3xt.com/docs/book.php
  25.  * http://www.manning.com/lowagie/
  26.  */
  27.  
  28. public class PeekABoo {
  29.  
  30.     /** The first resulting PDF. */
  31.     public static String RESULT1 = "results/part4/chapter15/peek-a-boo1.pdf";
  32.     /** The second resulting PDF. */
  33.     public static String RESULT2 = "results/part4/chapter15/peek-a-boo2.pdf";
  34.  
  35.     /**
  36.      * Creates a PDF document.
  37.      * @param filename the path to the new PDF document
  38.      * @throws DocumentException
  39.      * @throws IOException
  40.      */
  41.     public void createPdf(String filename, boolean on) throws DocumentException, IOException {
  42.         // step 1
  43.         Document document = new Document();
  44.         // step 2
  45.         PdfWriter writer = PdfWriter.getInstance(document,
  46.             new FileOutputStream(filename));
  47.         writer.setViewerPreferences(PdfWriter.PageModeUseOC);
  48.         writer.setPdfVersion(PdfWriter.VERSION_1_5);
  49.         // step 3
  50.         document.open();
  51.         // step 4
  52.         PdfLayer layer = new PdfLayer("Do you see me?", writer);
  53.         layer.setOn(on);
  54.         BaseFont bf = BaseFont.createFont();
  55.         PdfContentByte cb = writer.getDirectContent();
  56.         cb.beginText();
  57.         cb.setFontAndSize(bf, 18);
  58.         cb.showTextAligned(Element.ALIGN_LEFT, "Do you see me?", 50, 790, 0);
  59.         cb.beginLayer(layer);
  60.         cb.showTextAligned(Element.ALIGN_LEFT, "Peek-a-Boo!!!", 50, 766, 0);
  61.         cb.endLayer();
  62.         cb.endText();
  63.         // step 5
  64.         document.close();
  65.     }
  66.    
  67.     /**
  68.      * A simple example with optional content.
  69.      *
  70.      * @param args
  71.      *            no arguments needed here
  72.      * @throws IOException
  73.      * @throws DocumentException
  74.      */
  75.     public static void main(String[] args) throws DocumentException, IOException {
  76.         PeekABoo peekaboo = new PeekABoo();
  77.         peekaboo.createPdf(RESULT1, true);
  78.         peekaboo.createPdf(RESULT2, false);
  79.     }
  80. }
OptionalContentExample.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter15;
  8.  
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.util.ArrayList;
  12.  
  13. import com.itextpdf.text.Document;
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.Element;
  16. import com.itextpdf.text.Phrase;
  17. import com.itextpdf.text.pdf.ColumnText;
  18. import com.itextpdf.text.pdf.PdfContentByte;
  19. import com.itextpdf.text.pdf.PdfLayer;
  20. import com.itextpdf.text.pdf.PdfWriter;
  21.  
  22. public class OptionalContentExample {
  23.  
  24.     /** The resulting PDF. */
  25.     public static String RESULT = "results/part4/chapter15/layer_structure.pdf";
  26.  
  27.     /**
  28.      * Creates a PDF document.
  29.      * @param filename the path to the new PDF document
  30.      * @throws DocumentException
  31.      * @throws IOException
  32.      */
  33.     public void createPdf(String filename)
  34.         throws DocumentException, IOException {
  35.         // step 1
  36.         Document document = new Document();
  37.         // step 2
  38.         PdfWriter writer =
  39.             PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  40.         writer.setPdfVersion(PdfWriter.VERSION_1_5);
  41.         // step 3
  42.         document.open();
  43.         // step 4
  44.         PdfContentByte cb = writer.getDirectContent();
  45.         PdfLayer nested = new PdfLayer("Nested layers", writer);
  46.         PdfLayer nested_1 = new PdfLayer("Nested layer 1", writer);
  47.         PdfLayer nested_2 = new PdfLayer("Nested layer 2", writer);
  48.         nested.addChild(nested_1);
  49.         nested.addChild(nested_2);
  50.         writer.lockLayer(nested_2);
  51.         cb.beginLayer(nested);
  52.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(
  53.                 "nested layers"), 50, 775, 0);
  54.         cb.endLayer();
  55.         cb.beginLayer(nested_1);
  56.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(
  57.                 "nested layer 1"), 100, 800, 0);
  58.         cb.endLayer();
  59.         cb.beginLayer(nested_2);
  60.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(
  61.                 "nested layer 2"), 100, 750, 0);
  62.         cb.endLayer();
  63.  
  64.         PdfLayer group = PdfLayer.createTitle("Grouped layers", writer);
  65.         PdfLayer layer1 = new PdfLayer("Group: layer 1", writer);
  66.         PdfLayer layer2 = new PdfLayer("Group: layer 2", writer);
  67.         group.addChild(layer1);
  68.         group.addChild(layer2);
  69.         cb.beginLayer(layer1);
  70.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(
  71.                 "layer 1 in the group"), 50, 700, 0);
  72.         cb.endLayer();
  73.         cb.beginLayer(layer2);
  74.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(
  75.                 "layer 2 in the group"), 50, 675, 0);
  76.         cb.endLayer();
  77.  
  78.         PdfLayer radiogroup = PdfLayer.createTitle("Radio group", writer);
  79.         PdfLayer radio1 = new PdfLayer("Radiogroup: layer 1", writer);
  80.         radio1.setOn(true);
  81.         PdfLayer radio2 = new PdfLayer("Radiogroup: layer 2", writer);
  82.         radio2.setOn(false);
  83.         PdfLayer radio3 = new PdfLayer("Radiogroup: layer 3", writer);
  84.         radio3.setOn(false);
  85.         radiogroup.addChild(radio1);
  86.         radiogroup.addChild(radio2);
  87.         radiogroup.addChild(radio3);
  88.         ArrayList options = new ArrayList();
  89.         options.add(radio1);
  90.         options.add(radio2);
  91.         options.add(radio3);
  92.         writer.addOCGRadioGroup(options);
  93.         cb.beginLayer(radio1);
  94.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(
  95.                 "option 1"), 50, 600, 0);
  96.         cb.endLayer();
  97.         cb.beginLayer(radio2);
  98.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(
  99.                 "option 2"), 50, 575, 0);
  100.         cb.endLayer();
  101.         cb.beginLayer(radio3);
  102.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(
  103.                 "option 3"), 50, 550, 0);
  104.         cb.endLayer();
  105.  
  106.         PdfLayer not_printed = new PdfLayer("not printed", writer);
  107.         not_printed.setOnPanel(false);
  108.         not_printed.setPrint("Print", false);
  109.         cb.beginLayer(not_printed);
  110.         ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, new Phrase(
  111.                 "PRINT THIS PAGE"), 300, 700, 90);
  112.         cb.endLayer();
  113.  
  114.         PdfLayer zoom = new PdfLayer("Zoom 0.75-1.25", writer);
  115.         zoom.setOnPanel(false);
  116.         zoom.setZoom(0.75f, 1.25f);
  117.         cb.beginLayer(zoom);
  118.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(
  119.                 "Only visible if the zoomfactor is between 75 and 125%"), 30,
  120.                 530, 90);
  121.         cb.endLayer();
  122.  
  123.         // step 5
  124.         document.close();
  125.     }
  126.  
  127.     /**
  128.      * A simple example with optional content.
  129.      *
  130.      * @param args
  131.      *            no arguments needed here
  132.      * @throws IOException
  133.      * @throws DocumentException
  134.      */
  135.     public static void main(String[] args) throws DocumentException,
  136.             IOException {
  137.         new OptionalContentExample().createPdf(RESULT);
  138.     }
  139. }
LayerMembershipExample1.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter15;
  8.  
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11.  
  12. import com.itextpdf.text.Document;
  13. import com.itextpdf.text.DocumentException;
  14. import com.itextpdf.text.Element;
  15. import com.itextpdf.text.Phrase;
  16. import com.itextpdf.text.pdf.ColumnText;
  17. import com.itextpdf.text.pdf.PdfContentByte;
  18. import com.itextpdf.text.pdf.PdfLayer;
  19. import com.itextpdf.text.pdf.PdfLayerMembership;
  20. import com.itextpdf.text.pdf.PdfWriter;
  21.  
  22. public class LayerMembershipExample1 {
  23.  
  24.     /** The resulting PDF. */
  25.     public static String RESULT = "results/part4/chapter15/layer_membership1.pdf";
  26.  
  27.     /**
  28.      * Creates a PDF document.
  29.      * @param filename the path to the new PDF document
  30.      * @throws DocumentException
  31.      * @throws IOException
  32.      */
  33.     public void createPdf(String filename) throws DocumentException, IOException {
  34.         // step 1
  35.         Document document = new Document();
  36.         // step 2
  37.         PdfWriter writer = PdfWriter.getInstance(
  38.                 document, new FileOutputStream(RESULT));
  39.         writer.setPdfVersion(PdfWriter.VERSION_1_5);
  40.         // step 3
  41.         document.open();
  42.         // step 4
  43.         PdfContentByte cb = writer.getDirectContent();
  44.  
  45.         PdfLayer dog = new PdfLayer("layer 1", writer);
  46.         PdfLayer tiger = new PdfLayer("layer 2", writer);
  47.         PdfLayer lion = new PdfLayer("layer 3", writer);
  48.         PdfLayerMembership cat = new PdfLayerMembership(writer);
  49.         cat.addMember(tiger);
  50.         cat.addMember(lion);
  51.         PdfLayerMembership no_cat = new PdfLayerMembership(writer);
  52.         no_cat.addMember(tiger);
  53.         no_cat.addMember(lion);
  54.         no_cat.setVisibilityPolicy(PdfLayerMembership.ALLOFF);
  55.         cb.beginLayer(dog);
  56.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase("dog"),
  57.                 50, 775, 0);
  58.         cb.endLayer();
  59.         cb.beginLayer(tiger);
  60.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase("tiger"),
  61.                 50, 750, 0);
  62.         cb.endLayer();
  63.         cb.beginLayer(lion);
  64.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase("lion"),
  65.                 50, 725, 0);
  66.         cb.endLayer();
  67.         cb.beginLayer(cat);
  68.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase("cat"),
  69.                 50, 700, 0);
  70.         cb.endLayer();
  71.         cb.beginLayer(no_cat);
  72.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT,
  73.                 new Phrase("no cat"), 50, 700, 0);
  74.         cb.endLayer();
  75.  
  76.         // step 5
  77.         document.close();
  78.     }
  79.  
  80.     /**
  81.      * A simple example with optional content.
  82.      *
  83.      * @param args
  84.      *            no arguments needed here
  85.      * @throws IOException
  86.      * @throws DocumentException
  87.      */
  88.     public static void main(String[] args) throws DocumentException,
  89.             IOException {
  90.         new LayerMembershipExample1().createPdf(RESULT);
  91.     }
  92. }
LayerMembershipExample2.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter15;
  8.  
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11.  
  12. import com.itextpdf.text.Document;
  13. import com.itextpdf.text.DocumentException;
  14. import com.itextpdf.text.Element;
  15. import com.itextpdf.text.Phrase;
  16. import com.itextpdf.text.pdf.ColumnText;
  17. import com.itextpdf.text.pdf.PdfContentByte;
  18. import com.itextpdf.text.pdf.PdfLayer;
  19. import com.itextpdf.text.pdf.PdfLayerMembership;
  20. import com.itextpdf.text.pdf.PdfVisibilityExpression;
  21. import com.itextpdf.text.pdf.PdfWriter;
  22.  
  23. public class LayerMembershipExample2 {
  24.  
  25.     /** The resulting PDF. */
  26.     public static String RESULT = "results/part4/chapter15/layer_membership2.pdf";
  27.  
  28.     /**
  29.      * Creates a PDF document.
  30.      * @param filename the path to the new PDF document
  31.      * @throws DocumentException
  32.      * @throws IOException
  33.      */
  34.     public void createPdf(String filename) throws DocumentException,
  35.             IOException {
  36.         // step 1
  37.         Document document = new Document();
  38.         // step 2
  39.         PdfWriter writer = PdfWriter.getInstance(
  40.                 document, new FileOutputStream(RESULT));
  41.         writer.setPdfVersion(PdfWriter.VERSION_1_6);
  42.         // step 3
  43.         document.open();
  44.         // step 4
  45.         PdfContentByte cb = writer.getDirectContent();
  46.  
  47.         PdfLayer dog = new PdfLayer("layer 1", writer);
  48.         PdfLayer tiger = new PdfLayer("layer 2", writer);
  49.         PdfLayer lion = new PdfLayer("layer 3", writer);
  50.         PdfLayerMembership cat = new PdfLayerMembership(writer);
  51.         PdfVisibilityExpression ve1 = new PdfVisibilityExpression(PdfVisibilityExpression.OR);
  52.         ve1.add(tiger);
  53.         ve1.add(lion);
  54.         cat.setVisibilityExpression(ve1);
  55.         PdfLayerMembership no_cat = new PdfLayerMembership(writer);
  56.         PdfVisibilityExpression ve2 = new PdfVisibilityExpression(PdfVisibilityExpression.NOT);
  57.         ve2.add(ve1);
  58.         no_cat.setVisibilityExpression(ve2);
  59.         cb.beginLayer(dog);
  60.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase("dog"),
  61.                 50, 775, 0);
  62.         cb.endLayer();
  63.         cb.beginLayer(tiger);
  64.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase("tiger"),
  65.                 50, 750, 0);
  66.         cb.endLayer();
  67.         cb.beginLayer(lion);
  68.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase("lion"),
  69.                 50, 725, 0);
  70.         cb.endLayer();
  71.         cb.beginLayer(cat);
  72.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase("cat"),
  73.                 50, 700, 0);
  74.         cb.endLayer();
  75.         cb.beginLayer(no_cat);
  76.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT,
  77.                 new Phrase("no cat"), 50, 700, 0);
  78.         cb.endLayer();
  79.  
  80.         // step 5
  81.         document.close();
  82.     }
  83.  
  84.     /**
  85.      * A simple example with optional content.
  86.      *
  87.      * @param args
  88.      *            no arguments needed here
  89.      * @throws IOException
  90.      * @throws DocumentException
  91.      */
  92.     public static void main(String[] args) throws DocumentException,
  93.             IOException {
  94.         new LayerMembershipExample2().createPdf(RESULT);
  95.     }
  96. }
OptionalContentActionExample.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter15;
  8.  
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.util.ArrayList;
  12.  
  13. import com.itextpdf.text.Chunk;
  14. import com.itextpdf.text.Document;
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.Element;
  17. import com.itextpdf.text.Phrase;
  18. import com.itextpdf.text.pdf.BaseFont;
  19. import com.itextpdf.text.pdf.PdfAction;
  20. import com.itextpdf.text.pdf.PdfContentByte;
  21. import com.itextpdf.text.pdf.PdfLayer;
  22. import com.itextpdf.text.pdf.PdfWriter;
  23.  
  24. public class OptionalContentActionExample {
  25.  
  26.     /** The resulting PDF. */
  27.     public static String RESULT = "results/part4/chapter15/layer_actions.pdf";
  28.  
  29.     /**
  30.      * Creates a PDF document.
  31.      * @param filename the path to the new PDF document
  32.      * @throws DocumentException
  33.      * @throws IOException
  34.      */
  35.     public void createPdf(String filename) throws DocumentException, IOException {
  36.         // step 1
  37.         Document document = new Document();
  38.         // step 2
  39.         PdfWriter writer = PdfWriter.getInstance(
  40.                 document, new FileOutputStream(RESULT));
  41.         writer.setPdfVersion(PdfWriter.VERSION_1_5);
  42.         // step 3
  43.         document.open();
  44.         // step 4
  45.         PdfLayer a1 = new PdfLayer("answer 1", writer);
  46.         PdfLayer a2 = new PdfLayer("answer 2", writer);
  47.         PdfLayer a3 = new PdfLayer("answer 3", writer);
  48.         a1.setOn(false);
  49.         a2.setOn(false);
  50.         a3.setOn(false);
  51.  
  52.         BaseFont bf = BaseFont.createFont();
  53.         PdfContentByte cb = writer.getDirectContent();
  54.         cb.beginText();
  55.         cb.setFontAndSize(bf, 18);
  56.         cb.showTextAligned(Element.ALIGN_LEFT,
  57.             "Q1: Who is the director of the movie 'Paths of Glory'?", 50, 766, 0);
  58.         cb.showTextAligned(Element.ALIGN_LEFT,
  59.             "Q2: Who directed the movie 'Lawrence of Arabia'?", 50, 718, 0);
  60.         cb.showTextAligned(Element.ALIGN_LEFT,
  61.             "Q3: Who is the director of 'House of Flying Daggers'?", 50, 670, 0);
  62.         cb.endText();
  63.         cb.saveState();
  64.         cb.setRGBColorFill(0xFF, 0x00, 0x00);
  65.         cb.beginText();
  66.         cb.beginLayer(a1);
  67.         cb.showTextAligned(Element.ALIGN_LEFT,
  68.                 "A1: Stanley Kubrick", 50, 742, 0);
  69.         cb.endLayer();
  70.         cb.beginLayer(a2);
  71.         cb.showTextAligned(Element.ALIGN_LEFT,
  72.                 "A2: David Lean", 50, 694, 0);
  73.         cb.endLayer();
  74.         cb.beginLayer(a3);
  75.         cb.showTextAligned(Element.ALIGN_LEFT,
  76.                 "A3: Zhang Yimou", 50, 646, 0);
  77.         cb.endLayer();
  78.         cb.endText();
  79.         cb.restoreState();
  80.  
  81.         ArrayList stateOn = new ArrayList();
  82.         stateOn.add("ON");
  83.         stateOn.add(a1);
  84.         stateOn.add(a2);
  85.         stateOn.add(a3);
  86.         PdfAction actionOn = PdfAction.setOCGstate(stateOn, true);
  87.         ArrayList stateOff = new ArrayList();
  88.         stateOff.add("OFF");
  89.         stateOff.add(a1);
  90.         stateOff.add(a2);
  91.         stateOff.add(a3);
  92.         PdfAction actionOff = PdfAction.setOCGstate(stateOff, true);
  93.         ArrayList stateToggle = new ArrayList();
  94.         stateToggle.add("Toggle");
  95.         stateToggle.add(a1);
  96.         stateToggle.add(a2);
  97.         stateToggle.add(a3);
  98.         PdfAction actionToggle = PdfAction.setOCGstate(stateToggle, true);
  99.         Phrase p = new Phrase("Change the state of the answers:");
  100.         Chunk on = new Chunk(" on ").setAction(actionOn);
  101.         p.add(on);
  102.         Chunk off = new Chunk("/ off ").setAction(actionOff);
  103.         p.add(off);
  104.         Chunk toggle = new Chunk("/ toggle").setAction(actionToggle);
  105.         p.add(toggle);
  106.         document.add(p);
  107.         // step 5
  108.         document.close();
  109.     }
  110.  
  111.     /**
  112.      * A simple example with optional content.
  113.      *
  114.      * @param args
  115.      *            no arguments needed here
  116.      * @throws IOException
  117.      * @throws DocumentException
  118.      */
  119.     public static void main(String[] args) throws DocumentException,
  120.             IOException {
  121.         new OptionalContentActionExample().createPdf(RESULT);
  122.     }
  123. }
SvgToPdf.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter15;
  8.  
  9. import java.awt.Graphics2D;
  10. import java.io.File;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13.  
  14. import org.apache.batik.bridge.BridgeContext;
  15. import org.apache.batik.bridge.DocumentLoader;
  16. import org.apache.batik.bridge.GVTBuilder;
  17. import org.apache.batik.bridge.UserAgent;
  18. import org.apache.batik.bridge.UserAgentAdapter;
  19. import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
  20. import org.apache.batik.gvt.GraphicsNode;
  21. import org.apache.batik.util.XMLResourceDescriptor;
  22. import org.w3c.dom.svg.SVGDocument;
  23.  
  24. import com.itextpdf.awt.PdfGraphics2D;
  25. import com.itextpdf.text.Document;
  26. import com.itextpdf.text.DocumentException;
  27. import com.itextpdf.text.Rectangle;
  28. import com.itextpdf.text.pdf.PdfContentByte;
  29. import com.itextpdf.text.pdf.PdfTemplate;
  30. import com.itextpdf.text.pdf.PdfWriter;
  31.  
  32. public class SvgToPdf {
  33.  
  34.     /** The resulting PDF. */
  35.     public static final String RESULT = "results/part4/chapter15/foobar.pdf";
  36.     /** The map (shapes). */
  37.     public static final String CITY = "resources/xml/foobarcity.svg";
  38.     /** The map (text = street names in English). */
  39.     public static final String STREETS = "resources/xml/foobarstreets.svg";
  40.    
  41.     /** The SVG document factory. */
  42.     protected SAXSVGDocumentFactory factory;
  43.     /** The SVG bridge context. */
  44.     protected BridgeContext ctx;
  45.     /** The GVT builder */
  46.     protected GVTBuilder builder;
  47.    
  48.     /** Creates an SvgToPdf object. */
  49.     public SvgToPdf() {
  50.         String parser = XMLResourceDescriptor.getXMLParserClassName();
  51.         factory = new SAXSVGDocumentFactory(parser);
  52.        
  53.         UserAgent userAgent = new UserAgentAdapter();
  54.         DocumentLoader loader = new DocumentLoader(userAgent);
  55.         ctx = new BridgeContext(userAgent, loader);
  56.         ctx.setDynamicState(BridgeContext.DYNAMIC);
  57.  
  58.         builder = new GVTBuilder();
  59.     }
  60.    
  61.     /**
  62.      * Draws an SVG file to a PdfTemplate.
  63.      * @param map      the template to which the SVG has to be drawn.
  64.      * @param resource the SVG content.
  65.      * @throws IOException
  66.      */
  67.     public void drawSvg(PdfTemplate map, String resource) throws IOException {
  68.         Graphics2D g2d = new PdfGraphics2D(map, 6000, 6000);
  69.         SVGDocument city = factory.createSVGDocument(new File(resource).toURL()
  70.                 .toString());
  71.         GraphicsNode mapGraphics = builder.build(ctx, city);
  72.         mapGraphics.paint(g2d);
  73.         g2d.dispose();
  74.     }
  75.    
  76.     /**
  77.      * Creates a PDF document.
  78.      * @param filename the path to the new PDF document
  79.      * @throws DocumentException
  80.      * @throws IOException
  81.      * @throws SQLException
  82.      */
  83.     public void createPdf(String filename) throws IOException, DocumentException {
  84.         // step 1
  85.         Document document = new Document(new Rectangle(6000, 6000));
  86.         // step 2
  87.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  88.         // step 3
  89.         document.open();
  90.         // step 4
  91.         PdfContentByte cb = writer.getDirectContent();
  92.         PdfTemplate map = cb.createTemplate(6000, 6000);
  93.         drawSvg(map, CITY);
  94.         cb.addTemplate(map, 0, 0);
  95.         PdfTemplate streets = cb.createTemplate(6000, 6000);
  96.         drawSvg(streets, STREETS);
  97.         cb.addTemplate(streets, 0, 0);
  98.         // step 5
  99.         document.close();
  100.     }
  101.    
  102.     /**
  103.      * Main method.
  104.      *
  105.      * @param    args    no arguments needed
  106.      * @throws DocumentException
  107.      * @throws IOException
  108.      */
  109.     public static void main(String[] args) throws IOException, DocumentException {
  110.         new SvgToPdf().createPdf(RESULT);
  111.     }
  112. }
SvgLayers.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter15;
  8.  
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.util.ArrayList;
  12.  
  13.  
  14. import com.itextpdf.text.Document;
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.Rectangle;
  17. import com.itextpdf.text.pdf.BaseFont;
  18. import com.itextpdf.text.pdf.PdfContentByte;
  19. import com.itextpdf.text.pdf.PdfLayer;
  20. import com.itextpdf.text.pdf.PdfTemplate;
  21. import com.itextpdf.text.pdf.PdfWriter;
  22.  
  23. public class SvgLayers extends SvgToPdf {
  24.  
  25.     /** The resulting PDF. */
  26.     public static final String RESULT = "results/part4/chapter15/foobarcity.pdf";
  27.     /** The map. */
  28.     public static final String RUES = "resources/xml/foobarrues.svg";
  29.     /** The map. */
  30.     public static final String STRATEN = "resources/xml/foobarstraten.svg";
  31.  
  32.    
  33.     /**
  34.      * Creates a PDF document.
  35.      * @param filename the path to the new PDF document
  36.      * @throws DocumentException
  37.      * @throws IOException
  38.      * @throws SQLException
  39.      */
  40.     public void createPdf(String filename) throws IOException, DocumentException {
  41.         // step 1
  42.         Document document = new Document(new Rectangle(6000, 6000));
  43.         // step 2
  44.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  45.         writer.setViewerPreferences(PdfWriter.PageModeUseOC | PdfWriter.FitWindow);
  46.         writer.setPdfVersion(PdfWriter.VERSION_1_5);
  47.         // step 3
  48.         document.open();
  49.         // step 4
  50.         // CREATE GRID LAYER
  51.         PdfLayer gridLayer = new PdfLayer("Grid", writer);
  52.         gridLayer.setZoom(0.2f, 1);
  53.         gridLayer.setOnPanel(false);
  54.         // CREATE STREET LAYERS
  55.         PdfLayer streetlayer = PdfLayer.createTitle(
  56.                 "Streets / Rues / Straten", writer);
  57.         PdfLayer streetlayer_en = new PdfLayer("English", writer);
  58.         streetlayer_en.setOn(true);
  59.         streetlayer_en.setLanguage("en", true);
  60.         PdfLayer streetlayer_fr = new PdfLayer("Fran\u00e7ais", writer);
  61.         streetlayer_fr.setOn(false);
  62.         streetlayer_fr.setLanguage("fr", false);
  63.         PdfLayer streetlayer_nl = new PdfLayer("Nederlands", writer);
  64.         streetlayer_nl.setOn(false);
  65.         streetlayer_nl.setLanguage("nl", false);
  66.         streetlayer.addChild(streetlayer_en);
  67.         streetlayer.addChild(streetlayer_fr);
  68.         streetlayer.addChild(streetlayer_nl);
  69.         ArrayList radio = new ArrayList();
  70.         radio.add(streetlayer_en);
  71.         radio.add(streetlayer_fr);
  72.         radio.add(streetlayer_nl);
  73.         writer.addOCGRadioGroup(radio);
  74.         // CREATE MAP
  75.         PdfContentByte cb = writer.getDirectContent();
  76.         PdfTemplate map = cb.createTemplate(6000, 6000);
  77.         // DRAW CITY
  78.         drawSvg(map, CITY);
  79.         cb.addTemplate(map, 0, 0);
  80.         PdfTemplate streets = cb.createTemplate(6000, 6000);
  81.         // DRAW STREETS
  82.         drawSvg(streets, STREETS);
  83.         streets.setLayer(streetlayer_en);
  84.         cb.addTemplate(streets, 0, 0);
  85.         PdfTemplate rues = cb.createTemplate(6000, 6000);
  86.         drawSvg(rues, RUES);
  87.         rues.setLayer(streetlayer_fr);
  88.         cb.addTemplate(rues, 0, 0);
  89.         PdfTemplate straten = cb.createTemplate(6000, 6000);
  90.         drawSvg(straten, STRATEN);
  91.         straten.setLayer(streetlayer_nl);
  92.         cb.addTemplate(straten, 0, 0);
  93.         // DRAW GRID
  94.         cb.saveState();
  95.         cb.beginLayer(gridLayer);
  96.         cb.setGrayStroke(0.7f);
  97.         cb.setLineWidth(2);
  98.         for (int i = 0; i < 8; i++) {
  99.             cb.moveTo(1250, 1500 + i * 500);
  100.             cb.lineTo(4750, 1500 + i * 500);
  101.         }
  102.         for (int i = 0; i < 8; i++) {
  103.             cb.moveTo(1250 + i * 500, 1500);
  104.             cb.lineTo(1250 + i * 500, 5000);
  105.         }
  106.         cb.stroke();
  107.         cb.endLayer();
  108.         cb.restoreState();
  109.        
  110.         // CREATE INFO LAYERS
  111.         PdfLayer cityInfoLayer = new PdfLayer("Foobar Info", writer);
  112.         cityInfoLayer.setOn(false);
  113.         PdfLayer hotelLayer = new PdfLayer("Hotel", writer);
  114.         hotelLayer.setOn(false);
  115.         cityInfoLayer.addChild(hotelLayer);
  116.         PdfLayer parkingLayer = new PdfLayer("Parking", writer);
  117.         parkingLayer.setOn(false);
  118.         cityInfoLayer.addChild(parkingLayer);
  119.         PdfLayer businessLayer = new PdfLayer("Industry", writer);
  120.         businessLayer.setOn(false);
  121.         cityInfoLayer.addChild(businessLayer);
  122.         PdfLayer cultureLayer = PdfLayer.createTitle("Leisure and Culture",
  123.                 writer);
  124.         PdfLayer goingoutLayer = new PdfLayer("Going out", writer);
  125.         goingoutLayer.setOn(false);
  126.         cultureLayer.addChild(goingoutLayer);
  127.         PdfLayer restoLayer = new PdfLayer("Restaurants", writer);
  128.         restoLayer.setOn(false);
  129.         goingoutLayer.addChild(restoLayer);
  130.         PdfLayer theatreLayer = new PdfLayer("(Movie) Theatres", writer);
  131.         theatreLayer.setOn(false);
  132.         goingoutLayer.addChild(theatreLayer);
  133.         PdfLayer monumentLayer = new PdfLayer("Museums and Monuments",
  134.                 writer);
  135.         monumentLayer.setOn(false);
  136.         cultureLayer.addChild(monumentLayer);
  137.         PdfLayer sportsLayer = new PdfLayer("Sports", writer);
  138.         sportsLayer.setOn(false);
  139.         cultureLayer.addChild(sportsLayer);
  140.         // DRAW INFO
  141.         BaseFont font = BaseFont.createFont(
  142.                 "c:/windows/fonts/webdings.ttf", BaseFont.WINANSI,
  143.                 BaseFont.EMBEDDED);
  144.         cb.saveState();
  145.         cb.beginText();
  146.         cb.setRGBColorFill(0x00, 0x00, 0xFF);
  147.         cb.setFontAndSize(font, 36);
  148.         cb.beginLayer(cityInfoLayer);
  149.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  150.                 .valueOf((char) 0x69), 2700, 3100, 0);
  151.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  152.                 .valueOf((char) 0x69), 3000, 2050, 0);
  153.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  154.                 .valueOf((char) 0x69), 3100, 2550, 0);
  155.         cb.beginLayer(hotelLayer);
  156.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  157.                 .valueOf((char) 0xe3), 2000, 1900, 0);
  158.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  159.                 .valueOf((char) 0xe3), 2100, 1950, 0);
  160.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  161.                 .valueOf((char) 0xe3), 2200, 2200, 0);
  162.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  163.                 .valueOf((char) 0xe3), 2700, 3000, 0);
  164.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  165.                 .valueOf((char) 0xe3), 2750, 3050, 0);
  166.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  167.                 .valueOf((char) 0xe3), 2500, 3500, 0);
  168.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  169.                 .valueOf((char) 0xe3), 2300, 2000, 0);
  170.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  171.                 .valueOf((char) 0xe3), 3250, 2200, 0);
  172.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  173.                 .valueOf((char) 0xe3), 3300, 2300, 0);
  174.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  175.                 .valueOf((char) 0xe3), 3400, 3050, 0);
  176.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  177.                 .valueOf((char) 0xe3), 3250, 3200, 0);
  178.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  179.                 .valueOf((char) 0xe3), 2750, 3800, 0);
  180.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  181.                 .valueOf((char) 0xe3), 2900, 3800, 0);
  182.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  183.                 .valueOf((char) 0xe3), 3000, 2400, 0);
  184.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  185.                 .valueOf((char) 0xe3), 2000, 2800, 0);
  186.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  187.                 .valueOf((char) 0xe3), 2600, 3200, 0);
  188.         cb.endLayer(); // hotelLayer
  189.         cb.beginLayer(parkingLayer);
  190.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  191.                 .valueOf((char) 0xe8), 2400, 2000, 0);
  192.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  193.                 .valueOf((char) 0xe8), 2100, 2600, 0);
  194.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  195.                 .valueOf((char) 0xe8), 3300, 2250, 0);
  196.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  197.                 .valueOf((char) 0xe8), 3000, 3900, 0);
  198.         cb.endLayer(); // parkingLayer
  199.         cb.beginLayer(businessLayer);
  200.         cb.setRGBColorFill(0xC0, 0xC0, 0xC0);
  201.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  202.                 .valueOf((char) 0x46), 3050, 3600, 0);
  203.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  204.                 .valueOf((char) 0x46), 3200, 3900, 0);
  205.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  206.                 .valueOf((char) 0x46), 3150, 3700, 0);
  207.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  208.                 .valueOf((char) 0x46), 3260, 3610, 0);
  209.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  210.                 .valueOf((char) 0x46), 3350, 3750, 0);
  211.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  212.                 .valueOf((char) 0x46), 3500, 4000, 0);
  213.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  214.                 .valueOf((char) 0x46), 3500, 3800, 0);
  215.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  216.                 .valueOf((char) 0x46), 3450, 3700, 0);
  217.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  218.                 .valueOf((char) 0x46), 3450, 3600, 0);
  219.         cb.endLayer(); // businessLayer
  220.         cb.endLayer(); // cityInfoLayer
  221.         cb.beginLayer(goingoutLayer);
  222.         cb.beginLayer(restoLayer);
  223.         cb.setRGBColorFill(0xFF, 0x14, 0x93);
  224.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  225.                 .valueOf((char) 0xe4), 2650, 3500, 0);
  226.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  227.                 .valueOf((char) 0xe4), 2400, 1900, 0);
  228.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  229.                 .valueOf((char) 0xe4), 2750, 3850, 0);
  230.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  231.                 .valueOf((char) 0xe4), 2700, 3200, 0);
  232.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  233.                 .valueOf((char) 0xe4), 2900, 3100, 0);
  234.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  235.                 .valueOf((char) 0xe4), 2850, 3000, 0);
  236.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  237.                 .valueOf((char) 0xe4), 2800, 2900, 0);
  238.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  239.                 .valueOf((char) 0xe4), 2300, 2900, 0);
  240.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  241.                 .valueOf((char) 0xe4), 1950, 2650, 0);
  242.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  243.                 .valueOf((char) 0xe4), 1800, 2750, 0);
  244.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  245.                 .valueOf((char) 0xe4), 3350, 3150, 0);
  246.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  247.                 .valueOf((char) 0xe4), 3400, 3100, 0);
  248.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  249.                 .valueOf((char) 0xe4), 3250, 3450, 0);
  250.         cb.endLayer(); // restoLayer
  251.         cb.beginLayer(theatreLayer);
  252.         cb.setRGBColorFill(0xDC, 0x14, 0x3C);
  253.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  254.                 .valueOf((char) 0xae), 2850, 3300, 0);
  255.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  256.                 .valueOf((char) 0xae), 3050, 2900, 0);
  257.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  258.                 .valueOf((char) 0xae), 2650, 2900, 0);
  259.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  260.                 .valueOf((char) 0xae), 2750, 2600, 0);
  261.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  262.                 .valueOf((char) 0xB8), 2800, 3350, 0);
  263.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  264.                 .valueOf((char) 0xB8), 2550, 2850, 0);
  265.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  266.                 .valueOf((char) 0xB8), 2850, 3300, 0);
  267.         cb.endLayer(); // theatreLayer
  268.         cb.endLayer(); // goingoutLayer
  269.         cb.beginLayer(monumentLayer);
  270.         cb.setRGBColorFill(0x00, 0x00, 0x00);
  271.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  272.                 .valueOf((char) 0x47), 3250, 2750, 0);
  273.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  274.                 .valueOf((char) 0x47), 2750, 2900, 0);
  275.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  276.                 .valueOf((char) 0x47), 2850, 3500, 0);
  277.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  278.                 .valueOf((char) 0xad), 2150, 3550, 0);
  279.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  280.                 .valueOf((char) 0xad), 3300, 2730, 0);
  281.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  282.                 .valueOf((char) 0xad), 2200, 2000, 0);
  283.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  284.                 .valueOf((char) 0xad), 2900, 3300, 0);
  285.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  286.                 .valueOf((char) 0xad), 2080, 3000, 0);
  287.         cb.endLayer(); // monumentLayer
  288.         cb.beginLayer(sportsLayer);
  289.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  290.                 .valueOf((char) 0x53), 2700, 4050, 0);
  291.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  292.                 .valueOf((char) 0x53), 2700, 3900, 0);
  293.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  294.                 .valueOf((char) 0x53), 2800, 3980, 0);
  295.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  296.                 .valueOf((char) 0x53), 1950, 2800, 0);
  297.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER, String
  298.                 .valueOf((char) 0x53), 3700, 2450, 0);
  299.         cb.endLayer(); // sportsLayer
  300.         cb.endText();
  301.         cb.restoreState();
  302.         // step 5
  303.         document.close();
  304.     }
  305.    
  306.     /**
  307.      * Main method.
  308.      *
  309.      * @param    args    no arguments needed
  310.      * @throws DocumentException
  311.      * @throws IOException
  312.      * @throws SQLException
  313.      */
  314.     public static void main(String[] args) throws IOException, DocumentException {
  315.         new SvgLayers().createPdf(RESULT);
  316.     }
  317. }
ObjectData.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter15;
  8.  
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.sql.ResultSet;
  12. import java.sql.SQLException;
  13. import java.sql.Statement;
  14. import java.util.HashMap;
  15. import java.util.List;
  16. import java.util.Map;
  17. import java.util.TreeMap;
  18.  
  19. import com.itextpdf.text.Document;
  20. import com.itextpdf.text.DocumentException;
  21. import com.itextpdf.text.Image;
  22. import com.itextpdf.text.pdf.PdfArray;
  23. import com.itextpdf.text.pdf.PdfContentByte;
  24. import com.itextpdf.text.pdf.PdfDictionary;
  25. import com.itextpdf.text.pdf.PdfName;
  26. import com.itextpdf.text.pdf.PdfNumber;
  27. import com.itextpdf.text.pdf.PdfString;
  28. import com.itextpdf.text.pdf.PdfStructureElement;
  29. import com.itextpdf.text.pdf.PdfStructureTreeRoot;
  30. import com.itextpdf.text.pdf.PdfWriter;
  31. import com.lowagie.database.DatabaseConnection;
  32. import com.lowagie.database.HsqldbConnection;
  33. import com.lowagie.filmfestival.Director;
  34. import com.lowagie.filmfestival.Movie;
  35. import com.lowagie.filmfestival.PojoFactory;
  36.  
  37. public class ObjectData {
  38.  
  39.     /** The resulting PDF. */
  40.     public static final String RESULT = "results/part4/chapter15/objectdata.pdf";
  41.     /** Path to the resources. */
  42.     public static final String RESOURCE
  43.         = "resources/posters/%s.jpg";
  44.     /** SQL statement to get selected directors */
  45.     public static final String SELECTDIRECTORS =
  46.         "SELECT DISTINCT d.id, d.name, d.given_name, count(*) AS c "
  47.         + "FROM film_director d, film_movie_director md "
  48.         + "WHERE d.id = md.director_id AND d.id < 8 "
  49.         + "GROUP BY d.id, d.name, d.given_name ORDER BY id";
  50.    
  51.     /**
  52.      * Creates a PDF with information about the movies
  53.      * @param    filename the name of the PDF file that will be created.
  54.      * @throws    DocumentException
  55.      * @throws    IOException
  56.      * @throws    SQLException
  57.      */
  58.     public void createPdf(String filename)
  59.         throws IOException, DocumentException, SQLException {
  60.         // step 1
  61.         Document document = new Document();
  62.         // step 2
  63.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  64.         writer.setTagged();
  65.         writer.setUserProperties(true);
  66.         // step 3
  67.         document.open();
  68.         // step 4
  69.  
  70.         PdfStructureTreeRoot root = writer.getStructureTreeRoot();
  71.         root.mapRole(new PdfName("Directors"), PdfName.H);
  72.         for (int i = 1; i < 8; i++) {
  73.             root.mapRole(new PdfName("director" + i), PdfName.P);
  74.         }
  75.        
  76.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  77.  
  78.         PdfStructureTreeRoot tree = writer.getStructureTreeRoot();
  79.         PdfStructureElement top = new PdfStructureElement(tree, new PdfName("Directors"));
  80.        
  81.         Map directors = new HashMap();
  82.         Statement stm = connection.createStatement();
  83.         ResultSet rs = stm.executeQuery(SELECTDIRECTORS);
  84.         int id;
  85.         Director director;
  86.         PdfStructureElement e;
  87.         while (rs.next()) {
  88.             id = rs.getInt("id");
  89.             director = PojoFactory.getDirector(rs);
  90.             e = new PdfStructureElement(top, new PdfName("director" + id));
  91.             PdfDictionary userproperties = new PdfDictionary();
  92.             userproperties.put(PdfName.O, PdfName.USERPROPERTIES);
  93.             PdfArray properties = new PdfArray();
  94.             PdfDictionary property1 = new PdfDictionary();
  95.             property1.put(PdfName.N, new PdfString("Name"));
  96.             property1.put(PdfName.V, new PdfString(director.getName()));            
  97.             properties.add(property1);
  98.             PdfDictionary property2 = new PdfDictionary();
  99.             property2.put(PdfName.N, new PdfString("Given name"));
  100.             property2.put(PdfName.V, new PdfString(director.getGivenName()));            
  101.             properties.add(property2);
  102.             PdfDictionary property3 = new PdfDictionary();
  103.             property3.put(PdfName.N, new PdfString("Posters"));
  104.             property3.put(PdfName.V, new PdfNumber(rs.getInt("c")));            
  105.             properties.add(property3);
  106.             userproperties.put(PdfName.P, properties);
  107.             e.put(PdfName.A, userproperties);
  108.             directors.put(id, e);
  109.         }
  110.        
  111.         Map map = new TreeMap();
  112.         for (int i = 1; i < 8; i++) {
  113.             List movies = PojoFactory.getMovies(connection, i);
  114.             for (Movie movie : movies) {
  115.                 map.put(movie, i);
  116.             }
  117.         }
  118.        
  119.         PdfContentByte canvas = writer.getDirectContent();
  120.         Image img;
  121.         float x = 11.5f;
  122.         float y = 769.7f;
  123.         for (Map.Entry entry : map.entrySet()) {
  124.             img = Image.getInstance(String.format(RESOURCE, entry.getKey().getImdb()));
  125.             img.scaleToFit(1000, 60);
  126.             img.setAbsolutePosition(x + (45 - img.getScaledWidth()) / 2, y);
  127.             canvas.beginMarkedContentSequence(directors.get(entry.getValue()));
  128.             canvas.addImage(img);
  129.             canvas.endMarkedContentSequence();
  130.             x += 48;
  131.             if (x > 578) {
  132.                 x = 11.5f;
  133.                 y -= 84.2f;
  134.             }
  135.         }
  136.         // step 5
  137.         document.close();
  138.  
  139.     }
  140.  
  141.  
  142.     /**
  143.      * Main method.
  144.      *
  145.      * @param    args    no arguments needed
  146.      * @throws DocumentException
  147.      * @throws IOException
  148.      * @throws SQLException
  149.      */
  150.     public static void main(String[] args)
  151.         throws IOException, SQLException, DocumentException {
  152.         new ObjectData().createPdf(RESULT);
  153.     }
  154. }
ReadOutLoud.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter15;
  8.  
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11.  
  12. import com.itextpdf.text.Document;
  13. import com.itextpdf.text.DocumentException;
  14. import com.itextpdf.text.Image;
  15. import com.itextpdf.text.pdf.BaseFont;
  16. import com.itextpdf.text.pdf.PdfContentByte;
  17. import com.itextpdf.text.pdf.PdfDictionary;
  18. import com.itextpdf.text.pdf.PdfName;
  19. import com.itextpdf.text.pdf.PdfString;
  20. import com.itextpdf.text.pdf.PdfStructureElement;
  21. import com.itextpdf.text.pdf.PdfStructureTreeRoot;
  22. import com.itextpdf.text.pdf.PdfWriter;
  23.  
  24. public class ReadOutLoud {
  25.  
  26.     /** The resulting PDF. */
  27.     public static String RESULT = "results/part4/chapter15/read_out_loud.pdf";
  28.     /** A resource that is used in the PDF document. */
  29.     public static String RESOURCE = "resources/posters/0062622.jpg";
  30.  
  31.     /**
  32.      * Creates a PDF document.
  33.      * @param filename the path to the new PDF document
  34.      * @throws DocumentException
  35.      * @throws IOException
  36.      */
  37.     public void createPdf(String filename) throws IOException, DocumentException {
  38.         // step 1
  39.         Document document = new Document();
  40.         // step 2
  41.         PdfWriter writer = PdfWriter.getInstance(document,
  42.                 new FileOutputStream(filename));
  43.         writer.setTagged();
  44.         // step 3
  45.         document.open();
  46.         // step 4
  47.         PdfContentByte cb = writer.getDirectContent();
  48.         BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
  49.                 BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
  50.         BaseFont bf2 = BaseFont.createFont("c:/windows/fonts/msgothic.ttc,1",
  51.                 BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
  52.  
  53.         PdfStructureTreeRoot root = writer.getStructureTreeRoot();
  54.         PdfStructureElement div = new PdfStructureElement(root, new PdfName("Div"));
  55.         PdfDictionary dict;
  56.  
  57.         cb.beginMarkedContentSequence(div);
  58.  
  59.         cb.beginText();
  60.         cb.moveText(36, 788);
  61.         cb.setFontAndSize(bf, 12);
  62.         cb.setLeading(18);
  63.         cb.showText("These are some famous movies by Stanley Kubrick: ");
  64.         dict = new PdfDictionary();
  65.         dict.put(PdfName.E, new PdfString("Doctor"));
  66.         cb.beginMarkedContentSequence(new PdfName("Span"), dict, true);
  67.         cb.newlineShowText("Dr.");
  68.         cb.endMarkedContentSequence();
  69.         cb.showText(" Strangelove or: How I Learned to Stop Worrying and Love the Bomb.");
  70.         dict = new PdfDictionary();
  71.         dict.put(PdfName.E, new PdfString("Eyes Wide Shut."));
  72.         cb.beginMarkedContentSequence(new PdfName("Span"), dict, true);
  73.         cb.newlineShowText("EWS");
  74.         cb.endMarkedContentSequence();
  75.         cb.endText();
  76.         dict = new PdfDictionary();
  77.         dict.put(PdfName.LANG, new PdfString("en-us"));
  78.         dict.put(new PdfName("Alt"), new PdfString("2001: A Space Odyssey."));
  79.         cb.beginMarkedContentSequence(new PdfName("Span"), dict, true);
  80.         Image img = Image.getInstance(RESOURCE);
  81.         img.scaleToFit(1000, 100);
  82.         img.setAbsolutePosition(36, 640);
  83.         cb.addImage(img);
  84.         cb.endMarkedContentSequence();
  85.  
  86.         cb.beginText();
  87.         cb.moveText(36, 620);
  88.         cb.setFontAndSize(bf, 12);
  89.         cb.showText("This is a movie by Akira Kurosawa: ");
  90.         dict = new PdfDictionary();
  91.         dict.put(PdfName.ACTUALTEXT, new PdfString("Seven Samurai."));
  92.         cb.beginMarkedContentSequence(new PdfName("Span"), dict, true);
  93.         cb.setFontAndSize(bf2, 12);
  94.         cb.showText("\u4e03\u4eba\u306e\u4f8d");
  95.         cb.endMarkedContentSequence();
  96.         cb.endText();
  97.        
  98.         cb.endMarkedContentSequence();
  99.         // step 5
  100.         document.close();
  101.     }
  102.     /**
  103.      * Main method.
  104.      *
  105.      * @param    args    no arguments needed
  106.      * @throws DocumentException
  107.      * @throws IOException
  108.      */
  109.     public static void main(String[] args) throws IOException, DocumentException {
  110.         new ReadOutLoud().createPdf(RESULT);
  111.     }
  112. }
StructureParser.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter15;
  9. import java.util.List;
  10.  
  11. import org.xml.sax.Attributes;
  12. import org.xml.sax.SAXException;
  13. import org.xml.sax.helpers.DefaultHandler;
  14.  
  15. import com.itextpdf.text.pdf.PdfName;
  16. import com.itextpdf.text.pdf.PdfStructureElement;
  17.  
  18. public class StructureParser extends DefaultHandler {
  19.  
  20.     /** The top element in the PDF structure */
  21.     protected PdfStructureElement top;
  22.     /** The list of structure elements */
  23.     protected List elements;
  24.  
  25.     /** Creates a parser that will parse an XML file into a structure tree. */
  26.     public StructureParser(PdfStructureElement top, List elements) {
  27.         this.top = top;
  28.         this.elements = elements;
  29.     }
  30.    
  31.     /**
  32.      * @see org.xml.sax.ContentHandler#startElement(java.lang.String,
  33.      *      java.lang.String, java.lang.String, org.xml.sax.Attributes)
  34.      */
  35.     public void startElement(String uri, String localName, String qName,
  36.             Attributes attributes) throws SAXException {
  37.         if ("chapter".equals(qName)) return;
  38.         elements.add(new PdfStructureElement(top, new PdfName(qName)));
  39.     }
  40. }
ContentParser.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter15;
  9.  
  10. import java.io.IOException;
  11. import java.util.List;
  12.  
  13. import org.xml.sax.Attributes;
  14. import org.xml.sax.SAXException;
  15. import org.xml.sax.helpers.DefaultHandler;
  16.  
  17. import com.itextpdf.text.Document;
  18. import com.itextpdf.text.DocumentException;
  19. import com.itextpdf.text.Element;
  20. import com.itextpdf.text.Font;
  21. import com.itextpdf.text.Paragraph;
  22. import com.itextpdf.text.pdf.BaseFont;
  23. import com.itextpdf.text.pdf.ColumnText;
  24. import com.itextpdf.text.pdf.PdfContentByte;
  25. import com.itextpdf.text.pdf.PdfStructureElement;
  26. import com.itextpdf.text.pdf.PdfWriter;
  27.  
  28. public class ContentParser extends DefaultHandler {
  29.  
  30.     /** The StringBuffer that holds the characters. */
  31.     protected StringBuffer buf = new StringBuffer();
  32.  
  33.     /** The document to which content parsed form XML will be added. */
  34.     protected Document document;
  35.     /** The writer to which PDF syntax will be written. */
  36.     protected PdfWriter writer;
  37.     /** The canvas to which content will be written. */
  38.     protected PdfContentByte canvas;
  39.     /** A list with structure elements. */
  40.     protected List elements;
  41.     /** The current structure element during the parsing process. */
  42.     protected PdfStructureElement current;
  43.     /** The column to which content will be added. */
  44.     protected ColumnText column;
  45.     /** The font used when content elements are created. */
  46.     protected Font font;
  47.    
  48.     /**
  49.      * Creates a new ContentParser
  50.      * @param document
  51.      * @param writer
  52.      * @param elements
  53.      * @throws DocumentException
  54.      * @throws IOException
  55.      */
  56.     public ContentParser(Document document, PdfWriter writer, List elements)
  57.         throws DocumentException, IOException {
  58.         this.document = document;
  59.         this.writer = writer;
  60.         canvas = writer.getDirectContent();
  61.         column = new ColumnText(canvas);
  62.         column.setSimpleColumn(36, 36, 384, 569);
  63.         this.elements = elements;
  64.         font = new Font(
  65.             BaseFont.createFont("c:/windows/fonts/arial.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED), 12);
  66.     }
  67.  
  68.     /**
  69.      * @see org.xml.sax.ContentHandler#characters(char[], int, int)
  70.      */
  71.     public void characters(char[] ch, int start, int length)
  72.             throws SAXException {
  73.         for (int i = start; i < start + length; i++) {
  74.             if (ch[i] == '\n')
  75.                 buf.append(' ');
  76.             else
  77.                 buf.append(ch[i]);
  78.         }
  79.     }
  80.  
  81.     /**
  82.      * @see org.xml.sax.ContentHandler#startElement(java.lang.String,
  83.      *      java.lang.String, java.lang.String, org.xml.sax.Attributes)
  84.      */
  85.     public void startElement(String uri, String localName, String qName,
  86.             Attributes attributes) throws SAXException {
  87.         if ("chapter".equals(qName)) return;
  88.         current = elements.get(0);
  89.         elements.remove(0);
  90.         canvas.beginMarkedContentSequence(current);
  91.     }
  92.    
  93.     /**
  94.      * @see org.xml.sax.ContentHandler#endElement(java.lang.String,
  95.      *      java.lang.String, java.lang.String)
  96.      */
  97.     public void endElement(String uri, String localName, String qName)
  98.             throws SAXException {
  99.         if ("chapter".equals(qName)) return;
  100.         try {
  101.             String s = buf.toString().trim();
  102.             buf = new StringBuffer();
  103.             if (s.length() > 0) {
  104.                 Paragraph p = new Paragraph(s, font);
  105.                 p.setAlignment(Element.ALIGN_JUSTIFIED);
  106.                 column.addElement(p);
  107.                 int status = column.go();
  108.                 while (ColumnText.hasMoreText(status)) {
  109.                     canvas.endMarkedContentSequence();
  110.                     document.newPage();
  111.                     canvas.beginMarkedContentSequence(current);
  112.                     column.setSimpleColumn(36, 36, 384, 569);
  113.                     status = column.go();
  114.                 }
  115.             }
  116.         } catch (DocumentException e) {
  117.             e.printStackTrace();
  118.         }
  119.         canvas.endMarkedContentSequence();
  120.     }
  121. }
StructuredContent.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter15;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.util.ArrayList;
  14. import java.util.List;
  15.  
  16. import javax.xml.parsers.ParserConfigurationException;
  17. import javax.xml.parsers.SAXParser;
  18. import javax.xml.parsers.SAXParserFactory;
  19.  
  20. import org.xml.sax.InputSource;
  21. import org.xml.sax.SAXException;
  22.  
  23. import com.itextpdf.text.Document;
  24. import com.itextpdf.text.DocumentException;
  25. import com.itextpdf.text.PageSize;
  26. import com.itextpdf.text.pdf.PdfName;
  27. import com.itextpdf.text.pdf.PdfStructureElement;
  28. import com.itextpdf.text.pdf.PdfStructureTreeRoot;
  29. import com.itextpdf.text.pdf.PdfWriter;
  30.  
  31. public class StructuredContent {
  32.  
  33.     /** The resulting PDF. */
  34.     public static final String RESULT = "results/part4/chapter15/moby.pdf";
  35.     /** An XML file that will be converted to PDF. */
  36.     public static final String RESOURCE = "resources/xml/moby.xml";
  37.  
  38.     /**
  39.      * Main method.
  40.      * @param    args    no arguments needed
  41.      * @throws DocumentException
  42.      * @throws IOException
  43.      * @throws SAXException
  44.      * @throws ParserConfigurationException
  45.      */
  46.     public static void main(String[] args)
  47.         throws IOException, DocumentException, SAXException, ParserConfigurationException {
  48.         Document document = new Document(PageSize.A5);
  49.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
  50.         writer.setTagged();
  51.         document.open();
  52.         PdfStructureTreeRoot root = writer.getStructureTreeRoot();
  53.         root.mapRole(new PdfName("chapter"), PdfName.SECT);
  54.         root.mapRole(new PdfName("title"), PdfName.H);
  55.         root.mapRole(new PdfName("para"), PdfName.P);
  56.         PdfStructureElement top = new PdfStructureElement(root, new PdfName("chapter"));
  57.         SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
  58.         List elements = new ArrayList();
  59.         parser.parse(
  60.             new InputSource(new FileInputStream(RESOURCE)),
  61.             new StructureParser(top, elements));
  62.         parser.parse(
  63.             new InputSource(new FileInputStream(RESOURCE)),
  64.             new ContentParser(document, writer, elements));
  65.         document.close();
  66.     }
  67. }
ParseTaggedPdf.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter15;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import javax.xml.parsers.ParserConfigurationException;
  14.  
  15. import org.xml.sax.SAXException;
  16.  
  17. import com.itextpdf.text.DocumentException;
  18. import com.itextpdf.text.pdf.PdfReader;
  19. import com.itextpdf.text.pdf.parser.TaggedPdfReaderTool;
  20.  
  21. public class ParseTaggedPdf {
  22.  
  23.     /** The resulting XML file. */
  24.     public static final String RESULT
  25.         = "results/part4/chapter15/moby_extracted.xml";
  26.  
  27.     /**
  28.      * Creates a PDF file using a previous example,
  29.      * then parses the document.
  30.      * @param    args    no arguments needed
  31.      */
  32.     public static void main(String[] args)
  33.         throws IOException, DocumentException, SAXException, ParserConfigurationException {
  34.         StructuredContent.main(args);
  35.         TaggedPdfReaderTool readertool = new TaggedPdfReaderTool();
  36.         PdfReader reader = new PdfReader(StructuredContent.RESULT);
  37.         readertool.convertToXml(reader, new FileOutputStream(RESULT));
  38.         reader.close();
  39.     }
  40. }
ParsingHelloWorld.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter15;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.PrintWriter;
  13.  
  14. import part1.chapter01.HelloWorld;
  15.  
  16. import com.itextpdf.text.Document;
  17. import com.itextpdf.text.DocumentException;
  18. import com.itextpdf.text.io.RandomAccessSourceFactory;
  19. import com.itextpdf.text.pdf.BaseFont;
  20. import com.itextpdf.text.pdf.PRTokeniser;
  21. import com.itextpdf.text.pdf.PdfContentByte;
  22. import com.itextpdf.text.pdf.PdfDictionary;
  23. import com.itextpdf.text.pdf.PdfName;
  24. import com.itextpdf.text.pdf.PdfReader;
  25. import com.itextpdf.text.pdf.PdfTemplate;
  26. import com.itextpdf.text.pdf.PdfWriter;
  27. import com.itextpdf.text.pdf.RandomAccessFileOrArray;
  28. import com.itextpdf.text.pdf.parser.ContentByteUtils;
  29. import com.itextpdf.text.pdf.parser.PdfContentStreamProcessor;
  30. import com.itextpdf.text.pdf.parser.RenderListener;
  31.  
  32. public class ParsingHelloWorld {
  33.  
  34.     /** The resulting PDF. */
  35.     public static final String PDF = "results/part4/chapter15/hello_reverse.pdf";
  36.     /** A possible resulting after parsing the PDF. */
  37.     public static final String TEXT1 = "results/part4/chapter15/result1.txt";
  38.     /** A possible resulting after parsing the PDF. */
  39.     public static final String TEXT2 = "results/part4/chapter15/result2.txt";
  40.     /** A possible resulting after parsing the PDF. */
  41.     public static final String TEXT3 = "results/part4/chapter15/result3.txt";
  42.    
  43.     /**
  44.      * Generates a PDF file with the text 'Hello World'
  45.      * @throws DocumentException
  46.      * @throws IOException
  47.      */
  48.     public void createPdf(String filename) throws DocumentException, IOException {
  49.         // step 1
  50.         Document document = new Document();
  51.         // step 2
  52.         PdfWriter writer
  53.           = PdfWriter.getInstance(document, new FileOutputStream(filename));
  54.         // step 3
  55.         document.open();
  56.         // step 4
  57.         // we add the text to the direct content, but not in the right order
  58.         PdfContentByte cb = writer.getDirectContent();
  59.         BaseFont bf = BaseFont.createFont();
  60.         cb.beginText();
  61.         cb.setFontAndSize(bf, 12);
  62.         cb.moveText(88.66f, 367);
  63.         cb.showText("ld");
  64.         cb.moveText(-22f, 0);
  65.         cb.showText("Wor");
  66.         cb.moveText(-15.33f, 0);
  67.         cb.showText("llo");
  68.         cb.moveText(-15.33f, 0);
  69.         cb.showText("He");
  70.         cb.endText();
  71.         // we also add text in a form XObject
  72.         PdfTemplate tmp = cb.createTemplate(250, 25);
  73.         tmp.beginText();
  74.         tmp.setFontAndSize(bf, 12);
  75.         tmp.moveText(0, 7);
  76.         tmp.showText("Hello People");
  77.         tmp.endText();
  78.         cb.addTemplate(tmp, 36, 343);
  79.         // step 5
  80.         document.close();
  81.     }
  82.    
  83.     /**
  84.      * Parses the PDF using PRTokeniser
  85.      * @param src  the path to the original PDF file
  86.      * @param dest the path to the resulting text file
  87.      * @throws IOException
  88.      */
  89.     public void parsePdf(String src, String dest) throws IOException {
  90.         PdfReader reader = new PdfReader(src);
  91.         // we can inspect the syntax of the imported page
  92.         byte[] streamBytes = reader.getPageContent(1);
  93.         PRTokeniser tokenizer = new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().createSource(streamBytes)));
  94.         PrintWriter out = new PrintWriter(new FileOutputStream(dest));
  95.         while (tokenizer.nextToken()) {
  96.             if (tokenizer.getTokenType() == PRTokeniser.TokenType.STRING) {
  97.                 out.println(tokenizer.getStringValue());
  98.             }
  99.         }
  100.         out.flush();
  101.         out.close();
  102.         reader.close();
  103.     }
  104.    
  105.     /**
  106.      * Extracts text from a PDF document.
  107.      * @param src  the original PDF document
  108.      * @param dest the resulting text file
  109.      * @throws IOException
  110.      */
  111.     public void extractText(String src, String dest) throws IOException {
  112.         PrintWriter out = new PrintWriter(new FileOutputStream(dest));
  113.         PdfReader reader = new PdfReader(src);
  114.         RenderListener listener = new MyTextRenderListener(out);
  115.         PdfContentStreamProcessor processor = new PdfContentStreamProcessor(listener);
  116.         PdfDictionary pageDic = reader.getPageN(1);
  117.         PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES);
  118.         processor.processContent(ContentByteUtils.getContentBytesForPage(reader, 1), resourcesDic);
  119.         out.flush();
  120.         out.close();
  121.         reader.close();
  122.     }
  123.  
  124.     /**
  125.      * Main method.
  126.      * @param    args    no arguments needed
  127.      * @throws DocumentException
  128.      * @throws IOException
  129.      */
  130.     public static void main(String[] args) throws DocumentException, IOException {
  131.         ParsingHelloWorld example = new ParsingHelloWorld();
  132.         HelloWorld.main(args);
  133.         example.createPdf(PDF);
  134.         example.parsePdf(HelloWorld.RESULT, TEXT1);
  135.         example.parsePdf(PDF, TEXT2);
  136.         example.extractText(PDF, TEXT3);
  137.     }
  138. }
MyTextRenderListener.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. package part4.chapter15;
  8.  
  9. import java.io.PrintWriter;
  10.  
  11. import com.itextpdf.text.pdf.parser.ImageRenderInfo;
  12. import com.itextpdf.text.pdf.parser.RenderListener;
  13. import com.itextpdf.text.pdf.parser.TextRenderInfo;
  14.  
  15. public class MyTextRenderListener implements RenderListener {
  16.  
  17.     /** The print writer to which the information will be written. */
  18.     protected PrintWriter out;
  19.  
  20.     /**
  21.      * Creates a RenderListener that will look for text.
  22.      */
  23.     public MyTextRenderListener(PrintWriter out) {
  24.         this.out = out;
  25.     }
  26.    
  27.     /**
  28.      * @see com.itextpdf.text.pdf.parser.RenderListener#beginTextBlock()
  29.      */
  30.     public void beginTextBlock() {
  31.         out.print("");
  32.     }
  33.  
  34.     /**
  35.      * @see com.itextpdf.text.pdf.parser.RenderListener#renderImage(
  36.      *     com.itextpdf.text.pdf.parser.ImageRenderInfo)
  37.      */
  38.     public void renderImage(ImageRenderInfo renderInfo) {
  39.     }
  40.  
  41.     /**
  42.      * @see com.itextpdf.text.pdf.parser.RenderListener#renderText(
  43.      *     com.itextpdf.text.pdf.parser.TextRenderInfo)
  44.      */
  45.     public void renderText(TextRenderInfo renderInfo) {
  46.         out.print("");
  47.     }
  48. }
InspectPageContent.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter15;
  9.  
  10. import java.io.File;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.io.PrintWriter;
  14.  
  15. import part1.chapter03.MovieTemplates;
  16.  
  17. import com.itextpdf.text.DocumentException;
  18. import com.itextpdf.text.pdf.parser.PdfContentReaderTool;
  19.  
  20. public class InspectPageContent {
  21.  
  22.     /** Text file containing information about a PDF file. */
  23.     public static final String RESULT = "results/part4/chapter15/calendar_info.txt";
  24.    
  25.     /**
  26.      * Parses object and content information of a PDF into a text file.
  27.      * @param pdf the original PDF
  28.      * @param txt the resulting text
  29.      * @throws IOException
  30.      */
  31.     public void inspectPdf(String pdf, String txt) throws IOException {
  32.         PrintWriter out = new PrintWriter(new FileOutputStream(txt));
  33.         PdfContentReaderTool.listContentStream(new File(pdf), out);
  34.         out.flush();
  35.         out.close();
  36.     }
  37.  
  38.     /**
  39.      * Main method.
  40.      * @param    args    no arguments needed
  41.      * @throws DocumentException
  42.      * @throws IOException
  43.      */
  44.     public static void main(String[] args) throws IOException, DocumentException {
  45.         new MovieTemplates().createPdf(MovieTemplates.RESULT);
  46.         new InspectPageContent().inspectPdf(MovieTemplates.RESULT, RESULT);
  47.     }
  48. }
ExtractPageContent.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter15;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.PrintWriter;
  13.  
  14. import com.itextpdf.text.pdf.PdfReader;
  15. import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
  16. import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
  17. import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
  18.  
  19. public class ExtractPageContent {
  20.  
  21.     /** The original PDF that will be parsed. */
  22.     public static final String PREFACE = "resources/pdfs/preface.pdf";
  23.     /** The resulting text file. */
  24.     public static final String RESULT = "results/part4/chapter15/preface.txt";
  25.    
  26.     /**
  27.      * Parses a PDF to a plain text file.
  28.      * @param pdf the original PDF
  29.      * @param txt the resulting text
  30.      * @throws IOException
  31.      */
  32.     public void parsePdf(String pdf, String txt) throws IOException {
  33.         PdfReader reader = new PdfReader(pdf);
  34.         PdfReaderContentParser parser = new PdfReaderContentParser(reader);
  35.         PrintWriter out = new PrintWriter(new FileOutputStream(txt));
  36.         TextExtractionStrategy strategy;
  37.         for (int i = 1; i
ExtractPageContentSorted1.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter15;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.PrintWriter;
  13.  
  14. import com.itextpdf.text.pdf.PdfReader;
  15. import com.itextpdf.text.pdf.parser.LocationTextExtractionStrategy;
  16. import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
  17. import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
  18.  
  19. public class ExtractPageContentSorted1 {
  20.  
  21.     /** The original PDF that will be parsed. */
  22.     public static final String PREFACE = "resources/pdfs/preface.pdf";
  23.     /** The resulting text file. */
  24.     public static final String RESULT = "results/part4/chapter15/preface_sorted1.txt";
  25.    
  26.     /**
  27.      * Parses a PDF to a plain text file.
  28.      * @param pdf the original PDF
  29.      * @param txt the resulting text
  30.      * @throws IOException
  31.      */
  32.     public void parsePdf(String pdf, String txt) throws IOException {
  33.         PdfReader reader = new PdfReader(pdf);
  34.         PdfReaderContentParser parser = new PdfReaderContentParser(reader);
  35.         PrintWriter out = new PrintWriter(new FileOutputStream(txt));
  36.         TextExtractionStrategy strategy;
  37.         for (int i = 1; i
ExtractPageContentSorted2.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter15;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.PrintWriter;
  13.  
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.pdf.PdfReader;
  16. import com.itextpdf.text.pdf.parser.PdfTextExtractor;
  17.  
  18. public class ExtractPageContentSorted2 {
  19.  
  20.     /** The original PDF that will be parsed. */
  21.     public static final String PREFACE = "resources/pdfs/preface.pdf";
  22.     /** The resulting text file. */
  23.     public static final String RESULT = "results/part4/chapter15/preface_sorted2.txt";
  24.    
  25.     /**
  26.      * Parses a specific area of a PDF to a plain text file.
  27.      * @param pdf the original PDF
  28.      * @param txt the resulting text
  29.      * @throws IOException
  30.      */
  31.     public void parsePdf(String pdf, String txt) throws IOException {
  32.         PdfReader reader = new PdfReader(pdf);
  33.         PrintWriter out = new PrintWriter(new FileOutputStream(txt));
  34.         for (int i = 1; i
ExtractPageContentArea.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter15;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.PrintWriter;
  13.  
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.Rectangle;
  16. import com.itextpdf.text.pdf.PdfReader;
  17. import com.itextpdf.text.pdf.parser.FilteredTextRenderListener;
  18. import com.itextpdf.text.pdf.parser.LocationTextExtractionStrategy;
  19. import com.itextpdf.text.pdf.parser.PdfTextExtractor;
  20. import com.itextpdf.text.pdf.parser.RegionTextRenderFilter;
  21. import com.itextpdf.text.pdf.parser.RenderFilter;
  22. import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
  23.  
  24. public class ExtractPageContentArea {
  25.  
  26.     /** The original PDF that will be parsed. */
  27.     public static final String PREFACE = "resources/pdfs/preface.pdf";
  28.     /** The resulting text file. */
  29.     public static final String RESULT = "results/part4/chapter15/preface_clipped.txt";
  30.    
  31.     /**
  32.      * Parses a specific area of a PDF to a plain text file.
  33.      * @param pdf the original PDF
  34.      * @param txt the resulting text
  35.      * @throws IOException
  36.      */
  37.     public void parsePdf(String pdf, String txt) throws IOException {
  38.         PdfReader reader = new PdfReader(pdf);
  39.         PrintWriter out = new PrintWriter(new FileOutputStream(txt));
  40.         Rectangle rect = new Rectangle(70, 80, 490, 580);
  41.         RenderFilter filter = new RegionTextRenderFilter(rect);
  42.         TextExtractionStrategy strategy;
  43.         for (int i = 1; i
ShowTextMargins.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter15;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.DocumentException;
  14. import com.itextpdf.text.pdf.PdfContentByte;
  15. import com.itextpdf.text.pdf.PdfReader;
  16. import com.itextpdf.text.pdf.PdfStamper;
  17. import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
  18. import com.itextpdf.text.pdf.parser.TextMarginFinder;
  19.  
  20. public class ShowTextMargins {
  21.  
  22.     /** The original document. */
  23.     public static final String PREFACE = "resources/pdfs/preface.pdf";
  24.     /** The new document to which we've added a border rectangle. */
  25.     public static final String RESULT = "results/part4/chapter15/margins.pdf";
  26.    
  27.     /**
  28.      * Parses a PDF and ads a rectangle showing the text margin.
  29.      * @param src the source PDF
  30.      * @param dest the resulting PDF
  31.      */
  32.     public void addMarginRectangle(String src, String dest)
  33.         throws IOException, DocumentException {
  34.         PdfReader reader = new PdfReader(src);
  35.         PdfReaderContentParser parser = new PdfReaderContentParser(reader);
  36.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
  37.         TextMarginFinder finder;
  38.         for (int i = 1; i
MyImageRenderListener.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter15;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.pdf.parser.ImageRenderInfo;
  14. import com.itextpdf.text.pdf.parser.PdfImageObject;
  15. import com.itextpdf.text.pdf.parser.RenderListener;
  16. import com.itextpdf.text.pdf.parser.TextRenderInfo;
  17.  
  18. public class MyImageRenderListener implements RenderListener {
  19.  
  20.     /** The new document to which we've added a border rectangle. */
  21.     protected String path = "";
  22.  
  23.     /**
  24.      * Creates a RenderListener that will look for images.
  25.      */
  26.     public MyImageRenderListener(String path) {
  27.         this.path = path;
  28.     }
  29.    
  30.     /**
  31.      * @see com.itextpdf.text.pdf.parser.RenderListener#beginTextBlock()
  32.      */
  33.     public void beginTextBlock() {
  34.     }
  35.  
  36.     /**
  37.      * @see com.itextpdf.text.pdf.parser.RenderListener#endTextBlock()
  38.      */
  39.     public void endTextBlock() {
  40.     }
  41.  
  42.     /**
  43.      * @see com.itextpdf.text.pdf.parser.RenderListener#renderImage(
  44.      *     com.itextpdf.text.pdf.parser.ImageRenderInfo)
  45.      */
  46.     public void renderImage(ImageRenderInfo renderInfo) {
  47.         try {
  48.             String filename;
  49.             FileOutputStream os;
  50.             PdfImageObject image = renderInfo.getImage();
  51.             if (image == null) return;
  52.             filename = String.format(path, renderInfo.getRef().getNumber(), image.getFileType());
  53.             os = new FileOutputStream(filename);
  54.             os.write(image.getImageAsBytes());
  55.             os.flush();
  56.             os.close();
  57.         } catch (IOException e) {
  58.             System.out.println(e.getMessage());
  59.         }
  60.     }
  61.  
  62.     /**
  63.      * @see com.itextpdf.text.pdf.parser.RenderListener#renderText(
  64.      *     com.itextpdf.text.pdf.parser.TextRenderInfo)
  65.      */
  66.     public void renderText(TextRenderInfo renderInfo) {
  67.     }
  68. }
ExtractImages.java
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7.  
  8. package part4.chapter15;
  9.  
  10. import java.io.IOException;
  11.  
  12. import part3.chapter10.ImageTypes;
  13.  
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.pdf.PdfReader;
  16. import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
  17.  
  18. /**
  19.  * Extracts images from a PDF file.
  20.  */
  21. public class ExtractImages {
  22.  
  23.     /** The new document to which we've added a border rectangle. */
  24.     public static final String RESULT = "results/part4/chapter15/Img%s.%s";
  25.    
  26.     /**
  27.      * Parses a PDF and extracts all the images.
  28.      * @param src the source PDF
  29.      * @param dest the resulting PDF
  30.      */
  31.     public void extractImages(String filename)
  32.         throws IOException, DocumentException {
  33.         PdfReader reader = new PdfReader(filename);
  34.         PdfReaderContentParser parser = new PdfReaderContentParser(reader);
  35.         MyImageRenderListener listener = new MyImageRenderListener(RESULT);
  36.         for (int i = 1; i
PeekABoo.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using Ionic.Zip;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  16.   public class PeekABoo : IWriter {
  17. // ===========================================================================
  18.     /** The first resulting PDF. */
  19.     public const String RESULT1 = "peek-a-boo1.pdf";
  20.     /** The second resulting PDF. */
  21.     public const String RESULT2 = "peek-a-boo2.pdf";
  22. // ---------------------------------------------------------------------------    
  23.     public void Write(Stream stream) {
  24.       using (ZipFile zip = new ZipFile()) {
  25.         PeekABoo peekaboo = new PeekABoo();
  26.         zip.AddEntry(RESULT1, peekaboo.CreatePdf(true));      
  27.         zip.AddEntry(RESULT2, peekaboo.CreatePdf(false));      
  28.         zip.Save(stream);            
  29.       }
  30.     }    
  31. // ---------------------------------------------------------------------------    
  32.     public byte[] CreatePdf(bool on) {
  33.       using (MemoryStream ms = new MemoryStream()) {
  34.         using (Document document = new Document()) {    
  35.           // step 2
  36.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  37.           writer.ViewerPreferences = PdfWriter.PageModeUseOC;
  38.           writer.PdfVersion = PdfWriter.VERSION_1_5;        
  39.           // step 3
  40.           document.Open();
  41.           // step 4
  42.           PdfLayer layer = new PdfLayer("Do you see me?", writer);
  43.           layer.On = on;
  44.           BaseFont bf = BaseFont.CreateFont();
  45.           PdfContentByte cb = writer.DirectContent;
  46.           cb.BeginText();
  47.           cb.SetFontAndSize(bf, 18);
  48.           cb.ShowTextAligned(Element.ALIGN_LEFT, "Do you see me?", 50, 790, 0);
  49.           cb.BeginLayer(layer);
  50.           cb.ShowTextAligned(Element.ALIGN_LEFT, "Peek-a-Boo!!!", 50, 766, 0);
  51.           cb.EndLayer();
  52.           cb.EndText();
  53.         }
  54.         return ms.ToArray();
  55.       }
  56.     }
  57. // ===========================================================================
  58.   }
  59. }
OptionalContentActionExample.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  15.   public class OptionalContentActionExample : IWriter {
  16. // ===========================================================================
  17.     public void Write(Stream stream) {
  18.       // step 1
  19.       using (Document document = new Document()) {
  20.         // step 2
  21.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  22.         writer.PdfVersion = PdfWriter.VERSION_1_5;
  23.         // step 3
  24.         document.Open();
  25.         // step 4
  26.         PdfLayer a1 = new PdfLayer("answer 1", writer);
  27.         PdfLayer a2 = new PdfLayer("answer 2", writer);
  28.         PdfLayer a3 = new PdfLayer("answer 3", writer);
  29.         a1.On = false;
  30.         a2.On = false;
  31.         a3.On = false;
  32.  
  33.         BaseFont bf = BaseFont.CreateFont();
  34.         PdfContentByte cb = writer.DirectContent;
  35.         cb.BeginText();
  36.         cb.SetFontAndSize(bf, 18);
  37.         cb.ShowTextAligned(Element.ALIGN_LEFT,
  38.             "Q1: Who is the director of the movie 'Paths of Glory'?", 50, 766, 0);
  39.         cb.ShowTextAligned(Element.ALIGN_LEFT,
  40.             "Q2: Who directed the movie 'Lawrence of Arabia'?", 50, 718, 0);
  41.         cb.ShowTextAligned(Element.ALIGN_LEFT,
  42.             "Q3: Who is the director of 'House of Flying Daggers'?", 50, 670, 0);
  43.         cb.EndText();
  44.         cb.SaveState();
  45.         cb.SetRGBColorFill(0xFF, 0x00, 0x00);
  46.         cb.BeginText();
  47.         cb.BeginLayer(a1);
  48.         cb.ShowTextAligned(Element.ALIGN_LEFT,
  49.                 "A1: Stanley Kubrick", 50, 742, 0);
  50.         cb.EndLayer();
  51.         cb.BeginLayer(a2);
  52.         cb.ShowTextAligned(Element.ALIGN_LEFT,
  53.                 "A2: David Lean", 50, 694, 0);
  54.         cb.EndLayer();
  55.         cb.BeginLayer(a3);
  56.         cb.ShowTextAligned(Element.ALIGN_LEFT,
  57.                 "A3: Zhang Yimou", 50, 646, 0);
  58.         cb.EndLayer();
  59.         cb.EndText();
  60.         cb.RestoreState();
  61.  
  62.         List stateOn = new List();
  63.         stateOn.Add("ON");
  64.         stateOn.Add(a1);
  65.         stateOn.Add(a2);
  66.         stateOn.Add(a3);
  67.         PdfAction actionOn = PdfAction.SetOCGstate(stateOn, true);
  68.         List stateOff = new List();
  69.         stateOff.Add("OFF");
  70.         stateOff.Add(a1);
  71.         stateOff.Add(a2);
  72.         stateOff.Add(a3);
  73.         PdfAction actionOff = PdfAction.SetOCGstate(stateOff, true);
  74.         List stateToggle = new List();
  75.         stateToggle.Add("Toggle");
  76.         stateToggle.Add(a1);
  77.         stateToggle.Add(a2);
  78.         stateToggle.Add(a3);
  79.         PdfAction actionToggle = PdfAction.SetOCGstate(stateToggle, true);
  80.         Phrase p = new Phrase("Change the state of the answers:");
  81.         Chunk on = new Chunk(" on ").SetAction(actionOn);
  82.         p.Add(on);
  83.         Chunk off = new Chunk("/ off ").SetAction(actionOff);
  84.         p.Add(off);
  85.         Chunk toggle = new Chunk("/ toggle").SetAction(actionToggle);
  86.         p.Add(toggle);
  87.         document.Add(p);
  88.       }
  89.     }
  90. // ===========================================================================
  91.   }
  92. }                                
LayerMembershipExample1.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  15.   public class LayerMembershipExample1 : IWriter {
  16. // ===========================================================================
  17.     public void Write(Stream stream) {
  18.       // step 1
  19.       using (Document document = new Document()) {
  20.         // step 2
  21.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  22.         writer.PdfVersion = PdfWriter.VERSION_1_5;
  23.         // step 3
  24.         document.Open();
  25.         // step 4
  26.         PdfContentByte cb = writer.DirectContent;
  27.  
  28.         PdfLayer dog = new PdfLayer("layer 1", writer);
  29.         PdfLayer tiger = new PdfLayer("layer 2", writer);
  30.         PdfLayer lion = new PdfLayer("layer 3", writer);
  31.         PdfLayerMembership cat = new PdfLayerMembership(writer);
  32.         cat.AddMember(tiger);
  33.         cat.AddMember(lion);
  34.         PdfLayerMembership no_cat = new PdfLayerMembership(writer);
  35.         no_cat.AddMember(tiger);
  36.         no_cat.AddMember(lion);
  37.         no_cat.VisibilityPolicy = PdfLayerMembership.ALLOFF;
  38.         cb.BeginLayer(dog);
  39.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
  40.           new Phrase("dog"), 50, 775, 0
  41.         );
  42.         cb.EndLayer();
  43.         cb.BeginLayer(tiger);
  44.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
  45.           new Phrase("tiger"), 50, 750, 0
  46.         );
  47.         cb.EndLayer();
  48.         cb.BeginLayer(lion);
  49.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
  50.           new Phrase("lion"), 50, 725, 0
  51.         );
  52.         cb.EndLayer();
  53.         cb.BeginLayer(cat);
  54.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
  55.           new Phrase("cat"), 50, 700, 0
  56.         );
  57.         cb.EndLayer();
  58.         cb.BeginLayer(no_cat);
  59.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
  60.           new Phrase("no cat"), 50, 700, 0
  61.         );
  62.         cb.EndLayer();
  63.       }
  64.     }
  65. // ===========================================================================
  66.   }
  67. }
LayerMembershipExample2.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Web;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  16.   public class LayerMembershipExample2 : IWriter {
  17. // ===========================================================================
  18.     public void Write(Stream stream) {
  19.       // step 1
  20.       using (Document document = new Document()) {
  21.         // step 2
  22.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  23.         writer.PdfVersion = PdfWriter.VERSION_1_6;
  24.         // step 3
  25.         document.Open();
  26.         // step 4
  27.         PdfContentByte cb = writer.DirectContent;
  28.  
  29.         PdfLayer dog = new PdfLayer("layer 1", writer);
  30.         PdfLayer tiger = new PdfLayer("layer 2", writer);
  31.         PdfLayer lion = new PdfLayer("layer 3", writer);
  32.         PdfLayerMembership cat = new PdfLayerMembership(writer);
  33.         PdfVisibilityExpression ve1 = new PdfVisibilityExpression(
  34.           PdfVisibilityExpression.OR
  35.         );
  36.         ve1.Add(tiger);
  37.         ve1.Add(lion);
  38.         cat.VisibilityExpression = ve1;
  39.         PdfLayerMembership no_cat = new PdfLayerMembership(writer);
  40.         PdfVisibilityExpression ve2 = new PdfVisibilityExpression(
  41.           PdfVisibilityExpression.NOT
  42.         );
  43.         ve2.Add(ve1);
  44.         no_cat.VisibilityExpression = ve2;
  45.         cb.BeginLayer(dog);
  46.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("dog"),
  47.                 50, 775, 0);
  48.         cb.EndLayer();
  49.         cb.BeginLayer(tiger);
  50.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("tiger"),
  51.                 50, 750, 0);
  52.         cb.EndLayer();
  53.         cb.BeginLayer(lion);
  54.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("lion"),
  55.                 50, 725, 0);
  56.         cb.EndLayer();
  57.         cb.BeginLayer(cat);
  58.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("cat"),
  59.                 50, 700, 0);
  60.         cb.EndLayer();
  61.         cb.BeginLayer(no_cat);
  62.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
  63.                 new Phrase("no cat"), 50, 700, 0);
  64.         cb.EndLayer();
  65.       }
  66.     }
  67. // ===========================================================================
  68.   }
  69. }
OptionalContentExample.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  15.   public class OptionalContentExample : IWriter {
  16. // ===========================================================================
  17.     public void Write(Stream stream) {
  18.       // step 1
  19.       using (Document document = new Document()) {
  20.         // step 2
  21.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  22.         writer.PdfVersion = PdfWriter.VERSION_1_5;
  23.         // step 3
  24.         document.Open();
  25.         // step 4
  26.         PdfContentByte cb = writer.DirectContent;
  27.         PdfLayer nested = new PdfLayer("Nested layers", writer);
  28.         PdfLayer nested_1 = new PdfLayer("Nested layer 1", writer);
  29.         PdfLayer nested_2 = new PdfLayer("Nested layer 2", writer);
  30.         nested.AddChild(nested_1);
  31.         nested.AddChild(nested_2);
  32.         writer.LockLayer(nested_2);
  33.         cb.BeginLayer(nested);
  34.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
  35.           new Phrase("nested layers"), 50, 775, 0
  36.         );
  37.         cb.EndLayer();
  38.         cb.BeginLayer(nested_1);
  39.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
  40.           new Phrase("nested layer 1"), 100, 800, 0
  41.         );
  42.         cb.EndLayer();
  43.         cb.BeginLayer(nested_2);
  44.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
  45.           new Phrase("nested layer 2"), 100, 750, 0
  46.         );
  47.         cb.EndLayer();
  48.  
  49.         PdfLayer group = PdfLayer.CreateTitle("Grouped layers", writer);
  50.         PdfLayer layer1 = new PdfLayer("Group: layer 1", writer);
  51.         PdfLayer layer2 = new PdfLayer("Group: layer 2", writer);
  52.         group.AddChild(layer1);
  53.         group.AddChild(layer2);
  54.         cb.BeginLayer(layer1);
  55.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
  56.           new Phrase( "layer 1 in the group"), 50, 700, 0
  57.         );
  58.         cb.EndLayer();
  59.         cb.BeginLayer(layer2);
  60.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
  61.           new Phrase("layer 2 in the group"), 50, 675, 0
  62.         );
  63.         cb.EndLayer();
  64.  
  65.         PdfLayer radiogroup = PdfLayer.CreateTitle("Radio group", writer);
  66.         PdfLayer radio1 = new PdfLayer("Radiogroup: layer 1", writer);
  67.         radio1.On = true;
  68.         PdfLayer radio2 = new PdfLayer("Radiogroup: layer 2", writer);
  69.         radio2.On = false;
  70.         PdfLayer radio3 = new PdfLayer("Radiogroup: layer 3", writer);
  71.         radio3.On = false;
  72.         radiogroup.AddChild(radio1);
  73.         radiogroup.AddChild(radio2);
  74.         radiogroup.AddChild(radio3);
  75.         List options = new List();
  76.         options.Add(radio1);
  77.         options.Add(radio2);
  78.         options.Add(radio3);
  79.         writer.AddOCGRadioGroup(options);
  80.         cb.BeginLayer(radio1);
  81.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
  82.           new Phrase("option 1"), 50, 600, 0
  83.         );
  84.         cb.EndLayer();
  85.         cb.BeginLayer(radio2);
  86.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
  87.           new Phrase("option 2"), 50, 575, 0
  88.         );
  89.         cb.EndLayer();
  90.         cb.BeginLayer(radio3);
  91.         ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
  92.           new Phrase(
  93.                 "option 3"
  94.           ), 50, 550, 0
  95.         );
  96.         cb.EndLayer();
  97.  
  98.         PdfLayer not_printed = new PdfLayer("not printed", writer);
  99.         not_printed.OnPanel = false;
  100.         not_printed.SetPrint("Print", false);
  101.         cb.BeginLayer(not_printed);
  102.         ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER,
  103.           new Phrase(
  104.                 "PRINT THIS PAGE"
  105.           ), 300, 700, 90
  106.         );
  107.         cb.EndLayer();
  108.  
  109.         PdfLayer zoom = new PdfLayer("Zoom 0.75-1.25", writer);
  110.         zoom.OnPanel = false;
  111.         zoom.SetZoom(0.75f, 1.25f);
  112.         cb.BeginLayer(zoom);
  113.         ColumnText.ShowTextAligned(
  114.           cb, Element.ALIGN_LEFT,
  115.           new Phrase(
  116.             "Only visible if the zoomfactor is between 75 and 125%"
  117.           ), 30, 530, 90
  118.         );
  119.         cb.EndLayer();
  120.       }
  121.     }
  122. // ===========================================================================
  123.   }
  124. }
SvgToPdf.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Web;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12.  
  13. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  14.   public class SvgToPdf : IWriter {
  15. // ===========================================================================
  16.     public void Write(Stream stream) {
  17.       throw new NotImplementedException(
  18.         "Batik SVG toolkit is only implemented in Java"
  19.       );
  20.     }
  21. // ===========================================================================
  22.   }
  23. }
SvgLayers.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Web;
  10. using iTextSharp.text;
  11. using iTextSharp.text.pdf;
  12.  
  13. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  14.   public class SvgLayers : IWriter {
  15. // ===========================================================================
  16.     public void Write(Stream stream) {
  17.       throw new NotImplementedException(
  18.         "Batik SVG toolkit is only implemented in Java"
  19.       );
  20.     }
  21. // ===========================================================================
  22.   }
  23. }
ObjectData.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.Data;
  9. using System.Data.Common;
  10. using System.IO;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  18.   public class ObjectData : IWriter {
  19. // ===========================================================================
  20.     /** SQL statement to get selected directors */
  21.     public const string SELECTDIRECTORS =
  22.       @"SELECT DISTINCT d.id, d.name, d.given_name, count(*) AS c
  23.      FROM film_director d, film_movie_director md
  24.      WHERE d.id = md.director_id AND d.id < 8
  25.      GROUP BY d.id, d.name, d.given_name ORDER BY id";
  26. // ---------------------------------------------------------------------------
  27.     public void Write(Stream stream) {
  28.       // step 1
  29.       using (Document document = new Document()) {
  30.         // step 2
  31.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  32.         writer.SetTagged();
  33.         writer.UserProperties = true;        
  34.         // step 3
  35.         document.Open();
  36.         // step 4
  37.         PdfStructureTreeRoot tree = writer.StructureTreeRoot;
  38.         PdfStructureElement top = new PdfStructureElement(
  39.           tree, new PdfName("Directors")
  40.         );
  41.        
  42.         Dictionary directors =
  43.           new Dictionary();
  44.  
  45.         int id;
  46.         Director director;
  47.         PdfStructureElement e;
  48.         DbProviderFactory dbp = AdoDB.Provider;
  49.         using (var c = dbp.CreateConnection()) {
  50.           c.ConnectionString = AdoDB.CS;
  51.           using (DbCommand cmd = c.CreateCommand()) {
  52.             cmd.CommandText = SELECTDIRECTORS;
  53.             c.Open();
  54.             using (var r = cmd.ExecuteReader()) {
  55.               while (r.Read()) {
  56.                 id = Convert.ToInt32(r["id"]);
  57.                 director = PojoFactory.GetDirector(r);
  58.                 e = new PdfStructureElement(top, new PdfName("director" + id));
  59.                 PdfDictionary userproperties = new PdfDictionary();
  60.                 userproperties.Put(PdfName.O, PdfName.USERPROPERTIES);
  61.                 PdfArray properties = new PdfArray();
  62.                 PdfDictionary property1 = new PdfDictionary();
  63.                 property1.Put(PdfName.N, new PdfString("Name"));
  64.                 property1.Put(PdfName.V, new PdfString(director.Name));            
  65.                 properties.Add(property1);
  66.                 PdfDictionary property2 = new PdfDictionary();
  67.                 property2.Put(PdfName.N, new PdfString("Given name"));
  68.                 property2.Put(PdfName.V, new PdfString(director.GivenName));            
  69.                 properties.Add(property2);
  70.                 PdfDictionary property3 = new PdfDictionary();
  71.                 property3.Put(PdfName.N, new PdfString("Posters"));
  72.                 property3.Put(PdfName.V, new PdfNumber(Convert.ToInt32(r["c"])));
  73.                 properties.Add(property3);
  74.                 userproperties.Put(PdfName.P, properties);
  75.                 e.Put(PdfName.A, userproperties);
  76.                 directors.Add(id, e);
  77.               }
  78.             }
  79.           }
  80.         }
  81.  
  82.         Dictionary map = new Dictionary();
  83.         for (int i = 1; i < 8; i++) {
  84.           foreach (Movie movie in PojoFactory.GetMovies(i)) {
  85.             map.Add(movie, i);
  86.           }
  87.         }
  88.        
  89.         PdfContentByte canvas = writer.DirectContent;
  90.         Image img;
  91.         float x = 11.5f;
  92.         float y = 769.7f;
  93.         string RESOURCE = Utility.ResourcePosters;
  94.         foreach (var entry in map.Keys) {
  95.           img = Image.GetInstance(Path.Combine(RESOURCE, entry.Imdb + ".jpg"));
  96.           img.ScaleToFit(1000, 60);
  97.           img.SetAbsolutePosition(x + (45 - img.ScaledWidth) / 2, y);
  98.           canvas.BeginMarkedContentSequence(directors[map[entry]]);
  99.           canvas.AddImage(img);
  100.           canvas.EndMarkedContentSequence();
  101.           x += 48;
  102.           if (x > 578) {
  103.             x = 11.5f;
  104.             y -= 84.2f;
  105.           }
  106.         }
  107.       }
  108.     }
  109. // ===========================================================================
  110.   }
  111. }
ReadOutLoud.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  15.   public class ReadOutLoud : IWriter {
  16. // ===========================================================================
  17.     public void Write(Stream stream) {
  18.       // step 1
  19.       using (Document document = new Document()) {
  20.         // step 2
  21.         PdfWriter writer = PdfWriter.GetInstance(document, stream);
  22.         writer.SetTagged();
  23.         // step 3
  24.         document.Open();
  25.         // step 4
  26.         PdfContentByte cb = writer.DirectContent;
  27.         BaseFont bf = BaseFont.CreateFont(
  28.           BaseFont.HELVETICA,
  29.           BaseFont.CP1252, BaseFont.NOT_EMBEDDED
  30.         );
  31.         BaseFont bf2 = BaseFont.CreateFont(
  32.           "c:/windows/fonts/msgothic.ttc,1",
  33.           BaseFont.IDENTITY_H, BaseFont.EMBEDDED
  34.         );
  35.  
  36.         PdfStructureTreeRoot root = writer.StructureTreeRoot;
  37.         PdfStructureElement div = new PdfStructureElement(
  38.           root, new PdfName("Div")
  39.         );
  40.         PdfDictionary dict;
  41.  
  42.         cb.BeginMarkedContentSequence(div);
  43.  
  44.         cb.BeginText();
  45.         cb.MoveText(36, 788);
  46.         cb.SetFontAndSize(bf, 12);
  47.         cb.SetLeading(18);
  48.         cb.ShowText("These are some famous movies by Stanley Kubrick: ");
  49.         dict = new PdfDictionary();
  50.         dict.Put(PdfName.E, new PdfString("Doctor"));
  51.         cb.BeginMarkedContentSequence(new PdfName("Span"), dict, true);
  52.         cb.NewlineShowText("Dr.");
  53.         cb.EndMarkedContentSequence();
  54.         cb.ShowText(
  55.           " Strangelove or: How I Learned to Stop Worrying and Love the Bomb."
  56.         );
  57.         dict = new PdfDictionary();
  58.         dict.Put(PdfName.E, new PdfString("Eyes Wide Shut."));
  59.         cb.BeginMarkedContentSequence(new PdfName("Span"), dict, true);
  60.         cb.NewlineShowText("EWS");
  61.         cb.EndMarkedContentSequence();
  62.         cb.EndText();
  63.         dict = new PdfDictionary();
  64.         dict.Put(PdfName.LANG, new PdfString("en-us"));
  65.         dict.Put(new PdfName("Alt"), new PdfString("2001: A Space Odyssey."));
  66.         cb.BeginMarkedContentSequence(new PdfName("Span"), dict, true);
  67.         Image img = Image.GetInstance(Path.Combine(
  68.           Utility.ResourcePosters, "0062622.jpg"
  69.         ));
  70.         img.ScaleToFit(1000, 100);
  71.         img.SetAbsolutePosition(36, 640);
  72.         cb.AddImage(img);
  73.         cb.EndMarkedContentSequence();
  74.  
  75.         cb.BeginText();
  76.         cb.MoveText(36, 620);
  77.         cb.SetFontAndSize(bf, 12);
  78.         cb.ShowText("This is a movie by Akira Kurosawa: ");
  79.         dict = new PdfDictionary();
  80.         dict.Put(PdfName.ACTUALTEXT, new PdfString("Seven Samurai."));
  81.         cb.BeginMarkedContentSequence(new PdfName("Span"), dict, true);
  82.         cb.SetFontAndSize(bf2, 12);
  83.         cb.ShowText("\u4e03\u4eba\u306e\u4f8d");
  84.         cb.EndMarkedContentSequence();
  85.         cb.EndText();
  86.        
  87.         cb.EndMarkedContentSequence();
  88.  
  89.       }
  90.     }
  91. // ===========================================================================
  92.   }
  93. }
StructureParser.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Web;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. /*
  15.  * Java book example uses SAX to parse XML. .NET uses XmlReader class instead of
  16.  * SAX, so this class is unnecessary.
  17.  * couple of good explanations of the differences between Java and C#:
  18.  * http://www.xml.com/pub/a/2002/03/06/csharpxml.html
  19.  * http://msdn.microsoft.com/en-us/library/aa478996.aspx
  20. */
  21. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  22.   public class StructureParser : IWriter {
  23. // ===========================================================================
  24.     public void Write(Stream stream) {
  25.       throw new NotImplementedException(
  26.         ".NET uses XmlReader class instead of SAX"
  27.       );
  28.     }
  29. // ===========================================================================
  30.   }
  31. }
ContentParser.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Web;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. /*
  15.  * Java book example uses SAX to parse XML. .NET uses XmlReader class instead of
  16.  * SAX, so this class is unnecessary.
  17.  * couple of good explanations of the differences between Java and C#:
  18.  * http://www.xml.com/pub/a/2002/03/06/csharpxml.html
  19.  * http://msdn.microsoft.com/en-us/library/aa478996.aspx
  20. */
  21. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  22.   public class ContentParser : IWriter {
  23. // ===========================================================================
  24.     public void Write(Stream stream) {
  25.       throw new NotImplementedException(
  26.         ".NET uses XmlReader class instead of SAX"
  27.       );
  28.     }
  29. // ===========================================================================
  30.   }
  31. }
StructuredContent.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using Ionic.Zip;
  13. using System.Xml;
  14. using iTextSharp.text;
  15. using iTextSharp.text.pdf;
  16. /*
  17.  * Java book example uses SAX to parse XML. .NET uses XmlReader class instead of
  18.  * SAX; i.e. ContentParser & StructureParser classes from book not needed and
  19.  * are implemented in __THIS__ class
  20.  *
  21.  * couple of good explanations of the differences between Java and C#:
  22.  * http://www.xml.com/pub/a/2002/03/06/csharpxml.html
  23.  * http://msdn.microsoft.com/en-us/library/aa478996.aspx
  24.  *
  25. */
  26. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  27.   public class StructuredContent : IWriter {
  28. // ===========================================================================
  29.     /** The resulting PDF. */
  30.     public const String RESULT = "moby.pdf";
  31.     /** An XML file that will be converted to PDF. */
  32.     public readonly String RESOURCE = Path.Combine(
  33.       Utility.ResourceXml, "moby.xml"
  34.     );
  35.     /** The StringBuffer that holds the characters. */
  36.     protected StringBuilder buf = new StringBuilder();
  37.  
  38.     /** The document to which content parsed form XML will be added. */
  39.     protected Document document;
  40.     /** The writer to which PDF syntax will be written. */
  41.     protected PdfWriter writer;
  42.     /** The canvas to which content will be written. */
  43.     protected PdfContentByte canvas;
  44.  
  45.     /** The current structure element during the parsing process. */
  46.     protected PdfStructureElement current;
  47.     /** The column to which content will be added. */
  48.     protected ColumnText column;
  49.     /** The font used when content elements are created. */
  50.     protected Font font;    
  51. // ---------------------------------------------------------------------------    
  52.     public void Write(Stream stream) {
  53.       using (ZipFile zip = new ZipFile()) {
  54.         zip.AddFile(RESOURCE, "");
  55.         StructuredContent s = new StructuredContent();      
  56.         zip.AddEntry(RESULT, s.CreatePdf());      
  57.         zip.Save(stream);            
  58.       }
  59.     }
  60. // ---------------------------------------------------------------------------    
  61.     public byte[] CreatePdf() {
  62.       using (MemoryStream ms = new MemoryStream()) {
  63.         using (document = new Document(PageSize.A5)) {
  64.           // step 2
  65.           writer = PdfWriter.GetInstance(document, ms);
  66.           writer.SetTagged();
  67.           // step 3
  68.           document.Open();
  69.           // step 4
  70.           PdfStructureTreeRoot root = writer.StructureTreeRoot;
  71.           root.MapRole(new PdfName("chapter"), PdfName.SECT);
  72.           root.MapRole(new PdfName("title"), PdfName.H);
  73.           root.MapRole(new PdfName("para"), PdfName.P);
  74.           top = new PdfStructureElement(
  75.             root, new PdfName("chapter")
  76.           );
  77.          
  78.           canvas = writer.DirectContent;
  79.           column = new ColumnText(canvas);
  80.           column.SetSimpleColumn(36, 36, 384, 569);
  81.           font = new Font(
  82.             BaseFont.CreateFont(
  83.               "c:/windows/fonts/arial.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED
  84.             ), 12
  85.           );          
  86.          
  87.           using (XmlReader xr = XmlReader.Create(RESOURCE)) {
  88.             xr.MoveToContent();
  89.             while (xr.Read()) {
  90.               switch (xr.NodeType) {
  91.                 case XmlNodeType.Element:
  92.                   StartElement(xr.Name);
  93.                   break;
  94.                 case XmlNodeType.Text:
  95.                   buf.Append(Regex.Replace(xr.Value.Trim(), "\n", " "));
  96.                   break;
  97.                 case XmlNodeType.EndElement:
  98.                   EndElement(xr.Name);
  99.                   break;
  100.               }
  101.             }
  102.           }
  103.         }
  104.         return ms.ToArray();
  105.       }
  106.     }
  107.    
  108.     PdfStructureElement top;
  109. // ---------------------------------------------------------------------------        
  110. // replace [StructureParser|ContentParser].startElement() from Java example
  111.     public void StartElement(string name) {
  112.       switch (name) {
  113.         case "chapter":
  114.           break;
  115.         default:
  116.           current = new PdfStructureElement(top, new PdfName(name));
  117.           canvas.BeginMarkedContentSequence(current);
  118.           break;
  119.       }
  120.     }    
  121. // ---------------------------------------------------------------------------        
  122. // replace ContentParser.endElement() from Java example
  123.     public void EndElement(string name) {  
  124.       if ("chapter".Equals(name)) return;
  125.      
  126.       String s = buf.ToString().Trim();
  127.       buf = new StringBuilder();
  128.       if (s.Length > 0) {
  129.         Paragraph p = new Paragraph(s, font);
  130.         p.Alignment = Element.ALIGN_JUSTIFIED;
  131.         column.AddElement(p);
  132.         int status = column.Go();
  133.         while (ColumnText.HasMoreText(status)) {
  134.           canvas.EndMarkedContentSequence();
  135.           document.NewPage();
  136.           canvas.BeginMarkedContentSequence(current);
  137.           column.SetSimpleColumn(36, 36, 384, 569);
  138.           status = column.Go();
  139.         }
  140.       }
  141.       canvas.EndMarkedContentSequence();    
  142.     }
  143. // ===========================================================================
  144.   }
  145. }
ParseTaggedPdf.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Text;
  11. using Ionic.Zip;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.parser;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  17.   public class ParseTaggedPdf : IWriter {
  18. // ===========================================================================
  19.     /** The resulting XML file. */
  20.     public const String RESULT = "moby_extracted.xml";
  21. // ---------------------------------------------------------------------------    
  22.     public void Write(Stream stream) {
  23.       using (ZipFile zip = new ZipFile()) {
  24.         StructuredContent s = new StructuredContent();
  25.         byte[] pdf = s.CreatePdf();
  26.         zip.AddEntry(Utility.ResultFileName(s.ToString() + ".pdf"), pdf);
  27.         TaggedPdfReaderTool reader = new TaggedPdfReaderTool();
  28.         using (MemoryStream ms = new MemoryStream()) {
  29.           reader.ConvertToXml(new PdfReader(pdf), ms);
  30.           StringBuilder sb =  new StringBuilder();
  31.           foreach (byte b in ms.ToArray()) {
  32.             sb.Append((char) b);
  33.           }
  34.           zip.AddEntry(RESULT, sb.ToString());
  35.         }
  36.         zip.Save(stream);
  37.       }
  38.     }    
  39. // ===========================================================================
  40.     }
  41. }
ParsingHelloWorld.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Text;
  11. using Ionic.Zip;
  12. using iTextSharp.text;
  13. using iTextSharp.text.io;
  14. using iTextSharp.text.pdf;
  15. using iTextSharp.text.pdf.parser;
  16. using kuujinbo.iTextInAction2Ed.Chapter01;
  17.  
  18. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  19.   public class ParsingHelloWorld : IWriter {
  20. // ===========================================================================
  21.     /** The resulting PDF. */
  22.     public const String PDF = "hello_reverse.pdf";
  23.     /** A possible resulting after parsing the PDF. */
  24.     public const String TEXT1 = "result1.txt";
  25.     /** A possible resulting after parsing the PDF. */
  26.     public const String TEXT2 = "result2.txt";
  27.     /** A possible resulting after parsing the PDF. */
  28.     public const String TEXT3 = "result3.txt";
  29. // ---------------------------------------------------------------------------
  30.     public void Write(Stream stream) {
  31.       using (ZipFile zip = new ZipFile()) {
  32.         ParsingHelloWorld example = new ParsingHelloWorld();
  33.         byte[] ePdf = example.CreatePdf();
  34.         zip.AddEntry(PDF, ePdf);
  35.         HelloWorld hello = new HelloWorld();
  36.         byte[] hPdf = Utility.PdfBytes(hello);
  37.         zip.AddEntry(Utility.ResultFileName(hello.ToString() + ".pdf"), hPdf);      
  38.         zip.AddEntry(TEXT1, example.ParsePdf(hPdf));
  39.         zip.AddEntry(TEXT2, example.ParsePdf(ePdf));
  40.         zip.AddEntry(TEXT3, example.ExtractText(ePdf));
  41.         zip.Save(stream);            
  42.       }
  43.     }
  44. // ---------------------------------------------------------------------------
  45.     /**
  46.      * Generates a PDF file with the text 'Hello World'
  47.      */    
  48.     public byte[] CreatePdf() {
  49.       using (MemoryStream ms = new MemoryStream()) {
  50.         using (Document document = new Document()) {
  51.           // step 2
  52.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  53.           // step 3
  54.           document.Open();
  55.           // step 4
  56.           // we add the text to the direct content, but not in the right order
  57.           PdfContentByte cb = writer.DirectContent;
  58.           BaseFont bf = BaseFont.CreateFont();
  59.           cb.BeginText();
  60.           cb.SetFontAndSize(bf, 12);
  61.           cb.MoveText(88.66f, 367);
  62.           cb.ShowText("ld");
  63.           cb.MoveText(-22f, 0);
  64.           cb.ShowText("Wor");
  65.           cb.MoveText(-15.33f, 0);
  66.           cb.ShowText("llo");
  67.           cb.MoveText(-15.33f, 0);
  68.           cb.ShowText("He");
  69.           cb.EndText();
  70.           // we also add text in a form XObject
  71.           PdfTemplate tmp = cb.CreateTemplate(250, 25);
  72.           tmp.BeginText();
  73.           tmp.SetFontAndSize(bf, 12);
  74.           tmp.MoveText(0, 7);
  75.           tmp.ShowText("Hello People");
  76.           tmp.EndText();
  77.           cb.AddTemplate(tmp, 36, 343);
  78.         }
  79.         return ms.ToArray();
  80.       }
  81.     }
  82. // ---------------------------------------------------------------------------    
  83.     /**
  84.      * Parses the PDF using PRTokeniser
  85.      * @param src the ]original PDF file
  86. ]     */
  87.     public string ParsePdf(byte[] src) {
  88.       PdfReader reader = new PdfReader(src);
  89.       // we can inspect the syntax of the imported page
  90.       byte[] streamBytes = reader.GetPageContent(1);
  91.       StringBuilder sb = new StringBuilder();
  92.       PRTokeniser tokenizer = new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().CreateSource(streamBytes)));
  93.       while (tokenizer.NextToken()) {
  94.         if (tokenizer.TokenType == PRTokeniser.TokType.STRING) {
  95.           sb.AppendLine(tokenizer.StringValue);
  96.         }
  97.       }
  98.       return sb.ToString();
  99.     }
  100. // ---------------------------------------------------------------------------    
  101.     /**
  102.      * Extracts text from a PDF document.
  103.      * @param src the original PDF document
  104.      */
  105.     public string ExtractText(byte[] src) {
  106.       PdfReader reader = new PdfReader(src);
  107.       MyTextRenderListener listener = new MyTextRenderListener();
  108.       PdfContentStreamProcessor processor = new PdfContentStreamProcessor(listener);
  109.       PdfDictionary pageDic = reader.GetPageN(1);
  110.       PdfDictionary resourcesDic = pageDic.GetAsDict(PdfName.RESOURCES);
  111.       processor.ProcessContent(
  112.         ContentByteUtils.GetContentBytesForPage(reader, 1),
  113.         resourcesDic
  114.       );
  115.       return listener.Text.ToString();
  116.     }    
  117. // ===========================================================================
  118.   }
  119. }
MyTextRenderListener.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Text;
  11. using Ionic.Zip;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.parser;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  17.   public class MyTextRenderListener : IRenderListener {
  18. // ===========================================================================
  19.     public StringBuilder Text { get; set; }
  20. // ---------------------------------------------------------------------------
  21.     /**
  22.      * Creates a RenderListener that will look for text.
  23.      */
  24.     public MyTextRenderListener() {
  25.       Text = new StringBuilder();
  26.     }
  27.    
  28.     /**
  29.      * @see com.itextpdf.text.pdf.parser.RenderListener#beginTextBlock()
  30.      */
  31.     public void BeginTextBlock() {
  32.       Text.Append("");
  33.     }
  34.  
  35.     /**
  36.      * @see com.itextpdf.text.pdf.parser.RenderListener#renderImage(
  37.      *     com.itextpdf.text.pdf.parser.ImageRenderInfo)
  38.      */
  39.     public void RenderImage(ImageRenderInfo renderInfo) {
  40.     }
  41.  
  42.     /**
  43.      * @see com.itextpdf.text.pdf.parser.RenderListener#renderText(
  44.      *     com.itextpdf.text.pdf.parser.TextRenderInfo)
  45.      */
  46.     public void RenderText(TextRenderInfo renderInfo) {
  47.       Text.Append("");
  48.     }    
  49. // ===========================================================================
  50.     }
  51. }
InspectPageContent.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Text;
  11. using Ionic.Zip;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.parser;
  15. using kuujinbo.iTextInAction2Ed.Chapter03;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  18.   public class InspectPageContent : IWriter {
  19. // ===========================================================================
  20.     /** Text file containing information about a PDF file. */
  21.     public const String RESULT = "calendar_info.txt";
  22. // ---------------------------------------------------------------------------
  23.     public void Write(Stream stream) {
  24.       using (ZipFile zip = new ZipFile()) {
  25.         MovieTemplates m = new MovieTemplates();
  26.         byte[] mPdf = Utility.PdfBytes(m);
  27.         zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), mPdf);
  28.         InspectPageContent i = new InspectPageContent();
  29.         zip.AddEntry(RESULT, i.InspectPdf(mPdf));
  30.         zip.Save(stream);            
  31.       }
  32.     }    
  33. // ---------------------------------------------------------------------------
  34.     /**
  35.      * Parses object and content information of a PDF into a text file.
  36.      * @param pdf the original PDF
  37.      *
  38.      * this method uses code from;
  39.      * PdfContentReaderTool.ListContentStreamForPage()
  40.      * so i can pass in a byte array instead of file path
  41.      *
  42.      */
  43.     public string InspectPdf(byte[] pdf) {
  44.       PdfReader reader = new PdfReader(pdf);
  45.       int maxPageNum = reader.NumberOfPages;
  46.       StringBuilder sb = new StringBuilder();
  47.       for (int pageNum = 1; pageNum
ExtractPageContent.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Text;
  11. using Ionic.Zip;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.parser;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  17.   public class ExtractPageContent : IWriter {
  18. // ===========================================================================
  19.     /** The original PDF that will be parsed. */
  20.     public readonly string PREFACE = Path.Combine(
  21.       Utility.ResourcePdf, "preface.pdf"
  22.     );    
  23.     /** The resulting text file. */
  24.     public const String RESULT = "preface.txt";
  25. // ---------------------------------------------------------------------------
  26.     public void Write(Stream stream) {
  27.       using (ZipFile zip = new ZipFile()) {
  28.         zip.AddFile(PREFACE, "");
  29.         PdfReader reader = new PdfReader(PREFACE);
  30.         PdfReaderContentParser parser = new PdfReaderContentParser(reader);
  31.         StringBuilder sb = new StringBuilder();
  32.         ITextExtractionStrategy strategy;
  33.         for (int i = 1; i
ExtractPageContentSorted1.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Text;
  11. using Ionic.Zip;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.parser;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  17.   public class ExtractPageContentSorted1 : IWriter {
  18. // ===========================================================================
  19.     /** The original PDF that will be parsed. */
  20.     public readonly string PREFACE = Path.Combine(
  21.       Utility.ResourcePdf, "preface.pdf"
  22.     );    
  23.     /** The resulting text file. */
  24.     public const String RESULT = "preface_sorted1.txt";
  25. // ---------------------------------------------------------------------------
  26.     public void Write(Stream stream) {
  27.       using (ZipFile zip = new ZipFile()) {
  28.         zip.AddFile(PREFACE, "");
  29.         PdfReader reader = new PdfReader(PREFACE);
  30.         PdfReaderContentParser parser = new PdfReaderContentParser(reader);
  31.         StringBuilder sb = new StringBuilder();
  32.         ITextExtractionStrategy strategy;
  33.         for (int i = 1; i
ExtractPageContentSorted2.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Text;
  11. using Ionic.Zip;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.parser;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  17.   public class ExtractPageContentSorted2 : IWriter {
  18. // ===========================================================================
  19.     /** The original PDF that will be parsed. */
  20.     public readonly string PREFACE = Path.Combine(
  21.       Utility.ResourcePdf, "preface.pdf"
  22.     );    
  23.     /** The resulting text file. */
  24.     public const String RESULT = "preface_sorted2.txt";
  25. // ---------------------------------------------------------------------------
  26.     public void Write(Stream stream) {
  27.       using (ZipFile zip = new ZipFile()) {
  28.         zip.AddFile(PREFACE, "");
  29.         PdfReader reader = new PdfReader(PREFACE);
  30.         PdfReaderContentParser parser = new PdfReaderContentParser(reader);
  31.         StringBuilder sb = new StringBuilder();
  32.         for (int i = 1; i
ExtractPageContentArea.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Text;
  11. using Ionic.Zip;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.parser;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  17.   public class ExtractPageContentArea : IWriter {
  18. // ===========================================================================
  19.     /** The original PDF that will be parsed. */
  20.     public readonly string PREFACE = Path.Combine(
  21.       Utility.ResourcePdf, "preface.pdf"
  22.     );    
  23.     /** The resulting text file. */
  24.     public const String RESULT = "preface_clipped.txt";
  25. // ---------------------------------------------------------------------------
  26.     public void Write(Stream stream) {
  27.       using (ZipFile zip = new ZipFile()) {
  28.         zip.AddFile(PREFACE, "");
  29.         PdfReader reader = new PdfReader(PREFACE);
  30.         System.util.RectangleJ rect = new System.util.RectangleJ(
  31.           70, 80, 420, 500
  32.         );
  33.         RenderFilter[] filter = {new RegionTextRenderFilter(rect)};
  34.         ITextExtractionStrategy strategy;
  35.         StringBuilder sb = new StringBuilder();
  36.         for (int i = 1; i
ShowTextMargins.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Text;
  11. using Ionic.Zip;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.parser;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  17.   public class ShowTextMargins : IWriter {
  18. // ===========================================================================
  19.     /** The original PDF that will be parsed. */
  20.     public readonly string PREFACE = Path.Combine(
  21.       Utility.ResourcePdf, "preface.pdf"
  22.     );    
  23.     /** The resulting text file. */
  24.     public const String RESULT = "margins.pdf";
  25. // ---------------------------------------------------------------------------
  26.     public void Write(Stream stream) {
  27.       using (ZipFile zip = new ZipFile()) {
  28.         zip.AddFile(PREFACE, "");
  29.         PdfReader reader = new PdfReader(PREFACE);
  30.         PdfReaderContentParser parser = new PdfReaderContentParser(reader);
  31.         using (MemoryStream ms = new MemoryStream()) {
  32.           using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  33.             TextMarginFinder finder;
  34.             for (int i = 1; i
MyImageRenderListener.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Web;
  12. using iTextSharp.text;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.parser;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  17.   public class MyImageRenderListener : IRenderListener {
  18. // ===========================================================================
  19.     /** the byte array of the extracted images */
  20.     private List _myImages;
  21.     public List MyImages {
  22.       get { return _myImages; }
  23.     }
  24.     /** the file names of the extracted images */
  25.     private List _imageNames;
  26.     public List ImageNames {
  27.       get { return _imageNames; }
  28.     }
  29. // ---------------------------------------------------------------------------
  30.     /**
  31.      * Creates a RenderListener that will look for images.
  32.      */
  33.     public MyImageRenderListener() {
  34.       _myImages = new List();
  35.       _imageNames = new List();
  36.     }
  37. // ---------------------------------------------------------------------------
  38.     /**
  39.      * @see com.itextpdf.text.pdf.parser.RenderListener#beginTextBlock()
  40.      */
  41.     public void BeginTextBlock() { }
  42. // ---------------------------------------------------------------------------    
  43.     /**
  44.      * @see com.itextpdf.text.pdf.parser.RenderListener#endTextBlock()
  45.      */
  46.     public void EndTextBlock() { }
  47. // ---------------------------------------------------------------------------    
  48.     /**
  49.      * @see com.itextpdf.text.pdf.parser.RenderListener#renderImage(
  50.      *     com.itextpdf.text.pdf.parser.ImageRenderInfo)
  51.      */
  52.     public void RenderImage(ImageRenderInfo renderInfo) {
  53.       try {
  54.         PdfImageObject image = renderInfo.GetImage();
  55.         if (image == null
  56. /*
  57.  * do not attempt to parse => jbig2 decoder not fully implemented.
  58.  * THE JAVA EXAMPLE INCORRECTLY CREATES A CORRUPT JBIG2 IMAGE
  59.  * BECAUSE THERE IS NO EXPLICIT CHECK. I POSTED TWICE TO THE MAILING
  60.  * LIST, SINCE VERSION 5.1.3 BUT THE ERROR HAS NOT BEEN CORRECTED.
  61.  */
  62.           || image.GetImageBytesType() == PdfImageObject.ImageBytesType.JBIG2
  63.         )
  64.         return;
  65.        
  66.         _imageNames.Add(string.Format(
  67.           "Image{0}.{1}",
  68.           renderInfo.GetRef().Number, image.GetFileType()
  69.         ) );
  70.         _myImages.Add(image.GetImageAsBytes());
  71.       }
  72.       catch {
  73. // pass through any other unsupported image types
  74.       }
  75.     }
  76.  // ---------------------------------------------------------------------------    
  77.    /**
  78.      * @see com.itextpdf.text.pdf.parser.RenderListener#renderText(
  79.      *     com.itextpdf.text.pdf.parser.TextRenderInfo)
  80.      */
  81.     public void RenderText(TextRenderInfo renderInfo) { }
  82. // ===========================================================================
  83.   }
  84. }
ExtractImages.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using Ionic.Zip;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13. using iTextSharp.text.pdf.parser;
  14. using kuujinbo.iTextInAction2Ed.Chapter10;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter15 {
  17.   public class ExtractImages : IWriter {
  18. // ===========================================================================
  19.     public void Write(Stream stream) {
  20.       ImageTypes it = new ImageTypes();
  21.       using (ZipFile zip = new ZipFile()) {
  22.         byte[] pdf = it.CreatePdf();
  23.         zip.AddEntry(Utility.ResultFileName(it.ToString() + ".pdf"), pdf);
  24.         PdfReader reader = new PdfReader(pdf);
  25.         PdfReaderContentParser parser = new PdfReaderContentParser(reader);
  26.         MyImageRenderListener listener = new MyImageRenderListener();
  27.         for (int i = 1; i
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now