Browse Source

PDFAnnotation(windows) - 签名功能的创建使用相关实现

zhuyi 1 year ago
parent
commit
2d5e1615de

+ 54 - 0
compdfkit_demo_windows/compdfkit/compdfkit-tools/Annotation/PDFAnnotationPanel/PDFAnnotationControl/CPDFAnnotationControl.xaml.cs

@@ -20,6 +20,8 @@ using System.Windows.Navigation;
 using System.Windows.Shapes;
 using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
 using compdfkit_tools.Annotation.PDFAnnotationPanel.PDFAnnotationUI;
+using System.IO;
+using System.Windows.Ink;
 
 namespace compdfkit_tools.Annotation.PDFAnnotationControl
 {
@@ -248,6 +250,12 @@ namespace compdfkit_tools.Annotation.PDFAnnotationControl
                     CPDFStampData stampData = pdfAnnotationData as CPDFStampData;
                     SetStamp(ref stampAnnot, stampData);
                     break;
+                case AnnotationType.Signature:
+                    annotHandlerEventArgs = new StampAnnotArgs();
+                    StampAnnotArgs SignatureAnnot = annotHandlerEventArgs as StampAnnotArgs;
+                    CPDFSignatureData SignatureData = pdfAnnotationData as CPDFSignatureData;
+                    SetSignature(ref SignatureAnnot, SignatureData);
+                    break;
                 case AnnotationType.None:
                 default:
                     break;
@@ -259,6 +267,52 @@ namespace compdfkit_tools.Annotation.PDFAnnotationControl
             }
         }
 
+        public void SetSignature(ref StampAnnotArgs Args, CPDFSignatureData stamp)
+        {
+            switch (stamp.Type)
+            {
+                case SignatureType.TextType:
+                case SignatureType.ImageType:
+                    {
+                        Args.Opacity = 1;
+                        Args.Type = StampType.IMAGE_STAMP;
+                        Args.ImagePath = stamp.SourcePath;
+                    }
+                    break;
+                case SignatureType.Drawing:
+                    {
+                        Args.SetInkData(GetPoints(stamp.DrawingPath), stamp.inkThickness, stamp.inkColor);
+                    }
+                    break;
+                default:
+                    break;
+            }
+        }
+        private List<List<Point>> GetPoints(string Path)
+        {
+            StrokeCollection Strokes;
+            List<List<Point>> RawPointList = new List<List<Point>>();
+            using (FileStream strokeStream = File.OpenRead(Path))
+            {
+                Strokes = new StrokeCollection(strokeStream);
+            }
+
+            for (int kk = 0; kk < Strokes.Count; kk++)
+            {
+                List<Point> p = new List<Point>();
+                RawPointList.Add(p);
+                for (int gg = 0; gg < Strokes[kk].StylusPoints.Count; gg++)
+                {
+                    var point = Strokes[kk].StylusPoints[gg].ToPoint();
+
+                    if (point.X >= 0 && point.Y >= 0)
+                        RawPointList[kk].Add(point);
+
+                }
+            }
+            return RawPointList;
+        }
+
         private void SetStamp(ref StampAnnotArgs Args, CPDFStampData stamp)
         {
             Args.StampText = stamp.StampText;

+ 2 - 0
compdfkit_demo_windows/compdfkit/compdfkit-tools/Annotation/PDFAnnotationPanel/PDFAnnotationUI/CPDFSignatureUI.xaml.cs

@@ -36,6 +36,8 @@ namespace compdfkit_tools.Annotation.PDFAnnotationPanel.PDFAnnotationUI
             Binding binding = new Binding();
             binding.Source = SignatureList;
             SignatureListBox.SetBinding(ListBox.ItemsSourceProperty, binding);
+
+            LoadSettings();
         }
         private void LoadSettings()
         {

+ 149 - 9
compdfkit_demo_windows/compdfkit/compdfkit-tools/Annotation/PDFAnnotationPanel/PDFAnnotationUI/CreateSignatureDialog.xaml.cs

@@ -2,6 +2,8 @@
 using Microsoft.Win32;
 using System;
 using System.Collections.Generic;
+using System.Drawing.Imaging;
+using System.Drawing;
 using System.IO;
 using System.Linq;
 using System.Text;
@@ -14,6 +16,11 @@ using System.Windows.Input;
 using System.Windows.Media;
 using System.Windows.Media.Imaging;
 using System.Windows.Shapes;
+using System.Globalization;
+using System.Reflection;
+using ComPDFKitViewer.AnnotEvent;
+using System.Windows.Ink;
+using ComPDFKitViewer;
 
 namespace compdfkit_tools.Annotation.PDFAnnotationPanel.PDFAnnotationUI
 {
@@ -25,7 +32,10 @@ namespace compdfkit_tools.Annotation.PDFAnnotationPanel.PDFAnnotationUI
         public CPDFSignatureData cPDFSignatureData;
         private string SaveToPath;
         private string SignaturePath;
-        private bool IsLoaded = false;
+        private string DrawingSaveToPath;
+        private const double StrokeWidth = 3;
+        private const double StrokeHigh = 3;
+        private bool IsPageLoaded = false;
         public CreateSignatureDialog()
         {
             InitializeComponent();
@@ -36,9 +46,9 @@ namespace compdfkit_tools.Annotation.PDFAnnotationPanel.PDFAnnotationUI
             SignaturePath = System.IO.Path.Combine(Environment.CurrentDirectory, "ComPDFKit");
             SignaturePath = System.IO.Path.Combine(SignaturePath, "Signature");
             System.IO.DirectoryInfo directoryInfo = System.IO.Directory.CreateDirectory(SignaturePath);
-            IsLoaded = true;
-            DrawinkCanvas.DefaultDrawingAttributes.Width = 3;
-            DrawinkCanvas.DefaultDrawingAttributes.Height = 3;
+            IsPageLoaded = true;
+            DrawinkCanvas.DefaultDrawingAttributes.Width = StrokeWidth;
+            DrawinkCanvas.DefaultDrawingAttributes.Height = StrokeHigh;
         }
 
         private void Cancel_Click(object sender, RoutedEventArgs e)
@@ -48,7 +58,21 @@ namespace compdfkit_tools.Annotation.PDFAnnotationPanel.PDFAnnotationUI
 
         private void Save_Click(object sender, RoutedEventArgs e)
         {
-
+            switch (CreateSignatureControl.SelectedIndex)
+            {
+                case 0:
+                    SaveDrawSignature();
+                    break;
+                case 1:
+                    SaveTextSignature();
+                    break;
+                case 2:
+                    SaveImageSignature();
+                    break;
+                default:
+                    break;
+            }
+            this.Close();
         }
 
         private void Clear_Click(object sender, RoutedEventArgs e)
@@ -109,22 +133,138 @@ namespace compdfkit_tools.Annotation.PDFAnnotationPanel.PDFAnnotationUI
                 SaveToPath = "";
             }
         }
+
         private void ColorPickerControl_ColorChanged(object sender, EventArgs e)
         {
-            if (IsLoaded)
+            if (IsPageLoaded)
             {
-                DrawinkCanvas.DefaultDrawingAttributes.Color = ((SolidColorBrush)ColorPickerControl.Brush).Color; 
+                DrawinkCanvas.DefaultDrawingAttributes.Color = ((SolidColorBrush)ColorPickerControl.Brush).Color;
                 UpDataToStrokesObject();
             }
         }
 
         private void TextColorPickerControl_ColorChanged(object sender, EventArgs e)
         {
-            if (IsLoaded)
+            if (IsPageLoaded)
+            {
+                InPutTextBox.Foreground = TextColorPickerControl.Brush;
+
+            }
+        }
+        private void SaveTextSignature()
+        {
+            if (string.IsNullOrEmpty(InPutTextBox.Text))
+            {
+                return;
+            }
+            System.Windows.Media.Brush fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#252629"));
+            fontcolor=TextColorPickerControl.Brush;
+
+            Bitmap bmp = TextToBitmap(InPutTextBox.Text, "Arial", 50, System.Drawing.Rectangle.Empty, fontcolor, System.Drawing.Color.Transparent);
+            string guid = Guid.NewGuid().ToString();
+            string path = System.IO.Path.Combine(SignaturePath, guid);
+            bmp.Save(path, ImageFormat.Png);
+            SaveToPath = path;
+
+            cPDFSignatureData = new CPDFSignatureData();
+            cPDFSignatureData.SourcePath = SaveToPath;
+            cPDFSignatureData.AnnotationType = AnnotationType.Signature;
+            cPDFSignatureData.Type = SignatureType.TextType;
+        }
+
+        private void SaveImageSignature()
+        {
+            cPDFSignatureData = new CPDFSignatureData();
+            cPDFSignatureData.SourcePath = SaveToPath;
+            cPDFSignatureData.AnnotationType = AnnotationType.Signature;
+            cPDFSignatureData.Type = SignatureType.ImageType;
+        }
+        private void SaveDrawSignature()
+        {
+            var FreeHandpath = SignaturePath;
+            string name = Guid.NewGuid().ToString();
+            FreeHandpath = System.IO.Path.Combine(FreeHandpath, name);
+            using (System.IO.FileStream stream = new System.IO.FileStream(FreeHandpath, System.IO.FileMode.Create))
+            {
+                DrawinkCanvas.Strokes.Save(stream);
+            }
+
+            StampAnnotArgs stampArgs = new StampAnnotArgs();
+
+            List<List<System.Windows.Point>> RawPointList = new List<List<System.Windows.Point>>();
+            for (int kk = 0; kk < DrawinkCanvas.Strokes.Count; kk++)
             {
-                InPutTextBox.Foreground= TextColorPickerControl.Brush;
+                List<System.Windows.Point> p = new List<System.Windows.Point>();
+                RawPointList.Add(p);
+                for (int gg = 0; gg < DrawinkCanvas.Strokes[kk].StylusPoints.Count; gg++)
+                {
+                    var point = DrawinkCanvas.Strokes[kk].StylusPoints[gg].ToPoint();
+
+                    if (point.X >= 0 && point.Y >= 0)
+                        RawPointList[kk].Add(point);
 
+                }
             }
+            DrawingSaveToPath = FreeHandpath;
+
+            //根据当前选项创建预览图片
+            double inkThickness;
+            inkThickness = StrokeWidth;
+            stampArgs.SetInkData(RawPointList, inkThickness, DrawinkCanvas.DefaultDrawingAttributes.Color);
+            var writeStamp = stampArgs.GetStampDrawing();
+
+            FreeHandpath = SignaturePath;
+            string thumbnailName = Guid.NewGuid().ToString();
+            FreeHandpath = System.IO.Path.Combine(FreeHandpath, thumbnailName);
+            using (FileStream stream5 = new FileStream(FreeHandpath, FileMode.Create))
+            {
+                PngBitmapEncoder encoder5 = new PngBitmapEncoder();
+                encoder5.Frames.Add(BitmapFrame.Create(writeStamp));
+                encoder5.Save(stream5);
+            }
+            SaveToPath = FreeHandpath;
+
+            cPDFSignatureData =new CPDFSignatureData();
+            cPDFSignatureData.AnnotationType = AnnotationType.Signature;
+            cPDFSignatureData.SourcePath = SaveToPath;
+            cPDFSignatureData.DrawingPath = DrawingSaveToPath;
+            cPDFSignatureData.Type = SignatureType.Drawing;
+            cPDFSignatureData.inkThickness = inkThickness;
+            cPDFSignatureData.inkColor = DrawinkCanvas.DefaultDrawingAttributes.Color;
+        }
+
+        private Bitmap TextToBitmap(string text, string FontFamily, double size, System.Drawing.Rectangle rect, System.Windows.Media.Brush fontcolor, System.Drawing.Color backColor)
+        {
+            FormattedText formatText = new FormattedText(
+            text,
+            CultureInfo.CurrentCulture,
+            FlowDirection.LeftToRight,
+            new Typeface(new System.Windows.Media.FontFamily(FontFamily), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal),
+            size,
+            fontcolor
+            );
+
+            DrawingVisual drawingVisual = new DrawingVisual();
+            DrawingContext dc = drawingVisual.RenderOpen();
+            dc.DrawText(formatText, new System.Windows.Point(2, 10));
+            dc.Close();
+
+
+            Rect x = drawingVisual.ContentBounds;
+            Rect DrawRect = new Rect(0, 0, x.Width + (x.X / 2), x.Height + x.Y);
+
+            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)((int)DrawRect.Width + (x.X / 2)), (int)((int)DrawRect.Height + x.Y), 96F, 96F, PixelFormats.Pbgra32);
+            renderTargetBitmap.Render(drawingVisual);
+
+            MemoryStream stream = new MemoryStream();
+            BitmapEncoder encoder = new PngBitmapEncoder();
+
+            encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
+            encoder.Save(stream);
+
+            Bitmap bitmap = new Bitmap(stream);
+
+            return bitmap;
         }
     }
 }

