xps 文件操作笔记

1. 在 Silverlight 显示XPS文件,参考:http://azharthegreat.codeplex.com/

2. Word,Excel, PPT 文件转换为XPS:

参考一(老外写的): http://mel-green.com/2010/05/officetoxps-convert-word-excel-and-powerpoint-to-xps/

代码:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.IO;
  4 using Excel = Microsoft.Office.Interop.Excel;
  5 using PowerPoint = Microsoft.Office.Interop.PowerPoint;
  6 using Word = Microsoft.Office.Interop.Word;
  7 
  8 namespace CGS
  9 {
 10     public class OfficeToXps
 11     {
 12         #region Properties & Constants
 13         private static List<string> wordExtensions = new List<string>
 14         {
 15             ".doc",
 16             ".docx"
 17         };
 18 
 19         private static List<string> excelExtensions = new List<string>
 20         {
 21             ".xls",
 22             ".xlsx"
 23         };
 24 
 25         private static List<string> powerpointExtensions = new List<string>
 26         {
 27             ".ppt",
 28             ".pptx"
 29         };
 30 
 31         #endregion
 32 
 33         #region Public Methods
 34         public static OfficeToXpsConversionResult ConvertToXps(string sourceFilePath, ref string resultFilePath)
 35         {
 36             var result = new OfficeToXpsConversionResult(ConversionResult.UnexpectedError);
 37 
 38             // Check to see if it's a valid file
 39             if (!IsValidFilePath(sourceFilePath))
 40             {
 41                 result.Result = ConversionResult.InvalidFilePath;
 42                 result.ResultText = sourceFilePath;
 43                 return result;
 44             }
 45 
 46 
 47 
 48             var ext = Path.GetExtension(sourceFilePath).ToLower();
 49 
 50             // Check to see if it's in our list of convertable extensions
 51             if (!IsConvertableFilePath(sourceFilePath))
 52             {
 53                 result.Result = ConversionResult.InvalidFileExtension;
 54                 result.ResultText = ext;
 55                 return result;
 56             }
 57 
 58             // Convert if Word
 59             if (wordExtensions.Contains(ext))
 60             {
 61                 return ConvertFromWord(sourceFilePath, ref resultFilePath);
 62             }
 63 
 64             // Convert if Excel
 65             if (excelExtensions.Contains(ext))
 66             {
 67                 return ConvertFromExcel(sourceFilePath, ref resultFilePath);
 68             }
 69 
 70             // Convert if PowerPoint
 71             if (powerpointExtensions.Contains(ext))
 72             {
 73                 return ConvertFromPowerPoint(sourceFilePath, ref resultFilePath);
 74             }
 75 
 76             return result;
 77         }
 78         #endregion
 79 
 80         #region Private Methods
 81         public static bool IsValidFilePath(string sourceFilePath)
 82         {
 83             if (string.IsNullOrEmpty(sourceFilePath))
 84                 return false;
 85 
 86             try
 87             {
 88                 return File.Exists(sourceFilePath);
 89             }
 90             catch (Exception)
 91             {
 92             }
 93 
 94             return false;
 95         }
 96 
 97         public static bool IsConvertableFilePath(string sourceFilePath)
 98         {
 99             var ext = Path.GetExtension(sourceFilePath).ToLower();
100 
101             return IsConvertableExtension(ext);
102         }
103         public static bool IsConvertableExtension(string extension)
104         {
105             return wordExtensions.Contains(extension) ||
106                    excelExtensions.Contains(extension) ||
107                    powerpointExtensions.Contains(extension);
108         }
109 
110         private static string GetTempXpsFilePath()
111         {
112             return Path.ChangeExtension(Path.GetTempFileName(), ".xps");
113         }
114 
115 
116         private static OfficeToXpsConversionResult ConvertFromWord(string sourceFilePath, ref string resultFilePath)
117         {
118             object pSourceDocPath = sourceFilePath;
119 
120             string pExportFilePath = string.IsNullOrWhiteSpace(resultFilePath) ? GetTempXpsFilePath() : resultFilePath;
121 
122             try
123             {
124                 var pExportFormat = Word.WdExportFormat.wdExportFormatXPS;
125                 bool pOpenAfterExport = false;
126                 var pExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen;
127                 var pExportRange = Word.WdExportRange.wdExportAllDocument;
128                 int pStartPage = 0;
129                 int pEndPage = 0;
130                 var pExportItem = Word.WdExportItem.wdExportDocumentContent;
131                 var pIncludeDocProps = true;
132                 var pKeepIRM = true;
133                 var pCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
134                 var pDocStructureTags = true;
135                 var pBitmapMissingFonts = true;
136                 var pUseISO19005_1 = false;
137 
138 
139                 Word.Application wordApplication = null;
140                 Word.Document wordDocument = null;
141 
142                 try
143                 {
144                     wordApplication = new Word.Application();
145                 }
146                 catch (Exception exc)
147                 {
148                     return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToInitializeOfficeApp, "Word", exc);
149                 }
150 
151                 try
152                 {
153                     try
154                     {
155                         wordDocument = wordApplication.Documents.Open(ref pSourceDocPath);
156                     }
157                     catch (Exception exc)
158                     {
159                         return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile, exc.Message, exc);
160                     }
161 
162                     if (wordDocument != null)
163                     {
164                         try
165                         {
166                             wordDocument.ExportAsFixedFormat(
167                                                 pExportFilePath,
168                                                 pExportFormat,
169                                                 pOpenAfterExport,
170                                                 pExportOptimizeFor,
171                                                 pExportRange,
172                                                 pStartPage,
173                                                 pEndPage,
174                                                 pExportItem,
175                                                 pIncludeDocProps,
176                                                 pKeepIRM,
177                                                 pCreateBookmarks,
178                                                 pDocStructureTags,
179                                                 pBitmapMissingFonts,
180                                                 pUseISO19005_1
181                                             );
182                         }
183                         catch (Exception exc)
184                         {
185                             return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToExportToXps, "Word", exc);
186                         }
187                     }
188                     else
189                     {
190                         return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile);
191                     }
192                 }
193                 finally
194                 {
195                     // Close and release the Document object.
196                     if (wordDocument != null)
197                     {
198                         wordDocument.Close();
199                         wordDocument = null;
200                     }
201 
202                     // Quit Word and release the ApplicationClass object.
203                     if (wordApplication != null)
204                     {
205                         wordApplication.Quit();
206                         wordApplication = null;
207                     }
208 
209                     GC.Collect();
210                     GC.WaitForPendingFinalizers();
211                     GC.Collect();
212                     GC.WaitForPendingFinalizers();
213                 }
214             }
215             catch (Exception exc)
216             {
217                 return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToAccessOfficeInterop, "Word", exc);
218             }
219 
220             resultFilePath = pExportFilePath;
221 
222             return new OfficeToXpsConversionResult(ConversionResult.OK, pExportFilePath);
223         }
224 
225         private static OfficeToXpsConversionResult ConvertFromPowerPoint(string sourceFilePath, ref string resultFilePath)
226         {
227             string pSourceDocPath = sourceFilePath;
228 
229             string pExportFilePath = string.IsNullOrWhiteSpace(resultFilePath) ? GetTempXpsFilePath() : resultFilePath;
230 
231             try
232             {
233                 PowerPoint.Application pptApplication = null;
234                 PowerPoint.Presentation pptPresentation = null;
235 
236                 try
237                 {
238                     pptApplication = new PowerPoint.Application();
239                 }
240                 catch (Exception exc)
241                 {
242                     return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToInitializeOfficeApp, "PowerPoint", exc);
243                 }
244 
245                 try
246                 {
247                     try
248                     {
249                         pptPresentation = pptApplication.Presentations.Open(pSourceDocPath,
250                                                                             Microsoft.Office.Core.MsoTriState.msoTrue,
251                                                                             Microsoft.Office.Core.MsoTriState.msoTrue,
252                                                                             Microsoft.Office.Core.MsoTriState.msoFalse);
253                     }
254                     catch (Exception exc)
255                     {
256                         return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile, exc.Message, exc);
257                     }
258 
259                     if (pptPresentation != null)
260                     {
261                         try
262                         {
263                             pptPresentation.ExportAsFixedFormat(
264                                                 pExportFilePath,
265                                                 PowerPoint.PpFixedFormatType.ppFixedFormatTypeXPS,
266                                                 PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentScreen,
267                                                 Microsoft.Office.Core.MsoTriState.msoFalse,
268                                                 PowerPoint.PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,
269                                                 PowerPoint.PpPrintOutputType.ppPrintOutputSlides,
270                                                 Microsoft.Office.Core.MsoTriState.msoFalse,
271                                                 null,
272                                                 PowerPoint.PpPrintRangeType.ppPrintAll,
273                                                 string.Empty,
274                                                 true,
275                                                 true,
276                                                 true,
277                                                 true,
278                                                 false
279                                             );
280                         }
281                         catch (Exception exc)
282                         {
283                             return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToExportToXps, "PowerPoint", exc);
284                         }
285                     }
286                     else
287                     {
288                         return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile);
289                     }
290                 }
291                 finally
292                 {
293                     // Close and release the Document object.
294                     if (pptPresentation != null)
295                     {
296                         pptPresentation.Close();
297                         pptPresentation = null;
298                     }
299 
300                     // Quit Word and release the ApplicationClass object.
301                     if (pptApplication != null)
302                     {
303                         pptApplication.Quit();
304                         pptApplication = null;
305                     }
306 
307                     GC.Collect();
308                     GC.WaitForPendingFinalizers();
309                     GC.Collect();
310                     GC.WaitForPendingFinalizers();
311                 }
312             }
313             catch (Exception exc)
314             {
315                 return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToAccessOfficeInterop, "PowerPoint", exc);
316             }
317 
318             resultFilePath = pExportFilePath;
319 
320             return new OfficeToXpsConversionResult(ConversionResult.OK, pExportFilePath);
321         }
322 
323         private static OfficeToXpsConversionResult ConvertFromExcel(string sourceFilePath, ref string resultFilePath)
324         {
325             string pSourceDocPath = sourceFilePath;
326 
327             string pExportFilePath = string.IsNullOrWhiteSpace(resultFilePath) ? GetTempXpsFilePath() : resultFilePath;
328 
329             try
330             {
331                 var pExportFormat = Excel.XlFixedFormatType.xlTypeXPS;
332                 var pExportQuality = Excel.XlFixedFormatQuality.xlQualityStandard;
333                 var pOpenAfterPublish = false;
334                 var pIncludeDocProps = true;
335                 var pIgnorePrintAreas = true;
336 
337 
338                 Excel.Application excelApplication = null;
339                 Excel.Workbook excelWorkbook = null;
340 
341                 try
342                 {
343                     excelApplication = new Excel.Application();
344                 }
345                 catch (Exception exc)
346                 {
347                     return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToInitializeOfficeApp, "Excel", exc);
348                 }
349 
350                 try
351                 {
352                     try
353                     {
354                         excelWorkbook = excelApplication.Workbooks.Open(pSourceDocPath);
355                     }
356                     catch (Exception exc)
357                     {
358                         return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile, exc.Message, exc);
359                     }
360 
361                     if (excelWorkbook != null)
362                     {
363                         try
364                         {
365                             excelWorkbook.ExportAsFixedFormat(
366                                                 pExportFormat,
367                                                 pExportFilePath,
368                                                 pExportQuality,
369                                                 pIncludeDocProps,
370                                                 pIgnorePrintAreas,
371 
372                                                 OpenAfterPublish: pOpenAfterPublish
373                                             );
374                         }
375                         catch (Exception exc)
376                         {
377                             return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToExportToXps, "Excel", exc);
378                         }
379                     }
380                     else
381                     {
382                         return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile);
383                     }
384                 }
385                 finally
386                 {
387                     // Close and release the Document object.
388                     if (excelWorkbook != null)
389                     {
390                         excelWorkbook.Close();
391                         excelWorkbook = null;
392                     }
393 
394                     // Quit Word and release the ApplicationClass object.
395                     if (excelApplication != null)
396                     {
397                         excelApplication.Quit();
398                         excelApplication = null;
399                     }
400 
401                     GC.Collect();
402                     GC.WaitForPendingFinalizers();
403                     GC.Collect();
404                     GC.WaitForPendingFinalizers();
405                 }
406             }
407             catch (Exception exc)
408             {
409                 return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToAccessOfficeInterop, "Excel", exc);
410             }
411 
412             resultFilePath = pExportFilePath;
413 
414             return new OfficeToXpsConversionResult(ConversionResult.OK, pExportFilePath);
415         }
416         #endregion
417     }
418 
419     public class OfficeToXpsConversionResult
420     {
421         #region Properties
422         public ConversionResult Result { get; set; }
423         public string ResultText { get; set; }
424         public Exception ResultError { get; set; }
425         #endregion
426 
427         #region Constructors
428         public OfficeToXpsConversionResult()
429         {
430             Result = ConversionResult.UnexpectedError;
431             ResultText = string.Empty;
432         }
433         public OfficeToXpsConversionResult(ConversionResult result)
434             : this()
435         {
436             Result = result;
437         }
438         public OfficeToXpsConversionResult(ConversionResult result, string resultText)
439             : this(result)
440         {
441             ResultText = resultText;
442         }
443         public OfficeToXpsConversionResult(ConversionResult result, string resultText, Exception exc)
444             : this(result, resultText)
445         {
446             ResultError = exc;
447         }
448         #endregion
449     }
450 
451     public enum ConversionResult
452     {
453         OK = 0,
454         InvalidFilePath = 1,
455         InvalidFileExtension = 2,
456         UnexpectedError = 3,
457         ErrorUnableToInitializeOfficeApp = 4,
458         ErrorUnableToOpenOfficeFile = 5,
459         ErrorUnableToAccessOfficeInterop = 6,
460         ErrorUnableToExportToXps = 7
461     }
462 }
OfficeToXps
            string filePath = @"f:\Test\test2.ppt";
            string xpsFilePath = @"f:\Test\Test2.xps";

            var convertResults = OfficeToXps.ConvertToXps(filePath, ref xpsFilePath);

            switch (convertResults.Result)
            {
                case ConversionResult.OK:
                    XpsDocument xpsDoc = new XpsDocument(xpsFilePath, FileAccess.ReadWrite);
                    break;

                case ConversionResult.InvalidFilePath:
                    // Handle bad file path or file missing
                    break;
                case ConversionResult.UnexpectedError:
                    // This should only happen if the code is modified poorly
                    break;
                case ConversionResult.ErrorUnableToInitializeOfficeApp:
                    // Handle Office 2007 (Word | Excel | PowerPoint) not installed
                    break;
                case ConversionResult.ErrorUnableToOpenOfficeFile:
                    // Handle source file being locked or invalid permissions
                    break;
                case ConversionResult.ErrorUnableToAccessOfficeInterop:
                    // Handle Office 2007 (Word | Excel | PowerPoint) not installed
                    break;
                case ConversionResult.ErrorUnableToExportToXps:
                    // Handle Microsoft Save As PDF or XPS Add-In missing for 2007
                    break;
            }        
