Save a PDF to a byte array using PDF Sharp/MigraDoc

9 03 2010

After looking at my blog stats since putting up my post about combining 2 PDF’s using PDF sharp, I see that a lot of people are coming here when searching for the above. So although it is in my previous post amongst the combining code, I thought I’d post another little code snippet specifically for saving the PDF to a byte array using MigraDoc/PDFSharp.

So the following code assumes I have created a Document object called pdfDoc and formatted it and populated it as required.

byte[] fileContents = null;
using(MemoryStream stream = new MemoryStream())
{
pdfDoc.Save(stream, true);
fileContents = stream.ToArray();
}

So I am saving the PDF document to a memory stream, rather than a physical file location. I can then use the ToArray() function on the memory stream to give me my byte array. I personally then save this to my database as a VARBINARY.

So there you go. A PDF saved as a byte array. Enjoy!





Creating PDF files using C#

12 02 2010

Being able to create PDF files from C# code is something I find incredibly useful. It’s taken me a while to find a good (free!) tool, but I’ve definitely found it. It’s a tool called MigraDoc which also comes with the renderer PDFSharp. They’re both fantastic open source .NET libraries.

The commands and way it works take a little getting used to but it’s all pretty straight forward. They have a Wiki that has loads of code examples which provides great knowledge to learn how to use the tool, but is also great if you get a bit stuck on something. If you can’t find an answer on the Wiki there’s also a forum. There’s lots of answered questions on there which has provided most of my answers to problems and the one time I couldn’t find an answer and posted, I had a reply from one of the developers within the hour.

So enough of the babbling, here’s a link to the site. Go forth and create PDF’s!

http://www.pdfsharp.net/MainPage.ashx

I may even post some code snippets using MigraDoc sometime in the near future.