There are a lot of situations, when program PDF generation is needed (e-commerce product labeling, periodic reports of collected data, company documentation, etc) and, in fact, there is frankly no such thing as a universal approach here. There are different ASP.NET APIs that can solve this task such as
- iTextSharp (free)
- PDFSharp and MigraDoc (free)
- Foxit PDF Generator (paid, starting from 500$ for the basic SDK).
PDFSharp is a semi-low level library for generating portable document format documents and it is not rational to use it as a standalone library. It provides two ways of generating pdf documents: by converting an xml to pdf (so you first create an xml document ) and by directly creating pdf.
XML to PDF
This approach is less flexible, however it provides a way of precise control over any object sizes and grid structure in the document. It is not a great idea to use it, if you don’t exactly see where it can ease your life and what are its exact advantages over the next methods.
This way is way much easier to use as it is based on step by step writing to your document page. Here is a simple “Hello world” pdf. You create a document, add a new page, write “Hello world” string to the page with the XGraphics class method DrawString.
There is a problem with writing formatted text using DrawString method though, that is why if you want to write a large string with e.g tabulation and linebreaks, you shoud use the XTextFormatter class:
There is also a variety of similar methods to draw images, geometrical objects etc, that require object position coordinates and size parameters:
The complete reference with all API features can be found here in the PDFSharp section.
MigraDoc is a separate library that provides a lot of useful things:
- Drawing dynamic tables
- Making documents with navigation (hyperlinks or bookmarks)
- Various output formats (PDF, Word, HTML, any printer supported by Windows)
- Extended text and layout formatting options
As it uses PDFSharp itself, you can mix PDFSharp and MigraDoc and this is the best choice, to my opinion. For example the task of creating dynamic tables with PDFSharp is quite a hard one. Of course, you can build everything “line by line”, writing a lot of extra code for table cell size modification, cell content length adaptation etc, but you don’t really need to because of MigraDoc. Here is a code sample, which shows how exactly you can mix these two libraries.