/iTextSharp/text/pdf/PdfStamper.cs

https://github.com/itextsharper/iTextSharp-4.1.6 · C# · 762 lines · 248 code · 46 blank · 468 comment · 15 complexity · 46fe0fef5f8d82aa7342e97184181b65 MD5 · raw file

  1. using System;
  2. using System.IO;
  3. using System.Collections;
  4. using iTextSharp.text.pdf.interfaces;
  5. using iTextSharp.text.pdf.collection;
  6. using Org.BouncyCastle.X509;
  7. /*
  8. * Copyright 2003, 2004 by Paulo Soares.
  9. *
  10. * The contents of this file are subject to the Mozilla Public License Version 1.1
  11. * (the "License"); you may not use this file except in compliance with the License.
  12. * You may obtain a copy of the License at http://www.mozilla.org/MPL/
  13. *
  14. * Software distributed under the License is distributed on an "AS IS" basis,
  15. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  16. * for the specific language governing rights and limitations under the License.
  17. *
  18. * The Original Code is 'iText, a free JAVA-PDF library'.
  19. *
  20. * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
  21. * the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
  22. * All Rights Reserved.
  23. * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
  24. * are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
  25. *
  26. * Contributor(s): all the names of the contributors are added in the source code
  27. * where applicable.
  28. *
  29. * Alternatively, the contents of this file may be used under the terms of the
  30. * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
  31. * provisions of LGPL are applicable instead of those above. If you wish to
  32. * allow use of your version of this file only under the terms of the LGPL
  33. * License and not to allow others to use your version of this file under
  34. * the MPL, indicate your decision by deleting the provisions above and
  35. * replace them with the notice and other provisions required by the LGPL.
  36. * If you do not delete the provisions above, a recipient may use your version
  37. * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
  38. *
  39. * This library is free software; you can redistribute it and/or modify it
  40. * under the terms of the MPL as stated above or under the terms of the GNU
  41. * Library General Public License as published by the Free Software Foundation;
  42. * either version 2 of the License, or any later version.
  43. *
  44. * This library is distributed in the hope that it will be useful, but WITHOUT
  45. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  46. * FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
  47. * details.
  48. *
  49. * If you didn't download this code from the following link, you should check if
  50. * you aren't using an obsolete version:
  51. * http://www.lowagie.com/iText/
  52. */
  53. namespace iTextSharp.text.pdf {
  54. /** Applies extra content to the pages of a PDF document.
  55. * This extra content can be all the objects allowed in PdfContentByte
  56. * including pages from other Pdfs. The original PDF will keep
  57. * all the interactive elements including bookmarks, links and form fields.
  58. * <p>
  59. * It is also possible to change the field values and to
  60. * flatten them. New fields can be added but not flattened.
  61. * @author Paulo Soares (psoares@consiste.pt)
  62. */
  63. public class PdfStamper : IPdfViewerPreferences, IPdfEncryptionSettings {
  64. /**
  65. * The writer
  66. */
  67. protected PdfStamperImp stamper;
  68. private Hashtable moreInfo;
  69. private bool hasSignature;
  70. private PdfSignatureAppearance sigApp;
  71. /** Starts the process of adding extra content to an existing PDF
  72. * document.
  73. * @param reader the original document. It cannot be reused
  74. * @param os the output stream
  75. * @throws DocumentException on error
  76. * @throws IOException on error
  77. */
  78. public PdfStamper(PdfReader reader, Stream os) {
  79. stamper = new PdfStamperImp(reader, os, '\0', false);
  80. }
  81. /**
  82. * Starts the process of adding extra content to an existing PDF
  83. * document.
  84. * @param reader the original document. It cannot be reused
  85. * @param os the output stream
  86. * @param pdfVersion the new pdf version or '\0' to keep the same version as the original
  87. * document
  88. * @throws DocumentException on error
  89. * @throws IOException on error
  90. */
  91. public PdfStamper(PdfReader reader, Stream os, char pdfVersion) {
  92. stamper = new PdfStamperImp(reader, os, pdfVersion, false);
  93. }
  94. /**
  95. * Starts the process of adding extra content to an existing PDF
  96. * document, possibly as a new revision.
  97. * @param reader the original document. It cannot be reused
  98. * @param os the output stream
  99. * @param pdfVersion the new pdf version or '\0' to keep the same version as the original
  100. * document
  101. * @param append if <CODE>true</CODE> appends the document changes as a new revision. This is
  102. * only useful for multiple signatures as nothing is gained in speed or memory
  103. * @throws DocumentException on error
  104. * @throws IOException on error
  105. */
  106. public PdfStamper(PdfReader reader, Stream os, char pdfVersion, bool append) {
  107. stamper = new PdfStamperImp(reader, os, pdfVersion, append);
  108. }
  109. /** Gets the optional <CODE>String</CODE> map to add or change values in
  110. * the info dictionary.
  111. * @return the map or <CODE>null</CODE>
  112. *
  113. */
  114. /** An optional <CODE>String</CODE> map to add or change values in
  115. * the info dictionary. Entries with <CODE>null</CODE>
  116. * values delete the key in the original info dictionary
  117. * @param moreInfo additional entries to the info dictionary
  118. *
  119. */
  120. public Hashtable MoreInfo {
  121. set {
  122. moreInfo = value;
  123. }
  124. get {
  125. return moreInfo;
  126. }
  127. }
  128. /**
  129. * Replaces a page from this document with a page from other document. Only the content
  130. * is replaced not the fields and annotations. This method must be called before
  131. * getOverContent() or getUndercontent() are called for the same page.
  132. * @param r the <CODE>PdfReader</CODE> from where the new page will be imported
  133. * @param pageImported the page number of the imported page
  134. * @param pageReplaced the page to replace in this document
  135. */
  136. public void ReplacePage(PdfReader r, int pageImported, int pageReplaced) {
  137. stamper.ReplacePage(r, pageImported, pageReplaced);
  138. }
  139. /**
  140. * Inserts a blank page. All the pages above and including <CODE>pageNumber</CODE> will
  141. * be shifted up. If <CODE>pageNumber</CODE> is bigger than the total number of pages
  142. * the new page will be the last one.
  143. * @param pageNumber the page number position where the new page will be inserted
  144. * @param mediabox the size of the new page
  145. */
  146. public void InsertPage(int pageNumber, Rectangle mediabox) {
  147. stamper.InsertPage(pageNumber, mediabox);
  148. }
  149. /**
  150. * Gets the signing instance. The appearances and other parameters can the be set.
  151. * @return the signing instance
  152. */
  153. public PdfSignatureAppearance SignatureAppearance {
  154. get {
  155. return sigApp;
  156. }
  157. }
  158. /**
  159. * Closes the document. No more content can be written after the
  160. * document is closed.
  161. * <p>
  162. * If closing a signed document with an external signature the closing must be done
  163. * in the <CODE>PdfSignatureAppearance</CODE> instance.
  164. * @throws DocumentException on error
  165. * @throws IOException on error
  166. */
  167. public void Close() {
  168. if (!hasSignature) {
  169. stamper.Close(moreInfo);
  170. return;
  171. }
  172. sigApp.PreClose();
  173. PdfSigGenericPKCS sig = sigApp.SigStandard;
  174. PdfLiteral lit = (PdfLiteral)sig.Get(PdfName.CONTENTS);
  175. int totalBuf = (lit.PosLength - 2) / 2;
  176. byte[] buf = new byte[8192];
  177. int n;
  178. Stream inp = sigApp.RangeStream;
  179. while ((n = inp.Read(buf, 0, buf.Length)) > 0) {
  180. sig.Signer.Update(buf, 0, n);
  181. }
  182. buf = new byte[totalBuf];
  183. byte[] bsig = sig.SignerContents;
  184. Array.Copy(bsig, 0, buf, 0, bsig.Length);
  185. PdfString str = new PdfString(buf);
  186. str.SetHexWriting(true);
  187. PdfDictionary dic = new PdfDictionary();
  188. dic.Put(PdfName.CONTENTS, str);
  189. sigApp.Close(dic);
  190. stamper.reader.Close();
  191. }
  192. /** Gets a <CODE>PdfContentByte</CODE> to write under the page of
  193. * the original document.
  194. * @param pageNum the page number where the extra content is written
  195. * @return a <CODE>PdfContentByte</CODE> to write under the page of
  196. * the original document
  197. */
  198. public PdfContentByte GetUnderContent(int pageNum) {
  199. return stamper.GetUnderContent(pageNum);
  200. }
  201. /** Gets a <CODE>PdfContentByte</CODE> to write over the page of
  202. * the original document.
  203. * @param pageNum the page number where the extra content is written
  204. * @return a <CODE>PdfContentByte</CODE> to write over the page of
  205. * the original document
  206. */
  207. public PdfContentByte GetOverContent(int pageNum) {
  208. return stamper.GetOverContent(pageNum);
  209. }
  210. /** Checks if the content is automatically adjusted to compensate
  211. * the original page rotation.
  212. * @return the auto-rotation status
  213. */
  214. /** Flags the content to be automatically adjusted to compensate
  215. * the original page rotation. The default is <CODE>true</CODE>.
  216. * @param rotateContents <CODE>true</CODE> to set auto-rotation, <CODE>false</CODE>
  217. * otherwise
  218. */
  219. public bool RotateContents {
  220. set {
  221. stamper.RotateContents = value;
  222. }
  223. get {
  224. return stamper.RotateContents;
  225. }
  226. }
  227. /** Sets the encryption options for this document. The userPassword and the
  228. * ownerPassword can be null or have zero length. In this case the ownerPassword
  229. * is replaced by a random string. The open permissions for the document can be
  230. * AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations,
  231. * AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting.
  232. * The permissions can be combined by ORing them.
  233. * @param userPassword the user password. Can be null or empty
  234. * @param ownerPassword the owner password. Can be null or empty
  235. * @param permissions the user permissions
  236. * @param strength128Bits <code>true</code> for 128 bit key length, <code>false</code> for 40 bit key length
  237. * @throws DocumentException if anything was already written to the output
  238. */
  239. public void SetEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, bool strength128Bits) {
  240. if (stamper.append)
  241. throw new DocumentException("Append mode does not support changing the encryption status.");
  242. if (stamper.ContentWritten)
  243. throw new DocumentException("Content was already written to the output.");
  244. stamper.SetEncryption(userPassword, ownerPassword, permissions, strength128Bits ? PdfWriter.STANDARD_ENCRYPTION_128 : PdfWriter.STANDARD_ENCRYPTION_40);
  245. }
  246. /** Sets the encryption options for this document. The userPassword and the
  247. * ownerPassword can be null or have zero length. In this case the ownerPassword
  248. * is replaced by a random string. The open permissions for the document can be
  249. * AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations,
  250. * AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting.
  251. * The permissions can be combined by ORing them.
  252. * @param userPassword the user password. Can be null or empty
  253. * @param ownerPassword the owner password. Can be null or empty
  254. * @param permissions the user permissions
  255. * @param encryptionType the type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128.
  256. * Optionally DO_NOT_ENCRYPT_METADATA can be ored to output the metadata in cleartext
  257. * @throws DocumentException if the document is already open
  258. */
  259. public void SetEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType) {
  260. if (stamper.IsAppend())
  261. throw new DocumentException("Append mode does not support changing the encryption status.");
  262. if (stamper.ContentWritten)
  263. throw new DocumentException("Content was already written to the output.");
  264. stamper.SetEncryption(userPassword, ownerPassword, permissions, encryptionType);
  265. }
  266. /**
  267. * Sets the encryption options for this document. The userPassword and the
  268. * ownerPassword can be null or have zero length. In this case the ownerPassword
  269. * is replaced by a random string. The open permissions for the document can be
  270. * AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations,
  271. * AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting.
  272. * The permissions can be combined by ORing them.
  273. * @param strength <code>true</code> for 128 bit key length, <code>false</code> for 40 bit key length
  274. * @param userPassword the user password. Can be null or empty
  275. * @param ownerPassword the owner password. Can be null or empty
  276. * @param permissions the user permissions
  277. * @throws DocumentException if anything was already written to the output
  278. */
  279. public void SetEncryption(bool strength, String userPassword, String ownerPassword, int permissions) {
  280. SetEncryption(DocWriter.GetISOBytes(userPassword), DocWriter.GetISOBytes(ownerPassword), permissions, strength);
  281. }
  282. /**
  283. * Sets the encryption options for this document. The userPassword and the
  284. * ownerPassword can be null or have zero length. In this case the ownerPassword
  285. * is replaced by a random string. The open permissions for the document can be
  286. * AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations,
  287. * AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting.
  288. * The permissions can be combined by ORing them.
  289. * @param encryptionType the type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128.
  290. * Optionally DO_NOT_ENCRYPT_METADATA can be ored to output the metadata in cleartext
  291. * @param userPassword the user password. Can be null or empty
  292. * @param ownerPassword the owner password. Can be null or empty
  293. * @param permissions the user permissions
  294. * @throws DocumentException if the document is already open
  295. */
  296. public void SetEncryption(int encryptionType, String userPassword, String ownerPassword, int permissions) {
  297. SetEncryption(DocWriter.GetISOBytes(userPassword), DocWriter.GetISOBytes(ownerPassword), permissions, encryptionType);
  298. }
  299. /**
  300. * Sets the certificate encryption options for this document. An array of one or more public certificates
  301. * must be provided together with an array of the same size for the permissions for each certificate.
  302. * The open permissions for the document can be
  303. * AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations,
  304. * AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting.
  305. * The permissions can be combined by ORing them.
  306. * Optionally DO_NOT_ENCRYPT_METADATA can be ored to output the metadata in cleartext
  307. * @param certs the public certificates to be used for the encryption
  308. * @param permissions the user permissions for each of the certicates
  309. * @param encryptionType the type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128.
  310. * @throws DocumentException if the encryption was set too late
  311. */
  312. public void SetEncryption(X509Certificate[] certs, int[] permissions, int encryptionType) {
  313. if (stamper.IsAppend())
  314. throw new DocumentException("Append mode does not support changing the encryption status.");
  315. if (stamper.ContentWritten)
  316. throw new DocumentException("Content was already written to the output.");
  317. stamper.SetEncryption(certs, permissions, encryptionType);
  318. }
  319. /** Gets a page from other PDF document. Note that calling this method more than
  320. * once with the same parameters will retrieve the same object.
  321. * @param reader the PDF document where the page is
  322. * @param pageNumber the page number. The first page is 1
  323. * @return the template representing the imported page
  324. */
  325. public PdfImportedPage GetImportedPage(PdfReader reader, int pageNumber) {
  326. return stamper.GetImportedPage(reader, pageNumber);
  327. }
  328. /** Gets the underlying PdfWriter.
  329. * @return the underlying PdfWriter
  330. */
  331. public PdfWriter Writer {
  332. get {
  333. return stamper;
  334. }
  335. }
  336. /** Gets the underlying PdfReader.
  337. * @return the underlying PdfReader
  338. */
  339. public PdfReader Reader {
  340. get {
  341. return stamper.reader;
  342. }
  343. }
  344. /** Gets the <CODE>AcroFields</CODE> object that allows to get and set field values
  345. * and to merge FDF forms.
  346. * @return the <CODE>AcroFields</CODE> object
  347. */
  348. public AcroFields AcroFields {
  349. get {
  350. return stamper.AcroFields;
  351. }
  352. }
  353. /** Determines if the fields are flattened on close. The fields added with
  354. * {@link #addAnnotation(PdfAnnotation,int)} will never be flattened.
  355. * @param flat <CODE>true</CODE> to flatten the fields, <CODE>false</CODE>
  356. * to keep the fields
  357. */
  358. public bool FormFlattening {
  359. set {
  360. stamper.FormFlattening = value;
  361. }
  362. }
  363. /** Determines if the FreeText annotations are flattened on close.
  364. * @param flat <CODE>true</CODE> to flatten the FreeText annotations, <CODE>false</CODE>
  365. * (the default) to keep the FreeText annotations as active content.
  366. */
  367. public bool FreeTextFlattening {
  368. set {
  369. stamper.FreeTextFlattening = value;
  370. }
  371. }
  372. /**
  373. * Adds an annotation of form field in a specific page. This page number
  374. * can be overridden with {@link PdfAnnotation#setPlaceInPage(int)}.
  375. * @param annot the annotation
  376. * @param page the page
  377. */
  378. public void AddAnnotation(PdfAnnotation annot, int page) {
  379. stamper.AddAnnotation(annot, page);
  380. }
  381. /**
  382. * Adds an empty signature.
  383. * @param name the name of the signature
  384. * @param page the page number
  385. * @param llx lower left x coordinate of the signature's position
  386. * @param lly lower left y coordinate of the signature's position
  387. * @param urx upper right x coordinate of the signature's position
  388. * @param ury upper right y coordinate of the signature's position
  389. * @return a signature form field
  390. * @since 2.1.4
  391. */
  392. public PdfFormField AddSignature(String name, int page, float llx, float lly, float urx, float ury) {
  393. PdfAcroForm acroForm = stamper.AcroForm;
  394. PdfFormField signature = PdfFormField.CreateSignature(stamper);
  395. acroForm.SetSignatureParams(signature, name, llx, lly, urx, ury);
  396. acroForm.DrawSignatureAppearences(signature, llx, lly, urx, ury);
  397. AddAnnotation(signature, page);
  398. return signature;
  399. }
  400. /**
  401. * Adds the comments present in an FDF file.
  402. * @param fdf the FDF file
  403. * @throws IOException on error
  404. */
  405. public void AddComments(FdfReader fdf) {
  406. stamper.AddComments(fdf);
  407. }
  408. /**
  409. * Sets the bookmarks. The list structure is defined in
  410. * {@link SimpleBookmark}.
  411. * @param outlines the bookmarks or <CODE>null</CODE> to remove any
  412. */
  413. public ArrayList Outlines {
  414. set {
  415. stamper.Outlines = value;
  416. }
  417. }
  418. /**
  419. * Sets the thumbnail image for a page.
  420. * @param image the image
  421. * @param page the page
  422. * @throws PdfException on error
  423. * @throws DocumentException on error
  424. */
  425. public void SetThumbnail(Image image, int page) {
  426. stamper.SetThumbnail(image, page);
  427. }
  428. /**
  429. * Adds <CODE>name</CODE> to the list of fields that will be flattened on close,
  430. * all the other fields will remain. If this method is never called or is called
  431. * with invalid field names, all the fields will be flattened.
  432. * <p>
  433. * Calling <CODE>setFormFlattening(true)</CODE> is needed to have any kind of
  434. * flattening.
  435. * @param name the field name
  436. * @return <CODE>true</CODE> if the field exists, <CODE>false</CODE> otherwise
  437. */
  438. public bool PartialFormFlattening(String name) {
  439. return stamper.PartialFormFlattening(name);
  440. }
  441. /** Adds a JavaScript action at the document level. When the document
  442. * opens all this JavaScript runs. The existing JavaScript will be replaced.
  443. * @param js the JavaScript code
  444. */
  445. public string JavaScript {
  446. set {
  447. stamper.AddJavaScript(value, !PdfEncodings.IsPdfDocEncoding(value));
  448. }
  449. }
  450. /** Adds a file attachment at the document level. Existing attachments will be kept.
  451. * @param description the file description
  452. * @param fileStore an array with the file. If it's <CODE>null</CODE>
  453. * the file will be read from the disk
  454. * @param file the path to the file. It will only be used if
  455. * <CODE>fileStore</CODE> is not <CODE>null</CODE>
  456. * @param fileDisplay the actual file name stored in the pdf
  457. * @throws IOException on error
  458. */
  459. public void AddFileAttachment(String description, byte[] fileStore, String file, String fileDisplay) {
  460. AddFileAttachment(description, PdfFileSpecification.FileEmbedded(stamper, file, fileDisplay, fileStore));
  461. }
  462. /** Adds a file attachment at the document level. Existing attachments will be kept.
  463. * @param description the file description
  464. * @param fs the file specification
  465. */
  466. public void AddFileAttachment(String description, PdfFileSpecification fs) {
  467. stamper.AddFileAttachment(description, fs);
  468. }
  469. /**
  470. * This is the most simple way to change a PDF into a
  471. * portable collection. Choose one of the following names:
  472. * <ul>
  473. * <li>PdfName.D (detailed view)
  474. * <li>PdfName.T (tiled view)
  475. * <li>PdfName.H (hidden)
  476. * </ul>
  477. * Pass this name as a parameter and your PDF will be
  478. * a portable collection with all the embedded and
  479. * attached files as entries.
  480. * @param initialView can be PdfName.D, PdfName.T or PdfName.H
  481. */
  482. public void MakePackage( PdfName initialView ) {
  483. PdfCollection collection = new PdfCollection(0);
  484. collection.Put(PdfName.VIEW, initialView);
  485. stamper.MakePackage( collection );
  486. }
  487. /**
  488. * Adds or replaces the Collection Dictionary in the Catalog.
  489. * @param collection the new collection dictionary.
  490. */
  491. public void MakePackage(PdfCollection collection) {
  492. stamper.MakePackage(collection);
  493. }
  494. /**
  495. * Sets the viewer preferences.
  496. * @param preferences the viewer preferences
  497. * @see PdfViewerPreferences#setViewerPreferences(int)
  498. */
  499. public virtual int ViewerPreferences {
  500. set {
  501. stamper.ViewerPreferences = value;
  502. }
  503. }
  504. /** Adds a viewer preference
  505. * @param preferences the viewer preferences
  506. * @see PdfViewerPreferences#addViewerPreference
  507. */
  508. public virtual void AddViewerPreference(PdfName key, PdfObject value) {
  509. stamper.AddViewerPreference(key, value);
  510. }
  511. /**
  512. * Sets the XMP metadata.
  513. * @param xmp
  514. * @see PdfWriter#setXmpMetadata(byte[])
  515. */
  516. public byte[] XmpMetadata {
  517. set {
  518. stamper.XmpMetadata = value;
  519. }
  520. }
  521. /**
  522. * Gets the 1.5 compression status.
  523. * @return <code>true</code> if the 1.5 compression is on
  524. */
  525. public bool FullCompression {
  526. get {
  527. return stamper.FullCompression;
  528. }
  529. }
  530. /**
  531. * Sets the document's compression to the new 1.5 mode with object streams and xref
  532. * streams. It can be set at any time but once set it can't be unset.
  533. */
  534. public void SetFullCompression() {
  535. if (stamper.append)
  536. return;
  537. stamper.SetFullCompression();
  538. }
  539. /**
  540. * Sets the open and close page additional action.
  541. * @param actionType the action type. It can be <CODE>PdfWriter.PAGE_OPEN</CODE>
  542. * or <CODE>PdfWriter.PAGE_CLOSE</CODE>
  543. * @param action the action to perform
  544. * @param page the page where the action will be applied. The first page is 1
  545. * @throws PdfException if the action type is invalid
  546. */
  547. public void SetPageAction(PdfName actionType, PdfAction action, int page) {
  548. stamper.SetPageAction(actionType, action, page);
  549. }
  550. /**
  551. * Sets the display duration for the page (for presentations)
  552. * @param seconds the number of seconds to display the page. A negative value removes the entry
  553. * @param page the page where the duration will be applied. The first page is 1
  554. */
  555. public void SetDuration(int seconds, int page) {
  556. stamper.SetDuration(seconds, page);
  557. }
  558. /**
  559. * Sets the transition for the page
  560. * @param transition the transition object. A <code>null</code> removes the transition
  561. * @param page the page where the transition will be applied. The first page is 1
  562. */
  563. public void SetTransition(PdfTransition transition, int page) {
  564. stamper.SetTransition(transition, page);
  565. }
  566. /**
  567. * Applies a digital signature to a document, possibly as a new revision, making
  568. * possible multiple signatures. The returned PdfStamper
  569. * can be used normally as the signature is only applied when closing.
  570. * <p>
  571. * A possible use for adding a signature without invalidating an existing one is:
  572. * <p>
  573. * <pre>
  574. * KeyStore ks = KeyStore.getInstance("pkcs12");
  575. * ks.load(new FileInputStream("my_private_key.pfx"), "my_password".toCharArray());
  576. * String alias = (String)ks.aliases().nextElement();
  577. * PrivateKey key = (PrivateKey)ks.getKey(alias, "my_password".toCharArray());
  578. * Certificate[] chain = ks.getCertificateChain(alias);
  579. * PdfReader reader = new PdfReader("original.pdf");
  580. * FileOutputStream fout = new FileOutputStream("signed.pdf");
  581. * PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0', new
  582. * File("/temp"), true);
  583. * PdfSignatureAppearance sap = stp.getSignatureAppearance();
  584. * sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
  585. * sap.setReason("I'm the author");
  586. * sap.setLocation("Lisbon");
  587. * // comment next line to have an invisible signature
  588. * sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null);
  589. * stp.close();
  590. * </pre>
  591. * @param reader the original document
  592. * @param os the output stream or <CODE>null</CODE> to keep the document in the temporary file
  593. * @param pdfVersion the new pdf version or '\0' to keep the same version as the original
  594. * document
  595. * @param tempFile location of the temporary file. If it's a directory a temporary file will be created there.
  596. * If it's a file it will be used directly. The file will be deleted on exit unless <CODE>os</CODE> is null.
  597. * In that case the document can be retrieved directly from the temporary file. If it's <CODE>null</CODE>
  598. * no temporary file will be created and memory will be used
  599. * @param append if <CODE>true</CODE> the signature and all the other content will be added as a
  600. * new revision thus not invalidating existing signatures
  601. * @return a <CODE>PdfStamper</CODE>
  602. * @throws DocumentException on error
  603. * @throws IOException on error
  604. */
  605. public static PdfStamper CreateSignature(PdfReader reader, Stream os, char pdfVersion, string tempFile, bool append) {
  606. PdfStamper stp;
  607. if (tempFile == null) {
  608. ByteBuffer bout = new ByteBuffer();
  609. stp = new PdfStamper(reader, bout, pdfVersion, append);
  610. stp.sigApp = new PdfSignatureAppearance(stp.stamper);
  611. stp.sigApp.Sigout = bout;
  612. }
  613. else {
  614. if (Directory.Exists(tempFile))
  615. tempFile = Path.GetTempFileName();
  616. FileStream fout = new FileStream(tempFile, FileMode.Create, FileAccess.Write);
  617. stp = new PdfStamper(reader, fout, pdfVersion, append);
  618. stp.sigApp = new PdfSignatureAppearance(stp.stamper);
  619. stp.sigApp.SetTempFile(tempFile);
  620. }
  621. stp.sigApp.Originalout = os;
  622. stp.sigApp.SetStamper(stp);
  623. stp.hasSignature = true;
  624. PdfDictionary catalog = reader.Catalog;
  625. PdfDictionary acroForm = (PdfDictionary)PdfReader.GetPdfObject(catalog.Get(PdfName.ACROFORM), catalog);
  626. if (acroForm != null) {
  627. acroForm.Remove(PdfName.NEEDAPPEARANCES);
  628. stp.stamper.MarkUsed(acroForm);
  629. }
  630. return stp;
  631. }
  632. /**
  633. * Applies a digital signature to a document. The returned PdfStamper
  634. * can be used normally as the signature is only applied when closing.
  635. * <p>
  636. * Note that the pdf is created in memory.
  637. * <p>
  638. * A possible use is:
  639. * <p>
  640. * <pre>
  641. * KeyStore ks = KeyStore.getInstance("pkcs12");
  642. * ks.load(new FileInputStream("my_private_key.pfx"), "my_password".toCharArray());
  643. * String alias = (String)ks.aliases().nextElement();
  644. * PrivateKey key = (PrivateKey)ks.getKey(alias, "my_password".toCharArray());
  645. * Certificate[] chain = ks.getCertificateChain(alias);
  646. * PdfReader reader = new PdfReader("original.pdf");
  647. * FileOutputStream fout = new FileOutputStream("signed.pdf");
  648. * PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
  649. * PdfSignatureAppearance sap = stp.getSignatureAppearance();
  650. * sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
  651. * sap.setReason("I'm the author");
  652. * sap.setLocation("Lisbon");
  653. * // comment next line to have an invisible signature
  654. * sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null);
  655. * stp.close();
  656. * </pre>
  657. * @param reader the original document
  658. * @param os the output stream
  659. * @param pdfVersion the new pdf version or '\0' to keep the same version as the original
  660. * document
  661. * @throws DocumentException on error
  662. * @throws IOException on error
  663. * @return a <CODE>PdfStamper</CODE>
  664. */
  665. public static PdfStamper CreateSignature(PdfReader reader, Stream os, char pdfVersion) {
  666. return CreateSignature(reader, os, pdfVersion, null, false);
  667. }
  668. /**
  669. * Applies a digital signature to a document. The returned PdfStamper
  670. * can be used normally as the signature is only applied when closing.
  671. * <p>
  672. * A possible use is:
  673. * <p>
  674. * <pre>
  675. * KeyStore ks = KeyStore.getInstance("pkcs12");
  676. * ks.load(new FileInputStream("my_private_key.pfx"), "my_password".toCharArray());
  677. * String alias = (String)ks.aliases().nextElement();
  678. * PrivateKey key = (PrivateKey)ks.getKey(alias, "my_password".toCharArray());
  679. * Certificate[] chain = ks.getCertificateChain(alias);
  680. * PdfReader reader = new PdfReader("original.pdf");
  681. * FileOutputStream fout = new FileOutputStream("signed.pdf");
  682. * PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0', new File("/temp"));
  683. * PdfSignatureAppearance sap = stp.getSignatureAppearance();
  684. * sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
  685. * sap.setReason("I'm the author");
  686. * sap.setLocation("Lisbon");
  687. * // comment next line to have an invisible signature
  688. * sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null);
  689. * stp.close();
  690. * </pre>
  691. * @param reader the original document
  692. * @param os the output stream or <CODE>null</CODE> to keep the document in the temporary file
  693. * @param pdfVersion the new pdf version or '\0' to keep the same version as the original
  694. * document
  695. * @param tempFile location of the temporary file. If it's a directory a temporary file will be created there.
  696. * If it's a file it will be used directly. The file will be deleted on exit unless <CODE>os</CODE> is null.
  697. * In that case the document can be retrieved directly from the temporary file. If it's <CODE>null</CODE>
  698. * no temporary file will be created and memory will be used
  699. * @return a <CODE>PdfStamper</CODE>
  700. * @throws DocumentException on error
  701. * @throws IOException on error
  702. */
  703. public static PdfStamper CreateSignature(PdfReader reader, Stream os, char pdfVersion, string tempFile) {
  704. return CreateSignature(reader, os, pdfVersion, tempFile, false);
  705. }
  706. /**
  707. * Gets the PdfLayer objects in an existing document as a Map
  708. * with the names/titles of the layers as keys.
  709. * @return a Map with all the PdfLayers in the document (and the name/title of the layer as key)
  710. * @since 2.1.2
  711. */
  712. public Hashtable GetPdfLayers() {
  713. return stamper.GetPdfLayers();
  714. }
  715. }
  716. }