Compare commits

...

26 Commits

Author SHA1 Message Date
36b03da084 fix(DependencyInjection): change AnnotationManager registration from Scoped to Transient 2025-11-07 15:21:36 +01:00
defa53fa26 refactor(BurnPdfCommand): rename SourceBuffer to Document in BurnPdfCommand and handler
- Renamed parameter `SourceBuffer` to `Document` in BurnPdfCommand record
- Updated all usages of `request.SourceBuffer` to `request.Document`
- Reorganized method order for better readability (Handle moved up)
- No functional or behavioral changes introduced
2025-11-07 14:56:34 +01:00
6134b58a4c refactor(BurnPdfCommand): extract GdPicture and math helpers into extension classes and simplify BurnPdfCommandHandler
- Refactored BurnPdfCommandHandler to use new extension methods for cleaner annotation handling.
- Introduced ITextStyle interface to generalize font styling for text annotations.
- Updated PDFBurnerParams to implement ITextStyle for consistent font settings reuse.
- Added MathematExtensions for coordinate and unit conversion (ToInches, ToPointF).
- Added GdPictureExtensions to encapsulate annotation-related logic (form fields, images, ink).
- Improved readability and maintainability by removing redundant helper methods.
2025-11-07 14:46:55 +01:00
5299016b43 move PSDPFKitModels namespace to Dto and rename as PSPDFKitInstant 2025-11-07 13:51:53 +01:00
55c20e83d8 refactor: convert BurnPdfCommand to record and update handler to return byte[]
- Changed `BurnPdfCommand` from empty class to a `record` with properties: `SourceBuffer`, `InstantJSONList`, `EnvelopeId`.
- Updated `BurnPdfCommandHandler` to implement `IRequestHandler<BurnPdfCommand, byte[]>`.
- Modified `Handle` method to be async and use the `request` data to return PDF bytes.
- Removed obsolete `BurnPdfCommand` class and updated related logic accordingly.
2025-11-07 13:44:53 +01:00
f1a140faa7 feat(BurnPdfCommandHandler): implement AddInkAnnotation for Annotation parameter
- Added implementation for AddInkAnnotation(Annotation) to handle ink annotations from Annotation objects.
- Retained existing AddInkAnnotation(int, string) method for backward compatibility.
- Refactored PDF burning logic to support both Annotation-based and JSON-based annotations.
2025-11-07 13:24:26 +01:00
b20d25e5b9 feat(BurnPdfCommandHandler): implement AddInkAnnotation for freehand annotations
- Added implementation for AddInkAnnotation(int page, string value) to render ink annotations from JSON.
- Deserialize ink lines and stroke color, convert points to PDF coordinates, and add as freehand annotations.
- Retained placeholder for AddInkAnnotation(Annotation pAnnotation) for future use.
2025-11-07 13:21:33 +01:00
e21eb2c0d6 refactor(BurnPdfCommandHandler): rename AddInstantJSONAnnotationToPdf to AddInstantJsonAnnotationToPdf for consistent casing 2025-11-07 13:16:14 +01:00
d237b4ab95 feat(BurnPdfCommand): implement AddImageAnnotation with attachment handling
- Added logic to AddImageAnnotation to handle image attachments from a dictionary.
- Removed NotImplementedException placeholder for AddImageAnnotation with attachments.
- Refactored code to convert annotation bounds from pixels to inches before adding images.
2025-11-07 13:14:02 +01:00
dff99b163d refactor: simplify AddFormFieldValue method and remove redundant parameters 2025-11-07 13:12:01 +01:00
70fbf31b14 feat(BurnPdfCommandHandler): implement AddImageAnnotation for base64 images
- Added implementation for AddImageAnnotation(double x, double y, double width, double height, int page, string base64)
- Allows embedding images directly from base64 into PDF pages
- Existing annotation burning logic remains unchanged
2025-11-07 13:09:54 +01:00
339e0e81cd feat(PDFBurnerParams): add DefaultIndexOfAnnot and GetAnnotationIndex
- add `DefaultIndexOfAnnot` property to provide a fallback index for annotations
 - add `GetAnnotationIndex(string name)` method to safely retrieve an annotation index, returning default if not found
