title: Signing dynamically generated PDF file with attached signature
body: <p>I'm working on an application that allows users to generate certain PDF documents using templates, then sign those documents and store the signed documents for later verification.</p>
  <p>When using completely external (detached, say RSA) signature, I can do the following optimization: as a document is generated using a template from a small structured dataset, I can ignore the document itself and only store structured data along with signature.</p>
  <p>This greatly reduces requirements for disk space and throughput, as PDF file is 50-100 times bigger than it's source data.</p>
  <p>However, recently we've got a requirement to use signatures embedded in PDF files themselves. Here it is - iText comes to rescue!</p>
  <p>The idea is to have the following process:</p>
  <ol>
  <li>Generate PDF on server. This includes getting the source data, transforming it to PDF using template, then using iText insert an empty signature container to it.</li>
  <li>Send PDF to client for signing</li>
  <li>Extract user signature from PDF. Store it separately along with source data, template version, and byte ranges used for signing</li>
  <li>When a document is requested, generate the same document from source data, then insert stored signature using previously recorded byte ranges.</li>
  </ol>
  <p>So far, sounds so good.</p>
  <p>However, the problem is getting repeatable result during transformation chain
  Source Data -&gt; PDF -&gt; PDF + Signature Container</p>
  <p>The step Source Data -&gt; PDF obviously works fine. The problem is with inserting a Signature Container. Each time I'm using the same code on the same PDF i get different result (in bytes) of resulting PDF + Container.</p>
  <p>I'm using roughly the following code to prepare document for signing:</p>
  <pre><code>PdfReader reader = new PdfReader(resultDocument);
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  PdfStamper stamper = PdfStamper.createSignature(reader, baos, '\0');
  PdfSignatureAppearance sap = stamper.getSignatureAppearance();
  sap.setReason(&quot;Sign reason&quot;);
  sap.setLocation(&quot;Sign location&quot;);
  sap.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, &quot;sig&quot;);
  sap.setSignDate(externallyStoredSignDate)
  PdfSignature dic = new PdfSignature(
  PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
  dic.setReason(sap.getReason());
  dic.setLocation(sap.getLocation());
  dic.setContact(sap.getContact());
  dic.setDate(new PdfDate(sap.getSignDate()));
  sap.setCryptoDictionary(dic);
  HashMap&lt;PdfName, Integer&gt; exc = new HashMap&lt;PdfName, Integer&gt;();
  exc.put(PdfName.CONTENTS, new Integer(8192 * 2 + 2));
  sap.preClose(exc);
  
  InputStream data = sap.getRangeStream(); // Whooops - different every time!
  </code></pre>
  <p>Any help on how to get repeatable PDFs with prepared space for signatures is greatly appreciated!
  Thanks in advance.</p>