Пример #1
0
        /// <summary>
        /// Writes the body of the MSG Appointment to html or text and extracts all the attachments. The
        /// result is return as a List of strings
        /// </summary>
        /// <param name="message"><see cref="Storage.Message"/></param>
        /// <param name="outputFolder">The folder where we need to write the output</param>
        /// <param name="hyperlinks">When true then hyperlinks are generated for the To, CC, BCC and attachments</param>
        /// <returns></returns>
        private List <string> WriteTask(Storage.Message message, string outputFolder, bool hyperlinks)
        {
            throw new NotImplementedException("Todo");
            // TODO: Rewrite this code so that an correct task is written

            var result = new List <string>();

            // Read MSG file from a stream
            // We first always check if there is a RTF body because appointments never have HTML bodies
            var body = message.BodyRtf;

            // If the body is not null then we convert it to HTML
            if (body != null)
            {
                var converter = new RtfToHtmlConverter();
                body = converter.ConvertRtfToHtml(body);
            }

            // Determine the name for the appointment body
            var appointmentFileName = outputFolder + "task" + (body != null ? ".htm" : ".txt");

            result.Add(appointmentFileName);

            // Write the body to a file
            File.WriteAllText(appointmentFileName, body, Encoding.UTF8);

            return(result);
        }
Пример #2
0
        public string GetText(System.Windows.Documents.FlowDocument document)
        {
            var range    = new TextRange(document.ContentStart, document.ContentEnd);
            var bodyXaml = string.Empty;

            using (MemoryStream stream = new MemoryStream())
            {
                range.Save(stream, DataFormats.Rtf);
                stream.Position = 0;

                using (StreamReader r = new StreamReader(stream))
                {
                    bodyXaml = r.ReadToEnd();
                    r.Close();
                }
                stream.Close();
            }
            var htmlText = RtfToHtmlConverter.ConvertRtfToHtml(bodyXaml);

            return(htmlText);

            //TextRange tr = new TextRange(document.ContentStart, document.ContentEnd);
            //using (MemoryStream ms = new MemoryStream())
            //{
            //    tr.Save(ms, DataFormats.Xaml);

            //    var txt = HtmlFromXamlConverter.ConvertXamlToHtml(UTF8Encoding.Default.GetString(ms.ToArray()));
            //    return txt;
            //}
        }
Пример #3
0
        private void ConvertData(object sender, ClipboardMonitor.ClipboardChangedEventArgs e)
        //private void ConvertData(object sender, System.Windows.Automation.AutomationFocusChangedEventArgs e)
        {
            //Console.WriteLine("ConvertData");
            iData = Clipboard.GetDataObject();

            if (!iData.GetDataPresent(DataFormats.Rtf))
            {
                return;
            }

            reset();

            rtfText = iData.GetData(DataFormats.Rtf).ToString();
            //Console.WriteLine(rtfText);


            RtfTree tree = new RtfTree();

            tree.LoadRtfText(rtfText);

            //tree = _ConvertMMath(tree);

            tree = _ConvertObject(tree);

            tree = _ConvertPict(tree);


            //Console.WriteLine(tree.Rtf);

            string html = RtfToHtmlConverter.ConvertRtfToHtml(tree.Rtf);
            //Console.WriteLine(html);

            string          regularExpressionPattern = string.Format(@"\[{0}\](.*?)\[\/{1}\]", REPLACETAG, REPLACETAG);
            Regex           regex      = new Regex(regularExpressionPattern, RegexOptions.Singleline);
            MatchCollection collection = regex.Matches(html);

            foreach (Match m in collection)
            {
                string Matchstr = m.Groups[0].Value;
                string Rid      = m.Groups[1].Value;
                int    index    = int.Parse(Rid);

                if (index < rtf_replace.Count)
                {
                    IReplace equationObj = (IReplace)rtf_replace[index];
                    string   s           = equationObj.toHtml();
                    //Console.WriteLine(m.Groups[0].Value + "\n\r");
                    //Console.WriteLine(s + "\n\r");
                    html = html.Replace(Matchstr, s);
                }
            }

            //Console.WriteLine(html + "\n\r");

            if (DataConverted != null)
            {
                DataConverted(this, new DataConvertEventArgs(rtfText, html));
            }
        }
        public static void Convert2()
        {
            RtfToHtmlConverter converter = new RtfToHtmlConverter();

            //Load rtf from file
            string content = File.ReadAllText("sample.rtf");

            converter.Load(content);

            //Images are exported in separate files
            converter.HtmlImageMode = HtmlImageMode.External;
            //The folder that will contain the external image files
            converter.ImagesFolder = "./images/";
            //The base folder that will be set as value to the 'src' attribute of the 'img' elements
            converter.ImagesSourceBaseFolder = "./images/";

            //Styles are exported to external CSS file
            converter.HtmlStyleMode = HtmlStyleMode.External;
            //The file that will contain the external styles
            converter.StyleFile = "./styles/test.css";
            //The file that will be set as 'href' attribute of the 'link' element pointing to the external styles.
            converter.StyleSourceFile = "./styles/test.css";

            //Convert rtf to html, and save it to hard disk
            File.WriteAllText("convert.html", converter.SaveAsString());
        }
        public void Build(FileModel model, IHostService host)
        {
            string content = (string)((Dictionary <string, object>)model.Content)["conceptual"];

            content = _taskFactory.StartNew(() => RtfToHtmlConverter.ConvertRtfToHtml(content)).Result;
            ((Dictionary <string, object>)model.Content)["conceptual"] = content;
        }
