Chapter 12: Protecting your PDF

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

10th October 2015
admin-marketing

Switch code for this example

MetadataPdf.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 part3.chapter12;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.util.Map;
  13.  
  14. import com.itextpdf.text.Document;
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.Paragraph;
  17. import com.itextpdf.text.pdf.PdfWriter;
  18. import com.itextpdf.text.pdf.PdfReader;
  19. import com.itextpdf.text.pdf.PdfStamper;
  20.  
  21.  
  22. public class MetadataPdf {
  23.     /** The resulting PDF file. */
  24.     public static final String RESULT1
  25.         = "results/part3/chapter12/pdf_metadata.pdf";
  26.     /** The resulting PDF file. */
  27.     public static final String RESULT2
  28.         = "results/part3/chapter12/pdf_metadata_changed.pdf";
  29.    
  30.     /**
  31.      * Creates a PDF document.
  32.      * @param filename the path to the new PDF document
  33.      * @throws DocumentException
  34.      * @throws IOException
  35.      */
  36.     public void createPdf(String filename) throws IOException, DocumentException {
  37.         // step 1
  38.         Document document = new Document();
  39.         // step 2
  40.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  41.         // step 3
  42.         document.addTitle("Hello World example");
  43.         document.addAuthor("Bruno Lowagie");
  44.         document.addSubject("This example shows how to add metadata");
  45.         document.addKeywords("Metadata, iText, PDF");
  46.         document.addCreator("My program using iText");
  47.         document.open();
  48.         // step 4
  49.         document.add(new Paragraph("Hello World"));
  50.         // step 5
  51.         document.close();
  52.     }
  53.  
  54.     /**
  55.      * Manipulates a PDF file src with the file dest as result
  56.      * @param src the original PDF
  57.      * @param dest the resulting PDF
  58.      * @throws IOException
  59.      * @throws DocumentException
  60.      */
  61.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  62.         PdfReader reader = new PdfReader(src);
  63.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  64.         Map info = reader.getInfo();
  65.         info.put("Title", "Hello World stamped");
  66.         info.put("Subject", "Hello World with changed metadata");
  67.         info.put("Keywords", "iText in Action, PdfStamper");
  68.         info.put("Creator", "Silly standalone example");
  69.         info.put("Author", "Also Bruno Lowagie");
  70.         stamper.setMoreInfo(info);
  71.         stamper.close();
  72.         reader.close();
  73.     }
  74.    
  75.     /**
  76.      * Main method.
  77.      *
  78.      * @param    args    no arguments needed
  79.      * @throws DocumentException
  80.      * @throws IOException
  81.      */
  82.     public static void main(String[] args) throws IOException, DocumentException {
  83.         MetadataPdf metadata = new MetadataPdf();
  84.         metadata.createPdf(RESULT1);
  85.         metadata.manipulatePdf(RESULT1, RESULT2);
  86.     }
  87. }
MetadataXmp.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 part3.chapter12;
  8.  
  9. import java.io.ByteArrayOutputStream;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.util.HashMap;
  13.  
  14. import com.itextpdf.text.Document;
  15. import com.itextpdf.text.DocumentException;
  16. import com.itextpdf.text.Paragraph;
  17. import com.itextpdf.text.pdf.PdfReader;
  18. import com.itextpdf.text.pdf.PdfStamper;
  19. import com.itextpdf.text.pdf.PdfWriter;
  20. import com.itextpdf.text.xml.xmp.DublinCoreSchema;
  21. import com.itextpdf.text.xml.xmp.PdfSchema;
  22. import com.itextpdf.text.xml.xmp.XmpArray;
  23. import com.itextpdf.text.xml.xmp.XmpSchema;
  24. import com.itextpdf.text.xml.xmp.XmpWriter;
  25.  
  26. public class MetadataXmp {
  27.  
  28.     /** The resulting PDF file. */
  29.     public static final String RESULT1
  30.         = "results/part3/chapter12/xmp_metadata.pdf";
  31.     /** The resulting PDF file. */
  32.     public static final String RESULT2
  33.         = "results/part3/chapter12/xmp_metadata_automatic.pdf";
  34.     /** The resulting PDF file. */
  35.     public static final String RESULT3
  36.         = "results/part3/chapter12/xmp_metadata_added.pdf";
  37.     /** An XML file containing an XMP stream. */
  38.     public static final String RESULT4
  39.         = "results/part3/chapter12/xmp.xml";
  40.    
  41.     /**
  42.      * Creates a PDF document.
  43.      * @param filename the path to the new PDF document
  44.      * @throws DocumentException
  45.      * @throws IOException
  46.      */
  47.     public void createPdf(String filename) throws IOException, DocumentException {
  48.         // step 1
  49.         Document document = new Document();
  50.         // step 2
  51.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT1));
  52.         ByteArrayOutputStream os = new ByteArrayOutputStream();
  53.         XmpWriter xmp = new XmpWriter(os);
  54.         XmpSchema dc = new com.itextpdf.text.xml.xmp.DublinCoreSchema();
  55.         XmpArray subject = new XmpArray(XmpArray.UNORDERED);
  56.         subject.add("Hello World");
  57.         subject.add("XMP & Metadata");
  58.         subject.add("Metadata");
  59.         dc.setProperty(DublinCoreSchema.SUBJECT, subject);
  60.         xmp.addRdfDescription(dc);
  61.         PdfSchema pdf = new PdfSchema();
  62.         pdf.setProperty(PdfSchema.KEYWORDS, "Hello World, XMP, Metadata");
  63.         pdf.setProperty(PdfSchema.VERSION, "1.4");
  64.         xmp.addRdfDescription(pdf);
  65.         xmp.close();
  66.         writer.setXmpMetadata(os.toByteArray());
  67.         // step 3
  68.         document.open();
  69.         // step 4
  70.         document.add(new Paragraph("Hello World"));
  71.         // step 5
  72.         document.close();
  73.     }
  74.     /**
  75.      * Creates a PDF document.
  76.      * @param filename the path to the new PDF document
  77.      * @throws DocumentException
  78.      * @throws IOException
  79.      */
  80.     public void createPdfAutomatic(String filename) throws IOException, DocumentException {
  81.         // step 1
  82.         Document document = new Document();
  83.         // step 2
  84.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  85.         document.addTitle("Hello World example");
  86.         document.addSubject("This example shows how to add metadata & XMP");
  87.         document.addKeywords("Metadata, iText, step 3");
  88.         document.addCreator("My program using 'iText'");
  89.         document.addAuthor("Bruno Lowagie & Paulo Soares");
  90.         writer.createXmpMetadata();
  91.         // step 3
  92.         document.open();
  93.         // step 4
  94.         document.add(new Paragraph("Hello World"));
  95.         // step 5
  96.         document.close();
  97.     }
  98.  
  99.     /**
  100.      * Manipulates a PDF file src with the file dest as result
  101.      * @param src the original PDF
  102.      * @param dest the resulting PDF
  103.      * @throws IOException
  104.      * @throws DocumentException
  105.      */
  106.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  107.         PdfReader reader = new PdfReader(src);
  108.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  109.         HashMap info = reader.getInfo();
  110.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  111.         XmpWriter xmp = new XmpWriter(baos, info);
  112.         xmp.close();
  113.         stamper.setXmpMetadata(baos.toByteArray());
  114.         stamper.close();
  115.         reader.close();
  116.     }
  117.    
  118.     /**
  119.      * Reads the XML stream inside a PDF file into an XML file.
  120.      * @param src  A PDF file containing XMP data
  121.      * @param dest XML file containing the XMP data extracted from the PDF
  122.      * @throws IOException
  123.      */
  124.     public void readXmpMetadata(String src, String dest) throws IOException {
  125.         PdfReader reader = new PdfReader(src);
  126.         FileOutputStream fos = new FileOutputStream(dest);
  127.         byte[] b = reader.getMetadata();
  128.         fos.write(b, 0, b.length);
  129.         fos.flush();
  130.         fos.close();
  131.         reader.close();
  132.     }
  133.    
  134.     /**
  135.      * Main method.
  136.      *
  137.      * @param    args    no arguments needed
  138.      * @throws DocumentException
  139.      * @throws IOException
  140.      */
  141.     public static void main(String[] args) throws IOException, DocumentException {
  142.         MetadataXmp metadata = new MetadataXmp();
  143.         metadata.createPdf(RESULT1);
  144.         metadata.createPdfAutomatic(RESULT2);
  145.         new MetadataPdf().createPdf(MetadataPdf.RESULT1);
  146.         metadata.manipulatePdf(MetadataPdf.RESULT1, RESULT3);
  147.         metadata.readXmpMetadata(RESULT3, RESULT4);
  148.     }
  149. }
HelloWorldCompression.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 part3.chapter12;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15.  
  16. import com.itextpdf.text.Document;
  17. import com.itextpdf.text.DocumentException;
  18. import com.itextpdf.text.List;
  19. import com.itextpdf.text.ListItem;
  20. import com.itextpdf.text.pdf.PdfReader;
  21. import com.itextpdf.text.pdf.PdfStamper;
  22. import com.itextpdf.text.pdf.PdfWriter;
  23. import com.lowagie.database.DatabaseConnection;
  24. import com.lowagie.database.HsqldbConnection;
  25. import com.lowagie.filmfestival.Director;
  26. import com.lowagie.filmfestival.FilmFonts;
  27. import com.lowagie.filmfestival.Movie;
  28. import com.lowagie.filmfestival.PojoFactory;
  29.  
  30. public class HelloWorldCompression {
  31.     /** The resulting PDF file. */
  32.     public static final String RESULT1
  33.         = "results/part3/chapter12/compression_not_at_all.pdf";
  34.     /** The resulting PDF file. */
  35.     public static final String RESULT2
  36.         = "results/part3/chapter12/compression_zero.pdf";
  37.     /** The resulting PDF file. */
  38.     public static final String RESULT3
  39.         = "results/part3/chapter12/compression_normal.pdf";
  40.     /** The resulting PDF file. */
  41.     public static final String RESULT4
  42.         = "results/part3/chapter12/compression_high.pdf";
  43.     /** The resulting PDF file. */
  44.     public static final String RESULT5
  45.         = "results/part3/chapter12/compression_full.pdf";
  46.     /** The resulting PDF file. */
  47.     public static final String RESULT6
  48.         = "results/part3/chapter12/compression_full_too.pdf";
  49.     /** The resulting PDF file. */
  50.     public static final String RESULT7
  51.         = "results/part3/chapter12/compression_removed.pdf";
  52.    
  53.     /**
  54.      * Creates a PDF with information about the movies
  55.      * @param    filename the name of the PDF file that will be created.
  56.      * @throws    DocumentException
  57.      * @throws    IOException
  58.      * @throws    SQLException
  59.      */
  60.     public void createPdf(String filename, int compression)
  61.         throws IOException, DocumentException, SQLException {
  62.         // step 1
  63.         Document document = new Document();
  64.         // step 2
  65.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  66.         switch(compression) {
  67.         case -1:
  68.             Document.compress = false;
  69.             break;
  70.         case 0:
  71.             writer.setCompressionLevel(0);
  72.             break;
  73.         case 2:
  74.             writer.setCompressionLevel(9);
  75.             break;
  76.         case 3:
  77.             writer.setFullCompression();
  78.             break;
  79.         }
  80.         // step 3
  81.         document.open();
  82.         // step 4
  83.         // Create database connection and statement
  84.         DatabaseConnection connection = new HsqldbConnection("filmfestival");
  85.         Statement stm = connection.createStatement();
  86.         ResultSet rs = stm.executeQuery(
  87.             "SELECT DISTINCT mc.country_id, c.country, count(*) AS c "
  88.             + "FROM film_country c, film_movie_country mc "
  89.             + "WHERE c.id = mc.country_id "
  90.             + "GROUP BY mc.country_id, country ORDER BY c DESC");
  91.         // Create a new list
  92.         List list = new List(List.ORDERED);
  93.         // loop over the countries
  94.         while (rs.next()) {
  95.             // create a list item for the country
  96.             ListItem item = new ListItem(
  97.                 String.format("%s: %d movies",
  98.                     rs.getString("country"), rs.getInt("c")),
  99.                 FilmFonts.BOLDITALIC);
  100.             // create a movie list for each country
  101.             List movielist = new List(List.ORDERED, List.ALPHABETICAL);
  102.             movielist.setLowercase(List.LOWERCASE);
  103.             for(Movie movie :
  104.                 PojoFactory.getMovies(connection, rs.getString("country_id"))) {
  105.                 ListItem movieitem = new ListItem(movie.getMovieTitle());
  106.                 List directorlist = new List(List.UNORDERED);
  107.                 for (Director director : movie.getDirectors()) {
  108.                     directorlist.add(
  109.                         String.format("%s, %s",
  110.                             director.getName(), director.getGivenName()));
  111.                 }
  112.                 movieitem.add(directorlist);
  113.                 movielist.add(movieitem);
  114.             }
  115.             item.add(movielist);
  116.             list.add(item);
  117.         }
  118.         document.add(list);
  119.         // close the statement and the database connection
  120.         stm.close();
  121.         connection.close();
  122.         // step 4
  123.         document.close();
  124.         Document.compress = true;
  125.     }
  126.  
  127.     /**
  128.      * Manipulates a PDF file src with the file dest as result
  129.      * @param src the original PDF
  130.      * @param dest the resulting PDF
  131.      * @param pow the PDF will be N-upped with N = Math.pow(2, pow);
  132.      * @throws IOException
  133.      * @throws DocumentException
  134.      */
  135.     public void compressPdf(String src, String dest) throws IOException, DocumentException {
  136.         PdfReader reader = new PdfReader(src);
  137.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest), PdfWriter.VERSION_1_5);
  138.         stamper.getWriter().setCompressionLevel(9);
  139.         int total = reader.getNumberOfPages() + 1;
  140.         for (int i = 1; i < total; i++) {
  141.             reader.setPageContent(i, reader.getPageContent(i));
  142.         }
  143.         stamper.setFullCompression();
  144.         stamper.close();
  145.         reader.close();
  146.     }
  147.  
  148.     /**
  149.      * Manipulates a PDF file src with the file dest as result
  150.      * @param src the original PDF
  151.      * @param dest the resulting PDF
  152.      * @param pow the PDF will be N-upped with N = Math.pow(2, pow);
  153.      * @throws IOException
  154.      * @throws DocumentException
  155.      */
  156.     public void decompressPdf(String src, String dest) throws IOException, DocumentException {
  157.         PdfReader reader = new PdfReader(src);
  158.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  159.         Document.compress = false;
  160.         int total = reader.getNumberOfPages() + 1;
  161.         for (int i = 1; i < total; i++) {
  162.             reader.setPageContent(i, reader.getPageContent(i));
  163.         }
  164.         stamper.close();
  165.         reader.close();
  166.         Document.compress = true;
  167.     }
  168.    
  169.     /**
  170.      * Generates a PDF file, then reads it to generate a copy that is fully
  171.      * compressed and one that isn't compressed.
  172.      *
  173.      * @param args
  174.      *            no arguments needed here
  175.      * @throws SQLException
  176.      * @throws DocumentException
  177.      * @throws IOException
  178.      */
  179.     public static void main(String[] args) throws IOException, DocumentException, SQLException {
  180.         HelloWorldCompression hello = new HelloWorldCompression();
  181.         hello.createPdf(RESULT1, -1);
  182.         hello.createPdf(RESULT2, 0);
  183.         hello.createPdf(RESULT3, 1);
  184.         hello.createPdf(RESULT4, 2);
  185.         hello.createPdf(RESULT5, 3);
  186.         hello.compressPdf(RESULT2, RESULT6);
  187.         hello.decompressPdf(RESULT6, RESULT7);
  188.     }
  189. }