2025-11-07 13:03:50 +01:00
a386ad72bb refactor(BurnPdfCommandHandler): use IOptions<PDFBurnerParams> and improve form field handling
- Updated BurnPdfCommandHandler constructor to accept IOptions<PDFBurnerParams> instead of raw PDFBurnerParams.
- Updated AddFormFieldValue to calculate coordinates based on PDFBurnerParams offsets and margins.
- Added helper methods for converting pixels to inches (ToInches, ToPointF).
- Removed unused NotImplemented methods in AddFormFieldValue overload.
- Improved code readability and maintainability for annotation burning logic.
2025-11-07 12:59:13 +01:00
02c5f286ec feat(pdf): implement AddFormFieldValue for PDF annotations
- Added implementation for AddFormFieldValue method to properly add text annotations to PDF pages using AnnotationManager.
- Preserves font settings from PDFBurnerParams.
- Other annotation methods remain unimplemented.
2025-11-07 12:44:05 +01:00
5fa358ca79 refactor(BurnPdfCommandHandler): deserialize and process instant JSON annotations
- Added Newtonsoft.Json to parse instant JSON into `InstantData`.
- Replaced `AddInstantJSONAnnotationToPDF` logic with `AddInstantJsonAnnotationToPdf`.
- Process annotations by type (Image, Ink, Widget) and apply attachments/form fields.
- Introduced checks for ignored form field values using `_pdfBurnerParams.IgnoredLabels`.
- Added logging for annotation IDs when processing instant JSON.
2025-11-07 12:36:19 +01:00
7233d2ce98 add InstantData 2025-11-07 11:37:28 +01:00
5784cc7a97 refactor(Application.Pdf.PSPDFKit): rename as Application.Pdf.PSPDFKitModels 2025-11-07 11:28:55 +01:00
f31f680f91 add PSPDFKit.Annotation 2025-11-07 11:27:07 +01:00
e7c2d46ef0 add PSPDFKit.Ink 2025-11-07 11:23:04 +01:00
85d70c1db4 feat(PDFBurnerParams): add IndexOfAnnot-dictionary 2025-11-07 11:16:22 +01:00
fb340fb08a create PSPDFKit.Lines 2025-11-07 10:59:13 +01:00
7d3959ae51 add PSPDFKit.Attachment 2025-11-07 10:56:53 +01:00
9d4890b10d add PSPDFKit.FormFieldValue 2025-11-07 10:52:15 +01:00
b64f4d71f5 feat(BurnPdfCommandHandler): add logging and implement BurnInstantJSONAnnotsToPDF
- Added ILogger<BurnPdfCommandHandler> to log warnings during annotation processing
- Implemented BurnInstantJSONAnnotsToPDF method to handle instant JSON annotations
- Added AddInstantJSONAnnotationToPDF stub for future implementation
- Updated PDF burn flow to include error handling and logging
2025-11-07 10:40:44 +01:00
b7d146ddb5 refactor: standardize annotation types and clean up PDF burn handler
- Introduced `AnnotationType.PSPDFKit` constants for consistent annotation type references.
- Updated `BurnPdfCommandHandler` to use new PSPDFKit annotation types.
- Refactored method signatures and local variables for clarity (e.g., using 'var', null-coalescing for annotation properties).
- Streamlined `using` statements and memory management in PDF burning process.
- Added placeholder methods for form fields, image, and ink annotations to centralize future implementations.
2025-11-07 10:11:48 +01:00
6a5c9a3489 fix(BurnPdfCommand): improve JSON serialization and null safety in Signature entity and BurnPdfCommandHandler
- Added System.Text.Json.Serialization namespace and [JsonIgnore] attributes to Top and Left properties in Signature entity for .NET builds
- Applied null-forgiving operator (!) and null-coalescing defaults for frame.X and frame.Y in BurnPdfCommandHandler
- Improved runtime safety and prevented unintended JSON serialization of computed properties
2025-11-07 09:51:02 +01:00
15 changed files with 693 additions and 141 deletions

View File

