How to Start Tutorials Troubleshooting Main Operations Convert PDF Read PDF Edit PDF PDF Report Generator Work with PDF Modules PDF Document PDF Pages Text Image Graph & Path Annotation, Markup & Drawing Redaction Security Digital Signature Forms Watermark Bookmark Link File Attachment File Metadata Printing Work with Other SDKs Barcode read Barcode create OCR Twain

C# PDF Editor Library
How to edit a PDF file using C# in ASP.NET Core web, windows application?


Detailed C# tutorials to edit PDF document, pages, contents in ASP.NET Core, Windows applications



Introduction



XDoc.PDF C# library includes many PDF editing functions to help .NET developers quickly build PDF editor Windows application or ASP.NET Core web app.

In this C# tutorial article, we will show you some of the major PDF editing features with C#.NET sample source codes and detailed explanations.

After reading the article, you will know how to edit PDF files with adding text, image, markup, password, signature, editing pages, document metadata in your .NET C# web or Windows applications using XDoc.PDF library.



Install XDoc.PDF library



It is an easy job to download and install XDoc.PDF for .NET for your .NET Core or .NET Framework projects. Please view the details at Download and Install XDoc.PDF C# PDF Editor library



Edit PDF document



Merge and split

Merge and split PDF file using C# are common operations to process PDF document in C# ASP.NET Core and Windows application. You could easily combining PDFs into one PDF file or seperating an existing PDF into multiple ones using XDoc.PDF .net library.

            PDFDocument doc1 = new PDFDocument(@"C:\1.pdf");
            PDFDocument doc2 = new PDFDocument(@"C:\2.pdf");

            doc1.AppendDocument(doc2);

            doc1.Save(@"C:\merged-pdf-file.pdf");


            List<String> outputFilePaths = new List<String>() { @"C:\output-file_0.pdf", @"C:\output-file_1.pdf" };

            PDFDocument.SplitDocument(@"C:\test-file.pdf", 1, outputFilePaths.ToArray());


Compress PDF

XDoc.PDF supports several methods to compress a PDF file.

  • Image compression. It is the most important and effiecient way to reduce the PDF file size.
  • Remove unused objects. It will delete all unused objects inside the PDF document, including form data, Javascript actions, all alternate images.
  • Remove user data. It will delete all acroform fields, mulitmedia, metadata information
  • Document clean up. All invalid data, such as bookmarks, links, will be removed.

            //  create optimizing options
            PDFOptimizeOptions ops = new PDFOptimizeOptions();

            //  Enable image optimization
            ops.EnableImagesOptimization = true;

            //  -- Options for Monochrome Image --
            //  to enable downsampling for those images with resolution higher than 300 dpi to 150 dpi
            ops.MonochromeImageOptions.DownsampleMode = ImageDownsampleMode.Bicubic;
            ops.MonochromeImageOptions.MaxResolutionLimit = 300F;
            ops.MonochromeImageOptions.TargetResolution = 150F;
            //  to change image compression mode to JBIG2
            ops.MonochromeImageOptions.KeepCompressionMode = false;
            ops.MonochromeImageOptions.Compression = PDFCompression.JBIG2Decode;

            //  -- Options for Grayscale Image --
            //  to enable downsampling for those images with resolution higher than 120 dpi to 96 dpi
            ops.GrayscaleImageOptions.DownsampleMode = ImageDownsampleMode.Bilinear;
            ops.GrayscaleImageOptions.MaxResolutionLimit = 120F;
            ops.GrayscaleImageOptions.TargetResolution = 96F;
            //  to change image compression mode to DCT
            ops.GrayscaleImageOptions.KeepCompressionMode = false;
            ops.GrayscaleImageOptions.Compression = PDFCompression.DCTDecode;
            //  set quality level, only available for compression mode DCT
            ops.GrayscaleImageOptions.JPEGImageQualityLevel = JPEGImageQualityLevel.High;

            //  -- Options for Color Image --
            //  to enable downsampling for those images with resolution higher than 120 dpi to 96 dpi
            ops.ColorImageOptions.DownsampleMode = ImageDownsampleMode.Bicubic;
            ops.ColorImageOptions.MaxResolutionLimit = 120F;
            ops.ColorImageOptions.TargetResolution = 96F;
            //  to change image compression mode to DCT
            ops.ColorImageOptions.KeepCompressionMode = false;
            ops.ColorImageOptions.Compression = PDFCompression.DCTDecode;
            //  set quality level, only available for compression mode DCT
            ops.ColorImageOptions.JPEGImageQualityLevel = JPEGImageQualityLevel.Highest;

            //  apply optimizing
            PDFOptimizer.Optimize(@"C:\test-file.pdf", @"C:\test-file-compressed.pdf", ops);


View more PDF compression source code here: How to compress PDF to reduce file size using C#?



Edit metadata

The C# source code below shows how to edit PDF file metadata informtion in C# application. You could modify the PDF author name, create and last modified datae time using C# code.

            // Update PDF document metadata.
            PDFMetadata metadata = new PDFMetadata();
            metadata.Title = "Title";
            metadata.Author = "Qi";
            metadata.Subject = "None";
            metadata.Keywords = "University, Public, etc.";
            metadata.Creator = "MS Office Word";
            metadata.Producer = "RE";
            metadata.CreatedDate = new DateTime(2014, 11, 21, 10, 45, 12);
            metadata.ModifiedDate = new DateTime(2015, 11, 21, 10, 45, 12);

            String inputFilePath = @"C:\demo.pdf";
            String outputFilePath = @"C:\output.pdf";
            PDFDocument doc = new PDFDocument(inputFilePath);

            doc.SetDescription(metadata);
            doc.Save(outputFilePath);


Protect PDF

String intputFilePath = Program.RootPath + "\\" + "1.pdf";
String outputFilePath = Program.RootPath + "\\" + "1_with_pw.pdf";
String userPassword = "you";
String ownerPassword = "me";
//  create password setting
PasswordSetting setting = new PasswordSetting(userPassword, ownerPassword);
//  add password to plain file
int errorCode = PDFDocument.AddPassword(intputFilePath, outputFilePath, setting);
if (errorCode == 0)
{
    Console.WriteLine("Success");
}
else
{
    Console.WriteLine("Failed");
}


Digital Signatures

            String inputFilePath = @"...";
            String outputFilePath = @"...";
            String imagePath = @"...";
            String certSubjectName = @"...";
            String fieldID = @"...";

            X509Cert cert = PDFDigitalSignatureHandler.MakeCert(StoreName.My, StoreLocation.CurrentUser, certSubjectName);

            // Set cert properties.
            cert.Location = "CHINA SHANGHAI";
            cert.Reason = "Reason";
            cert.APMode = APMode.Text; // APMode.Text | APMode.Image.
            cert.Image = new Bitmap(imagePath);

            if (PDFDigitalSignatureHandler.Sign(inputFilePath, outputFilePath, cert, fieldID) == 0)
            {
                Console.WriteLine("[SUCCESS]");
            }
            else
            {
                Console.WriteLine("[FAILED]");
            }


File Attachment

XDoc.PDF C# library allows you to easily add and remove attached files to or from an existing PDF document.

String inputFilePath = Program.RootPath + "\\" + "2.pdf";
String outputFilePath = Program.RootPath + "\\" + "Annot_7.pdf";

//  open a PDF file
PDFDocument doc = new PDFDocument(inputFilePath);
//  get the 1st page
PDFPage page = (PDFPage)doc.GetPage(0);

{
    //  create the annotation
    PDFAnnotFileAttach annot = new PDFAnnotFileAttach();

    annot.Position = new PointF(100F, 100F);
    annot.FilePath = @"C:\AttachmentFile.txt";

    //  add annotation to the page
    PDFAnnotHandler.AddAnnotation(page, annot);
}

