我需要从 wpf 窗口构建 pdf 文件。该窗口包含一个带有一些绘图的画布以及一些带有数据的文本框和标签。
一位朋友告诉我使用水晶报表,但对我来说似乎不是一个好的解决方案......
我想在画布上打印图像并用文本框和标签的数据写入一些行。
我需要一个非付费解决方案。
我该怎么做 ?
我使用名为 iTextSharp 的免费工具找到了解决此问题的方法(EDIT:iTextSharp 不能免费用于商业用途 - 对于错误信息深表歉意)。实际上,我需要将 WPF FixDocument 转换为 PDF,因此这与您想要做的略有不同,但也许它也可以帮助您。基本上,该方法是获取 WPF 固定文档(这实际上是 XPS 格式)并将其转换为位图图像。然后使用 iTextSharp 的 PdfWriter 类将该图像作为页面添加到 PDF 文档中。我尝试了其他几种方法,包括名为 gxps 的免费实用程序,但这种方法最适合我。
这是我的代码中的一个示例。
using iTextSharp.text;
using iTextSharp.text.pdf;
.
.
.
// create an iTextSharp document
Document doc = new Document(PageSize.LETTER, 0f, 0f, 0f, 0f);
PdfWriter.GetInstance(doc, new FileStream("C:\\myFile.pdf", FileMode.Create));
doc.Open();
// cycle through each page of the WPF FixedDocument
DocumentPaginator paginator = myFixedDocument.DocumentPaginator;
for (int i = 0; i < paginator.PageCount; i++)
{
// render the fixed document to a WPF Visual object
Visual visual = paginator.GetPage(i).Visual;
// create a temporary file for the bitmap image
string targetFile = Path.GetTempFileName();
// convert XPS file to an image
using (FileStream outStream = new FileStream(targetFile, FileMode.Create))
{
PngBitmapEncoder enc = new PngBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(CreateBitmapFromVisual(visual, 300, 300)));
enc.Save(outStream);
}
// add the image to the iTextSharp PDF document
using (FileStream fs = new FileStream(targetFile, FileMode.Open))
{
iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fs), System.Drawing.Imaging.ImageFormat.Png);
png.ScalePercent(24f);
doc.Add(png);
}
}
doc.Close();
以下是在 C# 中创建固定文档的方法:
using System.Windows.Documents;
using System.Windows.Documents.Serialization;
using System.Windows.Markup;
// create an instance of your XAML object (Window or UserControl)
var yourXAMLObj = new YourXAMLObject();
// create a FixedDocument and add a page of your XAML object
var fixedDocument = new FixedDocument();
fixedDocument.DocumentPaginator.PageSize = new Size(96 * 8.5, 96 * 11);
PageContent pageContent = new PageContent();
FixedPage fixedPage = new FixedPage();
fixedPage.Children.Add(yourXAMLObj);
fixedDocument.Pages.Add(pageContent);
((IAddChild)pageContent).AddChild(fixedPage);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)