We have already had an article of showing how to replace the image on the existing PDF file. Starts from Spire.PDF V3.8.45, it newly supports to update the image on button field via the method of field.SetButtonImage(PdfImage.FromFile(@"")). This article will focus on demonstrate how to replace the image on the button field in C#.
Firstly, check the original PDF file with the button field.
Step 1: Create a PDF document and load from file.
PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("Sample.PDF", FileFormat.PDF);
Step 2: Get the form from the loaded PDF document.
PdfFormWidget form = pdf.Form as PdfFormWidget;
Step 3: Find the button field named "Image" and then set a new image for this button field.
for (int i = 0; i < form.FieldsWidget.Count; i++) { if (form.FieldsWidget[i] is PdfButtonWidgetFieldWidget) { PdfButtonWidgetFieldWidget field = form.FieldsWidget[i] as PdfButtonWidgetFieldWidget; if (field.Name == "Image") { field.SetButtonImage(PdfImage.FromFile("logo.png")); } } }
Step 4: Save the document to file.
pdf.SaveToFile("result.pdf");
Effective screenshot after replace the image on the button field.
Full codes:
using Spire.Pdf; using Spire.Pdf.Graphics; using Spire.Pdf.Widget; namespace ImageButton { class Program { static void Main(string[] args) { PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("Sample.PDF", FileFormat.PDF); PdfFormWidget form = pdf.Form as PdfFormWidget; for (int i = 0; i < form.FieldsWidget.Count; i++) { if (form.FieldsWidget[i] is PdfButtonWidgetFieldWidget) { PdfButtonWidgetFieldWidget field = form.FieldsWidget[i] as PdfButtonWidgetFieldWidget; if (field.Name == "Image") { field.SetButtonImage(PdfImage.FromFile("logo.png")); } } } pdf.SaveToFile("result.pdf"); } } }