Test Case

参考二(原创不详):http://seanli888.blog.51cto.com/345958/112268/

代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 using oWord = Microsoft.Office.Interop.Word;
10 using oExcel = Microsoft.Office.Interop.Excel;
11 using oPpt = Microsoft.Office.Interop.PowerPoint;
12 
13 using Microsoft.Office.Core;
14 
15 namespace WindowsFormsApplication1
16 {
17     public partial class Form1 : Form
18     {
19         public Form1()
20         {
21             InitializeComponent();
22         }
23 
24 
25         private void button1_Click(object sender, EventArgs e)
26         {
27 
28             if (this.openFileDialog1.ShowDialog() != DialogResult.OK)
29             {
30                 return;
31             }
32             string strWordFile = openFileDialog1.FileName;
33 
34             PrintWord(strWordFile);
35 
36         }
37 
38         private void button2_Click(object sender, EventArgs e)
39         {
40             if (this.openFileDialog1.ShowDialog() != DialogResult.OK)
41             {
42                 return;
43             }
44             string strExcelFile = openFileDialog1.FileName;
45 
46             PrintExcel(strExcelFile);
47         }
48 
49         private void button3_Click(object sender, EventArgs e)
50         {
51             if (this.openFileDialog1.ShowDialog() != DialogResult.OK)
52             {
53                 return;
54             }
55             string strExcelFile = openFileDialog1.FileName;
56 
57             PrintExcel(strExcelFile);
58         }
59 
60 
61         public void PrintWord(string wordfile)
62         {
63             oWord.ApplicationClass word = new oWord.ApplicationClass();
64             Type wordType = word.GetType();
65 
66             oWord.Documents docs = word.Documents;
67             Type docsType = docs.GetType();
68             object objDocName = wordfile;
69             oWord.Document doc = (oWord.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { objDocName, true, true });
70 
71             //可以使用 doc.PrintOut();方法,次方法调用中的参数设置较繁琐,建议使用 Type.InvokeMember 来调用时可以不用将PrintOut的参数设置全,只设置4个主要参数 
72             Type docType = doc.GetType();
73             object printFileName = wordfile + ".xps";
74             docType.InvokeMember("PrintOut", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { false, false, oWord.WdPrintOutRange.wdPrintAllDocument, printFileName });
75 
76             //退出WORD 
77             wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
78         }
79 
80         public void PrintExcel(string execlfile)
81         {
82             oExcel.ApplicationClass eapp = new oExcel.ApplicationClass();
83             Type eType = eapp.GetType();
84             oExcel.Workbooks Ewb = eapp.Workbooks;
85             Type elType = Ewb.GetType();
86             object objelName = execlfile;
87             oExcel.Workbook ebook = (oExcel.Workbook)elType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, Ewb, new Object[] { objelName, true, true });
88 
89             object printFileName = execlfile + ".xps";
90 
91             Object oMissing = System.Reflection.Missing.Value;
92             ebook.PrintOut(oMissing, oMissing, oMissing, oMissing, oMissing, true, oMissing, printFileName);
93 
94             eType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, eapp, null);
95         }
96 
97     }
98 }
View Code

