Search code examples
c#itextpdftk

ITextSharp/Pdftk: place Base64 Image from Web on PDF as Pseude-Signature


I am trying to conceptualize a way to get base64 image onto an already rendered PDF in iText. The goal is to have the PDF save to disk then reopen to apply the "signature" in the right spot.

I haven't had any success with finding other examples online so I'm asking Stack.

My app uses .net c#.

Any advice on how to get started?


Solution

  • As @mkl mentioned the question is a confusing, especially the title - usually base64 and signature do not go together. Guessing you want to place a base64 image from web on the PDF as a pseudo signature?!?!

    A quick working example to get you started:

    static void Main(string[] args)
    {
        string currentDir = AppDomain.CurrentDomain.BaseDirectory;
        // 'INPUT' => already rendered pdf in iText
        PdfReader reader = new PdfReader(INPUT);
        string outputFile = Path.Combine(currentDir, OUTPUT);
        using (var stream = new FileStream(outputFile, FileMode.Create)) 
        {
            using (PdfStamper stamper = new PdfStamper(reader, stream))
            {
                AcroFields form = stamper.AcroFields;
                var fldPosition = form.GetFieldPositions("lname")[0];
                Rectangle rectangle = fldPosition.position;
                string base64Image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
                Regex regex = new Regex(@"^data:image/(?<mediaType>[^;]+);base64,(?<data>.*)");
                Match match = regex.Match(base64Image);
                Image image = Image.GetInstance(
                    Convert.FromBase64String(match.Groups["data"].Value)
                );
                // best fit if image bigger than form field
                if (image.Height > rectangle.Height || image.Width > rectangle.Width)
                {
                    image.ScaleAbsolute(rectangle);
                }
                // form field top left - change parameters as needed to set different position 
                image.SetAbsolutePosition(rectangle.Left + 2, rectangle.Top - 2);
                stamper.GetOverContent(fldPosition.page).AddImage(image);
            }
        }
    }
    

    If you're not working with a PDF form template, (AcroFields in code snippet) explicitly set the absolute position and scale the image as needed.