1

I am using itext7 to get the Stream of the file and fill in the form fields.

Here is my code:

using (MemoryStream outFile = new MemoryStream())
{
    var streamFile = await App.GraphClient.Me.Drive.Items[item.Id].Content.Request().GetAsync();

    using (PdfDocument pdf = new PdfDocument(new PdfReader(streamFile)))
    {

        PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);

        IDictionary<String, PdfFormField> fields = form.GetFormFields();

        PdfFormField toSet;
        fields.TryGetValue("Full_Names", out toSet);
        toSet.SetValue(Customer_Name.Text);

        form.FlattenFields();
        pdf.Close();

    }
}

But I get an error on this line: toSet.SetValue(Customer_Name.Text); when trying to set the value, the error is:

There is no associate PdfWriter for making indirects.

My question is what am I doing wrong and how do I fix this? I am getting the file from OneDrive using Microsoft Graph API. The IDictionary of fields is getting populated and the name of field I am trying to set the value for is accurate.

Alexey Subach
  • 11,903
  • 7
  • 34
  • 60
user979331
  • 11,039
  • 73
  • 223
  • 418

1 Answers1

2

The problem with your code is that you have dedicated outFile stream for the output result (the document with flattened fields) but you are not telling iText anything about that desired output destination.

PdfDocument has several constructors and the one you are using is PdfDocument(PdfReader) and it is dedicated for reading the document, not changing it (and setting a value is considered changing the document of course). So you should use PdfDocument(PdfReader, PdfWriter) constructor to provide the source document and the target destination to iText.

You should create your PdfDocument as follows:

PdfDocument pdf = new PdfDocument(new PdfReader(streamFile), new PdfWriter(outFile))

At the end of the execution, your outFile stream will contain the bytes of the resultant document.

Alexey Subach
  • 11,903
  • 7
  • 34
  • 60
  • Yes, you are correct, but when I do that I get a new error saying "Can not access a closed Stream." what am I doing wrong now? – user979331 Dec 02 '19 at 21:02
  • This is because the PdfReader closes the underlying stream automatically when being disposed of. The `using` statement does this automatically.For more details, you can check: https://stackoverflow.com/questions/10934585/memorystream-cannot-access-a-closed-stream – Jessie Zhang -MSFT Dec 03 '19 at 03:09