Hi,@don bradman. According to my tests, the code below works fine. You could refer to the following code to convert the .msg file to a word file and then to pdf.
xaml:
<Button Content="convert" Width="100" Height="50" Click="Button_Click"/>
Codebedhind:
using Microsoft.Office.Interop.Word;
using System;
using System.Runtime.InteropServices;
using System.Windows;
using Application = Microsoft.Office.Interop.Word.Application;
using Outlook = Microsoft.Office.Interop.Outlook;
using Window = System.Windows.Window;
using Word = Microsoft.Office.Interop.Word;
namespace ConverterMSGToPDF
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void ConvertMsgToWord(string msgFilePath, string outputFilePath)
{
Application wordApp = new Application();
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
wordApp.Visible = false;
try
{
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.Session.OpenSharedItem(msgFilePath);
Document document = wordApp.Documents.Add();
Range range = document.Range();
range.InsertAfter(mailItem.Body);
document.SaveAs(outputFilePath, Word.WdSaveFormat.wdFormatDocumentDefault);
document.Close();
Marshal.ReleaseComObject(document);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
wordApp.Quit();
Marshal.ReleaseComObject(wordApp);
}
}
public void ConvertWordToPdf(string wordFilePath, string outputFilePath)
{
Word.Application wordApp = new Word.Application();
Word.Document document = wordApp.Documents.Open(wordFilePath);
document.SaveAs2(outputFilePath, Word.WdSaveFormat.wdFormatPDF);
document.Close();
wordApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(document);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string msgFilePath = "C:\\Users\\Administrator\\Desktop\\sample.msg";
string wordFilePath = "C:\\Users\\Administrator\\Desktop\\output.docx";
ConvertMsgToWord(msgFilePath, wordFilePath);
string outputFilePath = "C:\\Users\\Administrator\\Desktop\\output.pdf";
ConvertWordToPdf(wordFilePath, outputFilePath);
}
}
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.