Hello XPS World - 第 2 部分





5.00/5 (2投票s)
好吧,总得有人做。
目录
引言
在本系列的第一篇文章中,我提到了我在寻找好的 XPS 生成源时遇到的问题 - 但我只在那篇文章中介绍了 XPS 结构。所以最后,这里是一个生成 XPS 文档的小例子,重点是使用 .NET Framework 中的 API。
背景
这篇文章来的有点晚,尤其是考虑到它有多短。尽管它是一个“Hello World”应用程序,但它并非完全无用。我希望它能提供一些好的指导。
在这一点上,我绝对应该感谢 Bob Watson 的文章:"XPS Documents: A First Look at APIs For Creating XML Paper Specification Documents"; 本项目中的大部分代码都是抄袭自他的文章。
Using the Code
这又是一个简单的控制台应用程序。执行后,它会创建文档 "HelloWorld.xps"。它也做了一些假设,例如,它可以在 C:\Windows\Fonts 位置找到 arial.ttf 字体文件。请进行必要的更改以使其正常工作。
首先,你需要什么才能访问 XPS API?为此,添加对 ReachFramework.dll 的引用。但是,它实际上需要引用 WindowsBase.dll 才能进行 zip 文件工作。换句话说,你需要同时引用这两个 DLL。在你的代码中,你还需要为 System.Windows.Xps.Packaging
添加一个 using
语句。
所以首先,让我们打开一个新的 XPS 文档。这是一个例子
#region The setup - Creating all the objects needed
// Create the new document
XpsDocument xd = new XpsDocument("HelloWorld.xps", FileAccess.ReadWrite);
// Create a new FixedDocumentSequence object in the document
IXpsFixedDocumentSequenceWriter xdSW = xd.AddFixedDocumentSequence();
// Ccreate a new FixedDocument object in in the document sequence
IXpsFixedDocumentWriter xdW = xdSW.AddFixedDocument();
// Add a new FixedPage to the FixedDocument
IXpsFixedPageWriter xpW = xdW.AddFixedPage();
// Add a Font to the FixedPage and get back where it ended up
string fontURI = AddFontResourceToFixedPage(xpW, "C:\\Windows\\Fonts\\Arial.ttf");
StringBuilder pageContents = new StringBuilder();
#endregion
你可以清楚地看到上面命令中 XPS 文档的层次结构。文档 -> 固定文档序列 -> 固定文档 -> 固定页。记住这个层次结构,在操作 XPS 文档时会更容易。
接下来是创建实际的 XPS 本身。对于这部分,我只是将 XPS 构建为一个字符串。但是,你也可以采用 XAML 并将其展平;有关此示例,请参阅上面 Bob 的文章参考。当然,另一种方法是生成 XPS (XML),并且有很多方法可以做到这一点。
#region The actual XPS markup
// Try changing the Width and Height and see what you get
pageContents.AppendLine("<FixedPage Width=\"793.76\" Height=\"1122.56\"
xmlns=\"http://schemas.microsoft.com/xps/2005/06\" xml:lang=\"und\">");
pageContents.AppendLine("<Glyphs Fill=\"#ff000000\" FontRenderingEmSize=\"16\"
StyleSimulations=\"None\" OriginX=\"75.68\" OriginY=\"90.56\"");
// Add the fontURI
pageContents.AppendFormat(" FontUri=\"{0}\" ", fontURI);
// HERE IT IS
pageContents.AppendLine(" UnicodeString=\"Hello XPS World!\"/>");
pageContents.AppendLine("</FixedPage>");
#endregion
这是我能得到的最简短的 XPS 文档。为了使事情更简单,我没有理会 Indices
属性。你会注意到 fontURI
来自上一节中函数调用的返回值。
最后一部分是完成所有对象;通过让他们提交,我们确保 zip 文件中的各种元素都已正确完成。
#region The shutdown - Commiting all of the objects
// Write the XPS markup out to the page
XmlWriter xmlWriter = xpW.XmlWriter;
xmlWriter.WriteRaw(pageContents.ToString());
// Commit the page
xpW.Commit();
// Close the XML writer
xmlWriter.Close();
// Commit the fixed document
xdW.Commit();
// Commite the fixed document sequence writer
xdSW.Commit();
// Commit the XPS document itself
xd.Close();
#endregion
就是这样。正如评论中建议的那样,尝试使用一些实际的 XPS 标记,看看它会生成什么。你可能会发现你需要每次运行之间删除 XPS(尤其是当出现问题时)。尝试添加更多资源、页面和文档;另外,尝试混淆字体文件,看看你会得到什么。但为此,你需要实际查看代码才能知道该怎么做。
其他部分
历史
- 2008-09-03:第一个版本完成。