Chr
2024-08-20 45c004d4bb5a6f73843a8e8020523f4df14a14e4
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
using Microsoft.Win32;
using System;
using System.IO;
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;
 
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;
                }
                /// 行内插入图片
                var insertImg = new Image() { Source = img, Stretch = Stretch.Uniform, Width = width };
                var imgContainer = new InlineUIContainer(insertImg);
                TextPointer pointer = richTextBox.CaretPosition;
                pointer.Paragraph.Inlines.Add(imgContainer);
 
                /// 下面注释的这段是直接插入新段落的写法
                //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)
            {
 
            }
        }
    }
}