Search code examples
c#.netbarcodeitext7

Can I set image to acrofield in iText7.NET


I want to upgrade from iTextSharp to iText7. I cant set the image of PdfButtonField to an System.Drawing.Image in the past. But now in iText7, the PdfButtonFormField.SetImage(string sImagePah) can only acccept file path. I create an System.Drawing.Image the fly, How can I set the image the an AcroField in iText7.NET ?


Solution

  • You can use SetValue method and provide Base64-encoded image value there.

    Example code to covert System.Drawing.Image to a Base64 string:

    public static string ImageToBase64(System.Drawing.Image image)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            image.Save(ms, ImageFormat.Png);
            byte[] imageBytes = ms.ToArray();
            return Convert.ToBase64String(imageBytes);
        }
    }
    

    Example code to set the image to the form field:

    PdfButtonFormField field = ...;
    field.SetValue(ImageToBase64(image));