Click here to Skip to main content
11,813,974 members (51,959 online)
Click here to Skip to main content

PDF creation using C# (and Office) from RTF/DOC files

, 25 Feb 2004 310.2K 16K 112
Rate this:
Please Sign up or sign in to vote.
Converts RTF, DOC to PDF; sample is a part of a big Project that converts nearly everything, parts can be used to convert html, bmp ,Lotus 1-2-3 documents...


Some time ago I had to write a C# application that was able to convert documents into various formats. The hardest part was to find a way to create PDF files without the use of any third party products. Here is a solution.


The source you see is out of a larger conversion-application. It is a "stand alone" projects, for educational use and describes a possible way of converting documents. I took me a lot of work to figure this out, so please don't copy the code; drop me a line if you wish to use a part of it. My comments are written in German, I had no time to build a proper release, sorry for that.

Using the code

The code listed below describes the main part of the program. I will give you a brief look, at the idea behind. Crystal reports (the .NET reporting system) is able to create PDF files. The only problem is it can only create PDF files out of a database. It requires an ole objects in the Database. But if you have a (very) close look at CR (IDA Smile | :) ) you will find out that it is able to process, bmp, emf, and wmf. So we only have to insert this kind of data in to a table (as blob) and hand it over to CR. Emf can be created by using PowerPoint, PPT can read html, WinWord can create html. The only problem left is the organization of our pages, we have to split the document manually, I did this by using a Richtextbox.

Now that we know the Way we can convert a rtf into a PDF:

  1. We load the rtf into a richtextbox.
  2. We split in into parts. every part is loaded into WinWord, saved as html, the WinWord header is being destroyed, the html page is loaded into PowerPoint and saved as emf. The emf file is written into a Access database as a blob object.
  3. Crystal Reports gets a rpt "template" the database the report is being created and saved as PDF.

I tried to use Ole32 functions, but I didn't find a way to accomplish this, if you know a way in C#.NET please let me know.

private static void DoRTF2ALL(
   CrystalDecisions.Shared.ExportFormatType outTp)
   int lastsplit = 0;
   int nextsplit = 0;
   int pageheight= 650;  //"Länge" unserer Seite
   int pcount= 1;
   Point xx;
   object Unknown =Type.Missing;
   Word.Application newApp;
   PowerPoint.Application  app;
   PowerPoint.Presentation ppp;
   string[] TempEnt;

   RichTextBox rtf = new RichTextBox();
   rtf.Height=25000;// nur page size required
   rtf.Width=4048;// Solle reichen
   rtf.LoadFile(scrfile, RichTextBoxStreamType.RichText);
   nCoreHlp.EmptyDB(WorkDir + "\\" + Database);
   while ((lastsplit+1)<rtf.Text.Length) ////start page split

     // die ersten paar seiten wegschneiden
     rtf.SelectionStart = 0;
     rtf.SelectionLength =lastsplit;
     for (int r=0;r<=rtf.Text.Length;r++) ////parse through whole text
       xx = rtf.GetPositionFromCharIndex(r);
       nextsplit = rtf.Text.Length;
       if (int.Parse(xx.Y.ToString()) > pageheight)

     lastsplit=lastsplit+nextsplit;// ende wegschneiden
     rtf.SelectionStart = nextsplit;
     rtf.SelectionLength =rtf.Text.Length-nextsplit;
     rtf.SaveFile(WorkDir + \\temp.rtf,
     //////////////////////////////////////////// insert db
     newApp = new Word.Application();
     newApp.Visible = false;

     object Source=WorkDir + "\\temp.rtf";
     object Target=WorkDir + "\\temp.html";

     newApp.Documents.Open(ref Source,ref Unknown,
       ref Unknown,ref Unknown,ref Unknown,
       ref Unknown,ref Unknown,ref Unknown,
       ref Unknown,ref Unknown,ref Unknown,
       ref Unknown,ref Unknown,ref Unknown,ref Unknown);

     object format = Word.WdSaveFormat.wdFormatHTML;// kein XML, nutzen?
     newApp.ActiveDocument.SaveAs(ref Target,ref format,
       ref Unknown,ref Unknown,ref Unknown,
       ref Unknown,ref Unknown,ref Unknown,
       ref Unknown,ref Unknown,ref Unknown,
       ref Unknown,ref Unknown,ref Unknown,
       ref Unknown,ref Unknown);
     newApp.Quit(ref Unknown,ref Unknown,ref Unknown);

     //kill word head
     StreamReader sr;
     bool not=true;
     while (not)

         sr = new StreamReader(WorkDir + "\\temp.html");
         StreamWriter sw = new StreamWriter(WorkDir + "\\temp.txt");
         String line;

         while ((line = sr.ReadLine()) != null)
           if (line.CompareTo(
             "<meta name=ProgId content=FrontPage.Editor.Document>")!=0)
             sw.WriteLine(line); else
             //line.Replace //Marina
             sw.WriteLine("<meta name=ProgId content=Word.Documens>");


       catch (Exception e){e=e;}
     }// kill word head end

     File.Delete(WorkDir + "\\temp.html");
     File.Move(WorkDir + "\\temp.txt", WorkDir + "\\temp.html");
     //File.Delete(WorkDir + "\\temp.txt");        

     app = new PowerPoint.Application();
     ppp = app.Presentations.Open(WorkDir + "\\temp.html",
       Microsoft.Office.Core.MsoTriState.msoFalse);//visible? immer no
     ppp.SaveAs(WorkDir + "\\temp",

     //output fangen
     TempEnt = Directory.GetFiles(WorkDir + "\\temp\\", "*.emf");
     nCoreHlp.InsertDB1(WorkDir + "\\" + Database,TempEnt[0],pcount);
     Console.WriteLine("1 Page Converted");// debug
     ////////////////////////////////////////////////// insert db off
     rtf.LoadFile(scrfile, RichTextBoxStreamType.RichText);

   }//////////// page split done
   ///Create PDF
   ReportDocument doc = new ReportDocument();

   doc.Load(WorkDir + "\\DtoD.rpt");
   doc.Database.Tables[0].Location = (WorkDir + "\\DtoD.mdb");

   doc.ExportOptions.ExportFormatType = outTp;
   doc.ExportOptions.ExportDestinationType =
   DiskFileDestinationOptions diskOpts = new DiskFileDestinationOptions();
   diskOpts.DiskFileName = dstfile;
   doc.ExportOptions.DestinationOptions = diskOpts;
   Directory.Delete(WorkDir + "\\temp\\", true);
   File.Delete(WorkDir + "\\temp.rtf");
   File.Delete(WorkDir + "\\temp.html");

Points of Interest

MS-Office 2000 or < has to be installed. I included the Word & PowerPoint interfaces in the project , the C# dlls are only in the bin/debug directory, because of the file size.


  • 1st version of the demo project.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

No Biography provided

You may also be interested in...

Comments and Discussions

