问题
I want to fill an existing PDF file in my web application (developed in ASP.NET MVC 5). The PDF file has a field named "Text1". In this field I want to write the value "abc". I am currently trying to use PdfSharp for this purpose.
This is how I am currently trying to set a value in a field in the PDF:
var doc = PdfReader.Open(ControllerContext.HttpContext.Server.MapPath("~/Documents/test.pdf"), PdfDocumentOpenMode.Modify);
doc.AcroForm.Fields["Text1"].ReadOnly = false;
That was the preparation.
And after that I tried various things. For example, this:
doc.AcroForm.Elements.SetValue("Text1", "abc");
But this did not work, because string
cannot be converted to PdfSharp.Pdf.PdfItem
.
I also tried this:
doc.AcroForm.Fields["Text1"].Value = "abc";
Again, I get the same exception as above.
Is there anyway to set the values of the fields of an existing PDF? Does this work with PdfSharp?
回答1:
You have to use PdfString
from PDFSharp library like this document.AcroForm.Elements.SetValue("/FieldName", new PdfString("yourstring"));
You also need this if you are attempting to populate PDF form fields, you also need to set the NeedsAppearances element to true. Otherwise, the PDF will "hide" the values on the form.
回答2:
Ok. I have found the solution.
First, as user Mu-Majid also writes, you have to set the NeedAppearances element to true. This is done as follows:
if (doc.AcroForm.Elements.ContainsKey("/NeedAppearances") == false)
{
doc.AcroForm.Elements.Add("/NeedAppearances", new PdfBoolean(true));
}
else
{
doc.AcroForm.Elements.SetValue("/NeedAppearances", new PdfBoolean(true));
}
Then to set the value of a field you have to consider which field type you have. For a simple text field you can set the value as follows:
doc.AcroForm.Fields["Text1"].Value = new PdfString("abc");
The value of a checkbox can be set as follows:
var chckBox = (PdfCheckBoxField)(doc.AcroForm.Fields["chckbx1"]);
chckBox.Checked = true;
As can be seen, you must first explicitly cast the field to the correct type. After that you can set the value.
The same applies to dropdown elements. This is how the value is set for a dropdown element:
var drpDwn = (PdfComboBoxField)(doc.AcroForm.Fields["Dropdown1"]);
drpDwn.Value = new PdfString("3");
In the PDF, the corresponding text for the value "3" then appears in the dropdown.
Many thanks at this point to Mu-Majid for his help.
来源:https://stackoverflow.com/questions/65726387/filling-pdf-fields-with-values-in-asp-net-mvc-5