Search code examples
c#ms-wordwpf-controlsxps

Converting Word Document to XPS Document in C# WPF


I am working on one application which is using XPS documents. I have word documents and I want to convert all the word documents to XPS documents.

I have one main Folder (Instructions) and inside (Instructions) there are many other Folders. Each Folder have so many Word Documents. How can I convert all these Word Documents to XPS Documents recursively.

Currently I have this Function which is Converting Word to XPS

public static string convertWordToXps(string path, string wordDocName)
    {
        Word.Application wordApp = new Word.Application();
        wordApp.Documents.Open(string.Concat(path, "\\", wordDocName), ConfirmConversions: false, ReadOnly: true);
        string xpsFile = string.Concat(path, "\\", Path.GetFileNameWithoutExtension(wordDocName), ".xps");

        try
        {
            //wordApp.ActiveDocument.ExportAsFixedFormat(xpsFileName, WdExportFormat.wdExportFormatXPS, false, WdExportOptimizeFor.wdExportOptimizeForOnScreen, WdExportRange.wdExportAllDocument, 1, 1, WdExportItem.wdExportDocumentContent, false, true, WdExportCreateBookmarks.wdExportCreateNoBookmarks, false, true, false, nullObject);
            wordApp.ActiveDocument.SaveAs2(xpsFile, FileFormat: Word.WdSaveFormat.wdFormatXPS);
            return xpsFile;
        }
        catch (Exception e)
        {
            MessageBox.Show(e.getDetailedErrorMessage());
        }
        finally
        {
            wordApp.Quit(SaveChanges: false, OriginalFormat: Type.Missing, RouteDocument: Type.Missing);
        }
        return null;
    }

Solution

  • I wrote an static method that do what you need.

    static void SearchDocuments(string directoryPath)
        {
            try
            {
                foreach (string fullName in System.IO.Directory.GetFiles(directoryPath,"*.docx")) // if your word documents come from an older version of word, they might have .doc extenstion
                {
                    convertWordToXps(System.IO.Path.GetDirectoryName(fullFileName), System.IO.Path.GetFileNameWithoutExtension(fullFileName));
                }
                foreach (string nestedDirectory in System.IO.Directory.GetDirectories(directoryPath))
                {
                    SearchDocuments(nestedDirectory);
                }
            }
            catch (System.Exception error)
            {
                //Do whatever u want on exception
            }
        }
    

    Btw. think over if you have reason to use static functions.