EncryptionPdf.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 part3.chapter12;
  9.  
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. import com.itextpdf.text.Document;
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.Paragraph;
  16. import com.itextpdf.text.pdf.PdfWriter;
  17. import com.itextpdf.text.pdf.PdfReader;
  18. import com.itextpdf.text.pdf.PdfStamper;
  19.  
  20.  
  21. public class EncryptionPdf {
  22.     /** User password. */
  23.     public static byte[] USER = "Hello".getBytes();
  24.     /** Owner password. */
  25.     public static byte[] OWNER = "World".getBytes();
  26.    
  27.     /** The resulting PDF file. */
  28.     public static final String RESULT1
  29.         = "results/part3/chapter12/encryption.pdf";
  30.     /** The resulting PDF file. */
  31.     public static final String RESULT2
  32.         = "results/part3/chapter12/encryption_decrypted.pdf";
  33.     /** The resulting PDF file. */
  34.     public static final String RESULT3
  35.         = "results/part3/chapter12/encryption_encrypted.pdf";
  36.    
  37.     /**
  38.      * Creates a PDF document.
  39.      * @param filename the path to the new PDF document
  40.      * @throws DocumentException
  41.      * @throws IOException
  42.      */
  43.     public void createPdf(String filename) throws IOException, DocumentException {
  44.         // step 1
  45.         Document document = new Document();
  46.         // step 2
  47.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  48.         writer.setEncryption(USER, OWNER, PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);
  49.         writer.createXmpMetadata();
  50.         // step 3
  51.         document.open();
  52.         // step 4
  53.         document.add(new Paragraph("Hello World"));
  54.         // step 5
  55.         document.close();
  56.     }
  57.  
  58.     /**
  59.      * Manipulates a PDF file src with the file dest as result
  60.      * @param src the original PDF
  61.      * @param dest the resulting PDF
  62.      * @throws IOException
  63.      * @throws DocumentException
  64.      */
  65.     public void decryptPdf(String src, String dest) throws IOException, DocumentException {
  66.         PdfReader reader = new PdfReader(src, OWNER);
  67.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  68.         stamper.close();
  69.         reader.close();
  70.     }
  71.  
  72.     /**
  73.      * Manipulates a PDF file src with the file dest as result
  74.      * @param src the original PDF
  75.      * @param dest the resulting PDF
  76.      * @throws IOException
  77.      * @throws DocumentException
  78.      */
  79.     public void encryptPdf(String src, String dest) throws IOException, DocumentException {
  80.         PdfReader reader = new PdfReader(src);
  81.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  82.         stamper.setEncryption(USER, OWNER,
  83.             PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
  84.         stamper.close();
  85.         reader.close();
  86.     }
  87.    
  88.     /**
  89.      * Main method.
  90.      *
  91.      * @param    args    no arguments needed
  92.      * @throws DocumentException
  93.      * @throws IOException
  94.      */
  95.     public static void main(String[] args) throws IOException, DocumentException {
  96.         EncryptionPdf metadata = new EncryptionPdf();
  97.         metadata.createPdf(RESULT1);
  98.         metadata.decryptPdf(RESULT1, RESULT2);
  99.         metadata.encryptPdf(RESULT2, RESULT3);
  100.     }
  101. }
EncryptWithCertificate.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 part3.chapter12;
  8.  
  9. import java.io.FileInputStream;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.security.GeneralSecurityException;
  13. import java.security.KeyStore;
  14. import java.security.PrivateKey;
  15. import java.security.Security;
  16. import java.security.cert.Certificate;
  17. import java.security.cert.CertificateException;
  18. import java.security.cert.CertificateFactory;
  19. import java.security.cert.X509Certificate;
  20. import java.util.Properties;
  21.  
  22. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  23.  
  24. import com.itextpdf.text.Document;
  25. import com.itextpdf.text.DocumentException;
  26. import com.itextpdf.text.Paragraph;
  27. import com.itextpdf.text.pdf.PdfReader;
  28. import com.itextpdf.text.pdf.PdfStamper;
  29. import com.itextpdf.text.pdf.PdfWriter;
  30.  
  31. public class EncryptWithCertificate {
  32.  
  33.     /** The resulting PDF */
  34.     public static String RESULT1 = "results/part3/chapter12/certificate_encryption.pdf";
  35.     /** The resulting PDF */
  36.     public static String RESULT2 = "results/part3/chapter12/certificate_decrypted.pdf";
  37.     /** The resulting PDF */
  38.     public static String RESULT3 = "results/part3/chapter12/certificate_encrypted.pdf";
  39.  
  40.     /**
  41.      * A properties file that is PRIVATE.
  42.      * You should make your own properties file and adapt this line.
  43.      */
  44.     public static String PATH = "c:/home/blowagie/key.properties";
  45.     /** Some properties used when signing. */
  46.     public static Properties properties = new Properties();
  47.    
  48.     /**
  49.      * Creates a PDF that is encrypted using two different public certificates.
  50.      * @param filename the path to the resulting PDF file
  51.      * @throws IOException
  52.      * @throws DocumentException
  53.      * @throws GeneralSecurityException
  54.      */
  55.     public void createPdf(String filename)
  56.         throws IOException, DocumentException, GeneralSecurityException {
  57.         // step 1
  58.         Document document = new Document();
  59.         // step 2
  60.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT1));
  61.         Certificate cert1 = getPublicCertificate("resources/encryption/foobar.cer");
  62.         Certificate cert2 = getPublicCertificate(properties.getProperty("PUBLIC"));
  63.         writer.setEncryption(new Certificate[]{cert1, cert2},
  64.             new int[]{PdfWriter.ALLOW_PRINTING, PdfWriter.ALLOW_COPY}, PdfWriter.ENCRYPTION_AES_128);
  65.         // step 3
  66.         document.open();
  67.         // step 4
  68.         document.add(new Paragraph("Hello World!"));
  69.         // step 5
  70.         document.close();
  71.     }
  72.    
  73.     /**
  74.      * Gets a public certificate from a certificate file.
  75.      * @param path the path to the certificate
  76.      * @return a Certificate object
  77.      * @throws IOException
  78.      * @throws CertificateException
  79.      */
  80.     public Certificate getPublicCertificate(String path)
  81.         throws IOException, CertificateException {
  82.         FileInputStream is = new FileInputStream(path);
  83.         CertificateFactory cf = CertificateFactory.getInstance("X.509");
  84.         X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
  85.         return cert;
  86.     }
  87.    
  88.     /**
  89.      * Gets a private key from a KeyStore.
  90.      * @return a PrivateKey object
  91.      * @throws GeneralSecurityException
  92.      * @throws IOException
  93.      */
  94.     public PrivateKey getPrivateKey() throws GeneralSecurityException, IOException {
  95.         String path = "resources/encryption/.keystore";
  96.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  97.         ks.load(new FileInputStream(path), "f00b4r".toCharArray());
  98.         PrivateKey pk = (PrivateKey)ks.getKey("foobar", "f1lmf3st".toCharArray());
  99.         return pk;
  100.     }
  101.    
  102.     /**
  103.      * Decrypts a PDF that was encrypted using a certificate
  104.      * @param src  The encrypted PDF
  105.      * @param dest The decrypted PDF
  106.      * @throws IOException
  107.      * @throws DocumentException
  108.      * @throws GeneralSecurityException
  109.      */
  110.     public void decryptPdf(String src, String dest)
  111.         throws IOException, DocumentException, GeneralSecurityException {
  112.         PdfReader reader = new PdfReader(src,
  113.             getPublicCertificate("resources/encryption/foobar.cer"), getPrivateKey(), "BC");
  114.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  115.         stamper.close();
  116.         reader.close();
  117.     }
  118.    
  119.     /**
  120.      * Encrypts a PDF using a public certificate.
  121.      * @param src  The original PDF document
  122.      * @param dest The encrypted PDF document
  123.      * @throws IOException
  124.      * @throws DocumentException
  125.      * @throws CertificateException
  126.      */
  127.     public void encryptPdf(String src, String dest)
  128.         throws IOException, DocumentException, CertificateException {
  129.         PdfReader reader = new PdfReader(src);
  130.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  131.         Certificate cert = getPublicCertificate("resources/encryption/foobar.cer");
  132.         stamper.setEncryption(new Certificate[]{cert},
  133.             new int[]{PdfWriter.ALLOW_PRINTING}, PdfWriter.ENCRYPTION_AES_128);
  134.         stamper.close();
  135.         reader.close();
  136.     }
  137.  
  138.     /**
  139.      * Main method.
  140.      *
  141.      * @param    args    no arguments needed
  142.      * @throws DocumentException
  143.      * @throws IOException
  144.      * @throws GeneralSecurityException
  145.      */
  146.     public static void main(String[] args)
  147.         throws IOException, DocumentException, GeneralSecurityException {
  148.         Security.addProvider(new BouncyCastleProvider());
  149.         properties.load(new FileInputStream(PATH));
  150.         EncryptWithCertificate hello = new EncryptWithCertificate();
  151.         hello.createPdf(RESULT1);
  152.         hello.decryptPdf(RESULT1, RESULT2);
  153.         hello.encryptPdf(RESULT2, RESULT3);
  154.     }
  155. }
