- Code: Select all
// create a PdfDocument object and load a PDF file
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"DigitalSignature.pdf");
PdfPageBase newPage = doc.Pages.Add(doc.Pages[0].Size);
//load the certificate .pfx file
PdfCertificate cert = new PdfCertificate(@"ari.pfx", "bobo");
//add a signature to the specified position
PdfBrush brush = PdfBrushes.Black;
PdfTrueTypeFont font = new PdfTrueTypeFont(new System.Drawing.Font("Arial", 15, FontStyle.Bold), true);
string ApprovalsLabel = "approvals";
// draw an approval report header and
// center it in the page.
SizeF size = font.MeasureString(ApprovalsLabel);
int x = (int)((newPage.Canvas.ClientSize.Width - size.Width) / 2.0);
newPage.Canvas.DrawString(ApprovalsLabel, font,
brush, new PointF(x, 0));
newPage = doc.Pages[doc.Pages.Count - 1];
RectangleF rect = new RectangleF(new PointF(10, 80),
new SizeF(newPage.Canvas.ClientSize.Width - 10, 40));
PdfFont detailsFont = new PdfFont(PdfFontFamily.TimesRoman, 10);
PdfSignature signature = new PdfSignature(doc, newPage, cert, "signature");
//set the signature content
// order of fields in the signature
signature.NameLabel = "First Approver:";
signature.Name = "Ari Hartstein";
// provide a blank line
signature.DistinguishedNameLabel = " ";
signature.DistinguishedName = null;
string bstrComment = "";
// comment specified.
if (bstrComment.Length > 0)
{
string CommentsLabel = "Comment";
// here we are using the available fields to format
// the signature to meet the spec. We are not using contact info
signature.ReasonLabel = CommentsLabel;
signature.Reason = bstrComment;
signature.LocationInfoLabel = null;
// provide a blank line
signature.ContactInfoLabel = " ";
// increase the size of the signature by the height of the comment
SizeF reasonSize = detailsFont.MeasureString(signature.ReasonLabel + signature.Reason);
SizeF reasonSizeBlank = detailsFont.MeasureString(" ");
// compute the number of lines needed for the comment, hopefully 1
float fCommentsHeight = (float)Math.Ceiling(reasonSize.Width / rect.Width) * rect.Height;
rect.Height +=
reasonSize.Height + reasonSizeBlank.Height;
}
signature.Bounds = rect;
// signature date.
string DateLabel = "Date:";
signature.DateLabel = DateLabel;
signature.Date = DateTime.Now;
signature.Bounds = rect;
bool IsFinal = false;
// if not final then allow for additional signatures.
signature.DocumentPermissions = IsFinal ?
PdfCertificationFlags.ForbidChanges :
PdfCertificationFlags.AllowComments;
// certify the document
signature.Certificated = IsFinal;
//Set fonts. if not set, default ones will be applied.
signature.SignDetailsFont = detailsFont;
signature.SignNameFont = new PdfFont(PdfFontFamily.Courier, 15, PdfFontStyle.Bold);
//Display signer name and all the above labels.
signature.SignImageLayout = SignImageLayout.None;
if (signature.Certificate.SignatureAlgorithm.FriendlyName ==
"sha1RSA")
signature.ConfigureTimestamp("http://timestamp.digicert.com");
doc.SaveToFile("output.pdf");