Using Spark to render pdfs

222 views
Skip to first unread message

Bill Barry

unread,
Mar 24, 2009, 8:33:45 PM3/24/09
to spar...@googlegroups.com
I was toying with Spark today and I realized that I could generate pdfs
if I used Spark to render xml that iTextSharp can take in. So I wrote
this method:

public static void Generate<T>(Stream outputStream, string view,
T Data) {
var viewFolder = new InMemoryViewFolder {{"\\document", view}};
var engine = new SparkViewEngine {
DefaultPageBaseType =
string.Format("Spark.Reporting.SparkView<{0}>", typeof (T).FullName),
ViewFolder = viewFolder.Append(new
SubViewFolder(viewFolder, "Shared"))
};
var sparkView = (SparkView<T>) engine.CreateInstance(new
SparkViewDescriptor().AddTemplate("\\document"));
sparkView.Data = Data;
var iTextDocument = new MemoryStream();
using (var writer = new StreamWriter(iTextDocument,
Encoding.UTF8)) {
sparkView.RenderView(writer);
writer.Flush();
iTextDocument.Position = 0;
var document = new Document();
document.Open();
var pdfwriter = PdfWriter.GetInstance(document,
outputStream);
var handler = new ITextHandler(document);
var reader = new XmlTextReader(iTextDocument);
handler.Parse(reader);
pdfwriter.Close();
}
}

I was wondering if anybody would have some pointers on making this
better. Does it compile the view every time right now (generating a new
type, eventually perhaps becoming a significant memory leak)?

Usage is something like this:

class Program {
static void Main(string[] args) {
var stream = new FileStream("example.pdf", FileMode.Create);
var data = new ExampleModel {
items = new[] {
"here is one item",
"here is another",
"and another"
}
};
ReportGenerator.Generate(stream, view, data);
}

const string view = @"
<itext creationdate=""3/24/2009 5:49:07 PM"" producer=""Spark.Reporting"">
<paragraph leading=""18.0"" font=""unknown"" align=""Default""
each=""var item in Model.items"">
${item}
<Chunk
once=""test"">${System.DateTime.Now.ToShortDateString()}</Chunk>
</paragraph>
</itext>
";
}

public class ExampleModel {
public string[] items;
}

Tim Schmidt

unread,
Mar 24, 2009, 8:37:28 PM3/24/09
to spar...@googlegroups.com
Wow, that's pretty cool!

Louis DeJardin

unread,
Mar 25, 2009, 12:23:27 AM3/25/09
to spar...@googlegroups.com
Very nice! That would be a great feature to have. Based on your
example I think I'd like to add a PdfViewResult type of ActionResult.

Dynamically loaded assemblies probably won't ever unload from the app
domain. That's not a problem from a utility app that executes and
terminates, but if it's in a web host you'll want to use the existing
views folder instead of a string argument.
Reply all
Reply to author
Forward
0 new messages