C#: convert document to PDF

Today I wrote small code to convert the document (.doc, .rtf etc) ionto PDF format using MS Word 12/2007 automation:

using Word = Microsoft.Office.Interop.Word;
private void SaveRTFToPDF(string RTFFileName, string PDFFileName)
			object oMissing = System.Reflection.Missing.Value;
			Object oTrue = true;
			Object oFalse = false;
			object ReadOnly = false;
			object IsVisible = true;
			object RTFFile = RTFFileName;
			object PDFFile = PDFFileName;
			Word._Application oWord = new Word.Application();
			Word._Document oDoc = oWord.Documents.Open(ref RTFFile,
				ref oMissing, ref ReadOnly,
			ref oMissing, ref oMissing,
				ref oMissing, ref oMissing,
				ref oMissing, ref oMissing,
				ref oMissing, ref oMissing,
				ref IsVisible, ref oMissing,
				ref oMissing, ref oMissing,
				ref oMissing);
			object FileFormat = Word.WdSaveFormat.wdFormatPDF;
			object LockComments = false;
			object AddToRecentFiles = true;
			object ReadOnlyRecommended = false;
			object EmbedTrueTypeFonts = false;
			object SaveNativePictureFormat = true;
			object SaveFormsData = true;
			object SaveAsAOCELetter = false;
			object InsertLineBreaks = false;
			object AllowSubstitutions = false;
			object LineEnding = Word.WdLineEndingType.wdCRLF;
			object AddBiDiMarks = false;
			oDoc.SaveAs(ref PDFFile, ref FileFormat, ref LockComments,
				ref oMissing, ref AddToRecentFiles, ref oMissing,
				ref ReadOnlyRecommended, ref EmbedTrueTypeFonts,
				ref SaveNativePictureFormat, ref SaveFormsData,
				ref SaveAsAOCELetter, ref oMissing, ref InsertLineBreaks,
				ref AllowSubstitutions, ref LineEnding, ref AddBiDiMarks);
			oDoc.Close(ref oFalse, ref oMissing, ref oMissing);
			oWord.Quit(ref oMissing, ref oMissing, ref oMissing);

Sample to use:

			SaveRTFToPDF(@"d:\C#\rtf2pdf\rtf\10-052561_1.RTF", @"d:\C#\rtf2pdf\rtf\10-052561_1.pdf");
			SaveRTFToPDF(@"d:\C#\rtf2pdf\rtf\10-052561_2.RTF", @"d:\C#\rtf2pdf\rtf\10-052561_2.pdf");
			SaveRTFToPDF(@"d:\C#\rtf2pdf\rtf\10-072410.RTF", @"d:\C#\rtf2pdf\rtf\10-072410.pdf");
			SaveRTFToPDF(@"d:\C#\rtf2pdf\rtf\10-080976.RTF", @"d:\C#\rtf2pdf\rtf\10-080976.pdf");
			SaveRTFToPDF(@"d:\C#\rtf2pdf\rtf\10-087077.RTF", @"d:\C#\rtf2pdf\rtf\10-087077.pdf");

I tried to convert the rtf into PDF using Crystal Reports. Just to generate the report form on fly from code and print there the RichTextBox.
But unfortunatelly only simple rtf-files exported as PDF in such way because Crystal Reports supports the limited syntax of rtf-format.
For example, header/footer of rtf-files is not converted correctly and images are not saved at all.


Leave a Reply

You must be logged in to post a comment.