Cri*_*edo 1 pdf wpf visual-studio-2010
我需要从wpf窗口构建一个pdf文件.该窗口包含一个画布,其中包含一些绘图和一些文本框以及带有数据的标签.
一位朋友告诉我使用水晶报告,但似乎对我来说不是一个好的解决方案....
我想在画布上打印图像并写一些带有texbox和标签数据的行.
我需要一个非付费的解决方案.
我该怎么做 ?
我使用名为iTextSharp的免费工具找到了解决这个问题的方法(编辑:iTextSharp不能免费用于商业用途 - 对于错误的信息感到抱歉).实际上,我需要将WPF FixedDocument转换为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();
Run Code Online (Sandbox Code Playgroud)
以下是如何在C#中创建FixedDocument:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6900 次 |
| 最近记录: |