SignatureField.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 part3.chapter12;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileNotFoundException;
  12. import java.io.FileOutputStream;
  13. import java.io.IOException;
  14. import java.security.GeneralSecurityException;
  15. import java.security.KeyStore;
  16. import java.security.KeyStoreException;
  17. import java.security.PrivateKey;
  18. import java.security.Security;
  19. import java.security.cert.Certificate;
  20. import java.util.Properties;
  21.  
  22. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  23.  
  24. import com.itextpdf.text.BaseColor;
  25. import com.itextpdf.text.Document;
  26. import com.itextpdf.text.DocumentException;
  27. import com.itextpdf.text.Image;
  28. import com.itextpdf.text.Paragraph;
  29. import com.itextpdf.text.Rectangle;
  30. import com.itextpdf.text.pdf.PdfAnnotation;
  31. import com.itextpdf.text.pdf.PdfAppearance;
  32. import com.itextpdf.text.pdf.PdfFormField;
  33. import com.itextpdf.text.pdf.PdfReader;
  34. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  35. import com.itextpdf.text.pdf.PdfStamper;
  36. import com.itextpdf.text.pdf.PdfWriter;
  37. import com.itextpdf.text.pdf.security.ExternalSignature;
  38. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  39. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  40. import com.itextpdf.text.pdf.security.ExternalDigest;
  41. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  42. import com.itextpdf.text.pdf.security.MakeSignature;
  43.  
  44. public class SignatureField {
  45.  
  46.     /** The resulting PDF */
  47.     public static String ORIGINAL = "results/part3/chapter12/unsigned.pdf";
  48.     /** The resulting PDF */
  49.     public static String SIGNED1 = "results/part3/chapter12/signed_1.pdf";
  50.     /** The resulting PDF */
  51.     public static String SIGNED2 = "results/part3/chapter12/signed_2.pdf";
  52.  
  53.     /** One of the resources. */
  54.     public static final String RESOURCE
  55.         = "resources/img/1t3xt.gif";
  56.  
  57.     /**
  58.      * A properties file that is PRIVATE.
  59.      * You should make your own properties file and adapt this line.
  60.      */
  61.     public static String PATH = "c:/home/blowagie/key.properties";
  62.     /** Some properties used when signing. */
  63.     public static Properties properties = new Properties();
  64.    
  65.     /**
  66.      * Creates a PDF document.
  67.      * @param filename the path to the new PDF document
  68.      * @throws DocumentException
  69.      * @throws IOException
  70.      */
  71.     public void createPdf(String filename) throws IOException, DocumentException {
  72.         // step 1
  73.         Document document = new Document();
  74.         // step 2
  75.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  76.         // step 3
  77.         document.open();
  78.         // step 4
  79.         document.add(new Paragraph("Hello World!"));
  80.         PdfFormField field = PdfFormField.createSignature(writer);
  81.         field.setWidget(new Rectangle(72, 732, 144, 780), PdfAnnotation.HIGHLIGHT_INVERT);
  82.         field.setFieldName("mySig");
  83.         field.setFlags(PdfAnnotation.FLAGS_PRINT);
  84.         field.setPage();
  85.         field.setMKBorderColor(BaseColor.BLACK);
  86.         field.setMKBackgroundColor(BaseColor.WHITE);
  87.         PdfAppearance tp = PdfAppearance.createAppearance(writer, 72, 48);
  88.         tp.rectangle(0.5f, 0.5f, 71.5f, 47.5f);
  89.         tp.stroke();
  90.         field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, tp);
  91.         writer.addAnnotation(field);
  92.         // step 5
  93.         document.close();
  94.     }
  95.  
  96.     /**
  97.      * Manipulates a PDF file src with the file dest as result
  98.      * @param src the original PDF
  99.      * @param dest the resulting PDF
  100.      * @throws GeneralSecurityException
  101.      * @throws IOException
  102.      * @throws DocumentException
  103.      * @throws FileNotFoundException
  104.      * @throws KeyStoreException
  105.      * @throws Exception
  106.      */
  107.     public void signPdf(String src, String dest, boolean certified, boolean graphic) throws GeneralSecurityException, IOException, DocumentException {
  108.         // private key and certificate
  109.         String path = properties.getProperty("PRIVATE");
  110.         String keystore_password = properties.getProperty("PASSWORD");
  111.         String key_password = properties.getProperty("PASSWORD");
  112.         KeyStore ks = KeyStore.getInstance("pkcs12", "BC");
  113.         ks.load(new FileInputStream(path), keystore_password.toCharArray());
  114.         String alias = (String)ks.aliases().nextElement();
  115.         PrivateKey pk = (PrivateKey)ks.getKey(alias, key_password.toCharArray());
  116.         Certificate[] chain = ks.getCertificateChain(alias);
  117.         // reader and stamper
  118.         PdfReader reader = new PdfReader(ORIGINAL);
  119.         PdfStamper stamper = PdfStamper.createSignature(reader, new FileOutputStream(dest), '\0');
  120.         // appearance
  121.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  122.         appearance.setVisibleSignature("mySig");
  123.         appearance.setReason("It's personal.");
  124.         appearance.setLocation("Foobar");
  125.         if (certified)
  126.             appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
  127.         if (graphic) {
  128.             appearance.setSignatureGraphic(Image.getInstance(RESOURCE));
  129.             appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
  130.         }
  131.         // signature
  132.         ExternalSignature es = new PrivateKeySignature(pk, "SHA-256", "BC");
  133.         ExternalDigest digest = new BouncyCastleDigest();
  134.         MakeSignature.signDetached(appearance, digest, es, chain, null, null, null, 0, CryptoStandard.CMS);
  135.     }
  136.    
  137.     /**
  138.      * Main method.
  139.      *
  140.      * @param    args    no arguments needed
  141.      */
  142.     public static void main(String[] args)
  143.         throws Exception {
  144.         Security.addProvider(new BouncyCastleProvider());
  145.         properties.load(new FileInputStream(PATH));
  146.         SignatureField signatures = new SignatureField();
  147.         signatures.createPdf(ORIGINAL);
  148.         signatures.signPdf(ORIGINAL, SIGNED1, false, false);
  149.         signatures.signPdf(ORIGINAL, SIGNED2, true, true);
  150.     }
  151. }