+ 30 - 38
compdfkit_demo_windows/compdfkit/compdfkit-tools/Properties/Resources.Designer.cs

@@ -1,69 +1,61 @@
 //------------------------------------------------------------------------------
 // <auto-generated>
-//     This code was generated by a tool.
-//     Runtime Version:4.0.30319.42000
+//     此代码由工具生成。
+//     运行时版本:4.0.30319.42000
 //
-//     Changes to this file may cause incorrect behavior and will be lost if
-//     the code is regenerated.
+//     对此文件的更改可能会导致不正确的行为,并且如果
+//     重新生成代码,这些更改将会丢失。
 // </auto-generated>
 //------------------------------------------------------------------------------
 
-namespace compdfkit_tools.Properties
-{
-
-
+namespace compdfkit_tools.Properties {
+    using System;
+    
+    
     /// <summary>
-    ///   A strongly-typed resource class, for looking up localized strings, etc.
+    ///   一个强类型的资源类,用于查找本地化的字符串等。
     /// </summary>
-    // This class was auto-generated by the StronglyTypedResourceBuilder
-    // class via a tool like ResGen or Visual Studio.
-    // To add or remove a member, edit your .ResX file then rerun ResGen
-    // with the /str option, or rebuild your VS project.
-    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+    // 此类是由 StronglyTypedResourceBuilder
+    // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
+    // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
+    // (以 /str 作为命令选项),或重新生成 VS 项目。
+    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
     [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
     [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
-    internal class Resources
-    {
-
+    internal class Resources {
+        
         private static global::System.Resources.ResourceManager resourceMan;
-
+        
         private static global::System.Globalization.CultureInfo resourceCulture;
-
+        
         [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
-        internal Resources()
-        {
+        internal Resources() {
         }
-
+        
         /// <summary>
-        ///   Returns the cached ResourceManager instance used by this class.
+        ///   返回此类使用的缓存的 ResourceManager 实例。
         /// </summary>
         [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
-        internal static global::System.Resources.ResourceManager ResourceManager
-        {
-            get
-            {
-                if ((resourceMan == null))
-                {
+        internal static global::System.Resources.ResourceManager ResourceManager {
+            get {
+                if (object.ReferenceEquals(resourceMan, null)) {
                     global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("compdfkit_tools.Properties.Resources", typeof(Resources).Assembly);
                     resourceMan = temp;
                 }
                 return resourceMan;
             }
         }
-
+        
         /// <summary>
-        ///   Overrides the current thread's CurrentUICulture property for all
-        ///   resource lookups using this strongly typed resource class.
+        ///   重写当前线程的 CurrentUICulture 属性,对
+        ///   使用此强类型资源类的所有资源查找执行重写。
         /// </summary>
         [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
-        internal static global::System.Globalization.CultureInfo Culture
-        {
-            get
-            {
+        internal static global::System.Globalization.CultureInfo Culture {
+            get {
                 return resourceCulture;
             }
-            set
-            {
+            set {
                 resourceCulture = value;
             }
         }

+ 2 - 2
compdfkit_demo_windows/compdfkit/compdfkit-tools/app.config

@@ -1,5 +1,5 @@
-<?xml version="1.0" encoding="utf-8" ?>
+<?xml version="1.0" encoding="utf-8"?>
 <configuration>
     <configSections>
     </configSections>
-</configuration>
+<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/></startup></configuration>

+ 1 - 0
compdfkit_demo_windows/compdfkit/compdfkit-tools/compdfkit-tools.csproj

@@ -14,6 +14,7 @@
     <WarningLevel>4</WarningLevel>
     <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
     <Deterministic>true</Deterministic>
+    <TargetFrameworkProfile />
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
     <PlatformTarget>AnyCPU</PlatformTarget>