@ -1,12 +1,13 @@
using System.Drawing;
using EnvelopeGenerator.Application.Common.Interfaces.Model;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
namespace EnvelopeGenerator.Application.Common.Configurations;
/// <summary>
///
/// </summary>
public class PDFBurnerParams
public class PDFBurnerParams : ITextStyle
{
/// <summary>
///
@ -45,4 +46,28 @@ public class PDFBurnerParams
/// </summary>
[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
public FontStyle FontStyle { get; set; } = FontStyle.Italic;
/// <summary>
///
/// </summary>
public Dictionary<string, int> IndexOfAnnot { get; init; } = new()
{
{ string.Empty, 0 },
{ "seal", 0 },
{ "position", 1 },
{ "city", 2 },
{ "date", 3 }
};
/// <summary>
///
/// </summary>
public int DefaultIndexOfAnnot { get; set; } = 0;
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public int GetAnnotationIndex(string name) => IndexOfAnnot.TryGetValue(name, out var value) ? value : DefaultIndexOfAnnot;
}

View File

@ -0,0 +1,122 @@
using EnvelopeGenerator.Application.Exceptions;
namespace EnvelopeGenerator.Application.Common.Dto.PSPDFKitInstant;
/// <summary>
///
/// </summary>
public class Annotation
{
private string? _id;
/// <summary>
///
/// </summary>
public int EnvelopeId { get; private set; } = 0;
/// <summary>
///
/// </summary>
public int ReceiverId { get; private set; } = 0;
/// <summary>
///
/// </summary>
public int Index { get; private set; } = 0;
/// <summary>
///
/// </summary>
public string EgName { get; private set; } = string.Empty;
/// <summary>
///
/// </summary>
public bool HasStructuredID { get; private set; } = false;
/// <summary>
///
/// </summary>
public bool IsLabel
{
get
{
if (string.IsNullOrEmpty(EgName))
return false;
var parts = EgName.Split('_');
return parts.Length > 1 && parts[1] == "label";
}
}
/// <summary>
///
/// </summary>
public string? Id
{
get => _id;
set
{
_id = value;
if (string.IsNullOrWhiteSpace(value))
throw new BurnAnnotationException("The identifier of annotation is null or empty.");
var parts = value.Split('#');
if (parts.Length != 4)
return;
// throw new BurnAnnotationException($"The identifier of annotation has more or less than 4 sub-part. Id: {_id}");
if (!int.TryParse(parts[0], out int envelopeId))
throw new BurnAnnotationException($"The envelope ID of annotation is not integer. Id: {_id}");
EnvelopeId = envelopeId;
if (!int.TryParse(parts[1], out int receiverId))
throw new BurnAnnotationException($"The receiver ID of annotation is not integer. Id: {_id}");
ReceiverId = receiverId;
if (!int.TryParse(parts[2], out int index))
throw new BurnAnnotationException($"The index of annotation is not integer. Id: {_id}");
Index = index;
EgName = parts[3];
HasStructuredID = true;
}
}
/// <summary>
///
/// </summary>
public List<double>? Bbox { get; set; }
/// <summary>
///
/// </summary>
public string? Type { get; set; }
/// <summary>
///
/// </summary>
public bool IsSignature { get; set; }
/// <summary>
///
/// </summary>
public string? ImageAttachmentId { get; set; }
/// <summary>
///
/// </summary>
public Lines? Lines { get; set; }
/// <summary>
///
/// </summary>
public int PageIndex { get; set; }
/// <summary>
///
/// </summary>
public string? StrokeColor { get; set; }
}

View File

@ -0,0 +1,8 @@
namespace EnvelopeGenerator.Application.Common.Dto.PSPDFKitInstant;
/// <summary>
///
/// </summary>
/// <param name="Binary"></param>
/// <param name="ContentType"></param>
public record Attachment(string Binary, string ContentType);

View File

@ -0,0 +1,8 @@
namespace EnvelopeGenerator.Application.Common.Dto.PSPDFKitInstant;
/// <summary>
///
/// </summary>
/// <param name="Name"></param>
/// <param name="Value"></param>
public record FormFieldValue(string Name, string? Value = null);

View File

@ -0,0 +1,8 @@
namespace EnvelopeGenerator.Application.Common.Dto.PSPDFKitInstant;
/// <summary>
///
/// </summary>
/// <param name="Lines"></param>
/// <param name="StrokeColor"></param>
public record Ink(Lines Lines, string? StrokeColor = null);

View File

@ -0,0 +1,50 @@
namespace EnvelopeGenerator.Application.Common.Dto.PSPDFKitInstant;
/// <summary>
///
/// </summary>
public class InstantData
{
/// <summary>
///
/// </summary>
public List<Annotation>? Annotations { get; set; }
/// <summary>
///
/// </summary>
public IEnumerable<List<Annotation>>? AnnotationsByReceiver
{
get
{
return Annotations?
.Where(a => a.HasStructuredID)
.GroupBy(a => a.ReceiverId)
.Select(g => g.ToList());
}
}
/// <summary>
///
/// </summary>
public IEnumerable<List<Annotation>>? UnstructuredAnnotations
{
get
{
return Annotations?
.Where(a => !a.HasStructuredID)
.GroupBy(a => a.ReceiverId)
.Select(g => g.ToList());
}
}
/// <summary>
///
/// </summary>
public Dictionary<string, Attachment>? Attachments { get; set; }
/// <summary>
///
/// </summary>
public List<FormFieldValue>? FormFieldValues { get; set; }
}

View File

@ -0,0 +1,7 @@
namespace EnvelopeGenerator.Application.Common.Dto.PSPDFKitInstant;
/// <summary>
///
/// </summary>
/// <param name="Points"></param>
public record Lines(List<List<List<float>>> Points);

View File

@ -0,0 +1,176 @@
using EnvelopeGenerator.Application.Common.Dto.PSPDFKitInstant;
using EnvelopeGenerator.Domain.Constants;
using GdPicture14;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SixLabors.ImageSharp;
using System.Drawing;
using EnvelopeGenerator.Application.Common.Extensions;
using EnvelopeGenerator.Application.Common.Interfaces.Model;
using EnvelopeGenerator.Application.Common.Configurations;
namespace EnvelopeGenerator.Application.Common.Extensions;
/// <summary>
///
/// </summary>
public static class GdPictureExtensions
{
/// <summary>
///
/// </summary>
/// <param name="manager"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="page"></param>
/// <param name="value"></param>
/// <param name="textStyle"></param>
public static void AddFormFieldValue(this AnnotationManager manager, double x, double y, double width, double height, int page, string value, ITextStyle textStyle)
{
manager.SelectPage(page);
// Add the text annotation
var ant = manager.AddTextAnnot((float)x, (float)y, (float)width, (float)height, value);
// Set the font properties
ant.FontName = textStyle.FontName;
ant.FontSize = textStyle.FontSize;
ant.FontStyle = textStyle.FontStyle;
manager.SaveAnnotationsToPage();
}
/// <summary>
///
/// </summary>
/// <param name="manager"></param>
/// <param name="pAnnotation"></param>
/// <param name="formFieldValue"></param>
/// <param name="options"></param>
public static void AddFormFieldValue(this AnnotationManager manager, Annotation pAnnotation, FormFieldValue formFieldValue, PDFBurnerParams options)
{
var ffIndex = options.GetAnnotationIndex(pAnnotation.EgName);
// Convert pixels to Inches
var oBounds = pAnnotation.Bbox?.Select(points => points.ToInches()).ToList();
if (oBounds is null || oBounds.Count < 4)
return;
double oX = oBounds[0];
double oY = oBounds[1] + options.YOffset * ffIndex + options.TopMargin;
double oWidth = oBounds[2];
double oHeight = oBounds[3];
manager.SelectPage(pAnnotation.PageIndex + 1);
// Add the text annotation
var ant = manager.AddTextAnnot((float)oX, (float)oY, (float)oWidth, (float)oHeight, formFieldValue.Value);
// Set the font properties
ant.FontName = options.FontName;
ant.FontSize = options.FontSize;
ant.FontStyle = options.FontStyle;
manager.SaveAnnotationsToPage();
}
/// <summary>
///
/// </summary>
/// <param name="manager"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="page"></param>
/// <param name="base64"></param>
public static void AddImageAnnotation(this AnnotationManager manager, double x, double y, double width, double height, int page, string base64)
{
manager.SelectPage(page);
manager.AddEmbeddedImageAnnotFromBase64(base64, (float)x, (float)y, (float)width, (float)height);
}
/// <summary>
///
/// </summary>
/// <param name="manager"></param>
/// <param name="pAnnotation"></param>
/// <param name="pAttachments"></param>
public static void AddImageAnnotation(this AnnotationManager manager, Annotation pAnnotation, Dictionary<string, Attachment> pAttachments)
{
var oAttachment = pAttachments
.Where(a => a.Key == pAnnotation.ImageAttachmentId)
.SingleOrDefault();
if (oAttachment.Value == null)
return;
// Convert pixels to Inches
var oBounds = pAnnotation.Bbox?.Select(post => post.ToInches()).ToList();
if (oBounds is null || oBounds.Count < 4)
return;
var oX = oBounds[0];
var oY = oBounds[1];
var oWidth = oBounds[2];
var oHeight = oBounds[3];
manager.SelectPage(pAnnotation.PageIndex + 1);
manager.AddEmbeddedImageAnnotFromBase64(oAttachment.Value.Binary, (float)oX, (float)oY, (float)oWidth, (float)oHeight);
}
/// <summary>
///
/// </summary>
/// <param name="manager"></param>
/// <param name="page"></param>
/// <param name="value"></param>
public static void AddInkAnnotation(this AnnotationManager manager, int page, string value)
{
var ink = JsonConvert.DeserializeObject<Ink>(value);
var oSegments = ink?.Lines.Points;
var oColor = ColorTranslator.FromHtml(ink?.StrokeColor ?? "#000000");
manager.SelectPage(page);
if (oSegments is null)
return;
foreach (var oSegment in oSegments)
{
var oPoints = oSegment
.Select(points => points.ToPointF())
.ToArray();
manager.AddFreeHandAnnot(oColor, oPoints);
}
}
/// <summary>
///
/// </summary>
/// <param name="manager"></param>
/// <param name="pAnnotation"></param>
public static void AddInkAnnotation(this AnnotationManager manager, Annotation pAnnotation)
{
var oSegments = pAnnotation.Lines?.Points;
var oColor = ColorTranslator.FromHtml(pAnnotation.StrokeColor ?? "#000000");
manager.SelectPage(pAnnotation.PageIndex + 1);
if (oSegments is null)
return;
foreach (var oSegment in oSegments)
{
var oPoints = oSegment
.Select(points => points.ToPointF())
.ToArray();
manager.AddFreeHandAnnot(oColor, oPoints);
}
}
}

View File

@ -0,0 +1,40 @@
using System.Drawing;
namespace EnvelopeGenerator.Application.Common.Extensions;
/// <summary>
///
/// </summary>
public static class MathematExtensions
{
/// <summary>
///
/// </summary>
/// <param name="points"></param>
/// <returns></returns>
public static PointF ToPointF(this List<float> points)
{
var pointsInch = points.Select(ToInches).ToList();
return new PointF(pointsInch[0], pointsInch[1]);
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static double ToInches(this double value)
{
return value / 72.0;
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static float ToInches(this float value)
{
return value / 72f;
}
}

View File

@ -0,0 +1,27 @@
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
namespace EnvelopeGenerator.Application.Common.Interfaces.Model;
/// <summary>
///
/// </summary>
public interface ITextStyle
{
/// <summary>
///
/// </summary>
public string FontName { get; set; }
/// <summary>
///
/// </summary>
public int FontSize { get; set; }
/// <summary>
///
/// </summary>
[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
public FontStyle FontStyle { get; set; }
}

View File

@ -67,7 +67,7 @@ public static class DependencyInjection
licenseManager.RegisterKEY(license);
return licenseManager;
});
services.AddScoped(provider => {
services.AddTransient(provider => {
// Ensure LicenseManager is resolved so that its constructor is called
_ = provider.GetRequiredService<LicenseManager>();
return new AnnotationManager();

View File

@ -1,92 +1,96 @@
using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Application.Common.Configurations;
using EnvelopeGenerator.Application.Exceptions;
using EnvelopeGenerator.Application.Common.Dto.PSPDFKitInstant;
using EnvelopeGenerator.Domain.Constants;
using EnvelopeGenerator.Domain.Entities;
using EnvelopeGenerator.PdfEditor;
using GdPicture14;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using EnvelopeGenerator.Application.Common.Extensions;
namespace EnvelopeGenerator.Application.Pdf;
/// <summary>
///
/// </summary>
public class BurnPdfCommand : IRequest
{
}
public record BurnPdfCommand(byte[] Document, List<string> InstantJSONList, int EnvelopeId) : IRequest<byte[]>;
/// <summary>
///
/// </summary>
public class BurnPdfCommandHandler : IRequestHandler<BurnPdfCommand>
public class BurnPdfCommandHandler : IRequestHandler<BurnPdfCommand, byte[]>
{
/// <summary>
///
/// </summary>
private readonly PDFBurnerParams _pdfBurnerParams;
private readonly PDFBurnerParams _options;
private readonly AnnotationManager _manager;
private readonly IRepository<Signature> _signRepo;
private readonly ILogger<BurnPdfCommandHandler> _logger;
/// <summary>
///
/// </summary>
/// <param name="pdfBurnerParams"></param>
/// <param name="manager"></param>
/// <param name="signRepo"></param>
public BurnPdfCommandHandler(PDFBurnerParams pdfBurnerParams, AnnotationManager manager, IRepository<Signature> signRepo)
/// <param name="logger"></param>
public BurnPdfCommandHandler(IOptions<PDFBurnerParams> pdfBurnerParams, AnnotationManager manager, IRepository<Signature> signRepo, ILogger<BurnPdfCommandHandler> logger)
{
_pdfBurnerParams = pdfBurnerParams;
_options = pdfBurnerParams.Value;
_manager = manager;
_signRepo = signRepo;
_logger = logger;
}
public byte[] BurnAnnotsToPDF(byte[] pSourceBuffer, List<string> pInstantJSONList, int envelopeId)
{
// read the elements of envelope with their annotations
var elements = _signRepo
.Where(sig => sig.Document.EnvelopeId == envelopeId)
.Include(sig => sig.Annotations)
.ToList();
return elements.Any()
? BurnElementAnnotsToPDF(pSourceBuffer, elements)
: BurnInstantJSONAnnotsToPDF(pSourceBuffer, pInstantJSONList);
}
/// <summary>
///
/// </summary>
/// <param name="pSourceBuffer"></param>
/// <param name="elements"></param>
/// <param name="request"></param>
/// <param name="cancel"></param>
/// <returns></returns>
public byte[] BurnElementAnnotsToPDF(byte[] pSourceBuffer, List<Signature> elements)
/// <exception cref="NotImplementedException"></exception>
public async Task<byte[]> Handle(BurnPdfCommand request, CancellationToken cancel)
{
// read the elements of envelope with their annotations
var elements = await _signRepo
.Where(sig => sig.Document.EnvelopeId == request.EnvelopeId)
.Include(sig => sig.Annotations)
.ToListAsync(cancel);
return elements.Count > 0
? BurnElementAnnotsToPDF(request.Document, elements)
: BurnInstantJSONAnnotsToPDF(request.Document, request.InstantJSONList);
}
private byte[] BurnElementAnnotsToPDF(byte[] pSourceBuffer, List<Signature> elements)
{
// Add background
using (var doc = PdfEditor.Pdf.FromMemory(pSourceBuffer))
{
using var doc = PdfEditor.Pdf.FromMemory(pSourceBuffer);
// TODO: take the length from the largest y
pSourceBuffer = doc.Background(elements, 1.9500000000000002 * 0.93, 2.52 * 0.67)
.ExportStream()
.ToArray();
GdPictureStatus oResult;
using (var oSourceStream = new MemoryStream(pSourceBuffer))
{
using var oSourceStream = new MemoryStream(pSourceBuffer);
// Open PDF
oResult = _manager.InitFromStream(oSourceStream);
if (oResult != GdPictureStatus.OK)
throw new BurnAnnotationException($"Could not open document for burning: [{oResult}]");
// Imported from background (add to configuration)
double margin = 0.2;
double inchFactor = 72;
var margin = 0.2;
var inchFactor = 72;
// Y offset of form fields
var keys = new[] { "position", "city", "date" }; // add to configuration
double unitYOffsets = 0.2;
var unitYOffsets = 0.2;
var yOffsetsOfFF = keys
.Select((k, i) => new { Key = k, Value = unitYOffsets * i + 1 })
@ -95,53 +99,52 @@ public class BurnPdfCommandHandler : IRequestHandler<BurnPdfCommand>
// Add annotations
foreach (var element in elements)
{
double frameX = element.Left - 0.7 - margin;
var frameX = element.Left - 0.7 - margin;
var frame = element.Annotations?.FirstOrDefault(a => a.Name == "frame");
double frameY = element.Top - 0.5 - margin;
double frameYShift = frame.Y - frameY * inchFactor;
double frameXShift = frame.X - frameX * inchFactor;
var frameY = element.Top - 0.5 - margin;
var frameYShift = (frame!.Y ?? default) - frameY * inchFactor;
var frameXShift = (frame.X ?? default) - frameX * inchFactor;
foreach (var annot in element.Annotations)
foreach (var annot in element.Annotations!)
{
double yOffsetofFF;
if (!yOffsetsOfFF.TryGetValue(annot.Name, out yOffsetofFF))
if (!yOffsetsOfFF.TryGetValue(annot.Name, out var yOffsetofFF))
yOffsetofFF = 0;
double y = frameY + yOffsetofFF;
var y = frameY + yOffsetofFF;
if (annot.Type == AnnotationType.FormField)
if (annot.Type == AnnotationType.PSPDFKit.FormField)
{
AddFormFieldValue(
annot.X / inchFactor,
_manager.AddFormFieldValue(
(annot.X ?? default) / inchFactor,
y,
annot.Width / inchFactor,
annot.Height / inchFactor,
(annot.Width ?? default) / inchFactor,
(annot.Height ?? default) / inchFactor,
element.Page,
annot.Value,
_options
);
}
else if (annot.Type == AnnotationType.PSPDFKit.Image)
{
_manager.AddImageAnnotation(
(annot.X ?? default) / inchFactor,
annot.Name == "signature" ? ((annot.Y ?? default) - frameYShift) / inchFactor : y,
(annot.Width ?? default) / inchFactor,
(annot.Height ?? default) / inchFactor,
element.Page,
annot.Value
);
}
else if (annot.Type == AnnotationType.Image)
else if (annot.Type == AnnotationType.PSPDFKit.Ink)
{
AddImageAnnotation(
annot.X / inchFactor,
annot.Name == "signature" ? (annot.Y - frameYShift) / inchFactor : y,
annot.Width / inchFactor,
annot.Height / inchFactor,
element.Page,
annot.Value
);
}
else if (annot.Type == AnnotationType.Ink)
{
AddInkAnnotation(element.Page, annot.Value);
_manager.AddInkAnnotation(element.Page, annot.Value);
}
}
}
// Save PDF
using (var oNewStream = new MemoryStream())
{
using var oNewStream = new MemoryStream();
oResult = _manager.SaveDocumentToPDF(oNewStream);
if (oResult != GdPictureStatus.OK)
throw new BurnAnnotationException($"Could not save document to stream: [{oResult}]");
@ -150,30 +153,89 @@ public class BurnPdfCommandHandler : IRequestHandler<BurnPdfCommand>
return oNewStream.ToArray();
}
private byte[] BurnInstantJSONAnnotsToPDF(byte[] pSourceBuffer, List<string> pInstantJSONList)
{
GdPictureStatus oResult;
using var oSourceStream = new MemoryStream(pSourceBuffer);
// Open PDF
oResult = _manager.InitFromStream(oSourceStream);
if (oResult != GdPictureStatus.OK)
{
throw new BurnAnnotationException($"Could not open document for burning: [{oResult}]");
}
// Add annotation to PDF
foreach (var oJSON in pInstantJSONList)
{
try
{
if (oJSON is string json)
AddInstantJsonAnnotationToPdf(json);
}
catch (Exception ex)
{
_logger.LogWarning("Error in AddInstantJSONAnnotationToPDF - oJson: ");
_logger.LogWarning(oJSON);
throw new BurnAnnotationException("Adding Annotation failed", ex);
}
}
/// <summary>
///
/// </summary>
/// <param name="pSourceBuffer"></param>
/// <param name="pInstantJSONList"></param>
/// <returns></returns>
public byte[] BurnInstantJSONAnnotsToPDF(byte[] pSourceBuffer, List<string> pInstantJSONList)
oResult = _manager.BurnAnnotationsToPage(RemoveInitialAnnots: true, VectorMode: true);
if (oResult != GdPictureStatus.OK)
{
return Enumerable.Empty<byte>().ToArray();
throw new BurnAnnotationException($"Could not burn annotations to file: [{oResult}]");
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public Task Handle(BurnPdfCommand request, CancellationToken cancellationToken)
// Save PDF
using var oNewStream = new MemoryStream();
oResult = _manager.SaveDocumentToPDF(oNewStream);
if (oResult != GdPictureStatus.OK)
{
throw new NotImplementedException();
throw new BurnAnnotationException($"Could not save document to stream: [{oResult}]");
}
_manager.Close();
return oNewStream.ToArray();
}
private void AddInstantJsonAnnotationToPdf(string instantJson)
{
var annotationData = JsonConvert.DeserializeObject<InstantData>(instantJson);
annotationData?.Annotations?.Reverse();
if (annotationData?.Annotations is null)
return;
foreach (var annotation in annotationData.Annotations)
{
_logger.LogDebug("Adding AnnotationID: {id}", annotation.Id);
switch (annotation.Type)
{
case AnnotationType.PSPDFKit.Image:
if (annotationData?.Attachments is not null)
_manager.AddImageAnnotation(annotation, annotationData.Attachments);
break;
case AnnotationType.PSPDFKit.Ink:
_manager.AddInkAnnotation(annotation);
break;
case AnnotationType.PSPDFKit.Widget:
// Add form field values
var formFieldValue = annotationData?.FormFieldValues?
.FirstOrDefault(fv => fv.Name == annotation.Id);
if (formFieldValue != null && !_options.IgnoredLabels.Contains(formFieldValue.Value))
{
_manager.AddFormFieldValue(annotation, formFieldValue, _options);
}
break;
}
}
}
}

View File

@ -0,0 +1,13 @@
namespace EnvelopeGenerator.Domain.Constants
{
public static class AnnotationType
{
public static class PSPDFKit
{
public const string Image = "pspdfkit/image";
public const string Ink = "pspdfkit/ink";
public const string Widget = "pspdfkit/widget";
public const string FormField = "pspdfkit/form-field-value";
}
}
}

View File

@ -5,6 +5,8 @@ using System.ComponentModel.DataAnnotations.Schema;
#if NETFRAMEWORK
using System;
using System.Collections.Generic;
#elif NET
using System.Text.Json.Serialization;
#endif
namespace EnvelopeGenerator.Domain.Entities
@ -120,13 +122,17 @@ public class Signature : ISignature, IHasReceiver
#endif
Annotations { get; set; }
#if NETFRAMEWORK
#if NET
[JsonIgnore]
#endif
[NotMapped]
public double Top => Math.Round(Y, 5);
#if NET
[JsonIgnore]
#endif
[NotMapped]
public double Left => Math.Round(X, 5);
#endif
}
#if NETFRAMEWORK

View File

@ -18,5 +18,5 @@
"Receiver": [],
"EmailTemplate": [ "TBSIG_EMAIL_TEMPLATE_AFT_UPD" ]
},
"UseInMemoryDb": true
"UseInMemoryDb": false
}