//  save to a new file
doc.Save(outputFilePath);




Manipulate PDF pages



You could easily add, insert PDF pages to specific index, copy, paste a page, resite or rotate pages, and delete pages from an existing PDF file.

Resize page size

String inputFilePath = @"C:\1.pdf";
String outputFilePath = @"C:\output.pdf";

//  Open file and get the target page
PDFDocument doc = new PDFDocument(inputFilePath);
PDFPage page = (PDFPage)doc.GetPage(0);

float[] bbox = page.GetPageBoundary(PDFPageBoundaryType.MediaBox);
//  Add (or update) bleed box.
page.SetPageBoundary(PDFPageBoundaryType.BleedBox, bbox[0] + 20, bbox[1] + 20, bbox[2] - 50, bbox[3] - 60);
//  Add (or update) trim box.
page.SetPageBoundary(PDFPageBoundaryType.TrimBox, bbox[0] + 60, bbox[1] + 40, bbox[2] - 100, bbox[3] - 160);
//  Add (or update) art box.
page.SetPageBoundary(PDFPageBoundaryType.ArtBox, bbox[0] + 90, bbox[1] + 50, bbox[2] - 150, bbox[3] - 260);

//  Save file
doc.Save(outputFilePath);


Add page

            String filepath = @"";
            String outPutFilePath = @"";
            PDFDocument doc = new PDFDocument(filepath);

            // Insert an empty page at 2 (previous to the third page).
            doc.AddEmptyPage(2, PaperSize.A4);

            // Save the file.
            doc.Save(outPutFilePath);


Copy, paste page

            // Copy three pages from test1.pdf and paste into test2.pdf.
            PDFDocument pdf = new PDFDocument(@"C:\test1.pdf");
            PDFDocument pdf2 = new PDFDocument(@"C:\test2.pdf");
            int[] pageindexes = new int[] { 1, 2, 4 };
            BasePage[] pages = pdf.DuplicatePages(pageindexes);
            pdf2.InsertPages(pages, 2);


Delete page

            String filepath = @"";
            String outPutFilePath = @"";
            PDFDocument doc = new PDFDocument(filepath);

            // Detele page 2 (actually the third page).
            doc.DeletePage(2);

            // Save the file.
            doc.Save(outPutFilePath);


Replace page

            //  load the PDF file that provides the page object 
            String resFilePath = @"C:\2.pdf";
            PDFDocument resDoc = new PDFDocument(resFilePath);
            //  get the 1st page in the document
            PDFPage page = (PDFPage)resDoc.GetPage(0);

            //  get PDFDocument object from a source file
            String inputFilePath = @"C:\1.pdf";
            PDFDocument doc = new PDFDocument(inputFilePath);
            //  replace the 3rd page by the PDFPage object
            int pageIndex = 2;
            doc.UpdatePage(page, pageIndex);

            //  save the PDFDocument
            String outputFilePath = @"C:\Output.pdf";
            doc.Save(outputFilePath);


Rotate page

            String inputFilePath = @"C:\1.pdf";
            String outputFilePath = @"C:\Output.pdf";

            // Specify the first page to be rotated.
            int pageIndex = 0;

            // Rotate 180 in clockwise.
            int rotateInDegree = 180;

            // Rotate the selected page.
            PDFDocument.RotatePage(inputFilePath, pageIndex, rotateInDegree, outputFilePath);


Crop page

String inputFilePath = Program.RootPath + "\\" + "1.pdf";
String outputFilePath = Program.RootPath + "\\" + "1_new.pdf";

//  open the file
PDFDocument doc = new PDFDocument(inputFilePath);
//  get the 2nd page
PDFPage page = (PDFPage)doc.GetPage(1);
//  set crop region: start point (100, 100), width = 300, height = 400
RectangleF cropArea = new RectangleF(100, 100, 300, 400);
//  crop the page
page.Crop(cropArea);

//  output the new document
doc.Save(outputFilePath);




Edit PDF Content



