Created
December 28, 2022 12:03
-
-
Save bjoerntx/367a08a9daab3c24bb52bee7ad733027 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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