XD blog

blog page

c sharp, python, pythonnet


2014-02-23 Python and C# in the same program

I pretty much use Python for everything, I link many of my tools with Python, having the same place to run them. However, C# is very convenient if you want to automate some processes on Windows. Since I discovered pythonnet, I do not look anymore for a way to do things in Python, I do it in C#, I make an assembly and I link it to Python.

For example, to convert a couple of Word documents into PDF, the C# code is quite simple:

using System;
using Microsoft.Office.Interop.Word;

namespace csharp_office_helper
{
    public static class WordHelper
    {
        public static void SaveAsPDF(string infile, string outfile)
        {
            Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
            // open it in read only mode
            var wordDocument = appWord.Documents.Open(infile, Type.Missing, true);
            wordDocument.ExportAsFixedFormat(outfile, WdExportFormat.wdExportFormatPDF);
        }
    }
}

It needs to be compiled in an assembly. With pythonnet, it can be used in Python as follows:

import clr
clr.AddReference("csharp_office_helper")
from csharp_office_helper import WordHelper 
WordHelper.SaveAsPDF("my_document.docx", "my_document.pdf")

<-- -->

Xavier Dupré