How can I set PdfFormField image in iTextSharp 7 and release the file after using it?

Viewed 422

I'm having a lot of trouble trying to set a PdfFormField image and release the file used by the itext process. Here is what I'm doing now (setting the image itself works just fine, but the file still being used by the process...):

public void SetImageField(string idFormField, string imagePath)
        {
            PdfButtonFormField pdfButtonFormField = (PdfButtonFormField)_pdfAcroForm
                    .GetField(idFormField);

            if (pdfButtonFormField == null)
                throw new InstanceNotFoundException("Não foi encontrado o campo de assinatura no pdf!");

            pdfButtonFormField
                .SetImage(imagePath);

            pdfButtonFormField
                .SetBorderWidth(0);

            pdfButtonFormField.Flush();
            pdfButtonFormField.Release();
        }

As you can see, I'm setting the pdfButtonFormField image through pdfButtonFormField.SetImage(imagePath). The thing is, I need to delete this file (imagePath) after using it, and it seems that itext process still using the resource, even if I call pdfButtonFormField.Flush() and also pdfButtonFormField.Release().

So you may say, "why don't you just open a filestream, and call fileStream.Dispose after using?". Because the file itself is not in my hands, its being managed by itext api.

So please, I'd like to know if theres any way to do it.

1 Answers

Looking at the iText 7 source code, PdfButtonFormField.SetImage does the following:

  1. Opens a FileStream using the image path (which it does not release).
  2. Calls an internal utility method to read the FileStream into a byte array.
  3. Calls Convert.ToBase64String to convert the byte array into a string.
  4. Passes the resulting string to PdfButtonFormField.SetValue.

You can do the first three steps yourself and then call SetValue on the PdfButtonFormField.

Assuming you've written your own method ReadFileToArray to read the image file and return it as an array of bytes, this should work:

public void SetImage(PdfAcroForm pdfAcroForm, string idFormField, string imagePath)
{
    var pdfButtonFormField = (PdfButtonFormField) pdfAcroForm.GetField(idFormField);
    if (pdfButtonFormField == null)
        throw new InstanceNotFoundException();
    var imageBytes = ReadFileToArray(imagePath);
    var imageStr = Convert.ToBase64String(imageBytes);
    pdfButtonFormField.SetValue(imageStr);
    pdfButtonFormField.SetBorderWidth(0);
}

Here is a link to the source for PdfButtonFormField: PdfButtonFormField.cs

Related