You can easily add, edit, remove text, image, header & footer, background, bookmarks and watermark on an existing PDF document using C#.

Add text

//  open a document
String inputFilePath = Program.RootPath + "\\" + "1.pdf";
PDFDocument doc = new PDFDocument(inputFilePath);
//  get a text manager from the document object
PDFTextMgr textMgr = PDFTextHandler.ExportPDFTextManager(doc);

//  set string value
String msg = "Hello World";
//  set text font
Font font = new Font("Arial", 36F, FontStyle.Italic);
//  get the first page from the document
int pageIndex = 0;
//  move cursor to (400F, 100F)
PointF cursor = new PointF(400F, 100F);
//  set font color: red
Color fontColor = Color.Red;

//  add a string to the page
textMgr.AddString(msg, font, pageIndex, cursor, fontColor);

//  output the new document
String outputFilePath = Program.RootPath + "\\" + "output.pdf";
doc.Save(outputFilePath);


Search, remove, replace text

String inputFilePath = @"C:\1.pdf";
String outputFilePath = @"C:\output.pdf";

//  Open file
PDFDocument doc = new PDFDocument(inputFilePath);

//  Search text "RasterEdge"
String matchString = "RasterEdge";
//  Set search option
RESearchOption searchOps = new RESearchOption();
searchOps.MatchString = matchString;
searchOps.IgnoreCase = true;
searchOps.WholeWord = false;
searchOps.ContextExpansion = 0;
//  Set search range (from page 1 to 3)
int pageOffset = 0;
int pageCount = 3;

//  New string to replace the old value.
String replaceText = "[Replace]";
//  Set replace text settings
PDFDocument.TextReplaceOption replaceOps = new PDFDocument.TextReplaceOption();
replaceOps.TextFont = new System.Drawing.Font("Arial", 16F, FontStyle.Regular);
replaceOps.TextColor = System.Drawing.Color.Red;
//  Apply string replacing
doc.Replace(matchString, replaceText, searchOps, pageOffset, pageCount, replaceOps);

//  Save file
doc.Save(outputFilePath);


Add image

String inputFilePath = Program.RootPath + "\\" + "1.pdf";
String outputFilePath = Program.RootPath + "\\" + "output.pdf";

//  load a sample image
Bitmap anImage = new Bitmap(Program.RootPath + "\\" + "1.png");

//  open the document
PDFDocument doc = new PDFDocument(inputFilePath);
//  get the first page
PDFPage page = (PDFPage)doc.GetPage(0);
//  set image position in the page: X = 100F, Y = 400F
PointF position = new PointF(100F, 400F);

//  add image to the page
PDFImageHandler.AddImage(page, anImage, position);

//  output the new document
doc.Save(outputFilePath);


Remove image

String inputFilePath = Program.RootPath + "\\" + "3.pdf";
String outputFilePath = Program.RootPath + "\\" + "output.pdf";

//  open the document
PDFDocument doc = new PDFDocument(inputFilePath);
//  extract all images from the document
List<PDFImage> allImages = PDFImageHandler.ExtractImages(doc);
//  delete all images from the document
foreach (PDFImage image in allImages)
{
    PDFImageHandler.DeleteImage(doc, image);
}

//  output the new document
doc.Save(outputFilePath);


Copy, paste image

String inputFilePath = Program.RootPath + "\\" + "2.pdf";
String outputFilePath = Program.RootPath + "\\" + "output.pdf";

PDFDocument doc = new PDFDocument(inputFilePath);

//  get the first page
int pageIndex = 0;
PDFPage page1 = (PDFPage)doc.GetPage(pageIndex);

//  select image at the position (480F, 550F) in the page
PointF cursorPos = new PointF(480F, 550F);
PDFImage image = PDFImageHandler.SelectImage(page1, cursorPos);

//  copy the image
Bitmap anImage = (Bitmap)image.Image.Clone();

//  get the second page
PDFPage page2 = (PDFPage)doc.GetPage(1);
//  set image position in the page: X = 100F, Y = 400F
PointF position = new PointF(100F, 400F);

//  add image to the page
PDFImageHandler.AddImage(page2, anImage, position);

//  output the new document
doc.Save(outputFilePath);


Edit header & footer

    //  define a header/footer setting
    PDFPageHeaderFooter hdrftr1 = new PDFPageHeaderFooter();
    //  set center header field
    hdrftr1.CenterHeaderField.Set(@"Title: *****", new Font("Arial", 12F, FontStyle.Regular), Color.Black);
    //  set left footer field
    hdrftr1.LeftFooterField.Set("Page <<1/n>>", new Font("Arial", 9F, FontStyle.Regular), Color.DarkGray);

    //  define page range: all odd pages
    PageRangeOptions pageRange1 = new PageRangeOptions();
    pageRange1.AllPages = true;
    pageRange1.Subset = PageRangeSubset.Odd;

    //  apply header/footer settings to all odd pages
    PDFPageFieldHandler.ApplyHeaderFooter(doc, hdrftr1, pageRange1);


Edit background

    //  define a page background setting
    PDFPageBackground background1 = new PDFPageBackground(resBackground);
    background1.Opacity = 0.2F;

    //  define page range: all odd pages
    PageRangeOptions pageRange1 = new PageRangeOptions();
    pageRange1.AllPages = true;
    pageRange1.Subset = PageRangeSubset.Odd;

    //  apply page background settings to all odd pages
    PDFPageFieldHandler.ApplyBackground(doc, background1, pageRange1);


Edit bookmarks and outlines

String inputFilePath = Program.RootPath + "\\" + "2.pdf";
String outputFilePath = Program.RootPath + "\\" + "Output_Outline.pdf";
PDFDocument doc = new PDFDocument(inputFilePath);

//  initial a new outline object
REOutline outline = new REOutline();

//  create 1st entry: Level = 1; Location: page index 0, y = 50
OutLine entryChapter1 = new OutLine("Chapter 1: *******", 1, 0, 50);
//  add 1st entry to outline
outline.Entry.Add(entryChapter1);

//  create 1st entry's child entries
//  create 1st child entry: Level = 2; Location: page index 1, y = 0
OutLine entryChapter11 = new OutLine("###### #### #### #### ###", 2, 1, 0);
//  connect this entry to the parent entry
entryChapter11.SetParentREEntry(entryChapter1);
//  add 1st child of 1st entry to outline
outline.Entry.Add(entryChapter11);

//  create 2nd child entry: Level = 2; Location: page index 2, y = 0
OutLine entryChapter12 = new OutLine("## ## ## ## ## #### ###", 2, 2, 0);
//  connect this entry to the parent entry
entryChapter12.SetParentREEntry(entryChapter1);
//  add 2nd child of 1st entry to outline
outline.Entry.Add(entryChapter12);

//  create 2nd entry: Level = 1; Location: page index 3, y = 100
OutLine entryChapter2 = new OutLine("Chapter 2: ******* ****", 1, 3, 100);
//  add 2nd entry to outline
outline.Entry.Add(entryChapter2);

//  create 3rd entry: Level = 1; Location: page index 5, y = 200
OutLine entryChapter3 = new OutLine("Chapter 3: **** **** ***", 1, 5, 200);
//  add 3rd entry to outline
outline.Entry.Add(entryChapter3);

//  create 3rd entry's child entries
//  create 1st child entry: Level = 2; Location: page index 9, y = 0
OutLine entryChapter31 = new OutLine("# #### ###", 2, 9, 0);
//  connect this entry to the parent entry
entryChapter31.SetParentREEntry(entryChapter3);
//  add 1st child of 3rd entry to outline
outline.Entry.Add(entryChapter31);

//  create a child entry for the 1st child entry of the 3rd entry
//  create entry: Level = 3; Location: page index 9, y = 500
OutLine entryChapter311 = new OutLine("???? ???? ??? ???", 3, 9, 500);
//  connect this entry to the parent entry
entryChapter311.SetParentREEntry(entryChapter31);
//  add 1st child of 3rd entry to outline
outline.Entry.Add(entryChapter311);

//  create 4th entry: Level = 1; Location: page index 10, y = 0
OutLine entryChapter4 = new OutLine("Chapter 4: ******* ** ** **** ***", 1, 10, 0);
//  add 4th entry to outline
outline.Entry.Add(entryChapter4);

//  create 5th entry: Level = 1; Location: page index 20, y = 0
OutLine entryChapter5 = new OutLine("Chapter 5: * ** **** **** ****", 1, 20, 0);
//  add 5th entry to outline
outline.Entry.Add(entryChapter5);

//  update the new outline
doc.SetOutline(outline);

doc.Save(outputFilePath);


Edit watermark

    //  define a watermark setting
    PDFPageWatermark watermark1 = new PDFPageWatermark(resWatermark);
    watermark1.IsAbovePage = false;
    watermark1.Rotate = -45F;
    watermark1.Opacity = 0.2F;

    //  define page range: all odd pages
    PageRangeOptions pageRange1 = new PageRangeOptions();
    pageRange1.AllPages = true;
    pageRange1.Subset = PageRangeSubset.Odd;

    //  apply watermark settings to all odd pages
    PDFPageFieldHandler.ApplyWatermark(doc, watermark1, pageRange1);




Edit PDF markups



XDoc.PDF C# library support full editing operations on annotations, markups, stamps and drawings for PDFs.

Edit annotations and markups

String inputFilePath = Program.RootPath + "\\" + "2.pdf";
String outputFilePath = Program.RootPath + "\\" + "Annot_3.pdf";

//  open a PDF file
PDFDocument doc = new PDFDocument(inputFilePath);
//  get the 2nd page
PDFPage page = (PDFPage)doc.GetPage(1);

//  create the annotation
PDFAnnotHighlight annot = new PDFAnnotHighlight();

annot.StartPoint = new PointF(100F, 200F);
annot.EndPoint = new PointF(300F, 400F);

//  add annotation to the page
page.AddPDFAnnot(annot);

//  save to a new file
doc.Save(outputFilePath);


Edit drawings

String inputFilePath = Program.RootPath + "\\" + "2.pdf";
String outputFilePath = Program.RootPath + "\\" + "Annot_6.pdf";

//  open a PDF file
PDFDocument doc = new PDFDocument(inputFilePath);
//  get the 1st page
PDFPage page = (PDFPage)doc.GetPage(0);

{
    //  create the annotation
    PDFAnnotLine annot = new PDFAnnotLine();

    annot.Start = new PointF(100F, 100F);
    annot.End = new PointF(200F, 200F);

    //  add annotation to the page
    PDFAnnotHandler.AddAnnotation(page, annot);
}

//  save to a new file
doc.Save(outputFilePath);


Edit stamps

Using XDoc.PDF, you can easily create templates for stamps, and adding stamps from templates on PDFs in C# code.

PDFContext ctx = new PDFContext();
ctx.SetWidth(new RELength(1F, Units.IN));
ctx.SetHeight(new RELength(1F, Units.IN));

//  draw shapes to context
ctx.DrawEllipse(new REPen(Color.Red, 6F), 3, 3, 90, 90);
ctx.DrawEllipse(new REPen(Color.Red, 1F), 8, 8, 80, 80);
ctx.DrawLine(new REPen(Color.Red, 1F), 8, 48, 88, 48);

//  create template by context
PDFStampTemplate template = PDFStampTemplate.Create(ctx);

//  define a dynamic text field for User Info - Name
PDFStampTemplateField field0 = new PDFStampTemplateField();
//  dynamic text field region in the context
field0.Boundary = new RectangleF(0, 18, 100, 20);
field0.FieldType = PDFStampTemplateFieldType.Name;
field0.TextColor = Color.FromArgb(255, 0, 0);
field0.TextFont = new Font("Times New Roman", 10, FontStyle.Regular);
//  add the filed
template.AddField(field0);

