using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Xps.Packaging;
using Microsoft.Office.Interop.Word;
using Word = Microsoft.Office.Interop.Word;
namespace Core.Mes.Client.Comm.Office
{
///
/// DocumentViewer tool
///
public class DocumentViewerHelper
{
///
/// Convert the word document to xps document
///
/// Word document Path
/// Xps document Path
///
public static XpsDocument ConvertWordToXps(string wordFilename, string xpsFilename)
{
// Create a WordApplication and host word document
Word.Application wordApp = new Word.Application();
try
{
object objMissing = System.Reflection.Missing.Value;
object wordName = wordFilename;
object xpsName = xpsFilename;
wordApp.Documents.Open(ref wordName, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing);
// To Invisible the word document
wordApp.Application.Visible = false;
wordApp.Visible = false;
// Minimize the opened word document
wordApp.WindowState = WdWindowState.wdWindowStateMinimize;
Document doc = wordApp.ActiveDocument;
object saveFormat = Word.WdSaveFormat.wdFormatXPS;
doc.ExportAsFixedFormat(xpsFilename, WdExportFormat.wdExportFormatXPS, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 0, 0, WdExportItem.wdExportDocumentContent, true, true, WdExportCreateBookmarks.wdExportCreateWordBookmarks, true, true, false, ref objMissing);
//doc.SaveAs(ref xpsName, ref saveFormat, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing);
XpsDocument xpsDocument = new XpsDocument(xpsFilename, FileAccess.Read);
return xpsDocument;
}
catch (Exception ex)
{
MessageBox.Show("Error occurs, The error message is " + ex.ToString());
return null;
}
finally
{
object saveOption = WdSaveOptions.wdDoNotSaveChanges;
object originalFormat = WdOriginalFormat.wdWordDocument;
object routeDocument = false;
wordApp.Documents.Close(ref saveOption, ref originalFormat, ref routeDocument);
((_Application)wordApp).Quit(ref saveOption, ref originalFormat, ref routeDocument);
}
}
}
}