public void Write(string outputPath, FlowDocument doc) { Document pdfDoc = new Document(PageSize.A4, 50, 50, 50, 50); Font textFont = new Font(baseFont, DEFAULT_FONTSIZE, Font.NORMAL, BaseColor.BLACK); Font headingFont = new Font(baseFont, DEFAULT_HEADINGSIZE, Font.BOLD, BaseColor.BLACK); using (FileStream stream = new FileStream(outputPath, FileMode.Create)) { PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); foreach (Block i in doc.Blocks) { if (i is System.Windows.Documents.Paragraph) { TextRange range = new TextRange(i.ContentStart, i.ContentEnd); Console.WriteLine(i.Tag); switch (i.Tag as string) { case "Paragraph": iTextSharp.text.Paragraph par = new iTextSharp.text.Paragraph(range.Text, textFont); par.Alignment = Element.ALIGN_JUSTIFIED; pdfDoc.Add(par); break; case "Heading": iTextSharp.text.Paragraph head = new iTextSharp.text.Paragraph(range.Text, headingFont); head.Alignment = Element.ALIGN_CENTER; head.SpacingAfter = 10; pdfDoc.Add(head); break; default: iTextSharp.text.Paragraph def = new iTextSharp.text.Paragraph(range.Text, textFont); def.Alignment = Element.ALIGN_JUSTIFIED; pdfDoc.Add(def); break; } } else if (i is System.Windows.Documents.List) { iTextSharp.text.List list = new iTextSharp.text.List(iTextSharp.text.List.UNORDERED, 10f); list.SetListSymbol("\u2022"); list.IndentationLeft = 15f; foreach (var li in (i as System.Windows.Documents.List).ListItems) { iTextSharp.text.ListItem listitem = new iTextSharp.text.ListItem(); TextRange range = new TextRange(li.Blocks.ElementAt(0).ContentStart, li.Blocks.ElementAt(0).ContentEnd); string text = range.Text.Substring(1); iTextSharp.text.Paragraph par = new iTextSharp.text.Paragraph(text, textFont); listitem.SpacingAfter = 10; listitem.Add(par); list.Add(listitem); } pdfDoc.Add(list); } } if (pdfDoc.PageNumber == 0) { iTextSharp.text.Paragraph par = new iTextSharp.text.Paragraph(" "); par.Alignment = Element.ALIGN_JUSTIFIED; pdfDoc.Add(par); } pdfDoc.Close(); } }
/// <summary> /// Converts the XHtml content to XAML and sets the converted content in a flow document. /// </summary> /// <param name="document">The flow document in which the XHtml content has to be loaded.</param> /// <param name="text">The Unicode UTF-8 coded XHtml text to load.</param> /// <exception cref="InvalidDataException">When an error occured while parsing xaml code.</exception> public void SetText(FlowDocument document, string text) { try { if (!string.IsNullOrEmpty(text)) { XDocument xDocument = XDocument.Parse(text); string xaml = HtmlToXamlConverter.ConvertXHtmlToXaml(xDocument, false); TextRange tr = new TextRange(document.ContentStart, document.ContentEnd); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xaml))) { tr.Load(ms, DataFormats.Xaml); } _xHtml = text; } } catch (Exception e) { // todo tb: Logging //log.Error("Data provided is not in the correct Xaml or XHtml format: {0}", e); throw e; } }
public UndoLevelStyle(OutlinerNote note) { __NoteId = note.Id; __Before = new MemoryStream[note.Columns.Count]; __After = new MemoryStream[note.Columns.Count]; __IsEmpty = true; for (int i = 0; i < note.Columns.Count; i++) { FlowDocument document = note.Columns[i].ColumnData as FlowDocument; if (document == null) continue; __Before[i] = new MemoryStream(); __After[i] = new MemoryStream(); TextRange range = new TextRange(document.ContentStart, document.ContentEnd); range.Save(__Before[i], DataFormats.Xaml); if (!range.IsEmpty) __IsEmpty = false; } }
void XmppConnection_OnMessage(object sender, Message msg) { if (!roomName.Contains(msg.From.User)) return; if (msg.From.Resource == Client.LoginPacket.AllSummonerData.Summoner.Name) return; Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() => { if (msg.Body == "This room is not anonymous") return; var tr = new TextRange(ChatText.Document.ContentEnd, ChatText.Document.ContentEnd) { Text = msg.From.Resource + ": " }; tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Turquoise); tr = new TextRange(ChatText.Document.ContentEnd, ChatText.Document.ContentEnd) { Text = msg.Body.Replace("<![CDATA[", "").Replace("]]>", string.Empty) + Environment.NewLine }; tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.White); ChatText.ScrollToEnd(); })); }
public RichTextBoxToolbar() { SpecialInitializeComponent(); cmbFontFamily.SelectionChanged += (s, e) => { if (cmbFontFamily.SelectedValue != null && RichTextBox != null) { TextRange tr = new TextRange(RichTextBox.Selection.Start, RichTextBox.Selection.End); var value = cmbFontFamily.SelectedValue; tr.ApplyPropertyValue(TextElement.FontFamilyProperty, value); } }; cmbFontSize.SelectionChanged += (s, e) => { if (cmbFontSize.SelectedValue != null && RichTextBox != null) { TextRange tr = new TextRange(RichTextBox.Selection.Start, RichTextBox.Selection.End); var value = ((ComboBoxItem)cmbFontSize.SelectedValue).Content.ToString(); tr.ApplyPropertyValue(TextElement.FontSizeProperty, double.Parse(value)); } }; cmbFontSize.AddHandler(TextBoxBase.TextChangedEvent, new TextChangedEventHandler((s, e) => { if (!string.IsNullOrEmpty(cmbFontSize.Text) && RichTextBox != null) { TextRange tr = new TextRange(RichTextBox.Selection.Start, RichTextBox.Selection.End); tr.ApplyPropertyValue(TextElement.FontSizeProperty, double.Parse(cmbFontSize.Text)); } })); }
private void RichTextBox_Drop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] docPath = (string[])e.Data.GetData(DataFormats.FileDrop); // By default, open as Rich Text (RTF). var dataFormat = DataFormats.Rtf; // If the Shift key is pressed, open as plain text. if (e.KeyStates == DragDropKeyStates.ShiftKey) { dataFormat = DataFormats.Text; } System.Windows.Documents.TextRange range; System.IO.FileStream fStream; if (System.IO.File.Exists(docPath[0])) { try { // Open the document in the RichTextBox. range = new System.Windows.Documents.TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); fStream = new System.IO.FileStream(docPath[0], System.IO.FileMode.OpenOrCreate); range.Load(fStream, dataFormat); fStream.Close(); } catch (System.Exception) { MessageBox.Show("File could not be opened. Make sure the file is a text file."); } } } }
public void ShowLobbyMessage(string message) { var tr = new TextRange(output.Document.ContentEnd, output.Document.ContentEnd); tr.Text = message + '\n'; tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red); if (scroller.VerticalOffset == scroller.ScrollableHeight) scroller.ScrollToBottom(); }
private void Details_Click(object sender, RoutedEventArgs e) { RoomClass rc=new RoomClass(); var a = this.alarmGrid.SelectedItem; var b = a as DataRowView; int _Aid = Convert.ToInt32(b.Row[0]); MySqlDataReader reader = rc.getHistoryAlarmImformation(_Aid); AlarmDetails ad = new AlarmDetails(); TextRange _Text = new TextRange(ad.Information.Document.ContentStart, ad.Information.Document.ContentEnd); if (reader.Read()) { ad.number.Text = reader["NUMBER"].ToString(); ad.Ename.Text = reader["NAME"].ToString(); ad.Etype.Text = reader["TYPE_NAME"].ToString(); ad.Atype.Text = reader["ALARM_TYPE_NAME"].ToString(); ad.room.Text = reader["ROOM_NAME"].ToString(); ad.Handle_User.Text = reader["USER_NAME"].ToString(); ad.Handle_Time.Text = reader["PROCESSING_TIME"].ToString(); ad.Alarm_Time.Text = reader["ALARM_TIME"].ToString(); _Text.Text = reader["REMARK"].ToString(); ad.title.Content = reader["NUMBER"] + " 历史报警信息:"; } ad.Owner = Window.GetWindow(this); ad.ShowDialog(); }
/// <summary> /// Converts HTML document to RTF format; Places this RTF in RichTextBox; /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Start_Click(object sender, RoutedEventArgs e) { string htmlFile = @"..\..\Sample.html"; string rtfString = String.Empty; // Create an instance of the converter. SautinSoft.HtmlToRtf h = new HtmlToRtf(); h.TextStyle.DefaultFontFamily = "Calibri"; // Convert HTML to RTF. if (h.OpenHtml(htmlFile)) { using (MemoryStream msRtf = new MemoryStream()) { // Convert HTML to RTF. if (h.ToRtf(msRtf)) { // Place the RTF into RichTextBox. System.Windows.Documents.TextRange tr = new System.Windows.Documents.TextRange( RtfControl.Document.ContentStart, RtfControl.Document.ContentEnd); tr.Load(msRtf, DataFormats.Rtf); } } } }
public void Update() { ChatText.Document.Blocks.Clear(); ChatPlayerItem tempItem = null; foreach (KeyValuePair<string, ChatPlayerItem> x in Client.AllPlayers) { if (x.Value.Username == (string)Client.ChatItem.PlayerLabelName.Content) { tempItem = x.Value; break; } } foreach (string x in tempItem.Messages.ToArray()) { string[] Message = x.Split('|'); TextRange tr = new TextRange(ChatText.Document.ContentEnd, ChatText.Document.ContentEnd); if (Message[0] == tempItem.Username) { tr.Text = tempItem.Username + ": "; tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Gold); } else { tr.Text = Message[0] + ": "; tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.SteelBlue); } tr = new TextRange(ChatText.Document.ContentEnd, ChatText.Document.ContentEnd); tr.Text = x.Replace(Message[0] + "|", "") + Environment.NewLine; tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.White); } ChatText.ScrollToEnd(); }
public TypefaceListItem(Typeface typeface) { _displayName = GetDisplayName(typeface); _simulated = typeface.IsBoldSimulated || typeface.IsObliqueSimulated; FontFamily = typeface.FontFamily; FontWeight = typeface.Weight; FontStyle = typeface.Style; FontStretch = typeface.Stretch; var itemLabel = _displayName; if (_simulated) { var formatString = Properties.Resources.ResourceManager.GetString( "simulated", CultureInfo.CurrentUICulture ); itemLabel = string.Format(formatString, itemLabel); } Text = itemLabel; ToolTip = itemLabel; // In the case of symbol font, apply the default message font to the text so it can be read. if (FontFamilyListItem.IsSymbolFont(typeface.FontFamily)) { var range = new TextRange(ContentStart, ContentEnd); range.ApplyPropertyValue(FontFamilyProperty, SystemFonts.MessageFontFamily); } }
private static string ConvertRtfToXaml(string rtfText) { var richTextBox = new RichTextBox(); if (string.IsNullOrEmpty(rtfText)) return ""; var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); //Create a MemoryStream of the Rtf content using (var rtfMemoryStream = new MemoryStream()) { using (var rtfStreamWriter = new StreamWriter(rtfMemoryStream)) { rtfStreamWriter.Write(rtfText); rtfStreamWriter.Flush(); rtfMemoryStream.Seek(0, SeekOrigin.Begin); //Load the MemoryStream into TextRange ranging from start to end of RichTextBox. textRange.Load(rtfMemoryStream, DataFormats.Rtf); } } using (var rtfMemoryStream = new MemoryStream()) { textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); textRange.Save(rtfMemoryStream, DataFormats.Xaml); rtfMemoryStream.Seek(0, SeekOrigin.Begin); using (var rtfStreamReader = new StreamReader(rtfMemoryStream)) { return rtfStreamReader.ReadToEnd(); } } }
private void Paste_RequestNavigate(object sender, RequestNavigateEventArgs e) { TextPointer start = this._rtb.Document.ContentStart, end = this._rtb.Document.ContentEnd; TextRange tr = new TextRange(start, end); tr.Select(start, end); MemoryStream ms; StringBuilder sb = new StringBuilder(); foreach (String dataFormat in _listOfFormats) { if (tr.CanSave(dataFormat)) { ms = new MemoryStream(); tr.Save(ms, dataFormat); ms.Seek(0, SeekOrigin.Begin); sb.AppendLine(dataFormat); foreach (char c in ms.ToArray().Select<byte, char>((b) => (char)b)) { sb.Append(c); } sb.AppendLine(); } //_tb.Text = sb.ToString(); } }
public void Apply(swd.TextRange range) { range.ApplyPropertyValue(swd.TextElement.FontFamilyProperty, Control.FontFamily); range.ApplyPropertyValue(swd.TextElement.FontStyleProperty, Control.Style); range.ApplyPropertyValue(swd.TextElement.FontStretchProperty, Control.Stretch); range.ApplyPropertyValue(swd.TextElement.FontWeightProperty, Control.Weight); }
private void open_button_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); openFileDialog1.Filter = @"Evennote File(*.note)|*.note"; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == true) { Note temp = Evennote.OpenNoteFromFile(openFileDialog1.FileName); titleTextBox.Text = temp.Title; using (MemoryStream mem = new MemoryStream()) { TextRange range = new TextRange(temp.Text.ContentStart, temp.Text.ContentEnd); range.Save(mem, DataFormats.XamlPackage); mem.Position = 0; TextRange kange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); kange.Load(mem, DataFormats.XamlPackage); } } }
public TypefaceListItem(Typeface typeface) { _displayName = GetDisplayName(typeface); _simulated = typeface.IsBoldSimulated || typeface.IsObliqueSimulated; this.FontFamily = typeface.FontFamily; this.FontWeight = typeface.Weight; this.FontStyle = typeface.Style; this.FontStretch = typeface.Stretch; string itemLabel = _displayName; //if (_simulated) //{ // string formatString = EpiDashboard.Properties.Resources.ResourceManager.GetString( // "simulated", // CultureInfo.CurrentUICulture // ); // itemLabel = string.Format(formatString, itemLabel); //} this.Text = itemLabel; this.ToolTip = itemLabel; // In the case of symbol font, apply the default message font to the text so it can be read. if (FontFamilyListItem.IsSymbolFont(typeface.FontFamily)) { TextRange range = new TextRange(this.ContentStart, this.ContentEnd); range.ApplyPropertyValue(TextBlock.FontFamilyProperty, SystemFonts.MessageFontFamily); } }
private void MyRichTextBox_Drop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] docPath = (string[])e.Data.GetData(DataFormats.FileDrop); // По умолчанию открыть как форматированный текст var dataFormat = DataFormats.Rtf; // Если нажата клавиша Shift, открыть как обычный текст. if (e.KeyStates == DragDropKeyStates.ShiftKey) { dataFormat = DataFormats.Text; } System.Windows.Documents.TextRange range; System.IO.FileStream fStream; if (System.IO.File.Exists(docPath[0])) { try { // Откройте документ в RichTextBox. range = new System.Windows.Documents.TextRange(MyRichTextBox.Document.ContentStart, MyRichTextBox.Document.ContentEnd); fStream = new System.IO.FileStream(docPath[0], System.IO.FileMode.OpenOrCreate); range.Load(fStream, dataFormat); fStream.Close(); } catch (System.Exception) { MessageBox.Show("File could not be opened. Make sure the file is a text file."); } } } }
private string GetMessageText() { var textSelection = new TextRange(_view.MessageTextBox.Document.ContentStart, _view.MessageTextBox.Document.ContentEnd); var messageText = textSelection.Text; return messageText; }
private void btnEventCreate_Click(object sender, RoutedEventArgs e) { if (!validateInput()) return; EventHelper client = new EventHelper(); try { DateTime startTime = dtpStart.SelectedDateTime; DateTime endTime = dtpEnd.SelectedDateTime; if (startTime.CompareTo(endTime) >= 0) { MessageBox.Show("Invalid Date Entry, End Date Must be at a Later Date Then Start Date"); return; } var textRange = new TextRange(txtDesc.Document.ContentStart, txtDesc.Document.ContentEnd); client.CreateEvent(user, txtEventName.Text, startTime, endTime, textRange.Text, txtWebsite.Text, txtTag.Text); MessageBox.Show("Operation succeeded!"); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { client.Close(); } Load_Event(); }
private void RichTextBox_Drop(object sender, DragEventArgs e) { RichTextBox currentRichTextBox = TabItemManipulate.GetCurrentRichTextBox(_ControlBox); if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] docPath = (string[])e.Data.GetData(DataFormats.FileDrop); var dataFormat = DataFormats.Text; System.Windows.Documents.TextRange range; System.IO.FileStream fStream; if (System.IO.File.Exists(docPath[0])) { try { // Open the document in the RichTextBox. range = new System.Windows.Documents.TextRange(currentRichTextBox.Document.ContentStart, currentRichTextBox.Document.ContentEnd); fStream = new System.IO.FileStream(docPath[0], System.IO.FileMode.OpenOrCreate); range.Load(fStream, dataFormat); fStream.Close(); } catch (System.Exception) { //MessageBox.Show("File could not be opened. Make sure the file is a text file."); } } } }
private void button_Click(object sender, RoutedEventArgs e) { DateTime current = DateTime.Now.Date; DateTime taskTime = (DateTime)Dpick.SelectedDate; int result = DateTime.Compare(current, taskTime); if (result > 0) { MessageBox.Show("Ви не можете створити завдання на попереднє число."); } else { string richText = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd).Text; Tasks task = new Tasks(); task.taskDate = Dpick.SelectedDate.ToString(); task.taskName = richText; task.taskPriority = comboBox.SelectedValue.ToString(); task.taskStatus = defaultStatus; CRUD crud = new CRUD(); task.UserID=crud.getId(); crud.Add(task); //MessageBox.Show(task.taskName); this.Close(); } }
private void LoadCompleted(object sender, RoutedEventArgs e) { string codeBase = Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); if (!string.IsNullOrEmpty(path)) { var legalReleasePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(path), "legal_release.txt"); try { if (File.Exists(legalReleasePath)) { var textRange = new TextRange(RtfContainer.Document.ContentStart, RtfContainer.Document.ContentEnd); using (var fileStream = new FileStream(legalReleasePath, FileMode.Open, FileAccess.Read)) { textRange.Load(fileStream, DataFormats.Text); } } else throw new FileNotFoundException("legal_release.txt"); } catch (Exception ex) { ServiceManager.LogError("Load Legal release", ex); } } }
private static void ColorizeText(RichTextBox box, string inputText) { var textRange = new TextRange(box.Document.ContentStart, box.Document.ContentEnd); var currentPosition = box.Document.ContentStart; var contentEnd = box.Document.ContentEnd; while(null != currentPosition && currentPosition.CompareTo(contentEnd) < 0 ) { if(currentPosition.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text) { var text = currentPosition.GetTextInRun(LogicalDirection.Forward); var p1 = currentPosition.GetPositionAtOffset(text.IndexOf(inputText)); var p2 = currentPosition.GetPositionAtOffset(text.IndexOf(inputText) + inputText.Length); if (null != p2 && null != p1) { Console.WriteLine("ind:{0}, txt:{1}, p1: {2}, p2: {3}", text.IndexOf(inputText), text, p1, p2); var range = new TextRange(p1, p2); range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush( _ltForeground[_indexColorLookup%_ltForeground.Length])); range.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush( _ltBackground[_indexColorLookup%_ltForeground.Length])); } } currentPosition = currentPosition.GetNextContextPosition(LogicalDirection.Forward); } }
void SetDecorations(swd.TextRange range, sw.TextDecorationCollection decorations, bool value) { var existingDecorations = range.GetPropertyValue(swd.Inline.TextDecorationsProperty) as sw.TextDecorationCollection; if (existingDecorations != null) { existingDecorations = new sw.TextDecorationCollection(existingDecorations); } if (value) { existingDecorations = existingDecorations ?? new sw.TextDecorationCollection(); existingDecorations.Add(decorations); } else if (existingDecorations != null) { foreach (var decoration in decorations) { if (existingDecorations.Contains(decoration)) { existingDecorations.Remove(decoration); } } if (existingDecorations.Count == 0) { existingDecorations = null; } } range.ApplyPropertyValue(swd.Inline.TextDecorationsProperty, existingDecorations); }
private void SubmitClick(object sender, RoutedEventArgs e) { // Create new Slide slides = pptPresentation.Slides; slide = slides.AddSlide(1, customLayout); // Add title objText = slide.Shapes[1].TextFrame.TextRange; System.Windows.Documents.TextRange titleRange = new System.Windows.Documents.TextRange (TitleBox.Document.ContentStart, TitleBox.Document.ContentEnd); objText.Text = titleRange.Text; // Add text objText = slide.Shapes[2].TextFrame.TextRange; System.Windows.Documents.TextRange textRange = new System.Windows.Documents.TextRange (TextBox.Document.ContentStart, TextBox.Document.ContentEnd); objText.Text = textRange.Text; int numPics = 0; if (selected != null) { numPics = selected.Count(); } Console.WriteLine("\n\nSelected Image URLs, \n"); Microsoft.Office.Interop.PowerPoint.Shape photo = slide.Shapes[2]; for (int i = 0; i < numPics && i < 3; i++) { Console.WriteLine(selected[i] + "\n"); slide.Shapes.AddPicture(selected[i], MsoTriState.msoFalse, MsoTriState.msoTrue, (i * 200), 300, photo.Width, photo.Height); } Console.WriteLine("\n\n"); }
private static void OnBoundDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { RichTextBox box = d as RichTextBox; if (box == null) return; RemoveEventHandler(box); string newXAML = e.NewValue as string; box.Document.Blocks.Clear(); if (!string.IsNullOrEmpty(newXAML)) { TextRange tr = new TextRange(box.Document.ContentStart, box.Document.ContentEnd); MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms); sw.Write(newXAML); sw.Flush(); tr.Load(ms, DataFormats.Rtf); sw.Close(); ms.Close(); } AttachEventHandler(box); }
public static string ConvertRtfToXaml(string rtfText) { var richTextBox = new System.Windows.Controls.RichTextBox(); if (string.IsNullOrEmpty(rtfText)) return String.Empty; var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); using (var rtfMemoryStream = new MemoryStream()) { using (var rtfStreamWriter = new StreamWriter(rtfMemoryStream)) { rtfStreamWriter.Write(rtfText); rtfStreamWriter.Flush(); rtfMemoryStream.Seek(0, SeekOrigin.Begin); textRange.Load(rtfMemoryStream, DataFormats.Rtf); } } using (var rtfMemoryStream = new MemoryStream()) { textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); textRange.Save(rtfMemoryStream, System.Windows.DataFormats.Xaml); rtfMemoryStream.Seek(0, SeekOrigin.Begin); using (var rtfStreamReader = new StreamReader(rtfMemoryStream)) { return rtfStreamReader.ReadToEnd(); } } }
private void InsertChar(char c) { if (rtb.Selection.Text.Length == 0) { TextPointer insertionPosition; if (rtb.CaretPosition.IsAtInsertionPosition == true) { insertionPosition = rtb.CaretPosition; } else { insertionPosition = rtb.CaretPosition.GetNextInsertionPosition(LogicalDirection.Forward); } if (rtb.Document.Blocks.Count == 0) rtb.Document.Blocks.Add(new Paragraph(new Run())); int offset = rtb.Document.ContentStart.GetOffsetToPosition(insertionPosition); insertionPosition.InsertTextInRun(c.ToString()); rtb.CaretPosition = rtb.Document.ContentStart.GetPositionAtOffset(offset + 1, LogicalDirection.Forward); } else { TextPointer selectionStartPosition = rtb.Selection.Start; TextRange selection = new TextRange(rtb.Selection.Start, rtb.Selection.End); selection.Text = ""; rtb.CaretPosition.InsertTextInRun(c.ToString()); rtb.CaretPosition = rtb.CaretPosition.GetPositionAtOffset(1, LogicalDirection.Forward); } }
private static void TextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var rtx = sender as RichTextBox; if (rtx == null) return; var range = new TextRange(rtx.Document.ContentStart, rtx.Document.ContentEnd); range.Text = e.NewValue as String; }
private void Handle_Click(object sender, RoutedEventArgs e) { TextRange _Text = new TextRange(this.Information.Document.ContentStart, this.Information.Document.ContentEnd); if (_Text.Text.Length > 150) { JXMessageBox.Show(this, "处理说明只能输入150个字符,请检查!", MsgImage.Error); return; } if (_Text.Text.Length <3 || _Text.Text.Equals("")) { JXMessageBox.Show(this, "请输入警报处理说明!", MsgImage.Error); return; } int Aid = int.Parse(this.Aid.Text); MessageBox.Show("id>>" + Aid.ToString() + " _Text.Text=" + _Text.Text); RoomClass rc=new RoomClass(); int state = rc.doAlarmInformation(Aid,_Text.Text); if (state == BaseRequest.SUCCESS) { Alarm alarm = RoomManagerBean.Alarm; RoomClass _Rclass = new RoomClass(); DataSet _Alarm_Set = _Rclass.queryAlarmList(); alarm.page.ShowPages(alarm.alarmGrid, _Alarm_Set, BaseRequest.PAGE_SIZE); JXMessageBox.Show(this, "警报处理完成!", MsgImage.Success); this.Close(); } else { JXMessageBox.Show(this, "系统异常,请联系管理员!", MsgImage.Error); } }
public void LoadData() { string Narr; string NarrFormat; if (mIsSummaryNarrative) { Narr = mDataSet.Tables["i9Narrative"].Rows[0]["SummaryNarrative"].ToString(); NarrFormat = mDataSet.Tables["i9Narrative"].Rows[0]["SummaryNarrativeFormat"].ToString(); } else { Narr = mDataSet.Tables["i9Narrative"].Rows[0]["Narrative"].ToString(); NarrFormat = mDataSet.Tables["i9Narrative"].Rows[0]["NarrativeFormat"].ToString(); } if (String.IsNullOrEmpty(NarrFormat.Trim()) == false) { // convert string to stream byte[] byteArray = Encoding.ASCII.GetBytes(NarrFormat); using (MemoryStream stream = new MemoryStream(byteArray)) { TextRange range = new TextRange(mainRTB.Document.ContentStart, mainRTB.Document.ContentEnd); range.Load(stream, DataFormats.Rtf); } } }
public void SaveData() { TextRange sourceDocument = new TextRange(mainRTB.Document.ContentStart, mainRTB.Document.ContentEnd); string rtf = ""; using (MemoryStream stream = new MemoryStream()) { sourceDocument.Save(stream, DataFormats.Rtf); stream.Seek(0, SeekOrigin.Begin); using (StreamReader reader = new StreamReader(stream)) { rtf = reader.ReadToEnd(); } } if (mIsSummaryNarrative) { mDataSet.Tables["i9Narrative"].Rows[0]["SummaryNarrative"] = sourceDocument.Text; mDataSet.Tables["i9Narrative"].Rows[0]["SummaryNarrativeFormat"] = rtf; } else { mDataSet.Tables["i9Narrative"].Rows[0]["Narrative"] = sourceDocument.Text; mDataSet.Tables["i9Narrative"].Rows[0]["NarrativeFormat"] = rtf; } }
public static void AddBlock(Block from, FlowDocument to) { if (from != null) { //if (from is ItemsContent) //{ // ((ItemsContent)from).RunBeforeCopy(); //} //else { TextRange range = new TextRange(from.ContentStart, from.ContentEnd); MemoryStream stream = new MemoryStream(); System.Windows.Markup.XamlWriter.Save(range, stream); range.Save(stream, DataFormats.XamlPackage); TextRange textRange2 = new TextRange(to.ContentEnd, to.ContentEnd); textRange2.Load(stream, DataFormats.XamlPackage); } } }
public void SetText(FlowDocument document, string text) { var newText = ChatToXamlConverter.Convert(text); var tr = new TextRange(document.ContentStart, document.ContentEnd); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(newText))) tr.Load(ms, DataFormats.Xaml); }
// --------------------------------------------------------------------- // // Internal Methods // // --------------------------------------------------------------------- #region Internal Methods public static string GetFlowDocumentText(FlowDocument flowDoc) { TextPointer contentstart = flowDoc.ContentStart; TextPointer contentend = flowDoc.ContentEnd; TextRange textRange = new TextRange(contentstart, contentend); return textRange.Text; }
/// <summary> /// 获取文档分页器 /// </summary> /// <param name="pageWidth"></param> /// <param name="pageHeight"></param> /// <returns></returns> public DocumentPaginator GetPaginator(double pageWidth,double pageHeight) { //将RichTextBox的文档内容转为XAML TextRange originalRange = new TextRange( _textBox.Document.ContentStart, _textBox.Document.ContentEnd ); MemoryStream memoryStream = new MemoryStream(); originalRange.Save(memoryStream, System.Windows.DataFormats.XamlPackage); //根据XAML将流文档复制一份 FlowDocument copy = new FlowDocument(); TextRange copyRange = new TextRange( copy.ContentStart, copy.ContentEnd ); copyRange.Load(memoryStream, System.Windows.DataFormats.XamlPackage); DocumentPaginator paginator = ((IDocumentPaginatorSource)copy).DocumentPaginator; //转换为新的分页器 return new PrintingPaginator( paginator,new Size( pageWidth,pageHeight), new Size(DPI,DPI) ); }
// Existing GetPropertyValue for the TextDecorationCollection will return the first collection, even if it is empty. // this skips empty collections so we can get the actual value. // slightly modified code from https://social.msdn.microsoft.com/Forums/vstudio/en-US/3ac626cf-60aa-427f-80e9-794f3775a70e/how-to-tell-if-richtextbox-selection-is-underlined?forum=wpf public static object GetRealPropertyValue(this swd.TextRange textRange, sw.DependencyProperty formattingProperty, out swd.TextRange fullRange) { object value = null; fullRange = null; var pointer = textRange.Start as swd.TextPointer; if (pointer != null) { var needsContinue = true; swd.TextElement text = null; sw.DependencyObject element = pointer.Parent as swd.TextElement; while (needsContinue && (element is swd.Inline || element is swd.Paragraph || element is swc.TextBlock)) { value = element.GetValue(formattingProperty); text = element as swd.TextElement; var seq = value as IEnumerable; needsContinue = (seq == null) ? value == null : seq.Cast <object>().Count() == 0; element = element is swd.TextElement ? ((swd.TextElement)element).Parent : null; } if (text != null) { fullRange = new swd.TextRange(text.ElementStart, text.ElementEnd); } } return(value); }
bool HasDecorations(swd.TextRange range, sw.TextDecorationCollection decorations) { swd.TextRange realRange; var existingDecorations = range.GetRealPropertyValue(swd.Inline.TextDecorationsProperty, out realRange) as sw.TextDecorationCollection; return(existingDecorations != null && decorations.All(r => existingDecorations.Contains(r))); }
/// <summary> /// Get text. /// </summary> /// <param name="rich">RichTextBox.</param> /// <returns>Text.</returns> public static string GetText(RichTextBox rich) { var block = rich.Document.Blocks.FirstBlock; if (block == null) { return string.Empty; } StringBuilder text = new StringBuilder(); do { Paragraph paragraph = block as Paragraph; if (paragraph != null) { var inline = paragraph.Inlines.FirstInline; do { if (0 < text.Length) { text.Append(Environment.NewLine); } TextRange range = new TextRange(inline.ContentStart, inline.ContentEnd); text.Append(range.Text); } while ((inline = inline.NextInline) != null); } } while ((block = block.NextBlock) != null); return text.ToString(); }
void ApplyCompositionAttributes(swi.TextCompositionEventArgs e) { // update the composition with the selection attributes, if any var rtcomp = e.TextComposition as swd.FrameworkRichTextComposition; var attributes = CompositionAttributes; if (rtcomp != null && attributes != null) { swd.TextRange range = null; if (rtcomp.CompositionStart != null && rtcomp.CompositionEnd != null) { range = new swd.TextRange(rtcomp.CompositionStart, rtcomp.CompositionEnd); } else if (rtcomp.ResultStart != null && rtcomp.ResultEnd != null) { range = new swd.TextRange(rtcomp.ResultStart, rtcomp.ResultEnd); } // need to async this as the styles still don't get applied properly at this stage. Yuck! if (range != null) { Application.Instance.AsyncInvoke(() => ApplySelectionAttributes(range, attributes)); } } }
public void Apply(swd.TextRange control) { control.ApplyPropertyValue(swd.TextElement.FontFamilyProperty, WpfFamily); control.ApplyPropertyValue(swd.TextElement.FontStyleProperty, WpfFontStyle); control.ApplyPropertyValue(swd.TextElement.FontWeightProperty, WpfFontWeight); control.ApplyPropertyValue(swd.TextElement.FontSizeProperty, PixelSize); control.ApplyPropertyValue(swd.Inline.TextDecorationsProperty, WpfTextDecorations); }
void SetDecorations(swd.TextRange range, sw.TextDecorationCollection decorations, bool value) { using (Control.DeclareChangeBlock()) { // set the property to each element in the range so it keeps all other decorations foreach (var element in range.GetInlineElements()) { var existingDecorations = element.GetValue(swd.Inline.TextDecorationsProperty) as sw.TextDecorationCollection; // need to keep the range before changing otherwise the range changes var elementRange = new swd.TextRange(element.ElementStart, element.ElementEnd); sw.TextDecorationCollection newDecorations = null; // remove decorations from the element element.SetValue(swd.Inline.TextDecorationsProperty, null); if (existingDecorations != null && existingDecorations.Count > 0) { // merge desired decorations with existing decorations. if (value) { newDecorations = new sw.TextDecorationCollection(existingDecorations.Union(decorations)); } else { newDecorations = new sw.TextDecorationCollection(existingDecorations.Except(decorations)); } // split up existing decorations to the parts of the element that don't fall within the range existingDecorations = new sw.TextDecorationCollection(existingDecorations); // copy so we don't update existing elements if (elementRange.Start.CompareTo(range.Start) < 0) { new swd.TextRange(elementRange.Start, range.Start).ApplyPropertyValue(swd.Inline.TextDecorationsProperty, existingDecorations); } if (elementRange.End.CompareTo(range.End) > 0) { new swd.TextRange(range.End, elementRange.End).ApplyPropertyValue(swd.Inline.TextDecorationsProperty, existingDecorations); } } else { // no existing decorations, just set the new value newDecorations = value ? decorations : null; } if (newDecorations != null && newDecorations.Count > 0) { // apply new decorations to the desired range, which may be a combination of existing decorations swd.TextPointer start = elementRange.Start.CompareTo(range.Start) < 0 ? range.Start : elementRange.Start; swd.TextPointer end = elementRange.End.CompareTo(range.End) > 0 ? range.End : elementRange.End; new swd.TextRange(start, end).ApplyPropertyValue(swd.Inline.TextDecorationsProperty, newDecorations); } } } }
private void MainWindowButtonClick(object sender, RoutedEventArgs e) { System.Windows.Documents.TextRange textRange = new System.Windows.Documents.TextRange(this.MainWindowSlideText.Document.ContentStart, this.MainWindowSlideText.Document.ContentEnd); //MessageBox.Show(textRange.Text); SearchResultsWindow newWindow = new SearchResultsWindow(this.MainWindowTitleText.Text, textRange.Text); newWindow.ShowDialog(); ArrayList selectedUrls = newWindow.getSelectedUrls(); createSlide(selectedUrls); }
void ApplySelectionAttributes(swd.TextRange range, Dictionary <sw.DependencyProperty, object> attributes) { if (attributes == null) { return; } foreach (var attribute in attributes) { range.ApplyPropertyValue(attribute.Key, attribute.Value); } }
bool HasDecorations(swd.TextRange range, sw.TextDecorationCollection decorations, bool useRealPropertyValue = true) { swd.TextRange realRange; sw.TextDecorationCollection existingDecorations; if (useRealPropertyValue) { existingDecorations = range.GetRealPropertyValue(swd.Inline.TextDecorationsProperty, out realRange) as sw.TextDecorationCollection; } else { existingDecorations = range.GetPropertyValue(swd.Inline.TextDecorationsProperty) as sw.TextDecorationCollection; } return(existingDecorations != null && decorations.All(r => existingDecorations.Contains(r))); }
public static FontFamily SetEtoFamily(this swd.TextRange control, FontFamily fontFamily) { if (control == null) { return(fontFamily); } if (fontFamily != null) { ((FontFamilyHandler)fontFamily.Handler).Apply(control); } else { control.ApplyPropertyValue(swd.TextElement.FontFamilyProperty, swc.Control.FontFamilyProperty.DefaultMetadata.DefaultValue); } return(fontFamily); }
public static IEnumerable <swd.TextElement> GetElements(this swd.TextRange range) { for (var position = range.Start; position != null && position.CompareTo(range.End) <= 0; position = position.GetNextContextPosition(swd.LogicalDirection.Forward)) { var obj = position.Parent as sw.FrameworkContentElement; while (obj != null) { var elem = obj as swd.TextElement; if (elem != null) { yield return(elem); } obj = obj.Parent as sw.FrameworkContentElement; } } }
private void Select_Click(object sender, RoutedEventArgs e) { //in one spot it says minimum of 3 images on slide, but final point in keeping from passing says UP TO 3 images ¯\_(ツ)_/¯ if (Selection.Where(x => x.Value).Count() != 3) { return; } var presentation = new PresentationDocument(); var slide = presentation.Slides.AddNew(SlideLayoutType.Custom); var textBox = slide.Content.AddTextBox(ShapeGeometryType.Rectangle, 10, 2, 5, 4, LengthUnit.Centimeter); var title = textBox.AddParagraph(); title.AddRun(Title.Text); var bodyTextBox = slide.Content.AddTextBox(ShapeGeometryType.Rectangle, 20, 2, 5, 4, LengthUnit.Centimeter); var body = bodyTextBox.AddParagraph(); var bodyText = new System.Windows.Documents.TextRange(SearchText.Document.ContentStart, SearchText.Document.ContentEnd).Text.Replace("\r", " "); bodyText = bodyText.Replace("\n", " "); body.AddRun(bodyText); double width = 0.0; foreach (var image in Selection) { if (image.Value) { slide.Content.AddPicture(image.Key.Source.ToString(), width, 250, image.Key.Width, image.Key.Height); width += image.Key.Width; } } presentation.Save($"Results_{Guid.NewGuid()}.pptx"); Image_Panel.Children.Clear(); Images.Clear(); Selection.Clear(); }
// Existing GetPropertyValue for the TextDecorationCollection will return the first collection, even if it is empty. // this skips empty collections so we can get the actual value. // slightly modified code from https://social.msdn.microsoft.com/Forums/vstudio/en-US/3ac626cf-60aa-427f-80e9-794f3775a70e/how-to-tell-if-richtextbox-selection-is-underlined?forum=wpf object GetPropertyValue(swd.TextRange textRange, sw.DependencyProperty formattingProperty) { object value = null; var pointer = textRange.Start as swd.TextPointer; if (pointer != null) { var needsContinue = true; sw.DependencyObject element = pointer.Parent as swd.TextElement; while (needsContinue && (element is swd.Inline || element is swd.Paragraph || element is swc.TextBlock)) { value = element.GetValue(formattingProperty); var seq = value as IEnumerable; needsContinue = (seq == null) ? value == null : seq.Cast <Object>().Count() == 0; element = element is swd.TextElement ? ((swd.TextElement)element).Parent : null; } } return(value); }
public static Font SetEtoFont(this swd.TextRange control, Font font) { if (control == null) { return(font); } if (font != null) { ((FontHandler)font.Handler).Apply(control); } else { control.ApplyPropertyValue(swd.TextElement.FontFamilyProperty, swc.Control.FontFamilyProperty.DefaultMetadata.DefaultValue); control.ApplyPropertyValue(swd.TextElement.FontStyleProperty, swc.Control.FontStyleProperty.DefaultMetadata.DefaultValue); control.ApplyPropertyValue(swd.TextElement.FontWeightProperty, swc.Control.FontWeightProperty.DefaultMetadata.DefaultValue); control.ApplyPropertyValue(swd.TextElement.FontSizeProperty, swc.Control.FontSizeProperty.DefaultMetadata.DefaultValue); control.ApplyPropertyValue(swd.Inline.TextDecorationsProperty, new sw.TextDecorationCollection()); } return(font); }
private void DocBox_Drop(object sender, DragEventArgs e) { MainWindow win = new MainWindow(); win.Show(); string[] docPath = (string[])e.Data.GetData(DataFormats.FileDrop); TextRange range = new System.Windows.Documents.TextRange(win.DocBox.Document.ContentStart, win.DocBox.Document.ContentEnd); FileStream fStream = new System.IO.FileStream(docPath[0], System.IO.FileMode.OpenOrCreate); range.Load(fStream, DataFormats.Text); path.Add(docPath[0]); AddLastFiles(); ReadLastFiles(); fStream.Close(); win.Title = docPath[0]; }
private void PhotosClick(object sender, RoutedEventArgs e) { System.Windows.Documents.TextRange textRange = new System.Windows.Documents.TextRange ( TextBox.Document.ContentStart, // TextPointer to the start of content in the RichTextBox. TextBox.Document.ContentEnd // TextPointer to the end of content in the RichTextBox. ); System.Windows.Documents.TextRange titleRange = new System.Windows.Documents.TextRange ( TitleBox.Document.ContentStart, TitleBox.Document.ContentEnd ); string convertedText = Regex.Replace(titleRange.Text, "\\s+", "+") + Regex.Replace(textRange.Text, "\\s+", "+").TrimEnd('+'); Console.WriteLine("\n\n Search criteria: " + convertedText + "\n\n"); ImageSearch newWindow = new ImageSearch(convertedText); newWindow.ShowDialog(); selected = newWindow.getSelected(); }
/// <summary> /// Converts RichTextBox text to string made up of xaml data. Searches for bolded words and inserts them into query. /// </summary> private void extractBoldedWordsFromBody(RichTextBox rtb) { // Convert RichTextbox text to string made of xaml data System.Windows.Documents.TextRange tr = new System.Windows.Documents.TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd); MemoryStream ms = new MemoryStream(); tr.Save(ms, DataFormats.Xaml); string xamlText = ASCIIEncoding.Default.GetString(ms.ToArray()); const string startDelimeter = "<Run FontWeight=\"Bold\">"; const string endDelimeter = "</Run>"; int start = 0; int end = 0; string[] temp; // Find all bolded sections in xamlText while ((start = xamlText.IndexOf(startDelimeter, end)) != -1) { // Find start and end position to each bolded sections start += startDelimeter.Length; end = xamlText.IndexOf(endDelimeter, start); // Separate words temp = xamlText.Substring(start, end - start).Split(); // Remove any whitespace entries temp = temp.Where(x => !string.IsNullOrEmpty(x)).ToArray(); // Join new words with query query.AddRange(temp); end += endDelimeter.Length; } }
private static string ConvertRtfToXaml(string rtfText) { var richTextBox = new RichTextBox(); if (string.IsNullOrEmpty(rtfText)) { return(""); } var textRange = new System.Windows.Documents.TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); //Create a MemoryStream of the Rtf content using (var rtfMemoryStream = new MemoryStream()) { using (var rtfStreamWriter = new StreamWriter(rtfMemoryStream)) { rtfStreamWriter.Write(rtfText); rtfStreamWriter.Flush(); rtfMemoryStream.Seek(0, SeekOrigin.Begin); //Load the MemoryStream into TextRange ranging from start to end of RichTextBox. textRange.Load(rtfMemoryStream, DataFormats.Rtf); } } using (var rtfMemoryStream = new MemoryStream()) { textRange = new System.Windows.Documents.TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); textRange.Save(rtfMemoryStream, DataFormats.Xaml); rtfMemoryStream.Seek(0, SeekOrigin.Begin); using (var rtfStreamReader = new StreamReader(rtfMemoryStream)) { return(rtfStreamReader.ReadToEnd()); } } }
private void createSlide(ArrayList selectedUrls) { // Create new Slide slides = pptPresentation.Slides; slide = slides.AddSlide(slideNumber, customLayout); //increment slide number slideNumber++; // Add title objText = slide.Shapes[1].TextFrame.TextRange; objText.Text = this.MainWindowTitleText.Text; objText.Font.Name = "Arial"; objText.Font.Size = 32; System.Windows.Documents.TextRange textRange = new System.Windows.Documents.TextRange(this.MainWindowSlideText.Document.ContentStart, this.MainWindowSlideText.Document.ContentEnd); objText = slide.Shapes[2].TextFrame.TextRange; objText.Text = textRange.Text; Microsoft.Office.Interop.PowerPoint.Shape shape = slide.Shapes[2]; foreach (string url in selectedUrls) { slide.Shapes.AddPicture(url, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, shape.Left, shape.Top, shape.Width, shape.Height); } }
public void Apply(sw.Documents.TextRange control) { control.ApplyPropertyValue(swd.TextElement.FontFamilyProperty, Control); }
/// <summary> /// Returns text inside RichTextBox /// </summary> private string stringFromRichTextBox(RichTextBox rtb) { System.Windows.Documents.TextRange textRange = new System.Windows.Documents.TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd); return(textRange.Text); }
private string ConvertRichTextBoxContentsToString(RichTextBox rtb) { System.Windows.Documents.TextRange textRange = new System.Windows.Documents.TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd); return(textRange.Text); }
bool HasDecorations(swd.TextRange range, sw.TextDecorationCollection decorations) { var existingDecorations = GetPropertyValue(range, swd.Inline.TextDecorationsProperty) as sw.TextDecorationCollection; return(existingDecorations != null && decorations.All(r => existingDecorations.Contains(r))); }
public static int GetLength(this swd.TextRange range) { return(range.End.GetTextOffset() - range.Start.GetTextOffset() + 1); }