Signatures.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 part3.chapter12;
  8.  
  9. import java.io.FileInputStream;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.io.PrintWriter;
  14. import java.security.GeneralSecurityException;
  15. import java.security.KeyStore;
  16. import java.security.PrivateKey;
  17. import java.security.Security;
  18. import java.security.cert.Certificate;
  19. import java.security.cert.CertificateFactory;
  20. import java.security.cert.X509Certificate;
  21. import java.util.ArrayList;
  22. import java.util.Calendar;
  23. import java.util.List;
  24. import java.util.Properties;
  25.  
  26. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  27.  
  28. import com.itextpdf.text.Document;
  29. import com.itextpdf.text.DocumentException;
  30. import com.itextpdf.text.Image;
  31. import com.itextpdf.text.Paragraph;
  32. import com.itextpdf.text.Rectangle;
  33. import com.itextpdf.text.pdf.AcroFields;
  34. import com.itextpdf.text.pdf.PdfReader;
  35. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  36. import com.itextpdf.text.pdf.PdfStamper;
  37. import com.itextpdf.text.pdf.PdfWriter;
  38. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  39. import com.itextpdf.text.pdf.security.CertificateInfo;
  40. import com.itextpdf.text.pdf.security.CertificateVerification;
  41. import com.itextpdf.text.pdf.security.ExternalDigest;
  42. import com.itextpdf.text.pdf.security.ExternalSignature;
  43. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  44. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  45. import com.itextpdf.text.pdf.security.MakeSignature;
  46. import com.itextpdf.text.pdf.security.PdfPKCS7;
  47. import com.itextpdf.text.pdf.security.VerificationException;
  48.  
  49. public class Signatures {
  50.  
  51.     /** The resulting PDF */
  52.     public static String ORIGINAL = "results/part3/chapter12/hello.pdf";
  53.     /** The resulting PDF */
  54.     public static String SIGNED1 = "results/part3/chapter12/signature_1.pdf";
  55.     /** The resulting PDF */
  56.     public static String SIGNED2 = "results/part3/chapter12/signature_2.pdf";
  57.     /** Info after verification of a signed PDF */
  58.     public static String VERIFICATION = "results/part3/chapter12/verify.txt";
  59.     /** The resulting PDF */
  60.     public static String REVISION = "results/part3/chapter12/revision_1.pdf";
  61.  
  62.     /**
  63.      * A properties file that is PRIVATE.
  64.      * You should make your own properties file and adapt this line.
  65.      */
  66.     public static String PATH = "c:/home/blowagie/key.properties";
  67.     /** Some properties used when signing. */
  68.     public static Properties properties = new Properties();
  69.     /** One of the resources. */
  70.     public static final String RESOURCE = "resources/img/logo.gif";
  71.    
  72.     /**
  73.      * Creates a PDF document.
  74.      * @param filename the path to the new PDF document
  75.      * @throws DocumentException
  76.      * @throws IOException
  77.      */
  78.     public void createPdf(String filename) throws IOException, DocumentException {
  79.         Document document = new Document();
  80.         PdfWriter.getInstance(document, new FileOutputStream(filename));
  81.         document.open();
  82.         document.add(new Paragraph("Hello World!"));
  83.         document.close();
  84.     }
  85.    
  86.     /**
  87.      * Manipulates a PDF file src with the file dest as result
  88.      * @param src the original PDF
  89.      * @param dest the resulting PDF
  90.      * @throws IOException
  91.      * @throws DocumentException
  92.      * @throws GeneralSecurityException
  93.      */
  94.     public void signPdfFirstTime(String src, String dest)
  95.         throws IOException, DocumentException, GeneralSecurityException {
  96.         String path = properties.getProperty("PRIVATE");
  97.         String keystore_password = properties.getProperty("PASSWORD");
  98.         String key_password = properties.getProperty("PASSWORD");
  99.         KeyStore ks = KeyStore.getInstance("pkcs12", "BC");
  100.         ks.load(new FileInputStream(path), keystore_password.toCharArray());
  101.         String alias = (String)ks.aliases().nextElement();
  102.         PrivateKey pk = (PrivateKey) ks.getKey(alias, key_password.toCharArray());
  103.         Certificate[] chain = ks.getCertificateChain(alias);
  104.         // reader and stamper
  105.         PdfReader reader = new PdfReader(src);
  106.         FileOutputStream os = new FileOutputStream(dest);
  107.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  108.         // appearance
  109.         PdfSignatureAppearance appearance = stamper .getSignatureAppearance();
  110.         appearance.setImage(Image.getInstance(RESOURCE));
  111.         appearance.setReason("I've written this.");
  112.         appearance.setLocation("Foobar");
  113.         appearance.setVisibleSignature(new Rectangle(72, 732, 144, 780), 1,    "first");
  114.         // digital signature
  115.         ExternalSignature es = new PrivateKeySignature(pk, "SHA-256", "BC");
  116.         ExternalDigest digest = new BouncyCastleDigest();
  117.         MakeSignature.signDetached(appearance, digest, es, chain, null, null, null, 0, CryptoStandard.CMS);
  118.     }
  119.    
  120.     /**
  121.      * Manipulates a PDF file src with the file dest as result
  122.      * @param src the original PDF
  123.      * @param dest the resulting PDF
  124.      * @throws IOException
  125.      * @throws DocumentException
  126.      * @throws GeneralSecurityException
  127.      */
  128.     public void signPdfSecondTime(String src, String dest)
  129.         throws IOException, DocumentException, GeneralSecurityException {
  130.         String path = "resources/encryption/.keystore";
  131.         String keystore_password = "f00b4r";
  132.         String key_password = "f1lmf3st";
  133.         String alias = "foobar";
  134.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  135.         ks.load(new FileInputStream(path), keystore_password.toCharArray());
  136.         PrivateKey pk = (PrivateKey) ks.getKey(alias, key_password.toCharArray());
  137.         Certificate[] chain = ks.getCertificateChain(alias);
  138.         // reader / stamper
  139.         PdfReader reader = new PdfReader(src);
  140.         FileOutputStream os = new FileOutputStream(dest);
  141.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
  142.         // appearance
  143.         PdfSignatureAppearance appearance = stamper
  144.                 .getSignatureAppearance();
  145.         appearance.setReason("I'm approving this.");
  146.         appearance.setLocation("Foobar");
  147.         appearance.setVisibleSignature(new Rectangle(160, 732, 232, 780), 1, "second");
  148.         // digital signature
  149.         ExternalSignature es = new PrivateKeySignature(pk, "SHA-256", "BC");
  150.         ExternalDigest digest = new BouncyCastleDigest();
  151.         MakeSignature.signDetached(appearance, digest, es, chain, null, null, null, 0, CryptoStandard.CMS);
  152.  
  153.     }
  154.    
  155.     /**
  156.      * Verifies the signatures of a PDF we've signed twice.
  157.      * @throws GeneralSecurityException
  158.      * @throws IOException
  159.      */
  160.     public void verifySignatures() throws GeneralSecurityException, IOException {
  161.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  162.         ks.load(null, null);
  163.         CertificateFactory cf = CertificateFactory.getInstance("X509");
  164.         FileInputStream is1 = new FileInputStream(properties.getProperty("ROOTCERT"));
  165.         X509Certificate cert1 = (X509Certificate) cf.generateCertificate(is1);
  166.         ks.setCertificateEntry("cacert", cert1);
  167.         FileInputStream is2 = new FileInputStream("resources/encryption/foobar.cer");
  168.         X509Certificate cert2 = (X509Certificate) cf.generateCertificate(is2);
  169.         ks.setCertificateEntry("foobar", cert2);
  170.        
  171.         PrintWriter out = new PrintWriter(new FileOutputStream(VERIFICATION));
  172.         PdfReader reader = new PdfReader(SIGNED2);
  173.         AcroFields af = reader.getAcroFields();
  174.         ArrayList names = af.getSignatureNames();
  175.         for (String name : names) {
  176.             out.println("Signature name: " + name);
  177.             out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
  178.             out.println("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());
  179.             PdfPKCS7 pk = af.verifySignature(name);
  180.             Calendar cal = pk.getSignDate();
  181.             Certificate[] pkc = pk.getCertificates();
  182.             out.println("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate()));
  183.             out.println("Revision modified: " + !pk.verify());
  184.             List errors = CertificateVerification.verifyCertificates(pkc, ks, null, cal);
  185.             if (errors.size() == 0)
  186.                 out.println("Certificates verified against the KeyStore");
  187.             else
  188.                 out.println(errors);    
  189.         }
  190.         out.flush();
  191.         out.close();
  192.     }
  193.    
  194.     /**
  195.      * Extracts the first revision of a PDF we've signed twice.
  196.      * @throws IOException
  197.      */
  198.     public void extractFirstRevision() throws IOException {
  199.         PdfReader reader = new PdfReader(SIGNED2);
  200.         AcroFields af = reader.getAcroFields();
  201.         FileOutputStream os = new FileOutputStream(REVISION);
  202.         byte bb[] = new byte[1028];
  203.         InputStream ip = af.extractRevision("first");
  204.         int n = 0;
  205.         while ((n = ip.read(bb)) > 0)
  206.             os.write(bb, 0, n);
  207.         os.close();
  208.         ip.close();
  209.     }
  210.    
  211.     /**
  212.      * Main method.
  213.      *
  214.      * @param    args    no arguments needed
  215.      * @throws DocumentException
  216.      * @throws IOException
  217.      * @throws GeneralSecurityException
  218.      */
  219.     public static void main(String[] args)
  220.         throws IOException, DocumentException, GeneralSecurityException {
  221.         Security.addProvider(new BouncyCastleProvider());
  222.         properties.load(new FileInputStream(PATH));
  223.         Signatures signatures = new Signatures();
  224.         signatures.createPdf(ORIGINAL);
  225.         signatures.signPdfFirstTime(ORIGINAL, SIGNED1);
  226.         signatures.signPdfSecondTime(SIGNED1, SIGNED2);
  227.         signatures.verifySignatures();
  228.         signatures.extractFirstRevision();
  229.     }
  230. }
SignatureExternalHash.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 part3.chapter12;
  8.  
  9. import java.io.FileInputStream;
  10. import java.io.FileNotFoundException;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.security.GeneralSecurityException;
  14. import java.security.KeyStore;
  15. import java.security.KeyStoreException;
  16. import java.security.PrivateKey;
  17. import java.security.Security;
  18. import java.security.cert.Certificate;
  19. import java.util.Properties;
  20.  
  21. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  22.  
  23. import com.itextpdf.text.DocumentException;
  24. import com.itextpdf.text.Rectangle;
  25. import com.itextpdf.text.pdf.PdfReader;
  26. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  27. import com.itextpdf.text.pdf.PdfStamper;
  28. import com.itextpdf.text.pdf.security.ExternalDigest;
  29. import com.itextpdf.text.pdf.security.ExternalSignature;
  30. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  31. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  32. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  33. import com.itextpdf.text.pdf.security.MakeSignature;
  34.  
  35. public class SignatureExternalHash {
  36.  
  37.     /**
  38.      * A properties file that is PRIVATE.
  39.      * You should make your own properties file and adapt this line.
  40.      */
  41.     public static String PATH = "c:/home/blowagie/key.properties";
  42.     /** Some properties used when signing. */
  43.     public static Properties properties = new Properties();
  44.  
  45.     /** The resulting PDF */
  46.     public static String SIGNED1 = "results/part3/chapter12/externalhash_1.pdf";
  47.     /** The resulting PDF */
  48.     public static String SIGNED2 = "results/part3/chapter12/externalhash_2.pdf";
  49.     /** The resulting PDF */
  50.     public static String SIGNED3 = "results/part3/chapter12/externalhash_3.pdf";
  51.  
  52.     /**
  53.      * Manipulates a PDF file src with the file dest as result
  54.      * @param src the original PDF
  55.      * @param dest the resulting PDF
  56.      * @throws GeneralSecurityException
  57.      * @throws IOException
  58.      * @throws DocumentException
  59.      * @throws FileNotFoundException
  60.      * @throws KeyStoreException
  61.      * @throws Exception
  62.      */
  63.     public void signPdfDetached(String src, String dest) throws GeneralSecurityException, IOException, DocumentException {
  64.         // Private key and certificate
  65.         String path = properties.getProperty("PRIVATE");
  66.         String keystore_password = properties.getProperty("PASSWORD");
  67.         String key_password = properties.getProperty("PASSWORD");
  68.         KeyStore ks = KeyStore.getInstance("pkcs12", "BC");
  69.         ks.load(new FileInputStream(path), keystore_password.toCharArray());
  70.         String alias = (String)ks.aliases().nextElement();
  71.         PrivateKey pk = (PrivateKey) ks.getKey(alias, key_password.toCharArray());
  72.         Certificate[] chain = ks.getCertificateChain(alias);
  73.        
  74.         // reader and stamper
  75.         PdfReader reader = new PdfReader(src);
  76.         FileOutputStream os = new FileOutputStream(dest);
  77.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  78.        
  79.         // appearance
  80.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  81.         appearance.setReason("External hash example");
  82.         appearance.setLocation("Foobar");
  83.         appearance.setVisibleSignature(new Rectangle(72, 732, 144, 780), 1, "sig");
  84.        
  85.         // digital signature
  86.         ExternalSignature es = new PrivateKeySignature(pk, "SHA-256", "BC");
  87.         ExternalDigest digest = new BouncyCastleDigest();
  88.         MakeSignature.signDetached(appearance, digest, es, chain, null, null, null, 0, CryptoStandard.CMS);
  89.     }
  90.    
  91.     /**
  92.      * Main method.
  93.      *
  94.      * @param    args    no arguments needed
  95.      * @throws DocumentException
  96.      * @throws IOException
  97.      * @throws GeneralSecurityException
  98.      */
  99.     public static void main(String[] args)
  100.         throws IOException, DocumentException, GeneralSecurityException {
  101.         Security.addProvider(new BouncyCastleProvider());
  102.         properties.load(new FileInputStream(PATH));
  103.         new Signatures().createPdf(Signatures.ORIGINAL);
  104.         SignatureExternalHash signatures = new SignatureExternalHash();
  105.         signatures.signPdfDetached(Signatures.ORIGINAL, SIGNED1);
  106.     }
  107. }
SignWithBC.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 part3.chapter12;
  8.  
  9. public class SignWithBC {
  10.  
  11.     /**
  12.      * Main method.
  13.      *
  14.      * @param    args    no arguments needed
  15.      */
  16.     public static void main(String[] args) {
  17.         System.out.println("This example is no longer relevant.");
  18.     }
  19. }
TimestampOCSP.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 part3.chapter12;
  8.  
  9. import java.io.FileInputStream;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.security.GeneralSecurityException;
  13. import java.security.KeyStore;
  14. import java.security.PrivateKey;
  15. import java.security.Security;
  16. import java.security.cert.Certificate;
  17. import java.util.Properties;
  18.  
  19. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  20.  
  21. import com.itextpdf.text.DocumentException;
  22. import com.itextpdf.text.Rectangle;
  23. import com.itextpdf.text.pdf.PdfReader;
  24. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  25. import com.itextpdf.text.pdf.PdfStamper;
  26. import com.itextpdf.text.pdf.security.ExternalSignature;
  27. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  28. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  29. import com.itextpdf.text.pdf.security.ExternalDigest;
  30. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  31. import com.itextpdf.text.pdf.security.MakeSignature;
  32. import com.itextpdf.text.pdf.security.OcspClient;
  33. import com.itextpdf.text.pdf.security.OcspClientBouncyCastle;
  34. import com.itextpdf.text.pdf.security.TSAClient;
  35. import com.itextpdf.text.pdf.security.TSAClientBouncyCastle;
  36.  
  37. public class TimestampOCSP {
  38.  
  39.     /** The resulting PDF */
  40.     public static String SIGNED0 = "results/part3/chapter12/without.pdf";
  41.     /** The resulting PDF */
  42.     public static String SIGNED1 = "results/part3/chapter12/ts.pdf";
  43.     /** The resulting PDF */
  44.     public static String SIGNED2 = "results/part3/chapter12/ocsp.pdf";
  45.     /** The resulting PDF */
  46.     public static String SIGNED3 = "results/part3/chapter12/ts_oscp.pdf";
  47.  
  48.     /**
  49.      * A properties file that is PRIVATE.
  50.      * You should make your own properties file and adapt this line.
  51.      */
  52.     public static String PATH = "c:/home/blowagie/key.properties";
  53.     /** Some properties used when signing. */
  54.     public static Properties properties = new Properties();
  55.    
  56.     /**
  57.      * Manipulates a PDF file src with the file dest as result
  58.      * @param src the original PDF
  59.      * @param dest the resulting PDF
  60.      * @throws IOException
  61.      * @throws DocumentException
  62.      * @throws GeneralSecurityException
  63.      */
  64.     public void signPdf(String src, String dest, boolean withTS, boolean withOCSP)
  65.         throws IOException, DocumentException, GeneralSecurityException {
  66.         // Keystore and certificate chain
  67.         String keystore = properties.getProperty("PRIVATE");
  68.         String password = properties.getProperty("PASSWORD");
  69.         KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
  70.         ks.load(new FileInputStream(keystore), password.toCharArray());
  71.         String alias = (String)ks.aliases().nextElement();
  72.         PrivateKey pk = (PrivateKey)ks.getKey(alias, password.toCharArray());
  73.         Certificate[] chain = ks.getCertificateChain(alias);
  74.         // reader and stamper
  75.         PdfReader reader = new PdfReader(src);
  76.         FileOutputStream fout = new FileOutputStream(dest);
  77.         PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
  78.         // appearance
  79.         PdfSignatureAppearance sap = stp.getSignatureAppearance();
  80.         sap.setReason("I'm approving this.");
  81.         sap.setLocation("Foobar");
  82.         sap.setVisibleSignature(new Rectangle(72, 732, 144, 780), 1, "Signature");
  83.         // preserve some space for the contents
  84.         // digital signature
  85.         ExternalSignature es = new PrivateKeySignature(pk, "SHA-256", "BC");
  86.         // If we add a time stamp:
  87.         TSAClient tsc = null;
  88.         if (withTS) {
  89.             String tsa_url    = properties.getProperty("TSA");
  90.             String tsa_login  = properties.getProperty("TSA_LOGIN");
  91.             String tsa_passw  = properties.getProperty("TSA_PASSWORD");
  92.             tsc = new TSAClientBouncyCastle(tsa_url, tsa_login, tsa_passw);
  93.         }
  94.         // If we use OCSP:
  95.         OcspClient ocsp = null;
  96.         if (withOCSP) {
  97.             ocsp = new OcspClientBouncyCastle();
  98.         }
  99.         ExternalDigest digest = new BouncyCastleDigest();
  100.         MakeSignature.signDetached(sap, digest, es, chain, null, ocsp, tsc, 0, CryptoStandard.CMS);
  101.     }
  102.    
  103.     /**
  104.      * Main method.
  105.      *
  106.      * @param    args    no arguments needed
  107.      * @throws DocumentException
  108.      * @throws IOException
  109.      * @throws GeneralSecurityException
  110.      */
  111.     public static void main(String[] args)
  112.         throws IOException, DocumentException, GeneralSecurityException {
  113.         Security.addProvider(new BouncyCastleProvider());
  114.         properties.load(new FileInputStream(PATH));
  115.         new Signatures().createPdf(Signatures.ORIGINAL);
  116.         TimestampOCSP signatures = new TimestampOCSP();
  117.         signatures.signPdf(Signatures.ORIGINAL, SIGNED0, false, false);
  118.         signatures.signPdf(Signatures.ORIGINAL, SIGNED1, true, false);
  119.         signatures.signPdf(Signatures.ORIGINAL, SIGNED2, false, true);
  120.         signatures.signPdf(Signatures.ORIGINAL, SIGNED3, true, true);
  121.     }
  122. }
MetadataPdf.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using Ionic.Zip;
  11. using iTextSharp.text;
  12. using iTextSharp.text.pdf;
  13.  
  14. namespace kuujinbo.iTextInAction2Ed.Chapter12 {
  15.   public class MetadataPdf : IWriter {
  16. // ===========================================================================
  17.     /** The resulting PDF file. */
  18.     public const string RESULT1 = "pdf_metadata.pdf";
  19.     /** The resulting PDF file. */
  20.     public const string RESULT2 = "pdf_metadata_changed.pdf";
  21. // ---------------------------------------------------------------------------
  22.     public void Write(Stream stream) {
  23.       using (ZipFile zip = new ZipFile()) {
  24.         MetadataPdf metadata = new MetadataPdf();
  25.         byte[] pdf = metadata.CreatePdf();
  26.         zip.AddEntry(RESULT1, pdf);
  27.         zip.AddEntry(RESULT2, metadata.ManipulatePdf(pdf));
  28.         zip.Save(stream);
  29.       }
  30.     }
  31. // ---------------------------------------------------------------------------
  32. /**
  33.  * Creates a PDF document.
  34.  */
  35.     public byte[] CreatePdf() {
  36.       using (MemoryStream ms = new MemoryStream()) {
  37.         // step 1
  38.         using (Document document = new Document()) {
  39.           // step 2
  40.           PdfWriter.GetInstance(document, ms);
  41.           // step 3
  42.           document.AddTitle("Hello World example");
  43.           document.AddAuthor("Bruno Lowagie");
  44.           document.AddSubject("This example shows how to add metadata");
  45.           document.AddKeywords("Metadata, iText, PDF");
  46.           document.AddCreator("My program using iText");
  47.           document.Open();
  48.           // step 4
  49.           document.Add(new Paragraph("Hello World"));
  50.         }
  51.         return ms.ToArray();    
  52.       }
  53.     }    
  54. // ---------------------------------------------------------------------------
  55. /**
  56.  * Manipulates a PDF file src with the file dest as result
  57.  * @param src the original PDF
  58.  */
  59.     public byte[] ManipulatePdf(byte[] src) {
  60.       PdfReader reader = new PdfReader(src);
  61.       using (MemoryStream ms = new MemoryStream()) {
  62.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  63.           Dictionary info = reader.Info;
  64.           info["Title"] = "Hello World stamped";
  65.           info["Subject"] = "Hello World with changed metadata";
  66.           info["Keywords"] = "iText in Action, PdfStamper";
  67.           info["Creator"] = "Silly standalone example";
  68.           info["Author"] = "Also Bruno Lowagie";
  69.           stamper.MoreInfo = info;
  70.         }
  71.         return ms.ToArray();
  72.       }
  73.     }  
  74. // ===========================================================================
  75.   }
  76. }
MetadataXmp.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.xml.xmp;
  15.  
  16. namespace kuujinbo.iTextInAction2Ed.Chapter12 {
  17.   public class MetadataXmp : IWriter {
  18. // ===========================================================================
  19.     /** The resulting PDF file. */
  20.     public const string RESULT1 = "xmp_metadata.pdf";
  21.     /** The resulting PDF file. */
  22.     public const string RESULT2 = "xmp_metadata_automatic.pdf";
  23.     /** The resulting PDF file. */
  24.     public const string RESULT3 = "xmp_metadata_added.pdf";
  25.     /** The resulting PDF file. */
  26.     public const string RESULT4 = "xmp.xml";
  27. // ---------------------------------------------------------------------------        
  28.     public void Write(Stream stream) {
  29.       using (ZipFile zip = new ZipFile()) {
  30.         MetadataXmp metadata = new MetadataXmp();
  31.         byte[] pdf = metadata.CreatePdf();
  32.         zip.AddEntry(RESULT1, pdf);
  33.         zip.AddEntry(RESULT2, metadata.CreatePdfAutomatic());
  34.         byte[] manipulated = metadata.ManipulatePdf(
  35.           new MetadataPdf().CreatePdf()
  36.         );
  37.         zip.AddEntry(RESULT3, manipulated );
  38.         zip.AddEntry(RESULT4, metadata.ReadXmpMetadata(manipulated));
  39.         zip.Save(stream);
  40.       }
  41.     }
  42. // ---------------------------------------------------------------------------
  43. /**
  44.  * Creates a PDF document.
  45.  */
  46.     public byte[] CreatePdf() {
  47.       using (MemoryStream ms = new MemoryStream()) {
  48.         // step 1
  49.         using (Document document = new Document()) {
  50.         // step 2
  51.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  52.           using (MemoryStream msXmp = new MemoryStream()) {
  53.             XmpWriter xmp = new XmpWriter(msXmp);
  54.             XmpSchema dc = new DublinCoreSchema();
  55.             XmpArray subject = new XmpArray(XmpArray.UNORDERED);
  56.             subject.Add("Hello World");
  57.             subject.Add("XMP & Metadata");
  58.             subject.Add("Metadata");
  59.             dc.SetProperty(DublinCoreSchema.SUBJECT, subject);
  60.             xmp.AddRdfDescription(dc);
  61.             PdfSchema pdf = new PdfSchema();
  62. /*
  63.  *  iTextSharp uses Item property instead of Java setProperty() method
  64.  *
  65.  *      pdf.SetProperty(PdfSchema.KEYWORDS, "Hello World, XMP, Metadata");
  66.  *      pdf.SetProperty(PdfSchema.VERSION, "1.4");
  67.  */
  68.             pdf[PdfSchema.KEYWORDS] = "Hello World, XMP, Metadata";
  69.             pdf[PdfSchema.VERSION] = "1.4";
  70.             xmp.AddRdfDescription(pdf);
  71.             xmp.Close();
  72.             writer.XmpMetadata = ms.ToArray();
  73.           }
  74.           // step 3
  75.           document.Open();
  76.           // step 4
  77.           document.Add(new Paragraph("Hello World"));
  78.         }
  79.         return ms.ToArray();
  80.       }
  81.     }
  82. // ---------------------------------------------------------------------------  
  83.     /**
  84.      * Creates a PDF document.
  85.      */
  86.     public byte[] CreatePdfAutomatic() {
  87.       using (MemoryStream ms = new MemoryStream()) {
  88.         // step 1
  89.         using (Document document = new Document()) {
  90.           // step 2
  91.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  92.           document.AddTitle("Hello World example");
  93.           document.AddSubject("This example shows how to add metadata & XMP");
  94.           document.AddKeywords("Metadata, iText, step 3");
  95.           document.AddCreator("My program using 'iText'");
  96.           document.AddAuthor("Bruno Lowagie & Paulo Soares");
  97.           writer.CreateXmpMetadata();
  98.           // step 3
  99.           document.Open();
  100.           // step 4
  101.           document.Add(new Paragraph("Hello World"));
  102.         }
  103.         return ms.ToArray();
  104.       }
  105.     }  
  106. // ---------------------------------------------------------------------------
  107.     /**
  108.      * Manipulates a PDF file src with the file dest as result
  109.      * @param src the original PDF
  110.      */
  111.     public byte[] ManipulatePdf(byte[] src) {
  112.       PdfReader reader = new PdfReader(src);
  113.       using (MemoryStream ms = new MemoryStream()) {
  114.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  115.           Dictionary info = reader.Info;
  116.           using (MemoryStream msXmp = new MemoryStream()) {
  117.             XmpWriter xmp = new XmpWriter(msXmp, info);
  118.             xmp.Close();
  119.             stamper.XmpMetadata = msXmp.ToArray();      
  120.           }
  121.         }
  122.         return ms.ToArray();
  123.       }
  124.     }      
  125. // ---------------------------------------------------------------------------
  126.     /**
  127.      * Reads the XML stream inside a PDF file into an XML file.
  128.      * @param src  A PDF file containing XMP data
  129.      */
  130.     public string ReadXmpMetadata(byte[] src) {
  131.       PdfReader reader = new PdfReader(src);
  132.       byte[] b = reader.Metadata;
  133.       return Encoding.UTF8.GetString(b, 0, b.Length);
  134.     }  
  135. // ===========================================================================
  136.   }
  137. }
