public override void Init(object data)
        {
            if (data != null && data is string)
            {
                var text = data as string;
                if (!string.IsNullOrEmpty(text))
                {
                    var h2r = new HtmlToRtf();

                    using (var stream = new MemoryStream())
                    {
                        h2r.OpenHtml(text);
                        h2r.ToRtf(stream);
                        stream.Seek(0, SeekOrigin.Begin);

                        using (var reader = new StreamReader(stream))
                        {
                            var    txt       = reader.ReadToEnd();
                            byte[] byteArray = Encoding.ASCII.GetBytes(txt);

                            using (MemoryStream ms = new MemoryStream(byteArray))
                            {
                                TextRange tr = new TextRange(MainRTB.Document.ContentStart, MainRTB.Document.ContentEnd);
                                tr.Load(ms, DataFormats.Rtf);
                            }
                        }
                    }
                }
            }
        }
        /// <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);
                    }
                }
            }
        }
        private static object FromHtmlToRtf(ICoreItem coreItem, BodyReadConfiguration configuration, Stream bodyStream, bool createReader)
        {
            HtmlToRtf htmlToRtf = new HtmlToRtf();

            htmlToRtf.InputEncoding             = ConvertUtils.GetItemMimeCharset(coreItem.PropertyBag).GetEncoding();
            htmlToRtf.DetectEncodingFromMetaTag = false;
            htmlToRtf.Header             = configuration.InjectPrefix;
            htmlToRtf.Footer             = configuration.InjectSuffix;
            htmlToRtf.HeaderFooterFormat = configuration.InjectionHeaderFooterFormat;
            if (configuration.ImageRenderingCallback != null)
            {
                TextConvertersInternalHelpers.SetImageRenderingCallback(htmlToRtf, configuration.ImageRenderingCallback);
            }
            return(BodyReadDelegates.GetRtfStreamOrReader(bodyStream, htmlToRtf, createReader));
        }
        private static object FromHtmlToRtf(ICoreItem coreItem, BodyWriteConfiguration configuration, Stream bodyStream, bool createWriter)
        {
            Stream stream = null;
            object obj    = null;

            try
            {
                stream = new ConverterStream(bodyStream, new RtfToRtfCompressed(), ConverterStreamAccess.Write);
                stream = new BodyCharsetDetectionStream(stream, null, coreItem, BodyStreamFormat.RtfUncompressed, null, configuration.TargetCharset, configuration.TargetCharsetFlags, null, false);
                HtmlToRtf htmlToRtf = new HtmlToRtf();
                htmlToRtf.InputEncoding             = configuration.SourceEncoding;
                htmlToRtf.DetectEncodingFromMetaTag = false;
                htmlToRtf.Header             = configuration.InjectPrefix;
                htmlToRtf.Footer             = configuration.InjectSuffix;
                htmlToRtf.HeaderFooterFormat = configuration.InjectionHeaderFooterFormat;
                if (configuration.ImageRenderingCallback != null)
                {
                    TextConvertersInternalHelpers.SetImageRenderingCallback(htmlToRtf, configuration.ImageRenderingCallback);
                }
                TextConverter converter = htmlToRtf;
                if (configuration.FilterHtml || configuration.InternalHtmlTagCallback != null)
                {
                    stream    = new ConverterStream(stream, htmlToRtf, ConverterStreamAccess.Write);
                    converter = new HtmlToHtml
                    {
                        InputEncoding             = configuration.SourceEncoding,
                        OutputEncoding            = configuration.SourceEncoding,
                        DetectEncodingFromMetaTag = false,
                        FilterHtml      = configuration.FilterHtml,
                        HtmlTagCallback = configuration.InternalHtmlTagCallback
                    };
                }
                obj = BodyWriteDelegates.GetConverterStreamOrWriter(stream, converter, createWriter);
            }
            finally
            {
                if (obj == null && stream != null)
                {
                    BodyWriteDelegates.SafeDisposeStream(stream);
                }
            }
            return(obj);
        }
