Hi,
I'm trying to convert a outlook message file i.e. .msg file to a .pdf file using PDFsharp library. Now, my goal is to make the pdf file looking identical to the msg file even if has tables, images or colored/formatted text. But my code is not doing that properly.
What I have tried:
public static void ConvertMsgToPdf(string msgFilePath, string pdfFilePath)
{
Application outlookApp = new Application();
MailItem mailItem = (MailItem)outlookApp.CreateItemFromTemplate(msgFilePath);
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
Microsoft.Office.Interop.Outlook.Inspector inspector = mailItem.GetInspector as Microsoft.Office.Interop.Outlook.Inspector;
if (inspector != null)
{
Microsoft.Office.Interop.Word.Document document2 = inspector.WordEditor as Microsoft.Office.Interop.Word.Document;
if (document2 != null)
{
foreach (Microsoft.Office.Interop.Word.Table table in document2.Tables)
{
for (int row = 1; row <= table.Rows.Count; row++)
{
for (int col = 1; col <= table.Columns.Count; col++)
{
string cellText = table.Cell(row, col).Range.Text;
gfx.DrawString(cellText, new XFont("Arial", 12), XBrushes.Black, new XRect(col * 100, row * 20, 100, 20), XStringFormats.TopLeft);
}
}
}
}
}
string[] lines = mailItem.Body.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
for (int i = 0; i < lines.Length; i++)
{
gfx.DrawString(lines[i], new XFont("Arial", 12), XBrushes.Black, new XRect(0, i * 20, page.Width, 20), XStringFormats.TopLeft);
}
foreach (Microsoft.Office.Interop.Outlook.Attachment attachment in mailItem.Attachments)
{
if (attachment.Type == Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue)
{
string fileName = Path.Combine(Path.GetTempPath(), attachment.FileName);
attachment.SaveAsFile(fileName);
XImage image = XImage.FromFile(fileName);
gfx.DrawImage(image, new XRect(0, 0, page.Width, page.Height));
}
}
document.Save(pdfFilePath);
}
Can anyone help me with this ?
Note: If there is any other open source library that can get this done I'm open to it as well. Also, I want to show the sender info and subject of the email at the top as well in the pdf.