HelloWorldCompression.cs
  1. /*
  2.  * This class is part of the book "iText in Action - 2nd Edition"
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)
  4.  * For more info, go to: http://itextpdf.com/examples/
  5.  * This example only works with the AGPL version of iText.
  6.  */
  7. using System;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. using System.Data;
  11. using System.Data.Common;
  12. using Ionic.Zip;
  13. using iTextSharp.text;
  14. using iTextSharp.text.pdf;
  15. using kuujinbo.iTextInAction2Ed.Intro_1_2;
  16.  
  17. namespace kuujinbo.iTextInAction2Ed.Chapter12 {
  18.   public class HelloWorldCompression : IWriter {
  19. // ===========================================================================
  20.     /** The resulting PDF file. */
  21.     public const string RESULT1 = "compression_not_at_all.pdf";
  22.     /** The resulting PDF file. */
  23.     public const string RESULT2 = "compression_zero.pdf";
  24.     /** The resulting PDF file. */
  25.     public const string RESULT3 = "compression_normal.pdf";
  26.     /** The resulting PDF file. */
  27.     public const string RESULT4 = "compression_high.pdf";
  28.     /** The resulting PDF file. */
  29.     public const string RESULT5 = "compression_full.pdf";
  30.     /** The resulting PDF file. */
  31.     public const string RESULT6 = "compression_full_too.pdf";
  32.     public const string RESULT7 = "compression_removed.pdf";
  33. // ---------------------------------------------------------------------------
  34.     public void Write(Stream stream) {
  35.       using (ZipFile zip = new ZipFile()) {
  36.         HelloWorldCompression hello = new HelloWorldCompression();
  37.         zip.AddEntry(RESULT1, hello.CreatePdf(-1));
  38.         byte[] compress0 = hello.CreatePdf(0);
  39.         zip.AddEntry(RESULT2, compress0);
  40.         zip.AddEntry(RESULT3, hello.CreatePdf(1));
  41.         zip.AddEntry(RESULT4, hello.CreatePdf(2));
  42.         zip.AddEntry(RESULT5, hello.CreatePdf(3));
  43.         byte[] compress6 = hello.CompressPdf(compress0);
  44.         zip.AddEntry(RESULT6, compress6);
  45.         zip.AddEntry(RESULT7, hello.DecompressPdf(compress6));
  46.         zip.Save(stream);
  47.       }    
  48.     }
  49. // ---------------------------------------------------------------------------
  50.     /**
  51.      * Creates a PDF with information about the movies
  52.      * @param    filename the name of the PDF file that will be created.
  53.      */
  54.     public byte[] CreatePdf(int compression) {
  55.       using (MemoryStream ms = new MemoryStream()) {
  56.       // step 1
  57.         using (Document document = new Document()) {
  58.         // step 2
  59.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  60.           switch(compression) {
  61.             case -1:
  62.               Document.Compress = false;
  63.               break;
  64.             case 0:
  65.               writer.CompressionLevel = 0;
  66.               break;
  67.             case 2:
  68.               writer.CompressionLevel = 9;
  69.               break;
  70.             case 3:
  71.               writer.SetFullCompression();
  72.               break;
  73.           }
  74.           // step 3
  75.           document.Open();
  76.         // step 4
  77.         // Create database connection and statement
  78.           var SQL =
  79. @"SELECT DISTINCT mc.country_id, c.country, count(*) AS c
  80. FROM film_country c, film_movie_country mc
  81.  WHERE c.id = mc.country_id
  82. GROUP BY mc.country_id, country ORDER BY c DESC";
  83.         // Create a new list
  84.           List list = new List(List.ORDERED);
  85.           DbProviderFactory dbp = AdoDB.Provider;
  86.           using (var c = dbp.CreateConnection()) {
  87.             c.ConnectionString = AdoDB.CS;
  88.             using (DbCommand cmd = c.CreateCommand()) {
  89.               cmd.CommandText = SQL;
  90.               c.Open();            
  91.               using (var r = cmd.ExecuteReader()) {
  92.                 while (r.Read()) {
  93.                 // create a list item for the country
  94.                   ListItem item = new ListItem(
  95.                     String.Format("{0}: {1} movies", r["country"], r["c"]),
  96.                     FilmFonts.BOLDITALIC
  97.                   );
  98.                   // create a movie list for each country
  99.                   List movielist = new List(List.ORDERED, List.ALPHABETICAL);
  100.                   movielist.Lowercase = List.LOWERCASE;
  101.                   foreach (Movie movie in
  102.                       PojoFactory.GetMovies(r["country_id"].ToString()))
  103.                   {
  104.                     ListItem movieitem = new ListItem(movie.MovieTitle);
  105.                     List directorlist = new List(List.UNORDERED);
  106.                     foreach (Director director in movie.Directors) {
  107.                       directorlist.Add(String.Format(
  108.                         "{0}, {1}", director.Name, director.GivenName
  109.                       ));
  110.                     }
  111.                     movieitem.Add(directorlist);
  112.                     movielist.Add(movieitem);
  113.                   }
  114.                   item.Add(movielist);
  115.                   list.Add(item);
  116.                 }
  117.               }
  118.             }
  119.           }
  120.           document.Add(list);
  121.         }
  122.         Document.Compress = true;
  123.         return ms.ToArray();
  124.       }    
  125.     }
  126. // ---------------------------------------------------------------------------
  127.     /**
  128.      * Manipulates a PDF file src with the file dest as result
  129.      * @param src the original PDF
  130.      */
  131.     public byte[] CompressPdf(byte[] src) {
  132.       PdfReader reader = new PdfReader(src);
  133.       using (MemoryStream ms = new MemoryStream()) {
  134.         using (PdfStamper stamper =
  135.             new PdfStamper(reader, ms, PdfWriter.VERSION_1_5))
  136.         {
  137.           stamper.Writer.CompressionLevel = 9;
  138.           int total = reader.NumberOfPages + 1;
  139.           for (int i = 1; i < total; i++) {
  140.             reader.SetPageContent(i, reader.GetPageContent(i));
  141.           }
  142.           stamper.SetFullCompression();
  143.         }
  144.         return ms.ToArray();
  145.       }
  146.     }
  147. // ---------------------------------------------------------------------------
  148.     /**
  149.      * Manipulates a PDF file src with the file dest as result
  150.      * @param src the original PDF
  151.      */
  152.     public byte[] DecompressPdf(byte[] src) {
  153.       PdfReader reader = new PdfReader(src);
  154.       using (MemoryStream ms = new MemoryStream()) {
  155.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  156.           Document.Compress = false;
  157.           int total = reader.NumberOfPages + 1;
  158.           for (int i = 1; i < total; i++) {
  159.             reader.SetPageContent(i, reader.GetPageContent(i));
  160.           }
  161.         }
  162.         Document.Compress = true;
  163.         return ms.ToArray();
  164.       }
  165.     }
  166. // ===========================================================================
  167.   }
  168. }