Пример #6
0
        /// <summary>
        /// RTF형식을 Html 형식으로
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ToHtmlButton_Click(object sender, RoutedEventArgs e)
        {
            using (var memory = new InMemoryRandomAccessStream())
            {
                RichEditBoxTest.Document.SaveToStream(Windows.UI.Text.TextGetOptions.FormatRtf, memory);
                var streamToSave = memory.AsStream();

                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

                TextReader textReader = new StreamReader(streamToSave, Encoding.UTF8);


                // RTFPipe 라이브러리 사용
                var libHtml = Rtf.ToHtml(new RtfSource(textReader));
                libHtml = RtfToHtmlConverter.ParseHtmlText(libHtml);
                // Html code 출력
                HtmlCodeViewer.Text = libHtml;

                var storageFolder = ApplicationData.Current.LocalFolder;
                // WebView navigation은 LoaclFolder 바로 밑에서는 동작하지 않아 폴더 새로 만들어줌
                var testFolder = await storageFolder.CreateFolderAsync("TestFolder", CreationCollisionOption.ReplaceExisting);

                var testHtmlFile = await testFolder.CreateFileAsync("rtftohtmltestpage.html", CreationCollisionOption.ReplaceExisting);

                await FileIO.WriteTextAsync(testHtmlFile, libHtml);

                RtfToHtmlViewer.Navigate(new Uri("ms-appdata:///local/TestFolder/rtftohtmltestpage.html"));
            }
            // 기존 제작 컨버터
            //RichEditBoxTest.Document.GetText(Windows.UI.Text.TextGetOptions.FormatRtf, out string fvff);
            //string htmlcode = await RtfToHtmlConverter.ParseRtfText(fvff);
        }
Пример #7
0
        private string GetBody()
        {
            try
            {
                var range    = new TextRange(BodyEditor.Document.ContentStart, BodyEditor.Document.ContentEnd);
                var bodyXaml = string.Empty;
                using (MemoryStream stream = new MemoryStream())
                {
                    range.Save(stream, DataFormats.Rtf);
                    stream.Position = 0;

                    using (StreamReader r = new StreamReader(stream))
                    {
                        bodyXaml = r.ReadToEnd();
                        r.Close();
                    }
                    stream.Close();
                }
                return(RtfToHtmlConverter.ConvertRtfToHtml(bodyXaml));
            }
            catch (Exception ex)
            {
                Utils.ShowWarning(ex.InnerException?.Message ?? ex.Message);
                return("");
            }
        }
Пример #8
0
        /// <summary>
        /// Writes the body of the MSG StickyNote to html or text and extracts all the attachments. The
        /// result is return as a List of strings
        /// </summary>
        /// <param name="message"><see cref="Storage.Message"/></param>
        /// <param name="outputFolder">The folder where we need to write the output</param>
        /// <param name="hyperlinks">When true then hyperlinks are generated for the To, CC, BCC and attachments</param>
        /// <returns></returns>
        private List <string> WriteStickyNote(Storage.Message message, string outputFolder, bool hyperlinks)
        {
            var    result = new List <string>();
            string stickyNoteFile;
            var    stickyNoteHeader = string.Empty;

            // Sticky notes only have RTF or Text bodies
            var body = message.BodyRtf;

            // If the body is not null then we convert it to HTML
            if (body != null)
            {
                var converter = new RtfToHtmlConverter();
                body           = converter.ConvertRtfToHtml(body);
                stickyNoteFile = outputFolder +
                                 (!string.IsNullOrEmpty(message.Subject)
                                     ? FileManager.RemoveInvalidFileNameChars(message.Subject)
                                     : "stickynote") + ".htm";

                stickyNoteHeader =
                    "<table style=\"width:100%; font-family: Times New Roman; font-size: 12pt;\">" + Environment.NewLine;

                if (message.SentOn != null)
                {
                    stickyNoteHeader +=
                        "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                        LanguageConsts.StickyNoteDateLabel + ":</td><td>" +
                        ((DateTime)message.SentOn).ToString(LanguageConsts.DataFormat) + "</td></tr>" +
                        Environment.NewLine;
                }

                // Empty line
                stickyNoteHeader += "<tr><td colspan=\"2\" style=\"height: 18px; \">&nbsp</td></tr>" + Environment.NewLine;

                // End of table + empty line
                stickyNoteHeader += "</table><br/>" + Environment.NewLine;

                body = InjectHeader(body, stickyNoteHeader);
            }
            else
            {
                body = message.BodyText ?? string.Empty;

                // Sent on
                if (message.SentOn != null)
                {
                    stickyNoteHeader +=
                        (LanguageConsts.StickyNoteDateLabel + ":") + ((DateTime)message.SentOn).ToString(LanguageConsts.DataFormat) + Environment.NewLine;
                }

                body           = stickyNoteHeader + body;
                stickyNoteFile = outputFolder + (!string.IsNullOrEmpty(message.Subject) ? FileManager.RemoveInvalidFileNameChars(message.Subject) : "stickynote") + ".txt";
            }

            // Write the body to a file
            File.WriteAllText(stickyNoteFile, body, Encoding.UTF8);
            result.Add(stickyNoteFile);
            return(result);
        }