QuestionConverting the ppt file to html file in c# Pin
JeffreyTharawad13-Jun-12 2:21
memberJeffreyTharawad13-Jun-12 2:21 
AnswerRe: Converting the ppt file to html file in c# Pin
JeffreyTharawad13-Jun-12 19:38
memberJeffreyTharawad13-Jun-12 19:38 
Questionhelp Pin
Muhammad Riadi14-Jan-12 19:44
memberMuhammad Riadi14-Jan-12 19:44 
QuestionNeed Code to Convert MS-Word 2003 Document to PDF Pin
Member 782949729-Nov-11 18:03
memberMember 782949729-Nov-11 18:03 
GeneralMy vote of 1 Pin
rutstyle19-Aug-09 20:26
memberrutstyle19-Aug-09 20:26 
Can't work!
GeneralThis stuff won't compile Pin
stapes5-Feb-09 23:22
memberstapes5-Feb-09 23:22 
GeneralSource Code Pin
Jansen20823-Sep-08 4:51
memberJansen20823-Sep-08 4:51 
GeneralRe: Source Code Pin
AhmedSuria10-Oct-08 3:02
memberAhmedSuria10-Oct-08 3:02 
GeneralCool things Pin
ggraham41220-Jun-08 8:52
memberggraham41220-Jun-08 8:52 
GeneralLicense Pin
Aleksei Krassovskikh27-Apr-08 2:22
memberAleksei Krassovskikh27-Apr-08 2:22 
GeneralGive the author an award Pin
rimblock15-Nov-07 7:06
memberrimblock15-Nov-07 7:06 
GeneralGlad that you are impressed with your code but... Pin
hybridguy27-Jul-07 11:52
memberhybridguy27-Jul-07 11:52 
RantRe: Glad that you are impressed with your code but... Pin
ggraham41220-Jun-08 8:34
memberggraham41220-Jun-08 8:34 
GeneralMessage Automatically Removed Pin
8-Jul-07 10:05
memberwinnovative8-Jul-07 10:05 
Generaldoc conversion Pin
janeeta30-Mar-07 21:09
memberjaneeta30-Mar-07 21:09 
GeneralBad Pin
[V]GreyWolf15-Feb-07 4:44
member[V]GreyWolf15-Feb-07 4:44 
GeneralConversion for pdf,word Doc, and ppt Pin
Mohdfaiz4-Feb-07 21:52
memberMohdfaiz4-Feb-07 21:52 
GeneralError in ReportDocument.Export Pin
Marcos Almeida29-Sep-06 11:34
memberMarcos Almeida29-Sep-06 11:34 
GeneralRe: Error in ReportDocument.Export Pin
Zevsky24-Jun-07 20:54
memberZevsky24-Jun-07 20:54 
GeneralWord to PDF creater Pin
Rajput Jitendra8-May-06 21:42
memberRajput Jitendra8-May-06 21:42 
GeneralRe: Word to PDF creater Pin
awen_k1-Sep-08 5:02
memberawen_k1-Sep-08 5:02 
Questionhow to create DtoD.rpt Pin
sridhar chatla13-Apr-06 6:08
membersridhar chatla13-Apr-06 6:08 
Generalerror Pin
sewedy3-Mar-06 14:51
membersewedy3-Mar-06 14:51 
GeneralRe: error Pin
Doan Quang Minh16-Jan-07 20:17
memberDoan Quang Minh16-Jan-07 20:17 
GeneralDemo Code Pin
Davey P13-Jan-06 5:31
memberDavey P13-Jan-06 5:31 
QuestionI would like to use a part of your implementation Pin
bigb_60215-Nov-05 15:52
memberbigb_60215-Nov-05 15:52 
Generalbmp to pdf conversion Pin
leojose26-May-05 20:24
memberleojose26-May-05 20:24 
GeneralRe: bmp to pdf conversion Pin
Refre07725-Oct-05 3:13
memberRefre07725-Oct-05 3:13 
GeneralBugs Pin
Zu Luong29-Apr-05 8:28
memberZu Luong29-Apr-05 8:28 
Question3rd party products? Pin
Kapslok27-Jun-04 23:41
memberKapslok27-Jun-04 23:41 
AnswerRe: 3rd party products? Pin
Ryan Beesley6-Mar-05 21:38
memberRyan Beesley6-Mar-05 21:38 
GeneralDon't know what to say... Pin
Oha Ooh5-Mar-04 2:10
memberOha Ooh5-Mar-04 2:10 
GeneralRe: Don't know what to say... Pin
travisowens@hotmail.com6-Sep-05 5:58
membertravisowens@hotmail.com6-Sep-05 5:58 
GeneralRe: Don't know what to say... Pin
stormhun25-Jun-06 23:44
memberstormhun25-Jun-06 23:44 
GeneralRe: Don't know what to say... Pin
Heeut4-May-14 23:54
memberHeeut4-May-14 23:54 
Generalpdf creation with graphics on html/doc file Pin
prafulla4-Mar-04 23:28
memberprafulla4-Mar-04 23:28 
GeneralRe: pdf creation with graphics on html/doc file Pin
Tugs22429-Jul-04 21:39
memberTugs22429-Jul-04 21:39 
GeneralAdditional info Pin
MREBI26-Feb-04 11:02
memberMREBI26-Feb-04 11:02 
GeneralRe: Additional info Pin
Links2348-Mar-04 2:43
memberLinks2348-Mar-04 2:43 
GeneralRe: Additional info Pin
saber378866124-Aug-04 20:58
membersaber378866124-Aug-04 20:58 
GeneralRe: Additional info Pin
Dr. Federico De Martino24-Oct-06 1:13
memberDr. Federico De Martino24-Oct-06 1:13 
GeneralRe: Additional info Pin
kant772-Jul-07 19:18
memberkant772-Jul-07 19:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.151002.1 | Last Updated 26 Feb 2004
Article Copyright 2004 by Stefan Eberhardt
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid