Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iTextSharp to generate PDF from WPF FixedDocument

I have a simple WPF app that displays and prints some reports with a FixedDocument.

How can generate PDF's from that, with a free and open solution, such as iTextSharp?

like image 582
leo.Mayer Avatar asked Aug 02 '10 08:08

leo.Mayer


2 Answers

A WPF FixedDocument, also known as an XPS document, is a definite improvement over PDF. It has many capabilities that PDF lacks. In most cases it is better to distribute your document as XPS rather than PDF, but sometimes it is necessary to convert from XPS to PDF, for example if you need to open the document on devices that have only PDF support. Unfortunately most free tools to convert from XPS to PDF, such as CutePDF and BullzipPDF, require installing a printer driver or are not open source.

A good open-source solution is to use the "gxps" tool that is part of GhostPDL. GhostPDL is part of the Ghostscript project and is open-source licensed under GPL2.

  1. Download GhostPDL from http://ghostscript.com/releases/ghostpdl-8.71.tar.bz2 and compile it.
  2. Copy the gxps.exe executable into your project as Content and call it from your code using Process.Start.

Your code might look like this:

string pdfPath = ... // Path to place PDF file

string xpsPath = Path.GetTempPath();
using(XpsDocument doc = new XpsDocument(xpsPath, FileAccess.Write))
  XpsDocument.CreateXpsDocumentWriter(doc).Write(... content ...);

Process.Start("gxps.exe",
              "-sDEVICE=pdfwrite -sOutputFile=" +
                  pdfPath +
                  "-dNOPAUSE " +
                  xpsPath).WaitForExit();

// Now the PDF file is found at pdfPath
like image 81
Ray Burns Avatar answered Sep 19 '22 07:09

Ray Burns


A simple way, which is easy, but probably not the most efficient way is to render the Fixed document to an image and then embed the image in a PDF using iTextSharp.

I have done it this way before successfully. Initially I tried to convert the control primitives (shapes) to PDF equivalents, but this proved too hard.

like image 26
John Mills Avatar answered Sep 19 '22 07:09

John Mills