Пример #9
0
        private void Exporttohtml_Click(object sender, RoutedEventArgs e)
        {
            string rtf              = GetRTF();
            var    htmlOutput       = @"D:\test21.html";
            var    contentUriPrefix = Path.GetFileNameWithoutExtension(htmlOutput);
            var    htmlResult       = RtfToHtmlConverter.RtfToHtml(rtf, contentUriPrefix);

            htmlResult.WriteToFile(htmlOutput);
        }
Пример #10
0
        private void Btn_selectrtffile_Click(object sender, RoutedEventArgs e)
        {
            var rtf = File.ReadAllText(@"C:\Users\Administrator\Desktop\test.rtf");

            var htmlOutput       = @"D:\test13.html";
            var contentUriPrefix = Path.GetFileNameWithoutExtension(htmlOutput);
            var htmlResult       = RtfToHtmlConverter.RtfToHtml(rtf, contentUriPrefix);

            htmlResult.WriteToFile(htmlOutput);

            this.wb.Navigate(htmlOutput);
        }
Пример #11
0
        private void NotifyBindingHtmlChanged()
        {
            //if (myBindingContent != this.ContentHtml)
            //{
            //    BindingContent = this.ContentHtml;
            //}

            //将rtf格式转换成html文本
            var rtf        = GetRTF();
            var htmlResult = RtfToHtmlConverter.RtfToHtml(rtf);

            BindingHtml = htmlResult.Html;
        }
        public static void Convert()
        {
            RtfToHtmlConverter converter = new RtfToHtmlConverter();

            //Load rtf from file
            string content = File.ReadAllText("sample.rtf");

            converter.Load(content);

            //Images are embedded in the main html file as Base64-encoded strings.
            converter.HtmlImageMode = HtmlImageMode.Embedded;
            //Styles are embedded in 'style' element in the 'head' section.
            converter.HtmlStyleMode = HtmlStyleMode.Embedded;

            //Convert rtf to html, and save it to file stream
            using (var stream = File.OpenWrite("convert.html"))
            {
                converter.Save(stream);
            }
        }
Пример #13
0
        /// <summary>
        /// Writes the body of the MSG StickyNote to html or text and extracts all the attachments. The
        /// result is return as a List of strings
        /// </summary>
        /// <param name="message"><see cref="Storage.Message"/></param>
        /// <param name="outputFolder">The folder where we need to write the output</param>
        /// <returns></returns>
        private static List<string> WriteMsgStickyNote(Storage.Message message, string outputFolder)
        {
            var files = new List<string>();
            string stickyNoteFile;
            var stickyNoteHeader = new StringBuilder();

            // Sticky notes only have RTF or Text bodies
            var body = message.BodyRtf;

            // If the body is not null then we convert it to HTML
            if (body != null)
            {
                var converter = new RtfToHtmlConverter();
                body = converter.ConvertRtfToHtml(body);
                stickyNoteFile = outputFolder +
                                 (!string.IsNullOrEmpty(message.Subject)
                                     ? FileManager.RemoveInvalidFileNameChars(message.Subject)
                                     : "stickynote") + ".htm";

                WriteHeaderStart(stickyNoteHeader, true);

                if (message.SentOn != null)
                    WriteHeaderLine(stickyNoteHeader, true, 0, LanguageConsts.StickyNoteDateLabel,
                        ((DateTime)message.SentOn).ToString(LanguageConsts.DataFormatWithTime));

                // Empty line
                WriteHeaderEmptyLine(stickyNoteHeader, true);

                // End of table + empty line
                WriteHeaderEnd(stickyNoteHeader, true);

                body = InjectHeader(body, stickyNoteHeader.ToString());
            }
            else
            {
                body = message.BodyText ?? string.Empty;

                // Sent on
                if (message.SentOn != null)
                    WriteHeaderLine(stickyNoteHeader, false, LanguageConsts.StickyNoteDateLabel.Length,
                        LanguageConsts.StickyNoteDateLabel,
                        ((DateTime)message.SentOn).ToString(LanguageConsts.DataFormatWithTime));

                body = stickyNoteHeader + body;
                stickyNoteFile = outputFolder +
                                 (!string.IsNullOrEmpty(message.Subject)
                                     ? FileManager.RemoveInvalidFileNameChars(message.Subject)
                                     : "stickynote") + ".txt";
            }

            // Write the body to a file
            stickyNoteFile = FileManager.FileExistsMakeNew(stickyNoteFile);
            File.WriteAllText(stickyNoteFile, body, Encoding.UTF8);
            files.Add(stickyNoteFile);
            return files;
        }
Пример #14
0
        /// <summary>
        /// Writes the body of the MSG Appointment to html or text and extracts all the attachments. The
        /// result is return as a List of strings
        /// </summary>
        /// <param name="message"><see cref="Storage.Message"/></param>
        /// <param name="outputFolder">The folder where we need to write the output</param>
        /// <param name="hyperlinks">When true then hyperlinks are generated for the To, CC, BCC and attachments</param>
        /// <returns></returns>
        private List<string> WriteTask(Storage.Message message, string outputFolder, bool hyperlinks)
        {
            throw new NotImplementedException("Todo");
            // TODO: Rewrite this code so that an correct task is written

            var result = new List<string>();

            // Read MSG file from a stream
            // We first always check if there is a RTF body because appointments never have HTML bodies
            var body = message.BodyRtf;

            // If the body is not null then we convert it to HTML
            if (body != null)
            {
                var converter = new RtfToHtmlConverter();
                body = converter.ConvertRtfToHtml(body);
            }

            // Determine the name for the appointment body
            var appointmentFileName = outputFolder + "task" + (body != null ? ".htm" : ".txt");
            result.Add(appointmentFileName);

            // Write the body to a file
            File.WriteAllText(appointmentFileName, body, Encoding.UTF8);

            return result;
        }
Пример #15
0
        /// <summary>
        /// Writes the body of the MSG Appointment to html or text and extracts all the attachments. The
        /// result is return as a List of strings
        /// </summary>
        /// <param name="message"><see cref="Storage.Message"/></param>
        /// <param name="outputFolder">The folder where we need to write the output</param>
        /// <param name="hyperlinks">When true then hyperlinks are generated for the To, CC, BCC and attachments</param>
        /// <returns></returns>
        private List <string> WriteAppointment(Storage.Message message, string outputFolder, bool hyperlinks)
        {
            //throw new NotImplementedException("Todo");
            // TODO: Rewrite this code so that an correct appointment is written

            var result = new List <string>();

            // Read MSG file from a stream
            // We first always check if there is a RTF body because appointments never have HTML bodies
            var body     = message.BodyRtf;
            var htmlBody = false;

            // If the body is not null then we convert it to HTML
            if (body != null)
            {
                var converter = new RtfToHtmlConverter();
                body     = converter.ConvertRtfToHtml(body);
                htmlBody = true;
            }

            if (string.IsNullOrEmpty(body))
            {
                body = message.BodyText;
                if (body == null)
                {
                    body     = "<html><head></head><body></body></html>";
                    htmlBody = true;
                }
            }

            // Determine the name for the appointment body
            var appointmentFileName = outputFolder +
                                      (!string.IsNullOrEmpty(message.Subject)
                                          ? FileManager.RemoveInvalidFileNameChars(message.Subject)
                                          : "appointment") + (htmlBody ? ".htm" : ".txt");

            result.Add(appointmentFileName);

            // Onderwerp
            // Locatie
            //
            // Begin
            // Eind
            // Tijd weergeven als
            //
            // Terugkeerpatroon
            // Type terugkeerpatroon
            //
            // Vergaderingstatus
            //
            // Organisator
            // Verplichte deelnemers
            // Optionele deelnemers
            //
            // Inhoud van het agenda item

            string appointmentHeader;

            if (htmlBody)
            {
                // Start of table
                appointmentHeader =
                    "<table style=\"width:100%; font-family: Times New Roman; font-size: 12pt;\">" + Environment.NewLine;

                // Subject
                appointmentHeader +=
                    "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                    LanguageConsts.AppointmentSubject + ":</td><td>" + message.Subject + "</td></tr>" + Environment.NewLine;

                // Location
                appointmentHeader +=
                    "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                    LanguageConsts.AppointmentLocation + ":</td><td>" + message.Appointment.Location + "</td></tr>" + Environment.NewLine;

                // Empty line
                appointmentHeader += "<tr><td colspan=\"2\" style=\"height: 18px; \">&nbsp</td></tr>" + Environment.NewLine;

                // Start
                appointmentHeader +=
                    "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                    LanguageConsts.AppointmentStartDate + ":</td><td>" + message.Appointment.Start + "</td></tr>" + Environment.NewLine;

                // End
                appointmentHeader +=
                    "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                    LanguageConsts.AppointmentEndDate + ":</td><td>" + message.Appointment.End + "</td></tr>" + Environment.NewLine;

                // Empty line
                appointmentHeader += "<tr><td colspan=\"2\" style=\"height: 18px; \">&nbsp</td></tr>" + Environment.NewLine;

                // Recurrence patern
                var recurrenceType = message.Appointment.RecurrenceType;
                if (!string.IsNullOrEmpty(recurrenceType))
                {
                    appointmentHeader +=
                        "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                        LanguageConsts.AppointmentRecurrenceTypeLabel + ":</td><td>" + message.Appointment.RecurrenceType + "</td></tr>" + Environment.NewLine;
                }

                // Recurrence patern
                var recurrencePatern = message.Appointment.RecurrencePatern;
                if (!string.IsNullOrEmpty(recurrencePatern))
                {
                    appointmentHeader +=
                        "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                        LanguageConsts.AppointmentRecurrencePaternLabel + ":</td><td>" + message.Appointment.RecurrencePatern + "</td></tr>" + Environment.NewLine;
                }


                // Categories
                var categories = message.Categories;
                if (categories != null)
                {
                    appointmentHeader +=
                        "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                        LanguageConsts.EmailCategoriesLabel + ":</td><td>" + String.Join("; ", categories) + "</td></tr>" +
                        Environment.NewLine;

                    // Empty line
                    appointmentHeader += "<tr><td colspan=\"2\" style=\"height: 18px; \">&nbsp</td></tr>" + Environment.NewLine;
                }

                // Attachments
                //if (attachmentList.Count != 0)
                //    appointmentHeader +=
                //        "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                //        LanguageConsts.AttachmentsLabel + ":</td><td>" + string.Join(", ", attachmentList) + "</td></tr>" +
                //        Environment.NewLine;

                // Empty line
                appointmentHeader += "<tr><td colspan=\"2\" style=\"height: 18px; \">&nbsp</td></tr>" + Environment.NewLine;

                // End of table + empty line
                appointmentHeader += "</table><br/>" + Environment.NewLine;
            }
            else
            {
                // text part, todo
                appointmentHeader = "todo";
            }

            body = InjectHeader(body, appointmentHeader);


            // Write the body to a file
            File.WriteAllText(appointmentFileName, body, Encoding.UTF8);

            return(result);
        }
