Replacing a text tag in a word document with an image using Novacode

2.1k views Asked by At

I have several dozen different types of documents that require a signature. Where the signature should go, there is a [[Signature]] tag. I'd like to find that tag and replace it with an image of the signature.

What I currently have takes a Novacode.DocX document and appends the image after the paragraph containing the [[Signature]] tag, but this doesn't really work for my needs as it places the signature below the signature tag's location. I'd like to insert it directly where the [[Signature]] tag is instead. This is the code I have presently:

        public static MemoryStream ToSignedPDFStream(this Novacode.DocX document, string signatureImgBase64, string signatureBiometric)
    {
        var bytes = System.Convert.FromBase64String(signatureImgBase64);

        System.Drawing.Image image;
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            image = System.Drawing.Image.FromStream(ms);
        }

        using (MemoryStream imgStream = new MemoryStream())
        {
            image.Save(imgStream, System.Drawing.Imaging.ImageFormat.Bmp);
            imgStream.Seek(0, SeekOrigin.Begin);
            var docxImage = document.AddImage(imgStream);


            var addresses = document.FindAll("[[Signature]]");
            var paragraphs = document.Paragraphs.Where(x => x.Text.Contains("[[Signature]]"));
            foreach (var paragraph in paragraphs)
            {
                paragraph.ReplaceText("[[Signature]]", "");
                paragraph.AppendPicture(docxImage.CreatePicture(50, 150));

            }

            var memoryStream = new MemoryStream();
            document.SaveAs(memoryStream);

        }

        var pdfStream =  document.ToPDFStream();

        var biometricFile = File.WriteAllText();

        return pdfStream;
    }

This works, technically, but places the signature incorrectly.

2

There are 2 answers

0
László Leber On

Solution:

paragraph.InsertPicture(docxImage.CreatePicture(img.width, img.height), characterPosition);

The caracterposition is the starting position of the tag in the paragraph. You need to collect this positions first with regexp or something else.

2
G.Dealmeida On

I had to manage the same issue here few days ago :)

The answer is to place your tag into a Cell, then the image can be fit into the cell, exactly where your cell stands.

Tell me if you want a code sample to do that