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.
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.