Пример #16
0
        /// <summary>
        /// Writes the body of the MSG StickyNote to html or text and extracts all the attachments. The
        /// result is return as a List of strings
        /// </summary>
        /// <param name="message"><see cref="Storage.Message"/></param>
        /// <param name="outputFolder">The folder where we need to write the output</param>
        /// <param name="hyperlinks">When true then hyperlinks are generated for the To, CC, BCC and attachments</param>
        /// <returns></returns>
        private List<string> WriteStickyNote(Storage.Message message, string outputFolder, bool hyperlinks)
        {
            var result = new List<string>();
            string stickyNoteFile;
            var stickyNoteHeader = string.Empty;

            // Sticky notes only have RTF or Text bodies
            var body = message.BodyRtf;

            // If the body is not null then we convert it to HTML
            if (body != null)
            {
                var converter = new RtfToHtmlConverter();
                body = converter.ConvertRtfToHtml(body);
                stickyNoteFile = outputFolder +
                                 (!string.IsNullOrEmpty(message.Subject)
                                     ? FileManager.RemoveInvalidFileNameChars(message.Subject)
                                     : "stickynote") + ".htm";

                stickyNoteHeader =
                    "<table style=\"width:100%; font-family: Times New Roman; font-size: 12pt;\">" + Environment.NewLine;

                if (message.SentOn != null)
                    stickyNoteHeader +=
                        "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                        LanguageConsts.StickyNoteDateLabel + ":</td><td>" +
                        ((DateTime) message.SentOn).ToString(LanguageConsts.DataFormat) + "</td></tr>" +
                        Environment.NewLine;

                // Empty line
                stickyNoteHeader += "<tr><td colspan=\"2\" style=\"height: 18px; \">&nbsp</td></tr>" + Environment.NewLine;

                // End of table + empty line
                stickyNoteHeader += "</table><br/>" + Environment.NewLine;

                body = InjectHeader(body, stickyNoteHeader);
            }
            else
            {
                body = message.BodyText ?? string.Empty;

                // Sent on
                if (message.SentOn != null)
                    stickyNoteHeader +=
                        (LanguageConsts.StickyNoteDateLabel + ":") + ((DateTime) message.SentOn).ToString(LanguageConsts.DataFormat) + Environment.NewLine;

                body = stickyNoteHeader + body;
                stickyNoteFile = outputFolder + (!string.IsNullOrEmpty(message.Subject) ? FileManager.RemoveInvalidFileNameChars(message.Subject) : "stickynote") + ".txt";
            }

            // Write the body to a file
            File.WriteAllText(stickyNoteFile, body, Encoding.UTF8);
            result.Add(stickyNoteFile);
            return result;
        }
