Wednesday, December 15, 2010

Conversion of a RTF document to PDF with C#

In my current project, I need to convert in an easy way RTF documents to PDF from managed code. I don't want to rebuild these documents in PDF, because the RTF's still have some need in the application.

After google-ing around for possible solutions, I tried two components: the last version of iTextSharp with RTF support (from version five on, the RTF support is split into a new project and removed from iTextSharp) and Aspose.Words.

After a quick conversion with iTextSharp, I understand why RTF support was dropped. The produced PDF was one piece of garbage. The code I used was:

using (FileStream outstream = File.Create(outFile))
{
Document docText = new Document();
PdfWriter writer = PdfWriter.GetInstance(docText, outstream);
docText.Open();
RtfParser rtf = new RtfParser(null);
using (FileStream rtfStream = File.OpenRead(inFile))
{
rtf.ConvertRtfDocument(rtfStream, docText);
}
docText.Close();
}


Aspose.Words worked like a charm, while using only two lines of code:

Aspose.Words.Document doc = new Aspose.Words.Document(inFile);
doc.Save(outFile, SaveFormat.Pdf);

The only drawback is iTextSharp is OpenSource and Aspose.Words isn't. But I guess there isn't another reliable OS alternative.

Share