#digitally sign a PDF file using a PFX certificate creted on the fly
#the script can be configured to use an existing PFX file or a certificate loaded from Microsoft Store (smart card certificate)



if ($args.Length -eq 0)
{
    echo "Usage: signpdf.ps1 <unsigned file> <signed file>"
}
else
{

#SignLib.dll and iTextSharp-4.1.6.dll are available here: ..\SignLib\netframework4.6.2
#Note that SignLib.dll with iTextSharp-4.1.6.dll (for PDF signatures) must be placed on a folder and the path must be added on the .ps1 file, as below:

$DllPath = 'SignLib.dll'
[System.Reflection.Assembly]::LoadFrom($DllPath)


$certificate = 'certificate.pfx'
$pFXFilePassword = '123456'
    
#digitally sign the pdf file
    $sign = new-object -typeName SignLib.Pdf.PdfSignature("serial number")
    $sign.LoadPdfDocument([System.IO.File]::ReadAllBytes($args[0]))
    $sign.DigitalSignatureCertificate = [SignLib.Certificates.DigitalCertificate]::LoadCertificate($certificate, $pFXFilePassword)


    $sign.SigningReason = "I approve this document"
    $sign.SigningLocation = "Europe branch"
    $sign.SignaturePage = 1
    $sign.SignaturePosition = [SignLib.Pdf.SignaturePosition]::TopRight

    echo "Perform the digital signature..."
    [System.IO.File]::WriteAllBytes($args[1], $sign.ApplyDigitalSignature())
    

}