Пример #17
0
 public string ConvertRtfToHtml(string rtfText)
 {
     return(RtfToHtmlConverter.ConvertRtfToHtml(rtfText));
 }
Пример #18
0
        /// <summary>
        /// This function pre processes the Outlook MSG <see cref="Storage.Message"/> object, it tries to find the html (or text) body
        /// and reads all the available <see cref="Storage.Attachment"/> objects. When an attachment is inline it tries to
        /// map this attachment to the html body part when this is available
        /// </summary>
        /// <param name="message">The <see cref="Storage.Message"/> object</param>
        /// <param name="hyperlinks">When true then hyperlinks are generated for the To, CC, BCC and 
        /// attachments (when there is an html body)</param>
        /// <param name="outputFolder">The outputfolder where alle extracted files need to be written</param>
        /// <param name="fileName">Returns the filename for the html or text body</param>
        /// <param name="htmlBody">Returns true when the <see cref="Storage.Message"/> object did contain 
        /// an HTML body</param>
        /// <param name="body">Returns the html or text body</param>
        /// <param name="contactPhotoFileName">Returns the filename of the contact photo. This field will only
        /// return a value when the <see cref="Storage.Message"/> object is a <see cref="Storage.Message.MessageType.Contact"/> 
        /// type and the <see cref="Storage.Message.Attachments"/> contains an object that has the 
        /// <param ref="Storage.Message.Attachment.IsContactPhoto"/> set to true, otherwise this field will always be null</param>
        /// <param name="attachments">Returns a list of names with the found attachment</param>
        /// <param name="files">Returns all the files that are generated after pre processing the <see cref="Storage.Message"/> object</param>
        private void PreProcessMsgFile(Storage.Message message,
            bool hyperlinks,
            string outputFolder,
            ref string fileName,
            out bool htmlBody,
            out string body,
            out string contactPhotoFileName,
            out List<string> attachments,
            out List<string> files)
        {
            const string rtfInlineObject = "[*[RTFINLINEOBJECT]*]";

            htmlBody = true;
            attachments = new List<string>();
            files = new List<string>();
            var htmlConvertedFromRtf = false;
            contactPhotoFileName = null;
            body = message.BodyHtml;

            if (string.IsNullOrEmpty(body))
            {
                htmlBody = false;
                body = message.BodyRtf;
                // If the body is not null then we convert it to HTML
                if (body != null)
                {
                    // The RtfToHtmlConverter doesn't support the RTF \objattph tag. So we need to 
                    // replace the tag with some text that does survive the conversion. Later on we 
                    // will replace these tags with the correct inline image tags
                    body = body.Replace("\\objattph", rtfInlineObject);
                    var converter = new RtfToHtmlConverter();
                    body = converter.ConvertRtfToHtml(body);
                    htmlConvertedFromRtf = true;
                    htmlBody = true;
                }
                else
                {
                    body = message.BodyText;

                    // When there is no body at all we just make an empty html document
                    if (body == null)
                    {
                        htmlBody = true;
                        body = "<html><head></head><body></body></html>";
                    }
                }
            }

            fileName = outputFolder +
                       (!string.IsNullOrEmpty(message.Subject)
                           ? FileManager.RemoveInvalidFileNameChars(message.Subject)
                           : fileName) + (htmlBody ? ".htm" : ".txt");

            fileName = FileManager.FileExistsMakeNew(fileName);
            files.Add(fileName);

            var inlineAttachments = new List<InlineAttachment>();

            foreach (var attachment in message.Attachments)
            {
                FileInfo fileInfo = null;
                var attachmentFileName = string.Empty;
                var renderingPosition = -1;
                var isInline = false;

                // ReSharper disable once CanBeReplacedWithTryCastAndCheckForNull
                if (attachment is Storage.Attachment)
                {
                    var attach = (Storage.Attachment)attachment;
                    attachmentFileName = attach.FileName;
                    renderingPosition = attach.RenderingPosition;
                    fileInfo = new FileInfo(FileManager.FileExistsMakeNew(outputFolder + attachmentFileName));
                    File.WriteAllBytes(fileInfo.FullName, attach.Data);
                    isInline = attach.IsInline;

                    if (attach.IsContactPhoto && htmlBody)
                    {
                        contactPhotoFileName = fileInfo.FullName;
                        continue;
                    }

                    if (!htmlConvertedFromRtf)
                    {
                        // When we find an inline attachment we have to replace the CID tag inside the html body
                        // with the name of the inline attachment. But before we do this we check if the CID exists.
                        // When the CID does not exists we treat the inline attachment as a normal attachment
                        if (htmlBody && !string.IsNullOrEmpty(attach.ContentId) && body.Contains(attach.ContentId))
                            body = body.Replace("cid:" + attach.ContentId, fileInfo.FullName);
                        else
                            // If we didn't find the cid tag we treat the inline attachment as a normal one 
                            isInline = false;
                    }
                }
                // ReSharper disable CanBeReplacedWithTryCastAndCheckForNull
                else if (attachment is Storage.Message)
                // ReSharper restore CanBeReplacedWithTryCastAndCheckForNull
                {
                    var msg = (Storage.Message)attachment;
                    attachmentFileName = msg.FileName;
                    renderingPosition = msg.RenderingPosition;

                    fileInfo = new FileInfo(FileManager.FileExistsMakeNew(outputFolder + attachmentFileName));
                    msg.Save(fileInfo.FullName);
                }

                if (fileInfo == null) continue;

                if (!isInline)
                    files.Add(fileInfo.FullName);

                // Check if the attachment has a render position. This property is only filled when the
                // body is RTF and the attachment is made inline
                if (htmlBody && renderingPosition != -1)
                {
                    if (!isInline)
                        using (var icon = FileIcon.GetFileIcon(fileInfo.FullName))
                        {
                            var iconFileName = outputFolder + Guid.NewGuid() + ".png";
                            icon.Save(iconFileName, ImageFormat.Png);
                            inlineAttachments.Add(new InlineAttachment(iconFileName, attachmentFileName, fileInfo.FullName));
                        }
                    else
                        inlineAttachments.Add(new InlineAttachment(renderingPosition, attachmentFileName));
                }
                else
                    renderingPosition = -1;

                if (!isInline && renderingPosition == -1)
                {
                    if (htmlBody)
                    {
                        if (hyperlinks)
                            attachments.Add("<a href=\"" + fileInfo.Name + "\">" +
                                            HttpUtility.HtmlEncode(attachmentFileName) + "</a> (" +
                                            FileManager.GetFileSizeString(fileInfo.Length) + ")");
                        else
                            attachments.Add(HttpUtility.HtmlEncode(attachmentFileName) + " (" +
                                            FileManager.GetFileSizeString(fileInfo.Length) + ")");
                    }
                    else
                        attachments.Add(attachmentFileName + " (" + FileManager.GetFileSizeString(fileInfo.Length) + ")");
                }
            }

            if (htmlBody)
                foreach (var inlineAttachment in inlineAttachments.OrderBy(m => m.RenderingPosition))
                {
                    if (inlineAttachment.RenderingPosition != null)
                        body = ReplaceFirstOccurence(body, rtfInlineObject,
                            "<table style=\"width: 70px; display: inline; text-align: center; font-family: Times New Roman; font-size: 12pt;\"><tr><td>" +
                            (hyperlinks ? "<a href=\"" + inlineAttachment.FullName + "\">" : string.Empty) + "<img alt=\"\" src=\"" +
                            inlineAttachment.RenderingPosition + "\">" + (hyperlinks ? "</a>" : string.Empty) + "</td></tr><tr><td>" +
                            HttpUtility.HtmlEncode(inlineAttachment.AttachmentFileName) +
                            "</td></tr></table>");
                    else
                        body = ReplaceFirstOccurence(body, rtfInlineObject, "<img alt=\"\" src=\"" + inlineAttachment.IconFileName + "\">");
                }
        }
