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.
I have managed to get it working, but I'd like to verify that it is the best way to do it.
Edit: It turns out it is not working as expected. The fields get malformatted with a big "x" instead of the text as per below image. If I click the field I can see that the text has been input though.
Old 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 {
"Could not find $($j.Key)"
}
}
}
$stamper.Close()
Modified 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 {
"Could not find $($j.Key)"
}
}
}
$pdfCopy.AddDocument($mainreader)
$mainreader.Dispose()
$attreader = New-Object iTextSharp.text.pdf.PdfReader($att)
$pdfCopy.AddDocument($attreader)
$attreader.Dispose()
$pdfCopy.Dispose()
$document.Dispose()
$fileStream.Dispose()
