chr
2024-08-30 3d4d3fc5b2ef7fc3904e2e79f0c0896241919958
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
using Microsoft.Win32;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
 
namespace PdmSwPlugin.UI
{
    /// <summary>
    /// UserControl1.xaml 的交互逻辑
    /// </summary>
    public partial class CustomRichBox : UserControl
    {
        public CustomRichBox()
        {
            InitializeComponent();
        }
 
        private void Color_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender == null)
            {
                return;
            }
            var item = sender as ComboBox;
            var buttonType = item.Name == "combBackground" ? "Background" : "Foreground";
            if (item != null)
            {
                var color = (item.SelectedItem as ComboBoxItem).Background;
                SetColor(buttonType, color);
            }
        }
 
        private void FontSize_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender == null)
            {
                return;
            }
            var item = sender as ComboBox;
            if (item != null)
            {
                string sizeStr = (item.SelectedItem as ComboBoxItem).Content.ToString();
                try
                {
                    double size = double.Parse(sizeStr);
                    var textSelection = this.richTextBox?.Selection;
                    if (textSelection == null) return;
                    textSelection.ApplyPropertyValue(TextElement.FontSizeProperty, size);
                }
                catch
                {
 
                }
            }
        }
 
        private void SetColor(string buttonType, Brush brush)
        {
            var textSelection = this.richTextBox.Selection;
 
            if (textSelection == null)
            {
                return;
            }
            if (buttonType == "Background")
            {
                var propertyValue = textSelection.GetPropertyValue(TextElement.BackgroundProperty);
                var bgBrush = (Brush)propertyValue;
                if (bgBrush == brush)
                {
                    textSelection.ApplyPropertyValue(TextElement.BackgroundProperty, Colors.White);
                }
                else
                {
                    textSelection.ApplyPropertyValue(TextElement.BackgroundProperty, brush);
                }
            }
            if (buttonType == "Foreground")
            {
                var propertyValue = textSelection.GetPropertyValue(TextElement.ForegroundProperty);
                var foreground = (Brush)propertyValue;
                if (foreground == brush)
                {
                    textSelection.ApplyPropertyValue(TextElement.ForegroundProperty, Colors.Black);
                }
                else
                {
                    textSelection.ApplyPropertyValue(TextElement.ForegroundProperty, brush);
                }
            }
            richTextBox.Focus();
        }
 
        private void Setting_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var textSelection = this.richTextBox.Selection;
            Button button = sender as Button;
            if (button == null) return;
            string buttonType = button.Tag.ToString();
            if (buttonType == "StrikeLine")
            {
                var propertyValue = textSelection.GetPropertyValue(Inline.TextDecorationsProperty);
                var textDecorationCollection = (TextDecorationCollection)propertyValue;
                if (textDecorationCollection == TextDecorations.Strikethrough)
                {
                    textSelection.ApplyPropertyValue(Inline.TextDecorationsProperty, null);
                }
                else
                {
                    textSelection.ApplyPropertyValue(Inline.TextDecorationsProperty, TextDecorations.Strikethrough);
                }
            }
            else if (buttonType == "Super")
            {
                var propertyValue = textSelection.GetPropertyValue(Inline.BaselineAlignmentProperty);
                var supper = (BaselineAlignment)propertyValue;
                if (supper == BaselineAlignment.Superscript)
                {
                    textSelection.ApplyPropertyValue(Inline.BaselineAlignmentProperty, BaselineAlignment.Top);
                }
                else
                {
                    textSelection.ApplyPropertyValue(Inline.BaselineAlignmentProperty, BaselineAlignment.Superscript);
                }
            }
            else if (buttonType == "Sub")
            {
                var propertyValue = textSelection.GetPropertyValue(Inline.BaselineAlignmentProperty);
                var sub = (BaselineAlignment)propertyValue;
                if (sub == BaselineAlignment.Subscript)
                {
                    textSelection.ApplyPropertyValue(Inline.BaselineAlignmentProperty, BaselineAlignment.Top);
                }
                else
                {
                    textSelection.ApplyPropertyValue(Inline.BaselineAlignmentProperty, BaselineAlignment.Subscript);
                }
            }
            else if (buttonType == "fontSize")
            {
 
            }
            else if (buttonType == "Image")
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Title = "请选择需要插入的图片";
                openFileDialog.Filter = "图片文件|*.png";
                bool? flag = openFileDialog.ShowDialog();
                if (flag == true)
                {
                    try
                    {
                        var fileName = openFileDialog.FileName;
                        var imgSource = new BitmapImage(new Uri(fileName));
                        InsertPicToRichBox(imgSource);
                        /*double imgWidth = imgSource.Width, imgHeight = imgSource.Height;
                        if (imgWidth > richTextBox.ActualWidth)
                        {
                            double rate = Math.Floor(richTextBox.ActualWidth / imgWidth);
                            imgWidth = imgWidth * rate;
                            imgHeight = imgHeight * rate;
                        }
 
                        var img = new Image() { Source = imgSource, Stretch = Stretch.Uniform, Width = this.richTextBox.ActualWidth - 50 };
                        var imgContainer = new BlockUIContainer(img);
                        this.richTextBox.CaretPosition.InsertParagraphBreak();
                        this.richTextBox.Document.Blocks.InsertAfter(this.richTextBox.CaretPosition.Paragraph, imgContainer);*/
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("不支持的图片格式");
                    }
                }
            }
            else if (buttonType == "Print")
            {
                PrintDialog pd = new PrintDialog();
                if ((pd.ShowDialog() == true))
                {
                    //use either one of the below
                    pd.PrintVisual(this.richTextBox as Visual, "打印富文本1");
                    pd.PrintDocument((((IDocumentPaginatorSource)this.richTextBox.Document).DocumentPaginator), "打印富文本2");
                }
            }
            richTextBox.Focus();
        }
 
        private string ImageToBase64(BitmapSource image)
        {
            JpegBitmapEncoder encoder = new JpegBitmapEncoder(); // 使用JPEG编码
            encoder.Frames.Add(BitmapFrame.Create(image));
            using (MemoryStream ms = new MemoryStream())
            {
                encoder.Save(ms);
                byte[] imageBytes = ms.ToArray();
                return Convert.ToBase64String(imageBytes); // 将字节数组转换为Base64字符串
            }
        }
 
        public byte[] GetBlob()
        {
            var range = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                range.Save(memoryStream, DataFormats.XamlPackage);
                return memoryStream.ToArray();
            }
        }
 
        public string GetContent()
        {
            FlowDocument flowDoc = richTextBox.Document;
 
            // 遍历文档中的所有Block
            foreach (Block block in flowDoc.Blocks)
            {
                if (block is Paragraph)
                {
                    Paragraph paragraph = block as Paragraph;
                    foreach (Inline inline in paragraph.Inlines)
                    {
                        if (inline is InlineUIContainer)
                        {
                            InlineUIContainer uiContainer = inline as InlineUIContainer;
                            if (uiContainer.Child is Image)
                            {
                                Image image = uiContainer.Child as Image;
                                BitmapSource bitmapSource = image.Source as BitmapSource;
                                string base64 = ImageToBase64(bitmapSource);
                                string imgXaml = $"<Image Source=\"data:image/jpg;base64,{base64}\" />";
                                // 替换原有的Image对象
                                uiContainer.Child = new Image() { Source = new BitmapImage(new Uri(imgXaml)) };
                            }
                        }
                    }
                }
            }
 
            using (MemoryStream memoryStream = new MemoryStream())
            {
                XamlWriter.Save(flowDoc, memoryStream);
                memoryStream.Seek(0, SeekOrigin.Begin);
                using (StreamReader reader = new StreamReader(memoryStream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
 
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            fontSizeComb.SelectedIndex = 0;
            combBackground.SelectedIndex = 0;
            combForeground.SelectedIndex = 0;
        }
 
        public void LoadFromBlob(byte[] blob)
        {
            if (blob == null || blob.Length <= 0)
            {
                return;
            }
            var range = new TextRange(this.richTextBox.Document.ContentStart, this.richTextBox.Document.ContentEnd);
            using (var ss = new MemoryStream(blob))
            {
                range.Load(ss, DataFormats.XamlPackage);
            }
        }
 
        private void InsertPicToRichBox(BitmapSource img)
        {
            bool DisableEdit = DProperty.GetDisableEdit(this);
            if (DisableEdit) return;
            try
            {
                double picMaxWidth = DProperty.GetPicMaxWidth(this);
                double width = img.PixelWidth;
                if (picMaxWidth > 0 && width > picMaxWidth)
                {
                    width = picMaxWidth;
                }
                TextPointer pointer = richTextBox.CaretPosition;
                /// 行内插入图片
                var insertImg = new Image() { Source = img, Stretch = Stretch.Uniform, Width = width };
                var imgContainer = new InlineUIContainer(insertImg);
                pointer.Paragraph.Inlines.Add(imgContainer);
 
                //string base64 = ImageToBase64(img);
                //string imgXaml = $"<Image Source=\"data:image/jpg;base64,{base64}\" />";
                //var imgContainer = new InlineUIContainer(imgXaml);
                //pointer.Paragraph.Inlines.Add(imgXaml);
 
                /// 下面注释的这段是直接插入新段落的写法
                //var imgContainer = new BlockUIContainer(insertImg);
                //this.richTextBox.CaretPosition.InsertParagraphBreak();
                //this.richTextBox.Document.Blocks.InsertAfter(this.richTextBox.CaretPosition.Paragraph, imgContainer);
            }
            catch (Exception e)
            {
 
 
            }
        }
 
        public void ChangeStatus(bool DisableEdit)
        {
            if (DisableEdit)
            {
                toolBar.Visibility = Visibility.Collapsed;
                richTextBox.IsReadOnly = true;
                richTextBox.BorderThickness = new Thickness(0);
            }
            else
            {
                toolBar.Visibility = Visibility.Visible;
                richTextBox.IsReadOnly = false;
                richTextBox.BorderThickness = new Thickness(1);
            }
        }
 
        /// <summary>
        /// 富文本 Ctrl+V 事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.V)
            {
                if (Clipboard.ContainsImage())
                {
                    var img = Clipboard.GetImage();
                    InsertPicToRichBox(img);
                    e.Handled = true;
                }
            }
        }
 
        /// <summary>
        /// 复制菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Copy_Click(object sender, RoutedEventArgs e)
        {
            richTextBox.Copy();
        }
 
        /// <summary>
        /// 粘贴菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Paste_Click(object sender, RoutedEventArgs e)
        {
 
            try
            {
                if (DProperty.GetDisableEdit(this) == true)
                {
                    return;
                }
                if (Clipboard.ContainsImage())
                {
                    var img = Clipboard.GetImage();
                    InsertPicToRichBox(img);
                }
                else
                {
                    richTextBox.Paste();
                }
            }
            catch (Exception ex)
            {
 
            }
        }
 
 
 
        public void ToBase64Image2()
        {
            richTextBox.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
            richTextBox.Arrange(new Rect(new Size(richTextBox.ActualWidth, richTextBox.ActualHeight)));
 
            // Create a DrawingVisual and use a VisualBrush to render the RichTextBox
            DrawingVisual visual = new DrawingVisual();
            using (DrawingContext context = visual.RenderOpen())
            {
                VisualBrush brush = new VisualBrush(richTextBox);
                context.DrawRectangle(brush, null, new Rect(new Size(richTextBox.ActualWidth, richTextBox.ActualHeight)));
            }
 
            // Render the DrawingVisual to a RenderTargetBitmap
            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(
                (int)richTextBox.ActualWidth,
                (int)richTextBox.ActualHeight,
                96d, 96d, PixelFormats.Pbgra32);
 
            renderTargetBitmap.Render(visual);
 
            // Create a BitmapEncoder to encode the RenderTargetBitmap
            PngBitmapEncoder pngEncoder = new PngBitmapEncoder();
            pngEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
            using (FileStream stream = new FileStream("C:\\Workspace\\test.png", FileMode.OpenOrCreate))
            {
                // Save the encoded PNG image to a memory stream
                pngEncoder.Save(stream);
 
                stream.Flush();
                stream.Close();
            }
 
           /* using (MemoryStream memoryStream = new MemoryStream())
            {
                // Save the encoded PNG image to a memory stream
                pngEncoder.Save(memoryStream);
                // Convert the memory stream to a byte array
                byte[] imageBytes = memoryStream.ToArray();
                // Convert the byte array to a Base64 string
                return Convert.ToBase64String(imageBytes);
            }*/
        }
 
        public string ToBase64Image()
        {
            //string sss = XamlWriter.Save(richTextBox.Document);
            //Debug.Print(sss);
            // Force a measure and arrange of the RichTextBox to ensure all content is rendered
            //richTextBox.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
            //richTextBox.Arrange(new Rect(new Size(richTextBox.ActualWidth, richTextBox.ActualHeight)));
 
 
            //// Render the DrawingVisual to a RenderTargetBitmap
            //RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(
            //    (int)richTextBox.ActualWidth,
            //    (int)richTextBox.ActualHeight,
            //    96d, 96d, PixelFormats.Pbgra32);
 
            //FlowDocumentReader reader = new FlowDocumentReader
            //{
            //    Document = richTextBox.Document
            //};
 
            //renderTargetBitmap.Render(reader);
 
            //// Create a BitmapEncoder to encode the RenderTargetBitmap
            //PngBitmapEncoder pngEncoder = new PngBitmapEncoder();
            //pngEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
 
            //using (FileStream stream = new FileStream("C:\\Workspace\\test.png",FileMode.OpenOrCreate))
            //{
            //    // Save the encoded PNG image to a memory stream
            //    pngEncoder.Save(stream);
 
            //    stream.Flush();
            //    stream.Close();
            //}
 
            //string sss = XamlWriter.Save(richTextBox.Document);
            //Debug.Print(sss);
            // Backup original size
            var originalWidth = richTextBox.ExtentWidth;
            var originalHeight = richTextBox.ExtentHeight;
 
            //richTextBox.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
            richTextBox.Arrange(new Rect(new Size(originalWidth, originalHeight)));
 
            int dpi = 300;
 
            // Create a RenderTargetBitmap with the new size
            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(
                (int)(originalWidth * dpi / 96),
                (int)(originalHeight * dpi / 96),
                300d, 300d, PixelFormats.Default);
 
            // Render the control to the RenderTargetBitmap
            renderTargetBitmap.Render(richTextBox);
 
            // Create an encoder (PNG in this case)
            PngBitmapEncoder pngEncoder = new PngBitmapEncoder();
            pngEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
 
 
            FileStream pngfs = new FileStream("C:\\1.png", FileMode.OpenOrCreate);
     
            BitmapEncoder be = new PngBitmapEncoder();
            be.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
 
            using (MemoryStream ms = new MemoryStream())
            {
                be.Save(ms);
                byte[] imageBytes = ms.ToArray();
                return Convert.ToBase64String(imageBytes); // 将字节数组转换为Base64字符串
            }
 
            //be.Save(pngfs);
            //pngfs.Close();
        }
    }
}