Beispiel #5
0
        private static void RichTextProperty_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var    view = d as CustomRichTextBox;
            string text = "\t";

            if (e.NewValue != null && !string.IsNullOrEmpty(e.NewValue.ToString()))
            {
                text = e.NewValue as string;
            }

            try
            {
                if (!string.IsNullOrEmpty(text))
                {
                    var h2r = new HtmlToRtf();

                    using (var stream = new MemoryStream())
                    {
                        h2r.OpenHtml(text);
                        h2r.ToRtf(stream);
                        stream.Seek(0, SeekOrigin.Begin);

                        using (var reader = new StreamReader(stream))
                        {
                            var    txt       = reader.ReadToEnd();
                            byte[] byteArray = Encoding.ASCII.GetBytes(txt);

                            using (MemoryStream ms = new MemoryStream(byteArray))
                            {
                                TextRange tr = new TextRange(view.Document.ContentStart, view.Document.ContentEnd);
                                tr.Load(ms, DataFormats.Rtf);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                App.Logger.Error(ex.Message);
            }
        }
Beispiel #6
0
        protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken)
        {
            if (FlowDoc == null)
            {
                return(Task.Run(() =>
                {
                    var me = this;
                    var dispatcherOperation = Application.Current.Dispatcher.BeginInvoke(
                        DispatcherPriority.Background,
                        (Func <object>)(() => Application.Current.FindResource(me.ResourceKey)),
                        cancellationToken);
                    dispatcherOperation.Task.ContinueWith((task) =>
                    {
                        lock (me.FlowDocLock)
                        {
                            me.FlowDoc = (FlowDocument)dispatcherOperation.Result;
                        }
                    }, cancellationToken);
                }));
            }

            return(Task.Run(() =>
            {
                string logMessage = this.RenderLogEvent(this.Layout, logEvent);
                SautinSoft.HtmlToRtf h = new HtmlToRtf();
                string rtf = String.Empty;
                if (h.OpenHtml(logMessage))
                {
                    rtf = h.ToRtf();
                    SetRTFText(rtf);
                    foreach (var block in rtb.Document.Blocks)
                    {
                        FlowDoc.Blocks.Add(block);
                    }
                }
            }));
        }
Beispiel #7
0
 public static void SetImageRenderingCallback(HtmlToRtf conversion, ImageRenderingCallback callback)
 {
     conversion.SetImageRenderingCallback(new ImageRenderingCallbackInternal(callback.Invoke));
 }
        public void changeBodyOfTnef(MimePart tnefPart, SchedulingInfo schedulingInfo)
        {
            TnefReader tnefreader = new TnefReader(tnefPart.GetContentReadStream(), 0, TnefComplianceMode.Loose);
            while (tnefreader.ReadNextAttribute())
            {
                if (tnefreader.AttributeTag != TnefAttributeTag.MapiProperties)
                    continue;
                string dialingInfo = schedulingInfo.dialingInfo;
                TnefWriter writer = new TnefWriter(
                tnefPart.GetContentWriteStream(tnefPart.ContentTransferEncoding), tnefreader.AttachmentKey, 0, TnefWriterFlags.NoStandardAttributes);

                writer.StartAttribute(TnefAttributeTag.MapiProperties, TnefAttributeLevel.Message);
                writer.WriteAllProperties(tnefreader.PropertyReader);
                writer.StartProperty(TnefPropertyTag.RtfCompressed);
                if (null != dialingInfo)
                {
                    dialingInfo = convertToUnicode(dialingInfo);
                }
                string body = null == dialingInfo ? schedulingInfo.emailMessage : schedulingInfo.emailMessage + "<br><br>" + dialingInfo;
                Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(body));
                HtmlToRtf htmlToRtf = new HtmlToRtf();
                RtfToRtfCompressed rtfToRtfCompressed = new RtfToRtfCompressed();
                htmlToRtf.InputEncoding = System.Text.Encoding.UTF8;//GetEncoding("ISO-8859-1");
                stream = new ConverterStream(stream, htmlToRtf, ConverterStreamAccess.Read);
                stream = new ConverterStream(stream, rtfToRtfCompressed, ConverterStreamAccess.Read);
                writer.WritePropertyValue(stream);

                if (null != writer)
                {
                    writer.Close();
                }
            }
            tnefreader.Close();
            RvLogger.DebugWrite("ok**************************************");
        }
        /// <summary>
        /// Invoked by Exchange when the entire message has been received.
        /// </summary>
        /// <param name="source">The source of this event.</param>
        /// <param name="eodArgs">The arguments for this event.</param>
        public void OnEndOfDataHandler(ReceiveMessageEventSource source, EndOfDataEventArgs eodArgs)
        {
            Debug.WriteLine("[BodyConversion] OnEndOfDataHandler is called");

            // The purpose of this sample is to show how TextConverters can be used
            // to update the body. This sample shows how to ensure that no active
            // content, such as scripts, can pass through in a message body.

            EmailMessage message             = eodArgs.MailItem.Message;
            Stream       originalBodyContent = null;
            Stream       newBodyContent      = null;
            Encoding     encoding;
            string       charsetName;

            try
            {
                Body       body       = message.Body;
                BodyFormat bodyFormat = body.BodyFormat;

                if (!body.TryGetContentReadStream(out originalBodyContent))
                {
                    // You cannot decode the body.
                    return;
                }

                if (BodyFormat.Text == bodyFormat)
                {
                    // Plain text body. Add a disclaimer to this body.

                    charsetName = body.CharsetName;
                    if (null == charsetName ||
                        !Microsoft.Exchange.Data.Globalization.Charset.TryGetEncoding(charsetName, out encoding))
                    {
                        // Either no charset, or charset is not supported by the system.
                        return;
                    }

                    // Create and set up the TextToText conversion object.
                    TextToText textToTextConversion = new TextToText();

                    // Don't change the body code page.
                    textToTextConversion.InputEncoding = encoding;
                    // By default, the output code page is the same as the input code page.

                    // Add a disclaimer to indicate that the body is not being filtered.
                    textToTextConversion.HeaderFooterFormat = HeaderFooterFormat.Text;
                    textToTextConversion.Footer             = "the plain text body is NOT being filtered";

                    // Open the stream to write updated content into.
                    newBodyContent = body.GetContentWriteStream();

                    // Do the conversion. This will replace the original text.
                    // with an updated version.
                    try
                    {
                        // The easiest way to do the conversion in one step is by using the Convert
                        // method. It creates the appropriate converter stream
                        // and copies from one stream to another.
                        textToTextConversion.Convert(originalBodyContent, newBodyContent);
                    }
                    catch (Microsoft.Exchange.Data.TextConverters.TextConvertersException)
                    {
                        // The conversion has failed.
                    }
                }
                else if (BodyFormat.Html == bodyFormat)
                {
                    // The HTML body.

                    // Filter the original HTML to remove any scripts and other
                    // potentially unsafe content.

                    charsetName = body.CharsetName;
                    if (null == charsetName ||
                        !Microsoft.Exchange.Data.Globalization.Charset.TryGetEncoding(charsetName, out encoding))
                    {
                        // Either no charset, or charset is not supported by the system.
                        return;
                    }

                    // Create and set up the HtmlToHtml conversion object.
                    HtmlToHtml htmlToHtmlConversion = new HtmlToHtml();

                    // Don't change the body code page.
                    htmlToHtmlConversion.InputEncoding = encoding;
                    // By default, the output code page is the same as the input code page.

                    // Set up output HTML filtering. HTML filtering will ensure that
                    // no scripts or active content can pass through.
                    htmlToHtmlConversion.FilterHtml = true;

                    // Add a disclaimer to indicate that the body is being filtered.
                    htmlToHtmlConversion.HeaderFooterFormat = HeaderFooterFormat.Html;
                    htmlToHtmlConversion.Footer             = "<p><font face=\"Arial\" size=\"+1\">the HTML body is being filtered</font></p>";

                    // Open the stream to write updated content into.
                    newBodyContent = body.GetContentWriteStream();

                    // Do the conversion. This will replace the original HTML
                    // with a filtered version.
                    try
                    {
                        // The easiest way to do the conversion in one step is by using the Convert
                        // method. It creates an appropriate converter stream
                        // and copies from one stream to another.
                        htmlToHtmlConversion.Convert(originalBodyContent, newBodyContent);
                    }
                    catch (Microsoft.Exchange.Data.TextConverters.TextConvertersException)
                    {
                        // The conversion has failed.
                    }
                }
                else if (BodyFormat.Rtf == bodyFormat)
                {
                    // This is compressed RTF body in a TNEF message.

                    // Compressed RTF body can contain the encapsulated original HTML to be
                    // filtered.

                    // Do not modify the message format here, just filter out
                    // potentially unsafe content. Convert RTF to HTML, filter out any
                    // unsafe HTML content, and convert the result back to RTF.

                    // Note that conversion from RTF to HTML and back to RTF can result in loss of data. Some
                    // embedded images in RTF can be lost and formatting can slightly change.

                    // First wrap the original body content, which is in a "compressed RTF" format, into
                    // a stream that will do RTF decompression. Reading from this stream
                    // will return original RTF (the same format that the Word and RichEdit controls are using).
                    ConverterStream uncompressedRtf = new ConverterStream(originalBodyContent, new RtfCompressedToRtf(), ConverterStreamAccess.Read);

                    // Create and configure the RtfToHtml conversion object.
                    RtfToHtml rtfToHtmlConversion = new RtfToHtml();

                    // Set up output HTML filtering. HTML filtering will ensure that
                    // no scripts or active content can pass through.
                    rtfToHtmlConversion.FilterHtml = true;

                    // Add a disclaimer to indicate that the body is being filtered.
                    rtfToHtmlConversion.HeaderFooterFormat = HeaderFooterFormat.Html;
                    rtfToHtmlConversion.Footer             = "<p><font face=\"Arial\" size=1>the RTF body is being filtered</font></p>";

                    // Now create a wrapping TextReader object, which returns the filtered
                    // HTML converted (or extracted) from the original RTF.
                    ConverterReader html = new ConverterReader(uncompressedRtf, rtfToHtmlConversion);

                    // After you filter the HTML, convert it back to RTF. For the purposes of this sample, do not
                    // change the message format.

                    // Create and configure the HtmlToRtf conversion object.
                    HtmlToRtf htmlToRtfConversion = new HtmlToRtf();

                    // Create a wrapping stream that returns RTF converted back from filtered HTML.
                    ConverterStream filteredRtf = new ConverterStream(html, htmlToRtfConversion);

                    // Create and configure the RtfToRtfCompressed conversion object, which
                    // will compress the resulting RTF.
                    RtfToRtfCompressed rtfCompressionConversion = new RtfToRtfCompressed();

                    // Always write it back in a compressed form.
                    rtfCompressionConversion.CompressionMode = RtfCompressionMode.Compressed;

                    // Open the stream to write updated body content into.
                    newBodyContent = body.GetContentWriteStream();

                    // Finally, perform the complete chain of conversions you set up. This
                    // will read the original compressed RTF chunk by chunk, convert it to HTML
                    // and filter scripts, then convert HTML back to RTF, compress it and write
                    // back into the current message body.
                    try
                    {
                        // Use the Convert method because it is convenient. This Convert
                        // method compresses the resulting RTF it reads from the conversion
                        // chain stream you set up and writes the result into the output stream.
                        // It saves a few lines of code that would be required to create another wrapper stream and
                        // copy from one stream to another.
                        rtfCompressionConversion.Convert(filteredRtf, newBodyContent);
                    }
                    catch (Microsoft.Exchange.Data.TextConverters.TextConvertersException)
                    {
                        // The conversion has failed.
                    }
                }

                else
                {
                    // Handle cases where the body format is not one of the above.
                }
            }

            finally
            {
                if (originalBodyContent != null)
                {
                    originalBodyContent.Close();
                }

                if (newBodyContent != null)
                {
                    newBodyContent.Close();
                }
            }
        }