转换过程需要Office组件,请确保项目引用添加了:

Microsoft Word 12.0 Object Library
Microsoft PowerPoint 12.0 Object Library
Microsoft Excel 12.0 Object Library
 
如果发生了这个异常:无法嵌入互操作类型“Microsoft.Office.Interop.Excel.ApplicationClass”。请改用适用的接口。
把你引用的Office程序集: 属性 > 嵌入互操作类型 修改为 False 即可;
 
 
代码:
        public void Split(string originalDocument, string detinationDocument)
        {
            using (Package package = Package.Open(originalDocument, FileMode.Open, FileAccess.Read))
            {
                using (Package packageDest = Package.Open(detinationDocument))
                {
                    string inMemoryPackageName = "memorystream://miXps.xps";
                    Uri packageUri = new Uri(inMemoryPackageName);
                    PackageStore.AddPackage(packageUri, package);
                    XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Maximum, inMemoryPackageName);
                    XpsDocument xpsDocumentDest = new XpsDocument(packageDest, CompressionOption.Normal, detinationDocument);
                    var fixedDocumentSequence = xpsDocument.GetFixedDocumentSequence();
                    DocumentReference docReference = xpsDocument.GetFixedDocumentSequence().References.First();
                    FixedDocument doc = docReference.GetDocument(false);
                    var content = doc.Pages[0];
                    var fixedPage = content.GetPageRoot(false);
                    var writter = XpsDocument.CreateXpsDocumentWriter(xpsDocumentDest);
                    writter.Write(fixedPage);
                    xpsDocumentDest.Close();
                    xpsDocument.Close();
                }
            }
        }
View Code

注意:调用 xpsDocument.GetFixedDocumentSequence() 方法是貌似必须在UI线程才可以,否则会抛出异常;如果你在后台服务分拆XPS,请将你的线程标注为STA

 
posted @ 2013-07-04 16:27  北方的河  阅读(882)  评论(0编辑  收藏  举报