I am trying to create PDFs with header and footer using Powershell. I am using PowerShell v5.1. My PowerShell experience is pretty rudimentary as I usually do coding in C#/VB. Unfortunately, one of the requirements is to do this in PowerShell. The library I am using is iTextSharp library.
I am including iTextSharp.dll in my script
Add-Type -Path "$ScriptLocationIncludesitextsharp.dll" -ErrorAction Stop
I need to inherit the iTextSharp.text.pdf.PdfPageEventHelper
class to override the OnEndPage
function. Everytime I load the script into PowerShell ISE environment, I get this error: Unable to find the type [iTextSharp.text.pdf.PdfPageEventHelper]
. However, the ‘missing’ type is part of the itextsharp.dll.
I am able to get the environment to recognize the type after the following steps:
- Comment out the inherited class and the command
- Run the script
- Uncomment the inherit class and function
In VB.NET, it has the imports
statement, sometime like this:
Imports iTextSharp.text
Is there something similar in Powershell? How can I force the PowerShell environment to recongnize the sub class (iTextSharp.text) without going through those steps I outlinged above?
My code is as follows:
Add-Type -Path "$ScriptLocationIncludesitextsharp.dll" -ErrorAction Stop
class PdfPageEvents : iTextSharp.text.pdf.PdfPageEventHelper {
[string]$headerText
PdfPageEvents([string]$headerText) {
$this.headerText = $headerText
}
# Override OnEndPage to add header and footer
[void] OnEndPage ([iTextSharp.text.pdf.PdfWriter]$writer, [iTextSharp.text.Document]$document) {
$cb = $writer.DirectContent
$pageSize = $document.PageSize
# Add header
$header = New-Object iTextSharp.text.Paragraph($this.headerText, New-Object iTextSharp.text.Font([iTextSharp.text.Font]::ARIAL, 12))
$header.Alignment = [iTextSharp.text.Element]::ALIGN_CENTER
$headerTable = New-Object iTextSharp.text.pdf.PdfPTable(1)
$headerTable.TotalWidth = $pageSize.Width - $document.LeftMargin - $document.RightMargin
$headerTable.AddCell($header)
$headerTable.WriteSelectedRows(0, -1, $document.LeftMargin, $pageSize.Height - $document.TopMargin + 15, $cb)
}
}
$pdfDocument = New-Object iTextSharp.text.Document([iTextSharp.text.Rectangle]::new([iTextSharp.text.PageSize]::A4.Height, [iTextSharp.text.PageSize]::A4.Width))
$fileStream = New-Object -TypeName IO.FileStream -ArgumentList ($FileOutputName, [System.IO.FileMode]::Create)
$pdfWriter = [iTextSharp.text.pdf.PdfWriter]::GetInstance($pdfDocument, $filestream)
[iTextSharp.text.FontFactory]::RegisterDirectories()
$pdfDocument.Open()
$paragraph = New-Object -TypeName iTextSharp.text.Paragraph
$headerString = "Header Text"
$pdfWriter.PageEvent = [PdfPageEvents]::new("$headerString")
$paragraph.add("blah blah blah")
$pdfDocument.Add($paragraph)
$pdfDocument.Close()