Draw text in PDF document is an important part and it is not easy to finish. With the help of Spire.PDF, a PDF component, you can not only draw text in PDF document easily for .NET and WPF, you can do this job easily for Silverlight.

We have introduced how to draw text for PDF .NET and PDF WPF. This article will give clear information of how to draw text with C# code for Silverlight.

Make sure Spire.PDF (or Spire.Office) has been installed correctly. Add Spire.PDF.dll as reference in the downloaded Bin folder though the below path: "..\Spire.PDF\Bin\Silverlight4\ Spire.PDF.dll".

Here comes to the steps:

Step 1: Create a PDF document and a page

[C#]
//create a pdf document
PdfDocument document = new PdfDocument();
//create one page
PdfPageBase page = document.Pages.Add();

Step 2: Draw Text

[C#]
//Draw Text - alignment
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 20f);
PdfSolidBrush brush = new PdfSolidBrush(Color.FromArgb(10, 0, 255, 0));

PdfStringFormat leftAlignment = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
page.Canvas.DrawString("Left!", font, brush, 0, 20, leftAlignment);
page.Canvas.DrawString("Left!", font, brush, 0, 50, leftAlignment);

PdfStringFormat rightAlignment = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
page.Canvas.DrawString("Right!", font, brush, page.Canvas.ClientSize.Width, 30, rightAlignment);
page.Canvas.DrawString("Right!", font, brush, page.Canvas.ClientSize.Width, 60, rightAlignment);

PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush, page.Canvas.ClientSize.Width / 2, 40, centerAlignment);

//Draw the text - align in rectangle
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 10f);
PdfSolidBrush brush = new PdfSolidBrush(Color.FromArgb(10, 0, 0, 255));
RectangleF rctg1 = new RectangleF(0, 70, page.Canvas.ClientSize.Width / 2, 100);
RectangleF rctg2 = new RectangleF(page.Canvas.ClientSize.Width / 2, 70, page.Canvas.ClientSize.Width / 2, 100);
page.Canvas.DrawRectangle(new PdfSolidBrush(Color.FromArgb(1, 0, 0, 100)), rctg1);
page.Canvas.DrawRectangle(new PdfSolidBrush(Color.FromArgb(1, 0, 0, 150)), rctg2);

PdfStringFormat leftAlignment = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Top);
page.Canvas.DrawString("Left! Left!", font, brush, rctg1, leftAlignment);
page.Canvas.DrawString("Left! Left!", font, brush, rctg2, leftAlignment);

PdfStringFormat rightAlignment = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
page.Canvas.DrawString("Right! Right!", font, brush, rctg1, rightAlignment);
page.Canvas.DrawString("Right! Right!", font, brush, rctg2, rightAlignment);

PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Bottom);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush, rctg1, centerAlignment);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush, rctg2, centerAlignment);

//Draw text - brush
String text = "Go! Turn Around! Go! Go! Go!";
PdfPen pen = PdfPens.DeepSkyBlue;
PdfSolidBrush brush = new PdfSolidBrush(Color.FromArgb(10, 0, 0, 0));
PdfStringFormat format = new PdfStringFormat();
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 18f, PdfFontStyle.Italic);
SizeF size = font.MeasureString(text, format);
RectangleF rctg= new RectangleF(page.Canvas.ClientSize.Width / 2 + 10, 180,
size.Width / 3 * 2, size.Height * 2);
page.Canvas.DrawString(text, font, pen, brush, rctg, format);

Step 3: Save the document to stream

