Skip to content

Instantly share code, notes, and snippets.

@bjoerntx
Last active October 20, 2022 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjoerntx/9252a4af8aeae5bb86060549e85964f3 to your computer and use it in GitHub Desktop.
Save bjoerntx/9252a4af8aeae5bb86060549e85964f3 to your computer and use it in GitHub Desktop.
[HttpPost]
public string MergeAnnotations() {
Stream inputStream = Request.InputStream;
inputStream.Position = 0;
StreamReader str = new StreamReader(inputStream);
string sBuf = str.ReadToEndAsync().Result;
List<List<TXTextControl.SignatureAnnotation.Annotation>> annotations =
JsonConvert.DeserializeObject<List<List<TXTextControl.SignatureAnnotation.Annotation>>>(sBuf);
byte[] bTx;
int iPageNumber = 0;
string prePng = "data:image/png;base64,";
string preSvg = "data:image/svg+xml;utf8,";
// calculate the current resolution
var dpi = 1440 / DocumentController.DpiX;
// create temporary ServerTextControl
using (ServerTextControl tx = new ServerTextControl()) {
tx.Create();
// load the document
tx.Load(Server.MapPath("~/App_Data/Documents/template_sign.tx"), StreamType.InternalUnicodeFormat);
// loop through the array of annotations
foreach (List<TXTextControl.SignatureAnnotation.Annotation> pages in annotations) {
iPageNumber++;
foreach (TXTextControl.SignatureAnnotation.Annotation annotation in pages) {
// handle only signatures
if (annotation.pen.type != "signature")
continue;
byte[] bytes;
// get SVG or PNG as bytes and remove the prefix
if (annotation.image.StartsWith(prePng))
bytes = Convert.FromBase64String(annotation.image.Remove(0, prePng.Length));
else
bytes = Encoding.UTF8.GetBytes(annotation.image.Remove(0, preSvg.Length));
// create a memory stream from SVG
using (MemoryStream ms = new MemoryStream(
bytes, 0, bytes.Length, writable: false, publiclyVisible: true)) {
// TX image from memory stream
TXTextControl.Image img = new TXTextControl.Image(ms);
// add the image as a fixed object on the current page (array)
tx.Images.Add(
img,
iPageNumber,
new System.Drawing.Point(0, (int)(annotation.location.y * dpi)),
TXTextControl.ImageInsertionMode.BelowTheText | TXTextControl.ImageInsertionMode.FixedOnPage);
// set the location
img.Location = new System.Drawing.Point(
(int)(annotation.location.x * dpi),
img.Location.Y);
}
}
}
// save the document as PDF
tx.Save(out bTx, TXTextControl.BinaryStreamType.InternalUnicodeFormat);
}
// return as base64 encoded string
return Convert.ToBase64String(bTx);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment