Friday, August 13, 2010

Convert Word and Excel to PDFs in C#

I had a very repetitive task I had to perform. Take a directory full of Word documents, open each, and do a Save As -> PDF on each of them. Not in this lifetime. So I wrote a quick program for it, and included Excel just to boot. I'll show the important methods.

You must have Office 2007 or greater installed on the machine the code will run on.

Add a reference to:
Microsoft Excel 12.0 Object Library (or greater)
Microsoft Word 12.0 Object Library (or greater)

Both can be found in the COM tab of the Add Reference dialog.

Here's the code:
using System;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
...

void ExportExcel(string infile, string outfile)
{
    Excel.Application excelApp = null;
    try
    {
        excelApp = new Excel.Application();
        excelApp.Workbooks.Open(infile);
        excelApp.ActiveWorkbook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, outfile);
    }
    finally
    {
        if (excelApp != null)
            excelApp.Quit();
    }
}

void ExportWord(string infile, string outfile)
{
    Word.Application wordApp = null;
    try
    {
        wordApp = new Word.Application();
        wordApp.Documents.Open(infile);
        wordApp.ActiveDocument.ExportAsFixedFormat(outfile, Word.WdExportFormat.wdExportFormatPDF);
    }
    finally
    {
        if (wordApp != null)
            wordApp.Quit();
    }
}


1 comment:

Speak your mind.