[C#]
using (Stream ms = saveFiledialog.OpenFile())
{
    document.SaveToStream(ms);

}

Now check the effective screenshot:

Draw_Text_in_PDF_Document_for_Silverlight.png

Excel Freeze Panes keeps rows and columns visible while the rest of the worksheet scrolls. Likewise, we need to unfreeze Excel panes due to work needs in some cases. This article aims at introducing the solution to unfreeze the Excel top row in c# and VB.NET through a utility Excel .NET library Spire.XLS.

First we need to complete the preparatory work:

  • Download the latest Spire.XLS and install it on your machine.
  • Add the Spire.XLS.dll files as reference.
  • Open bin folder and select the three dll files under .NET 4.0.
  • Right click property and select properties in its menu.
  • Set the target framework as .NET 4.
  • Add Spire.XLS as namespace.

Here comes to the explanation of the C# code:

Step 1: Create an instance of Spire.XLS.Workbook.

Workbook workbook = new Workbook();

Step 2: Load the file base on a specified file path.

workbook.LoadFromFile("sample.xls");

Step 3: Get the first worksheet.

Worksheet sheet = workbook.Worksheets[0];

Step 4: Unfreeze the top row.

sheet.RemovePanes();

Step 5: Save as the generated file.

workbook.SaveToFile("sample.xls",ExcelVersion.Version97to2003);

Please preview the freeze panes effect screenshot:

Excel freeze panes

And the unfreeze panes effect screenshot:

Excel unfreeze panes

Here is the full code in C# and VB.NET:

[C#]
using Spire.Xls;
namespace UnfreezeExcelPane
{
    class Program
    {

        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xls");
            Worksheet sheet = workbook.Worksheets[0];
            sheet.RemovePanes();
            workbook.SaveToFile("sample.xls", ExcelVersion.Version97to2003);

        }
    }
}
[VB.NET]
Imports Spire.Xls
Namespace UnfreezeExcelPane
	Class Program

		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.LoadFromFile("Sample.xls")
			Dim sheet As Worksheet = workbook.Worksheets(0)
			sheet.RemovePanes()
			workbook.SaveToFile("sample.xls", ExcelVersion.Version97to2003)

		End Sub
	End Class
End Namespace

Bookmark can locate a range. Assuming the content of the range is some html code, how to change the content of the range. Spire.Doc supports bookmarks. And you can use Spire.Doc to fulfill the job.

In this article, a solution will be introduced. Spire.Doc provides you a method:

[C#]
public void ReplaceBookmarkContent(TextBodyPart bodyPart)

Replace the content of bookmark with TextBodyPart bodyPart.

This method cannot handle html code directly. Here is what to do. First load the new html code to document. Then select the newly added data as TextBodyPart. At last, call the method to replace the content of the bookmark.

Step 1: Add bookmarks containing html code.

[C#]
Paragraph p2 = section.AddParagraph();
p2.AppendBookmarkStart("bookmark2");
p2.AppendHTML("<p><font color='blue'>This para is also Generated by Decoding HTML Code</font></p>");
p2.AppendBookmarkEnd("bookmark2");

Step 2: Add new html code to document.

[C#]
Section tempSection = document.AddSection();
String html
= "<p>This Bookmark has been <font color=\"#ff0000\">Edited</font></p>";
tempSection.AddParagraph().AppendHTML(html);

Step 3: Get the new added html as TextBodyPart.

[C#]
ParagraphBase replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase;
ParagraphBase replacementLastItem  = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
TextBodySelection selection = new TextBodySelection(replacementFirstItem, replacementLastItem);
TextBodyPart part = new TextBodyPart(selection);

Step 4: Locate the bookmark "bookmark2" and call the method ReplaceBookmarkContent to replace the content. Then remove the temp section.

[C#]
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
//locate the bookmark
bookmarkNavigator.MoveToBookmark("bookmark2");
//replace the content of bookmark
bookmarkNavigator.ReplaceBookmarkContent(part);
//remove temp section
document.Sections.Remove(tempSection);

Preview the original screenshot:

Edit and replace bookmark with HTML

Preview the effect screenshot:

Edit and replace bookmark with HTML

Here comes to the full code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;
namespace EditContent
{
    class Program
    {

        static void Main(string[] args)
        {
            Document document = new Document();
            Section section = document.AddSection();

            //create bookmarks
            Paragraph p1 = section.AddParagraph();
            p1.AppendBookmarkStart("bookmark1");
            p1.AppendHTML("

This para is also Generated by Decoding HTML Code

"); p1.AppendBookmarkEnd("bookmark1"); Paragraph p2 = section.AddParagraph(); p2.AppendBookmarkStart("bookmark2"); p2.AppendHTML("

This para is also Generated by Decoding HTML Code

"); p2.AppendBookmarkEnd("bookmark2"); document.SaveToFile("BeforeReplace.doc"); //create a temp section to contain multiple paragraph. Section tempSection = document.AddSection(); String html = "

This Bookmark has been Edited

"; tempSection.AddParagraph().AppendHTML(html); ParagraphBase replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase; ParagraphBase replacementLastItem = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase; TextBodySelection selection = new TextBodySelection(replacementFirstItem, replacementLastItem); TextBodyPart part = new TextBodyPart(selection); BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); //locate the bookmark bookmarkNavigator.MoveToBookmark("bookmark2"); //replace the content of bookmark bookmarkNavigator.ReplaceBookmarkContent(part); //remove temp section document.Sections.Remove(tempSection); document.SaveToFile(@"AfterReplace.doc"); } } }

Sometimes we need to insert a symbol or special character in the paragraph. The article is introducing the solution to insert a symbol in Word with c# code. We will use Ä and Ë as the symbol examples to complete the process, with the help of a Word .NET API called Spire.Doc.

First we need to complete the preparatory work:

  • Download the latest Spire.Doc and install it on your machine.
  • Add the Spire.Doc.dll files as reference.
  • Open bin folder and select the three dll files under .NET 4.0.
  • Right click property and select properties in its menu.
  • Set the target framework as .NET 4.
  • Add Spire.Doc as namespace.

Here comes to the explanation of the code.

Step 1: Create an instance of Spire.Doc.Document.

[C#]
Document document = new Document();

Step 2: Add a section.

[C#]
Section section = document.AddSection();

Step 3: Add a paragraph.

[C#]
Paragraph paragraph = section.AddParagraph();

Step 4: Use unicode characters to create symbol Ä.

[C#]
TextRange tr = paragraph.AppendText('\u00c4'.ToString());

In fact, the following step5 and step6 are just the option according to your requirement.

Step 5: Set the color of symbol Ä.

[C#]
tr.CharacterFormat.TextColor = Color.Red;

Step 6: Add symbol Ë.

[C#]
paragraph.AppendText('\u00cb'.ToString());

Step 7: Save to Word file.

[C#]
document.SaveToFile("sample.docx", FileFormat.Docx);

Here is the full code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace InsertSymbol
{

    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            Section section = document.AddSection();
            Paragraph paragraph = section.AddParagraph();
            TextRange tr = paragraph.AppendText('\u00c4'.ToString());
            tr.CharacterFormat.TextColor = Color.Red;
            paragraph.AppendText('\u00cb'.ToString());
            document.SaveToFile("sample.docx", FileFormat.Docx);
        }

    }
}

Preview the effect screenshot:

insert symbol in word

The digital signature ensures that the signed document cannot be altered by anyone other than its author. Adding signatures is the most common way to assure the authenticity of the document content. A visual digital signature in a PDF document can show text or an image (e.g., handwritten signature). This article introduces how to digitally sign PDFs using Spire.PDF for .NET from the following three aspects.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Digitally Sign PDF with Text

The following are the steps to add a plain text signature to a PDF document.

  • Create a PdfDocument object, and load a sample PDF file using PdfDocument.LoadFromFile() method.
  • Load a .pfx certificate file while initializing the PdfCertificate object.
  • Create a PdfSignature object, specifying its position and size in the document.
  • Set the signature graphics mode to SignDetail, which will show signature details in plain text.
  • Set the signature details, including name, contact information, reason, date, etc. through the properties under the PdfSignature object.
  • Set the permissions of the certificated document to ForbidChanges and AllowFormFill.
  • Save the document to another file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Security;
using System;
using System.Drawing;
using Spire.Pdf.Graphics;

namespace AddTextSignature
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Load a sample PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

            //Load the certificate 
            PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");

            //Create a PdfSignature object and specify its position and size 
            PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count-1], cert, "MySignature");     
            RectangleF rectangleF = new RectangleF(doc.Pages[0].ActualSize.Width - 340, 150, 290, 100);
            signature.Bounds = rectangleF;
            signature.Certificated = true;

            //Set the graphics mode to sign detail
            signature.GraphicsMode = GraphicMode.SignDetail;

            //Set the signature content 
            signature.NameLabel = "Signer:";
            signature.Name = "Gary";
            signature.ContactInfoLabel = "Phone:";
            signature.ContactInfo = "0123456";
            signature.DateLabel = "Date:";
            signature.Date = DateTime.Now;
            signature.LocationInfoLabel = "Location:";
            signature.LocationInfo = "USA";
            signature.ReasonLabel = "Reason:";
            signature.Reason = "I am the author";
            signature.DistinguishedNameLabel = "DN:";
            signature.DistinguishedName = signature.Certificate.IssuerName.Name;

            //Set the signature font 
            signature.SignDetailsFont = new PdfTrueTypeFont(new Font("Arial Unicode MS",12f,FontStyle.Regular));

            //Set the document permission to forbid changes but allow form fill
            signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;

            //Save to file 
            doc.SaveToFile("TextSignature.pdf");
            doc.Close();
        }
    }
}

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Digitally Sign PDF with an Image

The following are the steps to add an image signature to a PDF document.

  • Create a PdfDocument object, and load a sample PDF file using PdfDocument.LoadFromFile() method.
  • Load a .pfx certificate file while initializing the PdfCertificate object.
  • Create a PdfSignature object, specifying its position and size in the document.
  • Set the signature graphics mode to SignImageOnly, which will show signature image only.
  • Set the signature image through PdfSignature.SignImageSource property.
  • Set the permissions of the certificated document to ForbidChanges and AllowFormFill.
  • Save the document to another file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Security;
using System.Drawing;

namespace AddImageSignature
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Load a sample PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

            //Load the certificate 
            PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");

            //Create a PdfSignature object and specify its position and size 
            PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
            RectangleF rectangleF = new RectangleF(doc.Pages[0].ActualSize.Width - 200, 150, 130, 130);
            signature.Bounds = rectangleF;
            signature.Certificated = true;

            //Set the graphics mode to image only
            signature.GraphicsMode = GraphicMode.SignImageOnly;

            //Set the sign image source
            signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\verified.png");
            signature.SignImageLayout = SignImageLayout.Stretch; 

            //Set the signature font 
            signature.SignDetailsFont = new PdfTrueTypeFont(new Font("Arial Unicode MS", 12f, FontStyle.Regular));

            //Set the document permission to forbid changes but allow form fill
            signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;

            //Save to file 
            doc.SaveToFile("ImageSignature.pdf");
            doc.Close();
        }
    }
}

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Digitally Sign PDF with Text and an Image

The following are the steps to digitally sign a PDF document with text and an image.

  • Create a PdfDocument object, and load a sample PDF file using PdfDocument.LoadFromFile() method.
  • Load a .pfx certificate file while initializing the PdfCertificate object.
  • Create a PdfSignature object, specifying its position and size in the document.
  • Set the signature graphics mode to SignImageAndSignDetail, which will show both signature image and details.
  • Set the signature image through PdfSignature.SignImageSource property, and set the signature details, including name, contact information, reason, date, etc. through other properties under the PdfSignature object.
  • Set the permissions of the certificated document to ForbidChanges and AllowFormFill.
  • Save the document to another file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Security;
using System;
using System.Drawing;
using Spire.Pdf.Graphics;

namespace AddTextAndImageSignature
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Load a sample PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

            //Load the certificate 
            PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");

            //Create a PdfSignature object and specify its position and size 
            PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
            RectangleF rectangleF = new RectangleF(doc.Pages[0].ActualSize.Width - 320, 150, 260, 110);
            signature.Bounds = rectangleF;
            signature.Certificated = true;

            //Set the graphics mode to image and sign detail
            signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;

            //Set the signature content 
            signature.NameLabel = "Signer:";
            signature.Name = "Gary";
            signature.ContactInfoLabel = "Phone:";
            signature.ContactInfo = "0123456";
            signature.DateLabel = "Date:";
            signature.Date = DateTime.Now;
            signature.LocationInfoLabel = "Location:";
            signature.LocationInfo = "USA";
            signature.ReasonLabel = "Reason:";
            signature.Reason = "I am the author";
            signature.DistinguishedNameLabel = "DN:";
            signature.DistinguishedName = signature.Certificate.IssuerName.Name;

            //Set the signature image source
            signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\handSignature.png");

            //Set the signature font 
            signature.SignDetailsFont = new PdfTrueTypeFont(new Font("Arial Unicode MS", 12f, FontStyle.Regular));

            //Set the document permission to forbid changes but allow form fill
            signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;

            //Save to file 
            doc.SaveToFile("TextAndImageSignature.pdf");
            doc.Close();
        }
    }
}

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Securing PDFs with digital signatures is essential for ensuring the integrity and non-repudiation of the documents. With this in mind, the ability to verify the digital signatures is equally important. A valid signature means that the document hasn't been altered since it was signed and that it is indeed originated from the claimed source.

While dealing with the digital signatures, there are also times when you may want to get the certificates of the signatures to learn its issuer Information, subject information, serial number, and validity period, etc. In this article, you will learn how to verify or get the digital signatures in PDF in C# using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF 

Verify Digital Signatures in PDF Using C#

Spire.PDF for .NET provides the PdfSignature.VerifySignature() method to check the validity of the digital signatures in a PDF document directly. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get the form in the PDF file using PdfDocument.Form property, and then get a collection of form fields using PdfFormWidget.FieldsWidget property.
  • Iterate through all fields and get the signature fields.
  • Get PDF signatures using PdfSignatureFieldWidget.Signature property.
  • Check the validity of the PDF signatures using PdfSignature.VerifySignature() method.
  • C#
using Spire.Pdf;
using Spire.Pdf.Security;
using Spire.Pdf.Widget;

namespace GetSignatureCertificate
{
    class Program
    {
        static void Main(string[] args)
        {

            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a PDF file
            pdf.LoadFromFile("PDFSignature.pdf");

            //Get a collection of form fields in the PDF file
            PdfFormWidget pdfFormWidget = (PdfFormWidget)pdf.Form;
            PdfFormFieldWidgetCollection pdfFormFieldWidgetCollection = pdfFormWidget.FieldsWidget;

            //Iterate through all fields
            for (int i = 0; i < pdfFormFieldWidgetCollection.Count; i++)
            {
                //Get the signature fields
                if (pdfFormFieldWidgetCollection[i] is PdfSignatureFieldWidget)
                {
                    PdfSignatureFieldWidget signatureFieldWidget = (PdfSignatureFieldWidget)pdfFormFieldWidgetCollection[i];

                    //Get the signatures
                    PdfSignature signature = signatureFieldWidget.Signature;

                    //Verify signatures
                    bool valid = signature.VerifySignature();
                    if (valid)
                    {
                        Console.WriteLine("Valid signatures");
                    }
                    else
                    {
                        Console.WriteLine("Invalid signatures");
                    }
                }
            }
        }
    }
}

C#: Verify or Get Digital Signatures in PDF

Detect Whether a Signed PDF Has Been Modified Using C#

To verify if a PDF document has been modified after signing, you can use the PdfSignature.VerifyDocModified() method. If the result shows that document has been tampered with, this means that the signature will become invalid and the integrity of the document will be compromised. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the form in the PDF document using PdfDocument.Form property, and then get a collection of form fields using PdfFormWidget.FieldsWidget property.
  • Iterate through all fields and get the signature fields.
  • Get PDF signatures using PdfSignatureFieldWidget.Signature property.
  • Verify if the document has been modified after signing using PdfSignature.VerifyDocModified() method.
  • C#
using Spire.Pdf;
using Spire.Pdf.Security;
using Spire.Pdf.Widget;

namespace GetSignatureCertificate
{
    class Program
    {
        static void Main(string[] args)
        {

            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a PDF document
            pdf.LoadFromFile("PDFSignature.pdf");

            //Get a collection of form fields in the PDF file
            PdfFormWidget pdfFormWidget = (PdfFormWidget)pdf.Form;
            PdfFormFieldWidgetCollection pdfFormFieldWidgetCollection = pdfFormWidget.FieldsWidget;

            for (int i = 0; i < pdfFormFieldWidgetCollection.Count; i++)
            {
                //Get the signature fields
                if (pdfFormFieldWidgetCollection[i] is PdfSignatureFieldWidget)
                {
                    PdfSignatureFieldWidget signatureFieldWidget = (PdfSignatureFieldWidget)pdfFormFieldWidgetCollection[i];

                    //Get the signatures
                    PdfSignature signature = signatureFieldWidget.Signature;

                    //Check if the document has been modified after signing
                    bool modified = signature.VerifyDocModified();
                    if (modified)
                    {
                        Console.WriteLine("The document has been modified.");
                    }
                    else
                    {
                        Console.WriteLine("The document has not been modified.");
                    }
                }
            }
        }
    }
}

C#: Verify or Get Digital Signatures in PDF

Get the Certificates of Digital Signatures in PDF Using C#

The digital certificates used to sign PDF files typically contain various pieces of information that verifies the identity of the issuer. With Spire.PDF for .NET, you can get the certificates in a PDF file through the PdfSignatureFieldWidget.Signature.Certificate property. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the form in the PDF document using PdfDocument.Form property, and then get a collection of form fields using PdfFormWidget.FieldsWidget property.
  • Iterate through all fields and get the signature fields.
  • Get the certificate of the signature using PdfSignatureFieldWidget.Signature.Certificate property.
  • Set to display the certificate in text format using PdfCertificate.ToString() method.
  • Get the format of the certificate using PdfCertificate.GetFormat() method.
  • Output the obtained certificate information.
  • C#
using Spire.Pdf;
using Spire.Pdf.Widget;

namespace GetSignatureCertificate
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a PDF file
            pdf.LoadFromFile("PDFSignature.pdf");

            //Get a collection of form fields in the PDF file
            PdfFormWidget pdfFormWidget = (PdfFormWidget)pdf.Form;
            PdfFormFieldWidgetCollection pdfFormFieldWidgetCollection = pdfFormWidget.FieldsWidget;

            //Iterate through all fields
            for (int i = 0; i < pdfFormFieldWidgetCollection.Count; i++)
            {
                //Get the signature fields
                if (pdfFormFieldWidgetCollection[i] is PdfSignatureFieldWidget)
                {
                    PdfSignatureFieldWidget signatureFieldWidget = (PdfSignatureFieldWidget)pdfFormFieldWidgetCollection[i];

                    //Get the certificate of the signature
                    string certificateInfo = signatureFieldWidget.Signature.Certificate.ToString();

                    //Get the format of the certificate
                    string format = signatureFieldWidget.Signature.Certificate.GetFormat();

                    //Output the certificate information
                    Console.WriteLine(certificateInfo + "\n" + "[CertificateFormat]\n " + format);
                }
            }
            Console.ReadKey();
        }
    }
}

C#: Verify or Get Digital Signatures in PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

HTML is the standard format for web pages and online content. However, there are many scenarios where you may need to convert HTML documents into other file formats, such as PDF, XPS, and XML. Whether you're looking to generate a printable version of a web page, share HTML content in a more universally accepted format, or extract data from HTML for further processing, being able to reliably convert HTML documents to these alternate formats is an important skill to have. In this article, we will demonstrate how to convert HTML to PDF, XPS, and XML in C# using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Convert HTML to PDF in C#

Converting HTML to PDF offers several advantages, including enhanced portability, consistent formatting, and easy sharing. PDF files retain the original layout, styling, and visual elements of the HTML content, ensuring that the document appears the same across different devices and platforms.

You can use the Document.SaveToFile(string filename, FileFormat.PDF) method to convert an HTML file to PDF format. The detailed steps are as follows.

  • Create an instance of the Document object.
  • Load an HTML file using the Document.LoadFromFile() method.
  • Save the HTML file to PDF format using the Document.SaveToFile(string filename, FileFormat.PDF) method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace ConvertHtmlToPdf
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the Document class
            Document doc = new Document();
            // Load an HTML file
            doc.LoadFromFile("Sample.html", FileFormat.Html, XHTMLValidationType.None);

            //Convert the HTML file to PDF format
            doc.SaveToFile("HtmlToPDF.pdf", FileFormat.PDF);
            doc.Close();
        }
    }
}

C#: Convert HTML to PDF, XPS and XML

Convert HTML String to PDF in C#

In addition to converting HTML files to PDF, you are also able to convert HTML strings to PDF. Spire.Doc for .NET provides the Paragraph.AppendHTML() method to add an HTML string to a Word document. Once the HTML string has been added, you can convert the result document to PDF using the Document.SaveToFile(string filename, FileFormat.PDF) method. The detailed steps are as follows.

  • Create an instance of the Document object.
  • Add a paragraph to the document using the Document.AddSection().AddParagraph() method.
  • Append an HTML string to the paragraph using the Paragraph.AppendHTML() method.
  • Save the document to PDF format using the Document.SaveToFile(string filename, FileFormat.PDF) method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace ConvertHtmlStringToPdf
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the Document class
            Document doc = new Document();
            // Add a paragraph to the document
            Paragraph para = doc.AddSection().AddParagraph();
            // Specify the HTML string
            string htmlString = @"<h1>This is a Heading</h1>
                                  <p>This is a paragraph.</p>
                                  <ul>
                                    <li>Item 1</li>
                                    <li>Item 2</li>
                                    <li>Item 3</li>
                                  </ul>";

            // Append the HTML string to the paragraph
            para.AppendHTML(htmlString);

            // Convert the document to PDF format
            doc.SaveToFile("HtmlStringToPDF.pdf", FileFormat.PDF);
            doc.Close();
        }
    }
}

C#: Convert HTML to PDF, XPS and XML

Convert HTML to XPS in C#

XPS, or XML Paper Specification, is an alternative format to PDF that provides similar functionality and advantages. Converting HTML to XPS ensures the preservation of document layout, fonts, and images while maintaining high fidelity. XPS files are optimized for printing and can be viewed using XPS viewers or Windows' built-in XPS Viewer.

By using the Document.SaveToFile(string filename, FileFormat.XPS) method, you can convert HTML files to XPS format with ease. The detailed steps are as follows.

  • Create an instance of the Document object.
  • Load an HTML file using the Document.LoadFromFile() method.
  • Save the HTML file to XPS format using the Document.SaveToFile(string filename, FileFormat.XPS) method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace ConvertHtmlToXps
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the Document class
            Document doc = new Document();
            // Load an HTML file
            doc.LoadFromFile("Sample.html", FileFormat.Html, XHTMLValidationType.None);

            //Convert the HTML file to XPS format
            doc.SaveToFile("HtmlToXPS.xps", FileFormat.XPS);
            doc.Close();
        }
    }
}

C#: Convert HTML to PDF, XPS and XML

Convert HTML to XML in C#

Converting HTML to XML unlocks the potential for data extraction, manipulation, and integration with other systems. XML is a flexible and extensible markup language that allows for structured representation of data. By converting HTML to XML, you can extract specific elements, organize data hierarchically, and perform data analysis or integration tasks using XML processing tools and techniques.

To convert HTML files to XML format, you can use the Document.SaveToFile(string filename, FileFormat.Xml) method. The detailed steps are as follows.

  • Create an instance of the Document object.
  • Load an HTML file using the Document.LoadFromFile() method.
  • Save the HTML file to XML format using the Document.SaveToFile(string filename, FileFormat.Xml) method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace ConvertHtmlToXml
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the Document class
            Document doc = new Document();
            // Load an HTML file
            doc.LoadFromFile("Sample.html", FileFormat.Html, XHTMLValidationType.None);

            //Convert the HTML file to XML format
            doc.SaveToFile("HtmlToXML.xml", FileFormat.Xml);
            doc.Close();
        }
    }
}

C#: Convert HTML to PDF, XPS and XML

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

PDF annotation tools allow you to highlight text, add sticky notes, draw shapes, and insert comments directly on PDF documents. This can be useful for providing feedback, taking notes, marking up designs, and collaborating on documents. Mastering PDF annotation features can streamline workflows and improve productivity when working with PDF files.

In this article, you will learn how to programmatically add various types of annotations to a PDF document using Spire.PDF for .NET in C#.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Add a Markup Annotation to PDF in C#

Markup annotation in PDF enables users to select and apply a colored background to emphasize or draw attention to specific text within the document.

Spire.PDF provides the PdfTextMarkupAnnotation class to work with this type of annotation. To add a markup annotation to PDF using Spire.PDF in C#, follow these steps.

  • Create a PdfDocument object.
  • Load a PDF document from the specified file path.
  • Get a specific page from the document.
  • Find the desired text from the page using the methods provided by the PdfTextFinder class.
  • Create a PdfTextMarkupAnnotation object based on the text found.
  • Add the annotation to the page using PdfPageBase.Annotations.Add() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.Annotations;
using Spire.Pdf;
using Spire.Pdf.Texts;
using System.Drawing;

namespace AddMarkupAnnotation
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // Get a specific page
            PdfPageBase page = doc.Pages[0];

            // Create a PdfTextFinder object based on the page
            PdfTextFinder finder = new PdfTextFinder(page);

            // Set the find options
            finder.Options.Parameter = TextFindParameter.WholeWord;
            finder.Options.Parameter = TextFindParameter.IgnoreCase;

            // Find the instances of the specified text
            List<PdfTextFragment> fragments = finder.Find("In order to help make the Site a secure environment" +
                " for the purchase and sale of Marketplace Offerings, all users are required to accept and " +
                "comply with these Terms of Service.");

            // Get the first instance
            PdfTextFragment textFragment = fragments[0];

            // Specify annotation text
            String text = "There is a markup annotation added by Spire.PDF for .NET.";

            // Iterate through the bounds of the found text
            for (int i = 0; i < textFragment.Bounds.Length; i++)
            {
                // Get a specific bound
                RectangleF rect = textFragment.Bounds[i];

                // Create a text markup annotation
                PdfTextMarkupAnnotation annotation = new PdfTextMarkupAnnotation("Administrator", text, rect);

                // Set the markup color
                annotation.TextMarkupColor = Color.Green;

                // Add the annotation to the collection of the annotations
                page.Annotations.Add(annotation);
            }

            // Save result to file
            doc.SaveToFile("AddMarkups.pdf");

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add Various Types of Annotations to PDF

Add a Free Text Annotation to PDF in C#

Free Text Annotation in PDF files enables users to add handwritten-like or typed text directly onto the document, similar to taking notes on a printed document.

Spire.PDF provides the PdfFreeTextAnnotation to work with the free text annotations in PDF. Here is how you can use to create one in a PDF document.

  • Create a PdfDocument object.
  • Load a PDF document from the specified file path.
  • Get a specific page from the document.
  • Find the desired text from the page using the methods provided by the PdfTextFinder class.
  • Specify the x and y coordinates to add annotation.
  • Create a PdfFreeTextAnnotation object, and set its properties like text, font, border and color.
  • Add the annotation to the page using PdfPageBase.Annotations.Add() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.Annotations;
using Spire.Pdf.Texts;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace AddFreeTextAnnotation
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // Get a specific page
            PdfPageBase page = doc.Pages[0];

            // Create a PdfTextFinder object based on the page
            PdfTextFinder finder = new PdfTextFinder(page);

            // Set the find options
            finder.Options.Parameter = TextFindParameter.WholeWord;
            finder.Options.Parameter = TextFindParameter.IgnoreCase;

            // Find the instances of the specified text
            List<PdfTextFragment> fragments = finder.Find("Marketplace Offerings");

            // Get the first instance
            PdfTextFragment textFragment = fragments[0];

            // Get the text bound
            RectangleF rect = textFragment.Bounds[0];

            // Get the x and y coordinates to add annotation
            float x = rect.Right;
            float y = rect.Bottom;

            // Create a free text annotation
            RectangleF rectangle = new RectangleF(x, y, 130, 30);
            PdfFreeTextAnnotation textAnnotation = new PdfFreeTextAnnotation(rectangle);

            // Set the content of the annotation
            textAnnotation.Text = "There is a free text annotation\radded by Spire.PDF for .NET.";

            // Set other properties of annotation
            PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 10f, PdfFontStyle.Bold);
            PdfAnnotationBorder border = new PdfAnnotationBorder(1f);
            textAnnotation.Font = font;
            textAnnotation.Border = border;
            textAnnotation.BorderColor = Color.Purple;
            textAnnotation.Color = Color.Green;
            textAnnotation.Opacity = 1.0f;

            // Add the annotation to the collection of the annotations
            page.Annotations.Add(textAnnotation);

            // Save result to file
            doc.SaveToFile("FreeTextAnnotation.pdf");

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add Various Types of Annotations to PDF

Add a Popup Annotation to PDF in C#

Popup Annotation in PDF files allows users to attach a small label or comment that pops up when clicked, revealing additional information or a short message.

Spire.PDF offers the PdfPopupAnnotation class to work with the popup annotation in PDF. The following are the steps to add a popup annotation to PDF using it.

  • Create a PdfDocument object.
  • Load a PDF document from the specified file path.
  • Get a specific page from the document.
  • Find the desired text from the page using the methods provided by the PdfTextFinder class.
  • Specify the x and y coordinates to add annotation.
  • Create a PdfPopupAnnotation object, and set its properties like text, icon and color.
  • Add the annotation to the page using PdfPageBase.Annotations.Add() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.Annotations;
using Spire.Pdf.Texts;
using Spire.Pdf;
using System.Drawing;

namespace AddPopupAnnotation
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // Get a specific page
            PdfPageBase page = doc.Pages[0];

            // Create a PdfTextFinder object based on the page
            PdfTextFinder finder = new PdfTextFinder(page);

            // Set the find options
            finder.Options.Parameter = TextFindParameter.WholeWord;
            finder.Options.Parameter = TextFindParameter.IgnoreCase;

            // Find the instances of the specified text
            List<PdfTextFragment> fragments = finder.Find("Marketplace Offerings");

            // Get the first instance
            PdfTextFragment textFragment = fragments[0];

            // Get the text bound
            RectangleF textBound = textFragment.Bounds[0];

            // Get the x and y coordinates to add annotation
            float x = textBound.Right + 5;
            float y = textBound.Top - 15;

            // Create a popup annotation
            RectangleF rectangle = new RectangleF(x, y, 30, 30);
            PdfPopupAnnotation popupAnnotation = new PdfPopupAnnotation(rectangle);
            
            // Set the annotation text
            popupAnnotation.Text = "There is a popup annotation\radded by Spire.PDF for .NET.";

            // Set the icon and color of the annotation
            popupAnnotation.Icon = PdfPopupIcon.Comment;
            popupAnnotation.Color = Color.Red;

            // Add the annotation to the collection of the annotations
            page.Annotations.Add(popupAnnotation);

            // Save result to file
            doc.SaveToFile("PopupAnnotation.pdf");

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add Various Types of Annotations to PDF

Add a Shape Annotation to PDF in C#

Shape Annotation in PDF refers to the ability to add graphical shapes such as rectangles, circles, lines, or arrows onto a PDF document to highlight or provide additional information.

Spire.PDF offers the PdfPolyLineAnnotation class that allows the user to create a custom shape annotation in a PDF document. Here are the detailed steps.

  • Create a PdfDocument object.
  • Load a PDF document from the specified file path.
  • Get a specific page from the document.
  • Find the desired text from the page using the methods provided by the PdfTextFinder class.
  • Specify the coordinates to add annotation.
  • Create a PdfPloyLineAnnotation object, and set the text of the annotation.
  • Add the annotation to the page using PdfPageBase.Annotations.Add() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.Annotations;
using Spire.Pdf.Texts;
using Spire.Pdf;
using System.Drawing;

namespace AddShapeAnnotation
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // Get a specific page
            PdfPageBase page = doc.Pages[0];

            // Create a PdfTextFinder object based on the page
            PdfTextFinder finder = new PdfTextFinder(page);

            // Set the find options
            finder.Options.Parameter = TextFindParameter.WholeWord;
            finder.Options.Parameter = TextFindParameter.IgnoreCase;

            // Find the instances of the specified text
            List<PdfTextFragment> fragments = finder.Find("Marketplace Offerings");

            // Get the first instance
            PdfTextFragment textFragment = fragments[0];

            // Get the text bound
            RectangleF textBound = textFragment.Bounds[0];

            // Get the coordinates to add annotation
            float left = textBound.Left;
            float top = textBound.Top;
            float right = textBound.Right;
            float bottom = textBound.Bottom;

            // Create a shape nnotation
            PdfPolyLineAnnotation polyLineAnnotation = new PdfPolyLineAnnotation(page, new PointF[] { 
                new PointF(left, top), new PointF(right, top), new PointF(right - 5, bottom), new PointF(left - 5, bottom), new PointF(left, top) });

            // Set the annotation text
            polyLineAnnotation.Text = "There is a shape annotation\radded by Spire.PDF for .NET.";

            // Add the annotation to the collection of the annotations
            page.Annotations.Add(polyLineAnnotation);

            // Save result to file
            doc.SaveToFile("ShapeAnnotation.pdf");

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add Various Types of Annotations to PDF

Add a Web Link Annotation to PDF in C#

Web Link Annotation in PDF documents allows users to embed hyperlinks that direct readers to websites when clicked.

Spire.PDF provides the PdfUrlAnnotation class to represent a web link annotation. The following are the steps to add a web link annotation using it.

  • Create a PdfDocument object.
  • Load a PDF document from the specified file path.
  • Get a specific page from the document.
  • Find the desired text from the page using the methods provided by the PdfTextFinder class.
  • Create a PdfUrlAnnotation object based on the text found.
  • Add the annotation to the page using PdfPageBase.Annotations.Add() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.Annotations;
using Spire.Pdf.Texts;
using Spire.Pdf;
using System.Drawing;

namespace AddUrlAnnotation
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // Get a specific page
            PdfPageBase page = doc.Pages[0];

            // Create a PdfTextFinder object based on the page
            PdfTextFinder finder = new PdfTextFinder(page);

            // Set the find options
            finder.Options.Parameter = TextFindParameter.WholeWord;
            finder.Options.Parameter = TextFindParameter.IgnoreCase;

            // Find the instances of the specified text
            List<PdfTextFragment> fragments = finder.Find("Marketplace Offerings");

            // Get the first instance
            PdfTextFragment textFragment = fragments[0];

            // Get the text bound
            RectangleF textBound = textFragment.Bounds[0];

            // Create a Url annotation
            PdfUriAnnotation urlAnnotation = new PdfUriAnnotation(textBound, "https://www.e-iceblue.com/");

            // Add the annotation to the collection of the annotations
            page.Annotations.Add(urlAnnotation);

            // Save result to file
            doc.SaveToFile("UrlAnnotation.pdf");

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add Various Types of Annotations to PDF

Add a File Link Annotation to PDF in C#

File link annotation in PDF documents refers to interactive links that allow users to navigate to external files directly from the PDF.

Spire.PDF offers the PdfFileLinkAnnotation class to work with the file link annotation. Here are the steps to add a file link annotation to a PDF document using it.

  • Create a PdfDocument object.
  • Load a PDF document from the specified file path.
  • Get a specific page from the document.
  • Find the desired text from the page using the methods provided by the PdfTextFinder class.
  • Create a PdfFileLinkAnnotation object based on the text found.
  • Add the annotation to the page using PdfPageBase.Annotations.Add() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.Annotations;
using Spire.Pdf.Texts;
using Spire.Pdf;
using System.Drawing;

namespace AddFileLinkAnnotation
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // Get a specific page
            PdfPageBase page = doc.Pages[0];

            // Create a PdfTextFinder object based on the page
            PdfTextFinder finder = new PdfTextFinder(page);

            // Set the find options
            finder.Options.Parameter = TextFindParameter.WholeWord;
            finder.Options.Parameter = TextFindParameter.IgnoreCase;

            // Find the instances of the specified text
            List<PdfTextFragment> fragments = finder.Find("Marketplace Offerings");

            // Get the first instance
            PdfTextFragment textFragment = fragments[0];

            // Get the text bound
            RectangleF textBound = textFragment.Bounds[0];

            // Create a file link annotation
            PdfFileLinkAnnotation fileLinkAnnotation = new PdfFileLinkAnnotation(textBound, "C:\\Users\\Administrator\\Desktop\\Report.docx");

            // Add the annotation to the collection of the annotations
            page.Annotations.Add(fileLinkAnnotation);

            // Save result to file
            doc.SaveToFile("FileLinkAnnotation.pdf");

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add Various Types of Annotations to PDF

Add a Document Link Annotation to PDF in C#

Document link annotation in PDF files refers to hyperlinks that allow users to navigate between different pages or sections within the same PDF document.

Spire.PDF offers the PdfDocumentLinkAnnotation class to work with the document link annotation. Here are the steps to add a document link annotation to a PDF document using it.

  • Create a PdfDocument object.
  • Load a PDF document from the specified file path.
  • Get a specific page from the document.
  • Find the desired text from the page using the methods provided by the PdfTextFinder class.
  • Create a PdfDocumentLinkAnnotation object based on the text found.
  • Add the annotation to the page using PdfPageBase.Annotations.Add() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.Annotations;
using Spire.Pdf.Texts;
using Spire.Pdf;
using Spire.Pdf.General;
using System.Drawing;

namespace AddDocumentLinkAnnotation
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // Get a specific page
            PdfPageBase page = doc.Pages[0];

            // Create a PdfTextFinder object based on the page
            PdfTextFinder finder = new PdfTextFinder(page);

            // Set the find options
            finder.Options.Parameter = TextFindParameter.WholeWord;
            finder.Options.Parameter = TextFindParameter.IgnoreCase;

            // Find the instances of the specified text
            List<PdfTextFragment> fragments = finder.Find("Marketplace Offerings");

            // Get the first instance
            PdfTextFragment textFragment = fragments[0];

            // Get the text bound
            RectangleF textBound = textFragment.Bounds[0];

            // Create a document link annotation
            PdfDocumentLinkAnnotation documentLinkAnnotation = new PdfDocumentLinkAnnotation(textBound);
     
            // Set the destination of the annotation
            documentLinkAnnotation.Destination = new PdfDestination(doc.Pages[1]);

            // Add the annotation to the collection of the annotations
            page.Annotations.Add(documentLinkAnnotation);

            // Save result to file
            doc.SaveToFile("DocumentLinkAnnotation.pdf");

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add Various Types of Annotations to PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Extracting image from PDF is not a complex operation, but sometimes we need to save the image to new PDF file. So the article describes the simple c# code to extract image from PDF and save it to new PDF file through a professional PDF .NET library Spire.PDF.

First we need to complete the preparatory work before the procedure:

  • Download the Spire.PDF and install it on your machine.
  • Add the Spire.PDF.dll files as reference.
  • Open bin folder and select the three dll files under .NET 4.0.
  • Right click property and select properties in its menu.
  • Set the target framework as .NET 4.
  • Add Spire.PDF as namespace.

The following steps will show you how to do this with ease:

Step 1: Create a PDF document.

[C#]
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"..\..\Sample.pdf");

Step 2: Extract the image from PDF document.

[C#]
doc.ExtractImages();

Step 3: Save image file.

[C#]
image.Save("image.png",System.Drawing.Imaging.ImageFormat.Png);
PdfImage image2 = PdfImage.FromFile(@"image.png");
PdfDocument doc2=new PdfDocument ();
PdfPageBase page=doc2.Pages.Add();

Step 4: Draw image to new PDF file.

[C#]
float width = image.Width * 0.75f;
float height = image.Height * 0.75f;
float x = (page.Canvas.ClientSize.Width - width) / 2;
page.Canvas.DrawImage(image2,x,60,width,height);
doc2.SaveToFile(@"..\..\Image.pdf");

Here is the whole code:

[C#]
static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"..\..\Sample.pdf");
            doc.ExtractImages();
            image.Save("image.png",System.Drawing.Imaging.ImageFormat.Png);
            PdfImage image2 = PdfImage.FromFile(@"image.png");
            PdfDocument doc2=new PdfDocument ();
            PdfPageBase page=doc2.Pages.Add();
            float width = image.Width * 0.75f;
            float height = image.Height * 0.75f;
            float x = (page.Canvas.ClientSize.Width - width) / 2;
            page.Canvas.DrawImage(image2,x,60,width,height);
            doc2.SaveToFile(@"..\..\Image.pdf");
        }

Here comes to the preview of the effect picture:

extract image from pdf

draw image to new pdf

We have already demonstrated how to create form field. This article mainly shows you how developers fill form field in word document in C# only with 4 simple steps by using a standalone .NET Word component Spire.Doc.

Make sure Spire.Doc for .NET has been installed correctly and then add Spire.Doc.dll as reference in the downloaded Bin folder thought the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll". Here comes to the details of how developers Fill Form Field by using Spire.Doc:

Step 1: Open the form that needs to fill the data.

[C#]
//Create word document
Document document = new Document(@"..\..\..\Data\UserForm.doc");

Step 2: Load data that will fill the form.

[C#]
//Fill data from XML file
using (Stream stream = File.OpenRead(@"..\..\..\Data\User.xml"))
{
    XPathDocument xpathDoc = new XPathDocument(stream);
    XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode("/user");

Step 3: Use the loaded data to fill the form.

[C#]
//fill data
  foreach (FormField field in document.Sections[0].Body.FormFields)
  {
     String path = String.Format("{0}/text()", field.Name);
     XPathNavigator propertyNode = user.SelectSingleNode(path);
     if (propertyNode != null)
     {
         switch (field.Type)
         {
             case FieldType.FieldFormTextInput:
                  field.Text = propertyNode.Value;
                  break;

             case FieldType.FieldFormDropDown:
                  DropDownFormField combox = field as DropDownFormField;
                  for(int i = 0; i < combox.DropDownItems.Count; i++)
                  {
                      if (combox.DropDownItems[i].Text == propertyNode.Value)
                      {
                         combox.DropDownSelectedIndex = i;
                         break;
                      }
                      if (field.Name == "country" && combox.DropDownItems[i].Text == "Others")
                      {
                         combox.DropDownSelectedIndex = i;
                      }
                  }
                  break;

             case FieldType.FieldFormCheckBox:
                  if (Convert.ToBoolean(propertyNode.Value))
                  {
                      CheckBoxFormField checkBox = field as CheckBoxFormField;
                      checkBox.Checked = true;
                  }
                  break;
            }
       }
   }
 }

Step 4: Save the document to file in XML or Microsoft Word format.

[C#]
//Save doc file
document.SaveToFile("Sample.doc",FileFormat.Doc);

Effective Screenshot:

Fill FormField

Full Source Code for Fill FormField:

[C#]
namespace FillFormField
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //open form
            Document document = new Document(@"..\..\..\..\..\..\Data\UserForm.doc");

            //load data
            using (Stream stream = File.OpenRead(@"..\..\..\..\..\..\Data\User.xml"))
            {
                XPathDocument xpathDoc = new XPathDocument(stream);
                XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode("/user");

                //fill data
                foreach (FormField field in document.Sections[0].Body.FormFields)
                {
                    String path = String.Format("{0}/text()", field.Name);
                    XPathNavigator propertyNode = user.SelectSingleNode(path);
                    if (propertyNode != null)
                    {
                        switch (field.Type)
                        {
                            case FieldType.FieldFormTextInput:
                                field.Text = propertyNode.Value;
                                break;

                            case FieldType.FieldFormDropDown:
                                DropDownFormField combox = field as DropDownFormField;
                                for(int i = 0; i < combox.DropDownItems.Count; i++)
                                {
                                    if (combox.DropDownItems[i].Text == propertyNode.Value)
                                    {
                                        combox.DropDownSelectedIndex = i;
                                        break;
                                    }
                                    if (field.Name == "country" && combox.DropDownItems[i].Text == "Others")
                                    {
                                        combox.DropDownSelectedIndex = i;
                                    }
                                }
                                break;

                            case FieldType.FieldFormCheckBox:
                                if (Convert.ToBoolean(propertyNode.Value))
                                {
                                    CheckBoxFormField checkBox = field as CheckBoxFormField;
                                    checkBox.Checked = true;
                                }
                                break;
                        }
                    }
                }
            }

            //Save doc file.
            document.SaveToFile("Sample.doc",FileFormat.Doc);

            //Launching the MS Word file.
            WordDocViewer("Sample.doc");
        }

        private void WordDocViewer(string fileName)
        {
            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch { }
        }

    }
}
page 62