title: itextsharp - stamp AND add additional page
body: <p>I already have a working snippet for stamping PDF's.
  But, now a request has reached me for adding an additional page to the same document.</p>
  <p>I have managed to get it working, but I'd like to verify that it is the best way to do it.</p>
  <p>Edit: It turns out it is not working as expected.
  The fields get malformatted with a big &quot;x&quot; instead of the text as per below image.  If I click the field I can see that the text has been input though.</p>
  <p><a href="https://i.stack.imgur.com/G4lRW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G4lRW.png" alt="enter image description here" /></a></p>
  <p>Old code</p>
  <pre><code>$FieldsHash = ConvertFrom-StringData -StringData $Fields
  $FieldsHash | Export-Clixml C:\Temp\fieldhash.xml
  
  $reader = New-Object iTextSharp.text.pdf.PdfReader -ArgumentList $InputPdfFilePath
  $stamper = New-Object iTextSharp.text.pdf.PdfStamper($reader, [System.IO.File]::Create($OutputPdfFilePath))
              
  foreach ($j in $FieldsHash.GetEnumerator())
  {
      try {
          $formattedDate = Get-Date $j.Value -Format $DatePattern
          $null = $stamper.AcroFields.SetField($j.Key, $formattedDate)
      }
      catch {
          try {
              $null = $stamper.AcroFields.SetField($j.Key, $j.Value)
          } catch {
              &quot;Could not find $($j.Key)&quot;
          }
      }
  }
  
  $stamper.Close()
  </code></pre>
  <p>Modified code:</p>
  <pre><code>$fileStream = New-Object System.IO.FileStream($OutputPdfFilePath, [System.IO.FileMode]::OpenOrCreate)
  $document = New-Object iTextSharp.text.Document
  $pdfCopy = New-Object iTextSharp.text.pdf.PdfCopy($document, $fileStream)
  
  $mainreader = New-Object iTextSharp.text.pdf.PdfReader($InputPdfFilePath)
  $stamper = New-Object iTextSharp.text.pdf.PdfStamper($mainreader, $fileStream)
  
  $document.Open()
  
  $FieldsHash = ConvertFrom-StringData -StringData $Fields
  $FieldsHash | Export-Clixml C:\Temp\pdf\fieldhash.xml
  
  foreach ($j in $FieldsHash.GetEnumerator())
  {
      try {
          $formattedDate = Get-Date $j.Value -Format $DatePattern
          $null = $stamper.AcroFields.SetField($j.Key, $formattedDate)
      } catch {
          try {
              $null = $stamper.AcroFields.SetField($j.Key, $j.Value)
          } catch {
              &quot;Could not find $($j.Key)&quot;
          }
      }
  }
  
  $pdfCopy.AddDocument($mainreader)
  $mainreader.Dispose()
  
  $attreader = New-Object iTextSharp.text.pdf.PdfReader($att)
  $pdfCopy.AddDocument($attreader)
  $attreader.Dispose()
  
  $pdfCopy.Dispose()
  $document.Dispose()
  $fileStream.Dispose()
  </code></pre>