EncryptionPdf.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.  
  15. namespace kuujinbo.iTextInAction2Ed.Chapter12 {
  16.   public class EncryptionPdf : IWriter {
  17. // ===========================================================================
  18.     /** User password. */
  19.     public readonly byte[] USER = ASCIIEncoding.UTF8.GetBytes("Hello");
  20.     /** Owner password. */
  21.     public readonly byte[] OWNER = ASCIIEncoding.UTF8.GetBytes("World");
  22.  
  23.     /** The resulting PDF file. */
  24.     public const string RESULT1 = "encryption.pdf";
  25.     /** The resulting PDF file. */
  26.     public const string RESULT2 = "encryption_decrypted.pdf";
  27.     /** The resulting PDF file. */
  28.     public const string RESULT3 = "encryption_encrypted.pdf";
  29. // ---------------------------------------------------------------------------
  30.     public void Write(Stream stream) {
  31.       using (ZipFile zip = new ZipFile()) {
  32.         EncryptionPdf metadata = new EncryptionPdf();
  33.         byte[] enc1 = metadata.CreatePdf();        
  34.         zip.AddEntry(RESULT1,enc1);
  35.         byte[] enc2 = metadata.DecryptPdf(enc1);
  36.         zip.AddEntry(RESULT2, enc2);
  37.         zip.AddEntry(RESULT3, metadata.EncryptPdf(enc2));
  38.         zip.Save(stream);
  39.       }    
  40.     }
  41. // ---------------------------------------------------------------------------
  42.     /**
  43.      * Creates a PDF document.
  44.      */
  45.     public byte[] CreatePdf() {
  46.       using (MemoryStream ms = new MemoryStream()) {
  47.       // step 1
  48.         using (Document document = new Document()) {
  49.           PdfWriter writer = PdfWriter.GetInstance(document, ms);
  50.           writer.SetEncryption(
  51.             USER, OWNER,
  52.             PdfWriter.ALLOW_PRINTING,
  53.             PdfWriter.STANDARD_ENCRYPTION_128
  54.           );
  55.           writer.CreateXmpMetadata();
  56.           // step 3
  57.           document.Open();
  58.           // step 4
  59.           document.Add(new Paragraph("Hello World"));
  60.         }
  61.         return ms.ToArray();
  62.       }    
  63.     }
  64. // ---------------------------------------------------------------------------
  65.     /**
  66.      * Manipulates a PDF file src with the file dest as result
  67.      * @param src the original PDF
  68.      */
  69.     public byte[] DecryptPdf(byte[] src) {
  70.       PdfReader reader = new PdfReader(src, OWNER);
  71.       using (MemoryStream ms = new MemoryStream()) {
  72.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  73.         }
  74.         return ms.ToArray();
  75.       }
  76.     }
  77. // ---------------------------------------------------------------------------
  78.     /**
  79.      * Manipulates a PDF file src with the file dest as result
  80.      * @param src the original PDF
  81.      */
  82.     public byte[] EncryptPdf(byte[] src) {
  83.       PdfReader reader = new PdfReader(src);
  84.       using (MemoryStream ms = new MemoryStream()) {
  85.         using (PdfStamper stamper = new PdfStamper(reader, ms)) {
  86.           stamper.SetEncryption(
  87.             USER, OWNER,
  88.             PdfWriter.ALLOW_PRINTING,
  89.             PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA
  90.           );
  91.         }
  92.         return ms.ToArray();
  93.       }
  94.     }    
  95. // ===========================================================================
  96.   }
  97. }
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