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

 

PDFsharp-80x80PDFSharp


 

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.

Direct API

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.

pdf1

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:

pdf5pdf6

There is also a variety of similar methods to draw images, geometrical objects etc, that require object position coordinates and size parameters:

pdf4pdf3pdf2

The complete reference with all API features can be found here in the PDFSharp section.

 

MigraDoc-80x80

MigraDoc


 

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.

Advertisements