Export Word Documents to PDF with C#
Readers of my blog (both of you!) will know that I've been working on Technicana's build process, creating a continuous integration platform with automated release builds.
I have become a great believer in automated builds, to the point where I've always got an eye on whether I can automate any part of the process. The latest candidate for entry into the build process is my product documentation.
Word 2007 gives you the option to export your documents to PDF, which makes it a great platform for creating straightforward documentation (and let's be frank - when it comes to documentation, the more straightforward the better). However, I didn't want to be manually creating the PDF each time I updated the documentation.
My approach was to treat my source Word document as source code and the resulting PDF as compiled code. Therefore I checked the Word document into source control, then added a step to my build process to automatically export the document as PDF. To perform the export itself, I used C# Word automation as follows.
static void Main(string args)
object visible = true;
object readOnly = true;
object sourceFilename = args;
string targetFilename = args;
Application wordApp = new Application();
Document doc = wordApp.Documents.Open(ref sourceFilename, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref visible, ref missing, ref missing,
ref missing, ref missing);
doc.ExportAsFixedFormat(targetFilename, WdExportFormat.wdExportFormatPDF, false, WdExportOptimizeFor.wdExportOptimizeForOnScreen,
WdExportRange.wdExportAllDocument, 0, 0, WdExportItem.wdExportDocumentContent, false, false,
WdExportCreateBookmarks.wdExportCreateNoBookmarks, false, false, false, ref missing);
object saveChanges = false;
doc.Close(ref saveChanges, ref missing, ref missing);
wordApp.Quit(ref saveChanges, ref missing, ref missing);
static object missing = Type.Missing;
Note that this was targetted at .NET 3.5. The code would look a lot cleaner with C# 4.0 or if I'd used VB.NET.
I then created a batch file with the source and target file names, and added the batch file to the CruiseControl.NET config file. Hey presto - a fresh copy of the documentation upon each release build.
Are you a VBA developer? Working with Subversion or Perforce? See how VbaDiff can fit into your workflow.