iTextSharp 从 WPF 固定文档生成 PDF
我有一个简单的 WPF 应用程序,可以显示和打印一些内容 使用固定文档进行报告。
如何使用免费且开放的解决方案从中生成 PDF, 比如iTextSharp?
I have a simple WPF app that displays and prints some
reports with a FixedDocument.
How can generate PDF's from that, with a free and open solution,
such as iTextSharp?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
WPF 固定文档(也称为 XPS 文档)是对 PDF 的明显改进。它具有 PDF 所缺乏的许多功能。在大多数情况下,最好将文档作为 XPS 而不是 PDF 分发,但有时需要从 XPS 转换为 PDF,例如,如果您需要在仅支持 PDF 的设备上打开文档。不幸的是,大多数从 XPS 转换为 PDF 的免费工具(例如 CutePDF 和 BullzipPDF)需要安装打印机驱动程序或者不是开源的。
一个好的开源解决方案是使用 GhostPDL 的“gxps”工具。 GhostPDL 是 Ghostscript 项目的一部分,并在 GPL2 下获得开源许可。
您的代码可能如下所示:
A WPF FixedDocument, also known as an XPS document, is a definite improvement over PDF. It has many capabilities that PDF lacks. In most cases it is better to distribute your document as XPS rather than PDF, but sometimes it is necessary to convert from XPS to PDF, for example if you need to open the document on devices that have only PDF support. Unfortunately most free tools to convert from XPS to PDF, such as CutePDF and BullzipPDF, require installing a printer driver or are not open source.
A good open-source solution is to use the "gxps" tool that is part of GhostPDL. GhostPDL is part of the Ghostscript project and is open-source licensed under GPL2.
Your code might look like this:
一种简单的方法(很容易,但可能不是最有效的方法)是将固定文档渲染为图像,然后使用 iTextSharp 将图像嵌入到 PDF 中。
我以前也是按照这个方法成功完成的。最初,我尝试将控件基元(形状)转换为 PDF 等效项,但事实证明这太难了。
A simple way, which is easy, but probably not the most efficient way is to render the Fixed document to an image and then embed the image in a PDF using iTextSharp.
I have done it this way before successfully. Initially I tried to convert the control primitives (shapes) to PDF equivalents, but this proved too hard.
如果您可以将其从 WPF 中获取到图像中,那么您可以将其导入到 iTextSharp 中,就像本文中所做的那样。如果将文件系统写入 MemoryStream,然后使用它而不是使用 FileStream,您甚至可以完全避免使用文件系统。
http://www.mikesdotnetting.com/Article/87/iTextSharp-处理图像
If you can get it into an image from WPF then you can import it into iTextSharp like they do in this article. You can even avoid the filesystem all together if you write it to a MemoryStream and then use that instead of using a FileStream.
http://www.mikesdotnetting.com/Article/87/iTextSharp-Working-with-images
如果您想以编程方式执行此操作,则最好的选择是以下路径 XPS(固定文档)->打印到 PS ->使用 Ghostscript 读取 PS 并转换为 PDF。
如果您不关心在代码中读回 PDF,则可以打印到任何一台可以传递目标路径的免费 PDF 打印机。这样,如果您的报告中有任何测试,您的目标 PDF 文件仍然可以搜索。
IF you want to do it programatically, your Best bet would be the following path XPS (Fixed Document) -> Print to PS -> Use Ghostscript to read the PS and convert to PDF.
If you dont care about reading the PDF back in the code, you can print to any one of the free PDF printers to which you can pass the destination path. This way your target PDF file will still be searchable if you have any test in your report.