//  define a dynamic text field for User Info - Company
PDFStampTemplateField field1 = new PDFStampTemplateField();
field1.Boundary = new RectangleF(0, 62, 100, 20);
field1.FieldType = PDFStampTemplateFieldType.Company;
field1.TextColor = Color.FromArgb(255, 0, 0);
field1.TextFont = new Font("Times New Roman", 8, FontStyle.Regular);
template.AddField(field1);

//  define a dynamic text field for User Info - Current Date Time
PDFStampTemplateField field2 = new PDFStampTemplateField();
field2.Boundary = new RectangleF(0, 40, 100, 20);
field2.FieldType = PDFStampTemplateFieldType.CurrertDateTime;
field2.TextColor = Color.FromArgb(255, 0, 0);
field2.TextFont = new Font("Times New Roman", 6, FontStyle.Regular);
template.AddField(field2);




Edit PDF Acro Forms



With XDoc.PDF, you could add, insert AcroForms fields on existing PDF document, and read user filled form data from PDF using C#.

Edit form fields

String inputFilePath = Program.RootPath + "\\" + "empty.pdf";
String outputFilePath = Program.RootPath + "\\" + "Output.pdf";

List<BaseFormField> fields = new List<BaseFormField>();

//  add a radio button field with default setting
AFRadioButton field1 = new AFRadioButton("AF_RadioButton_01");
field1.PageIndex = 0;
field1.Position = new PointF(100F, 100F);
fields.Add(field1);

//  add fields to the input file
PDFFormHandler.AddFormFields(inputFilePath, fields, outputFilePath);


Fill in form data

String inputFilePath = Program.RootPath + "\\" + "1_AF.pdf";
String outputFilePath = Program.RootPath + "\\" + "output.pdf";

List<BaseFormField> fields = PDFFormHandler.GetFormFields(inputFilePath);

int cnt = 0;
foreach (BaseFormField field in fields)
{
    float x = field.Position.X + field.Size.Width / 2F;
    float y = field.Position.Y + field.Size.Height / 2F;

    if (field is AFCheckBox)
    {   //  fill a CheckBox field, set state to ON
        AFCheckBoxInput input = new AFCheckBoxInput(true);
        PDFFormHandler.FillFormField(inputFilePath, 0, new PointF(x, y), input, outputFilePath + cnt.ToString() + ".pdf");
    }
    else if (field is AFRadioButton)
    {   //  fill a RadioButton field, set state to ON 
        AFRadioButtonInput input = new AFRadioButtonInput(true);
        PDFFormHandler.FillFormField(inputFilePath, 0, new PointF(x, y), input, outputFilePath + cnt.ToString() + ".pdf");
    }
    else if (field is AFTextBox)
    {   //  fill a TextBox field, change content to "Hello World"
        AFTextBoxInput input = new AFTextBoxInput("Hello World");
        PDFFormHandler.FillFormField(inputFilePath, 0, new PointF(x, y), input, outputFilePath + cnt.ToString() + ".pdf");
    }
    else if (field is AFListBox)
    {   //  fill a ListBox field, selete the 3rd item (with index value 2)
        AFListBoxInput input = new AFListBoxInput(new int[1] { 2 });
        PDFFormHandler.FillFormField(inputFilePath, 0, new PointF(x, y), input, outputFilePath + cnt.ToString() + ".pdf");
    }
    else if (field is AFComboBox)
    {   //  fill a BomboBox field, selete the 3rd item (with index value 2)
        AFComboBoxInput input = new AFComboBoxInput(2);
        PDFFormHandler.FillFormField(inputFilePath, 0, new PointF(x, y), input, outputFilePath + cnt.ToString() + ".pdf");
    }

    cnt++;
}




Conclusion



The above C# sample source code shows that XDoc.PDF provides comprehensive features to edit a PDF document in your C# ASP.NET, MVC, Windows application.