问题
Background
I am working on a WPF application that I need to implement reporting functionality for, in PDF and RTF formats. The reports are mostly tabular.
The application doesn't have a database. Instead its data is taken from local XML files from which I create View Models which are in turn passed to the UI for presentation to the user. I need to use these View Models for the reports.
Question
What is the best way for me to approach this requirement, so that I can use my existing View Models to produce reports in PDF and RTF formats?
Potentials
I was thinking if this was a web application I could generate a report in HTML and use 3rd party tools to convert it to PDF and RTF. I've done this before, and I know it would work. Unfortunately there's no guarantee that the user will have an internet connection so I have to keep the report generation local.
So I'm wondering about using XAML to define the report template. Is this possible? I see a utility for Xaml FlowDocument or XPS to PDF Converter on CodePlex but this works with FlowDocument, but I don't think this is what I need. The reports I'll be generating are mostly tabular.
回答1:
It turns out this:
Xaml FlowDocument or XPS to PDF Converter
appears to be the solution.
I can specify tables in the FlowDocument and and specify a DataContext to bind my View Models to it, and then I can either convert that to PDF using the in-built functionality, or convert it to RTF with something similar to the following:
// get FlowDocument object
var uri = new Uri("/Documents/SamplePDF.xaml", UriKind.Relative);
FlowDocument doc = App.LoadComponent(uri) as FlowDocument;
// create TextRange representation of the FlowDocument
var content = new TextRange(doc.ContentStart, doc.ContentEnd);
if (content.CanSave(DataFormats.Rtf))
{
using (var stream = new FileStream(@"C:\Path\To\file.rtf", FileMode.OpenOrCreate))
{
// save it
content.Save(stream, DataFormats.Rtf);
}
}
来源:https://stackoverflow.com/questions/17294196/how-to-approach-production-of-pdf-and-rtf-reports-in-a-wpf-application