Пример #19
0
        /// <summary>
        /// Writes the body of the MSG Appointment to html or text and extracts all the attachments. The
        /// result is return as a List of strings
        /// </summary>
        /// <param name="message"><see cref="Storage.Message"/></param>
        /// <param name="outputFolder">The folder where we need to write the output</param>
        /// <param name="hyperlinks">When true then hyperlinks are generated for the To, CC, BCC and attachments</param>
        /// <returns></returns>
        private List<string> WriteAppointment(Storage.Message message, string outputFolder, bool hyperlinks)
        {
            //throw new NotImplementedException("Todo");
            // TODO: Rewrite this code so that an correct appointment is written

            var result = new List<string>();

            // Read MSG file from a stream
            // We first always check if there is a RTF body because appointments never have HTML bodies
            var body = message.BodyRtf;
            var htmlBody = false;

            // If the body is not null then we convert it to HTML
            if (body != null)
            {
                var converter = new RtfToHtmlConverter();
                body = converter.ConvertRtfToHtml(body);
                htmlBody = true;
            }

            if (string.IsNullOrEmpty(body))
            {
                body = message.BodyText;
                if (body == null)
                {
                    body = "<html><head></head><body></body></html>";
                    htmlBody = true;
                }
            }

            // Determine the name for the appointment body
            var appointmentFileName = outputFolder +
                                      (!string.IsNullOrEmpty(message.Subject)
                                          ? FileManager.RemoveInvalidFileNameChars(message.Subject)
                                          : "appointment") + (htmlBody ? ".htm" : ".txt");

            result.Add(appointmentFileName);

            // Onderwerp
            // Locatie
            //
            // Begin
            // Eind
            // Tijd weergeven als
            //
            // Terugkeerpatroon
            // Type terugkeerpatroon
            //
            // Vergaderingstatus
            //
            // Organisator
            // Verplichte deelnemers
            // Optionele deelnemers
            //
            // Inhoud van het agenda item

            string appointmentHeader;

            if (htmlBody)
            {
                // Start of table
                appointmentHeader =
                    "<table style=\"width:100%; font-family: Times New Roman; font-size: 12pt;\">" + Environment.NewLine;

                // Subject
                appointmentHeader +=
                    "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                    LanguageConsts.AppointmentSubject + ":</td><td>" + message.Subject + "</td></tr>" + Environment.NewLine;

                // Location
                appointmentHeader +=
                    "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                    LanguageConsts.AppointmentLocation + ":</td><td>" + message.Appointment.Location + "</td></tr>" + Environment.NewLine;

                // Empty line
                appointmentHeader += "<tr><td colspan=\"2\" style=\"height: 18px; \">&nbsp</td></tr>" + Environment.NewLine;

                // Start
                appointmentHeader +=
                    "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                    LanguageConsts.AppointmentStartDate + ":</td><td>" + message.Appointment.Start + "</td></tr>" + Environment.NewLine;

                // End
                appointmentHeader +=
                    "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                    LanguageConsts.AppointmentEndDate + ":</td><td>" + message.Appointment.End + "</td></tr>" + Environment.NewLine;

                // Empty line
                appointmentHeader += "<tr><td colspan=\"2\" style=\"height: 18px; \">&nbsp</td></tr>" + Environment.NewLine;

                // Recurrence patern
                var recurrenceType = message.Appointment.RecurrenceType;
                if (!string.IsNullOrEmpty(recurrenceType))
                    appointmentHeader +=
                        "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                        LanguageConsts.AppointmentRecurrenceTypeLabel + ":</td><td>" + message.Appointment.RecurrenceType + "</td></tr>" + Environment.NewLine;

                // Recurrence patern
                var recurrencePatern = message.Appointment.RecurrencePatern;
                if (!string.IsNullOrEmpty(recurrencePatern))
                    appointmentHeader +=
                        "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                        LanguageConsts.AppointmentRecurrencePaternLabel + ":</td><td>" + message.Appointment.RecurrencePatern + "</td></tr>" + Environment.NewLine;

                // Categories
                var categories = message.Categories;
                if (categories != null)
                {
                    appointmentHeader +=
                        "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                        LanguageConsts.EmailCategoriesLabel + ":</td><td>" + String.Join("; ", categories) + "</td></tr>" +
                        Environment.NewLine;

                    // Empty line
                    appointmentHeader += "<tr><td colspan=\"2\" style=\"height: 18px; \">&nbsp</td></tr>" + Environment.NewLine;
                }

                // Attachments
                //if (attachmentList.Count != 0)
                //    appointmentHeader +=
                //        "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" +
                //        LanguageConsts.AttachmentsLabel + ":</td><td>" + string.Join(", ", attachmentList) + "</td></tr>" +
                //        Environment.NewLine;

                // Empty line
                appointmentHeader += "<tr><td colspan=\"2\" style=\"height: 18px; \">&nbsp</td></tr>" + Environment.NewLine;

                // End of table + empty line
                appointmentHeader += "</table><br/>" + Environment.NewLine;
            }
            else
            {
                // text part, todo
                appointmentHeader = "todo";
            }

            body = InjectHeader(body, appointmentHeader);

            // Write the body to a file
            File.WriteAllText(appointmentFileName, body, Encoding.UTF8);

            return result;
        }