Я нашел решение этой проблемы с помощью бесплатного инструмента iTextSharp ( EDIT : iTextSharp НЕ является бесплатным для коммерческого использования - извините за дезинформацию).На самом деле мне нужно было конвертировать WPF FixedDocument в PDF, так что это немного отличается от того, что вы хотите сделать, но, возможно, это может вам помочь.По сути, подход заключается в том, чтобы взять фиксированный документ WPF (на самом деле это формат XPS) и преобразовать его в растровое изображение.Затем это изображение добавляется в виде страницы в документ PDF с помощью класса iTextSharp PdfWriter.Я попробовал несколько других методов, включая бесплатную утилиту под названием 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);