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/
代码:
using System;
using System.Collections.Generic;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Word = Microsoft.Office.Interop.Word; namespace CGS
{
public class OfficeToXps
{
#region Properties & Constants
private static List<string> wordExtensions = new List<string>
{
".doc",
".docx"
}; private static List<string> excelExtensions = new List<string>
{
".xls",
".xlsx"
}; private static List<string> powerpointExtensions = new List<string>
{
".ppt",
".pptx"
}; #endregion #region Public Methods
public static OfficeToXpsConversionResult ConvertToXps(string sourceFilePath, ref string resultFilePath)
{
var result = new OfficeToXpsConversionResult(ConversionResult.UnexpectedError); // Check to see if it's a valid file
if (!IsValidFilePath(sourceFilePath))
{
result.Result = ConversionResult.InvalidFilePath;
result.ResultText = sourceFilePath;
return result;
} var ext = Path.GetExtension(sourceFilePath).ToLower(); // Check to see if it's in our list of convertable extensions
if (!IsConvertableFilePath(sourceFilePath))
{
result.Result = ConversionResult.InvalidFileExtension;
result.ResultText = ext;
return result;
} // Convert if Word
if (wordExtensions.Contains(ext))
{
return ConvertFromWord(sourceFilePath, ref resultFilePath);
} // Convert if Excel
if (excelExtensions.Contains(ext))
{
return ConvertFromExcel(sourceFilePath, ref resultFilePath);
} // Convert if PowerPoint
if (powerpointExtensions.Contains(ext))
{
return ConvertFromPowerPoint(sourceFilePath, ref resultFilePath);
} return result;
}
#endregion #region Private Methods
public static bool IsValidFilePath(string sourceFilePath)
{
if (string.IsNullOrEmpty(sourceFilePath))
return false; try
{
return File.Exists(sourceFilePath);
}
catch (Exception)
{
} return false;
} public static bool IsConvertableFilePath(string sourceFilePath)
{
var ext = Path.GetExtension(sourceFilePath).ToLower(); return IsConvertableExtension(ext);
}
public static bool IsConvertableExtension(string extension)
{
return wordExtensions.Contains(extension) ||
excelExtensions.Contains(extension) ||
powerpointExtensions.Contains(extension);
} private static string GetTempXpsFilePath()
{
return Path.ChangeExtension(Path.GetTempFileName(), ".xps");
} private static OfficeToXpsConversionResult ConvertFromWord(string sourceFilePath, ref string resultFilePath)
{
object pSourceDocPath = sourceFilePath; string pExportFilePath = string.IsNullOrWhiteSpace(resultFilePath) ? GetTempXpsFilePath() : resultFilePath; try
{
var pExportFormat = Word.WdExportFormat.wdExportFormatXPS;
bool pOpenAfterExport = false;
var pExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen;
var pExportRange = Word.WdExportRange.wdExportAllDocument;
int pStartPage = ;
int pEndPage = ;
var pExportItem = Word.WdExportItem.wdExportDocumentContent;
var pIncludeDocProps = true;
var pKeepIRM = true;
var pCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
var pDocStructureTags = true;
var pBitmapMissingFonts = true;
var pUseISO19005_1 = false; Word.Application wordApplication = null;
Word.Document wordDocument = null; try
{
wordApplication = new Word.Application();
}
catch (Exception exc)
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToInitializeOfficeApp, "Word", exc);
} try
{
try
{
wordDocument = wordApplication.Documents.Open(ref pSourceDocPath);
}
catch (Exception exc)
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile, exc.Message, exc);
} if (wordDocument != null)
{
try
{
wordDocument.ExportAsFixedFormat(
pExportFilePath,
pExportFormat,
pOpenAfterExport,
pExportOptimizeFor,
pExportRange,
pStartPage,
pEndPage,
pExportItem,
pIncludeDocProps,
pKeepIRM,
pCreateBookmarks,
pDocStructureTags,
pBitmapMissingFonts,
pUseISO19005_1
);
}
catch (Exception exc)
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToExportToXps, "Word", exc);
}
}
else
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile);
}
}
finally
{
// Close and release the Document object.
if (wordDocument != null)
{
wordDocument.Close();
wordDocument = null;
} // Quit Word and release the ApplicationClass object.
if (wordApplication != null)
{
wordApplication.Quit();
wordApplication = null;
} GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
catch (Exception exc)
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToAccessOfficeInterop, "Word", exc);
} resultFilePath = pExportFilePath; return new OfficeToXpsConversionResult(ConversionResult.OK, pExportFilePath);
} private static OfficeToXpsConversionResult ConvertFromPowerPoint(string sourceFilePath, ref string resultFilePath)
{
string pSourceDocPath = sourceFilePath; string pExportFilePath = string.IsNullOrWhiteSpace(resultFilePath) ? GetTempXpsFilePath() : resultFilePath; try
{
PowerPoint.Application pptApplication = null;
PowerPoint.Presentation pptPresentation = null; try
{
pptApplication = new PowerPoint.Application();
}
catch (Exception exc)
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToInitializeOfficeApp, "PowerPoint", exc);
} try
{
try
{
pptPresentation = pptApplication.Presentations.Open(pSourceDocPath,
Microsoft.Office.Core.MsoTriState.msoTrue,
Microsoft.Office.Core.MsoTriState.msoTrue,
Microsoft.Office.Core.MsoTriState.msoFalse);
}
catch (Exception exc)
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile, exc.Message, exc);
} if (pptPresentation != null)
{
try
{
pptPresentation.ExportAsFixedFormat(
pExportFilePath,
PowerPoint.PpFixedFormatType.ppFixedFormatTypeXPS,
PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentScreen,
Microsoft.Office.Core.MsoTriState.msoFalse,
PowerPoint.PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,
PowerPoint.PpPrintOutputType.ppPrintOutputSlides,
Microsoft.Office.Core.MsoTriState.msoFalse,
null,
PowerPoint.PpPrintRangeType.ppPrintAll,
string.Empty,
true,
true,
true,
true,
false
);
}
catch (Exception exc)
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToExportToXps, "PowerPoint", exc);
}
}
else
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile);
}
}
finally
{
// Close and release the Document object.
if (pptPresentation != null)
{
pptPresentation.Close();
pptPresentation = null;
} // Quit Word and release the ApplicationClass object.
if (pptApplication != null)
{
pptApplication.Quit();
pptApplication = null;
} GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
catch (Exception exc)
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToAccessOfficeInterop, "PowerPoint", exc);
} resultFilePath = pExportFilePath; return new OfficeToXpsConversionResult(ConversionResult.OK, pExportFilePath);
} private static OfficeToXpsConversionResult ConvertFromExcel(string sourceFilePath, ref string resultFilePath)
{
string pSourceDocPath = sourceFilePath; string pExportFilePath = string.IsNullOrWhiteSpace(resultFilePath) ? GetTempXpsFilePath() : resultFilePath; try
{
var pExportFormat = Excel.XlFixedFormatType.xlTypeXPS;
var pExportQuality = Excel.XlFixedFormatQuality.xlQualityStandard;
var pOpenAfterPublish = false;
var pIncludeDocProps = true;
var pIgnorePrintAreas = true; Excel.Application excelApplication = null;
Excel.Workbook excelWorkbook = null; try
{
excelApplication = new Excel.Application();
}
catch (Exception exc)
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToInitializeOfficeApp, "Excel", exc);
} try
{
try
{
excelWorkbook = excelApplication.Workbooks.Open(pSourceDocPath);
}
catch (Exception exc)
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile, exc.Message, exc);
} if (excelWorkbook != null)
{
try
{
excelWorkbook.ExportAsFixedFormat(
pExportFormat,
pExportFilePath,
pExportQuality,
pIncludeDocProps,
pIgnorePrintAreas, OpenAfterPublish: pOpenAfterPublish
);
}
catch (Exception exc)
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToExportToXps, "Excel", exc);
}
}
else
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile);
}
}
finally
{
// Close and release the Document object.
if (excelWorkbook != null)
{
excelWorkbook.Close();
excelWorkbook = null;
} // Quit Word and release the ApplicationClass object.
if (excelApplication != null)
{
excelApplication.Quit();
excelApplication = null;
} GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
catch (Exception exc)
{
return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToAccessOfficeInterop, "Excel", exc);
} resultFilePath = pExportFilePath; return new OfficeToXpsConversionResult(ConversionResult.OK, pExportFilePath);
}
#endregion
} public class OfficeToXpsConversionResult
{
#region Properties
public ConversionResult Result { get; set; }
public string ResultText { get; set; }
public Exception ResultError { get; set; }
#endregion #region Constructors
public OfficeToXpsConversionResult()
{
Result = ConversionResult.UnexpectedError;
ResultText = string.Empty;
}
public OfficeToXpsConversionResult(ConversionResult result)
: this()
{
Result = result;
}
public OfficeToXpsConversionResult(ConversionResult result, string resultText)
: this(result)
{
ResultText = resultText;
}
public OfficeToXpsConversionResult(ConversionResult result, string resultText, Exception exc)
: this(result, resultText)
{
ResultError = exc;
}
#endregion
} public enum ConversionResult
{
OK = ,
InvalidFilePath = ,
InvalidFileExtension = ,
UnexpectedError = ,
ErrorUnableToInitializeOfficeApp = ,
ErrorUnableToOpenOfficeFile = ,
ErrorUnableToAccessOfficeInterop = ,
ErrorUnableToExportToXps =
}
}
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/
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using oWord = Microsoft.Office.Interop.Word;
using oExcel = Microsoft.Office.Interop.Excel;
using oPpt = Microsoft.Office.Interop.PowerPoint; using Microsoft.Office.Core; namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{ if (this.openFileDialog1.ShowDialog() != DialogResult.OK)
{
return;
}
string strWordFile = openFileDialog1.FileName; PrintWord(strWordFile); } private void button2_Click(object sender, EventArgs e)
{
if (this.openFileDialog1.ShowDialog() != DialogResult.OK)
{
return;
}
string strExcelFile = openFileDialog1.FileName; PrintExcel(strExcelFile);
} private void button3_Click(object sender, EventArgs e)
{
if (this.openFileDialog1.ShowDialog() != DialogResult.OK)
{
return;
}
string strExcelFile = openFileDialog1.FileName; PrintExcel(strExcelFile);
} public void PrintWord(string wordfile)
{
oWord.ApplicationClass word = new oWord.ApplicationClass();
Type wordType = word.GetType(); oWord.Documents docs = word.Documents;
Type docsType = docs.GetType();
object objDocName = wordfile;
oWord.Document doc = (oWord.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { objDocName, true, true }); //可以使用 doc.PrintOut();方法,次方法调用中的参数设置较繁琐,建议使用 Type.InvokeMember 来调用时可以不用将PrintOut的参数设置全,只设置4个主要参数
Type docType = doc.GetType();
object printFileName = wordfile + ".xps";
docType.InvokeMember("PrintOut", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { false, false, oWord.WdPrintOutRange.wdPrintAllDocument, printFileName }); //退出WORD
wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
} public void PrintExcel(string execlfile)
{
oExcel.ApplicationClass eapp = new oExcel.ApplicationClass();
Type eType = eapp.GetType();
oExcel.Workbooks Ewb = eapp.Workbooks;
Type elType = Ewb.GetType();
object objelName = execlfile;
oExcel.Workbook ebook = (oExcel.Workbook)elType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, Ewb, new Object[] { objelName, true, true }); object printFileName = execlfile + ".xps"; Object oMissing = System.Reflection.Missing.Value;
ebook.PrintOut(oMissing, oMissing, oMissing, oMissing, oMissing, true, oMissing, printFileName); eType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, eapp, null);
} }
}
转换过程需要Office组件,请确保项目引用添加了:
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[];
var fixedPage = content.GetPageRoot(false);
var writter = XpsDocument.CreateXpsDocumentWriter(xpsDocumentDest);
writter.Write(fixedPage);
xpsDocumentDest.Close();
xpsDocument.Close();
}
}
}
注意:调用 xpsDocument.GetFixedDocumentSequence() 方法是貌似必须在UI线程才可以,否则会抛出异常;如果你在后台服务分拆XPS,请将你的线程标注为STA
xps 文件操作笔记的更多相关文章
- C# 文件操作笔记
C#中的文件操作 文件操作中的常见类: 静态类 File类:提供很多静态方法,用于移动.复制和删除文件. Directory类:用于移动.复制和删除目录. Path类:用于处理与路径相关的操作. 实例 ...
- python文件操作笔记
一.python中对文件.文件夹操作时经常用到的os模块和shutil模块常用方法. 1.得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd() 2.切换工作目录: os.c ...
- C的文件操作---笔记
打开文件 FILE *fp = fopen(char *filename, char *mode) 关闭文件 fclose(fp) 字符形式读 char ch = fgetc(fp) 字符形式写 ...
- nodejs文件操作笔记
nodejs添加了流的概念,通过流操作文件如行云流水,比早前便利畅快多了. 先来第一个例子,我们建一个stream.js文件,里面内容如下: var fs = require("fs&quo ...
- Py修行路 python基础 (七)文件操作 笔记(随时更改添加)
文件操作流程: 1.打开文件 open() 2.操作文件 read .writeread(n) n对应读指定个数的 2.x中读取的是字节! 3.x中读取的是字符!read 往外读取文件,是以光标位置开 ...
- Linux文件操作 笔记
fstat stat lstat 原型 #include <unistd.h> #include <sys/stat.h> #include <sys/types.h&g ...
- Tornado 文件操作笔记
import tornado.web import tornado.ioloop import tornado.options import tornado.httpserver from torna ...
- C#中基于流的XML文件操作笔记
System.Xml.XmlReader和System.Xml.XmlWriters是两个抽象类,XmlReader提供了对于XML数据的快速,非缓存,只进模式的读取器,XmlWriter表示一个编写 ...
- Python基础—文件操作(Day8)
一.文件操作参数 1.文件路径 1)绝对路径:从根目录开始一级一级查找直到找到文件. f=open('e:\文件操作笔记.txt',encoding='utf-8',mode='r') content ...
随机推荐
- 各种数据库分页sql
1.oracle数据库分页 select * from (select a.*,rownum rc from 表名 where rownum<=endrow) a where a.rc>= ...
- 使用timer控件控制进度条
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using Sy ...
- kafka命令
./kafka-topics.sh --zookeeper ip:port --list ./kafka-topics.sh --create --topic test --zookeeper ip: ...
- Java NIO教程 Buffer
缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存,这块内存中有很多可以存储byte(或int.char等)的小单元.这块内存被包装成NIO Buffer对象,并提供了一组方法,用来方便的访问 ...
- ubuntu初次安装后设置root用户密码
在ubuntu系统下,为了安全起见,在安装过程中,系统屏蔽了用户设置root用户. 设置方法如下: 登录普通用户 打开终端 sudo passwd[sudo] password for [userna ...
- POJ 1113 - Wall 凸包
此题为凸包问题模板题,题目中所给点均为整点,考虑到数据范围问题求norm()时先转换成double了,把norm()那句改成<vector>压栈即可求得凸包. 初次提交被坑得很惨,在GDB ...
- SPI数据传输(库函数方法)
主机端: /********************************* 代码功能:SPI数据传输(主机端) 引脚说明: SS/CS:片选(高电平屏蔽,低电平启用) MOSI :主机送出信号 M ...
- UISearchBar
UISearchBar——方便用户搜索信息 在移动应用程序的世界里,用户对信息获取的速度要求非常高!iOS用户希望他们需要的信息能够迅速地,直观地展现在他们面前 因为UITableView的上下滚动能 ...
- 高频交易[z]
著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处.作者:袁浩瀚链接:https://www.zhihu.com/question/21789812/answer/22178178来源 ...
- db2 进程
DB2 通用数据库进程全接触 Dwaine Snow, DB2 UDB 和 Informix IDS 产品经理, IBM 多伦多实验室 Dwaine Snow 是 DB2 UDB 分区数据库以及查询巡 ...