Click here to Skip to main content
15,885,216 members
Articles / Programming Languages / C#
Tip/Trick

Converting Document (Word\ Excel\ PowerPoint\ Visio\ text\ XML\ RTF\ CSV etc.) to PDF using MSOffice .NET API

Rate me:
Please Sign up or sign in to vote.
4.67/5 (6 votes)
14 May 2013CPOL2 min read 87.9K   7.1K   33   15
Easy steps for converting Word /Excel /PowerPoint /Visio file to PDF.

Sample Image

Contents

Introduction

Easy steps for converting Word /Excel /PowerPoint /Visio file to PDF. .NET provides an easy MSOffice API for exporting PDF.

System Requirement

  1. Framework 3.5
  2. MS Office 2010
  3. Visual Studio 2010

Solution Overview

Add Library of Microsoft Office (version: 14.0.0.0) by step below:

  1. Right click to References & select ‘Add Reference..’
  2. Sample Image

  3. In .NET tab select library listed below:
    1. Microsoft.Office.Interop.Excel
    2. Microsoft.Office.Interop.PowerPoint
    3. Microsoft.Office.Interop.Visio
    4. Microsoft.Office.Interop.Word
    5. Office

Sample Image

I. Code for Word \ TXT \ XML to PDF conversion

Method Word2Pdf has four steps to convert Word \ TXT \ XML to PDF.

  1. Start Word Application in hidden mode
  2. C#
    //
    // Start MS word application
    //
    Microsoft.Office.Interop.Word.Application msWordDoc = null;
    Microsoft.Office.Interop.Word.Document doc = null;
    
    // C# doesn't have optional arguments so we'll need a dummy value 
    object oMissing = System.Reflection.Missing.Value;
    
    msWordDoc = new Microsoft.Office.Interop.Word.Application
    {
        Visible = false,
        ScreenUpdating = false
    };
  3. Open Document that need to convert.
  4. C#
    //
    //Open Document
    //
    
    doc = msWordDoc.Documents.Open(ref originalDocPath, ref oMissing
          , ref oMissing, ref oMissing, ref oMissing, ref oMissing
          , ref oMissing,ref oMissing, ref oMissing, ref oMissing
          , ref oMissing, ref oMissing,ref oMissing, ref oMissing
          , ref oMissing, ref oMissing);
    ...
  5. Export Document as PDF.
  6. C#
    //
    // save Document as PDF
    //
    if (doc != null)
    {
        doc.Activate();
        // save Document as PDF
        object fileFormat = WdSaveFormat.wdFormatPDF;
        doc.SaveAs(ref pdfPath,
        ref fileFormat, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing);
    }
    else
    {
        Console.WriteLine("Error occured while converting office Word to PDF");
    }
    ...
  7. Release occupied Object.
  8. C#
    //
    //  Quit Word and release the ApplicationClass object
    //
     finally
    {
    // Close and release the Document object.
    if (doc != null)
    {
        object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
        doc.Close(ref saveChanges, ref oMissing, ref oMissing);
        Util.releaseObject(doc);
    }
    // Quit Word and release the ApplicationClass object.
    ((_Application)msWordDoc).Quit(ref oMissing, ref oMissing, ref oMissing);
    Util.releaseObject(msWordDoc);
    msWordDoc = null;
    }
    ...

II. Code for Excel to PDF conversion

Method Excel2Pdf have 4 steps to convert Excel to PDF

  1. Start Excel Application in hidden mode
  2. C#
    //
    // Create COM Objects
    //  
      Microsoft.Office.Interop.Excel.Application excelApplication = null;
      Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
      object unknownType = Type.Missing;
    // Create new instance of Excel
    //open excel application
      excelApplication = new Microsoft.Office.Interop.Excel.Application
      {
        ScreenUpdating = false,
        DisplayAlerts = false
      };
    ...
  3. Open Excel that need to convert.
  4. C#
    //
    //Open Excel \ CSV
    //
    if (excelApplication != null)
        excelWorkbook = excelApplication.Workbooks.Open(originalXlsPath, unknownType, unknownType,
        unknownType, unknownType, unknownType,
        unknownType, unknownType, unknownType,
        unknownType, unknownType, unknownType,
        unknownType, unknownType, unknownType);
    ...
  5. Export Excel as PDF.
  6. C#
    //
    // save Excel as PDF
    //
     
    // Call Excel's native export function (valid in Office 2007 and Office 2010, AFAIK)
    
    excelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF,
        pdfPath,unknownType, unknownType, unknownType, unknownType, unknownType,
        unknownType, unknownType);
    ...
  7. Release Occupied Object.
  8. C#
    //
    //  Quit Excel and release the ApplicationClass object
    //
    
    finally
    {
    // Close the workbook, quit the Excel, and clean up regardless of the results...
        if (excelWorkbook != null)
        excelWorkbook.Close(unknownType, unknownType, unknownType);
        if (excelApplication != null) excelApplication.Quit();
    
        Util.releaseObject(excelWorkbook);
        Util.releaseObject(excelApplication);
    }
    ...

III. Code for PowerPoint to PDF conversion

Method Powerpoint2Pdf have 4 steps to convert PowerPoint to PDF.

  1. Start PowerPoint Application in hidden mode
  2. C#
    //
    // Create COM Objects
    //  
      PowerPoint.Application pptApplication = null;
      PowerPoint.Presentation pptPresentation = null;
    
        object unknownType = Type.Missing;
    
    //start power point 
        pptApplication = new PowerPoint.Application();
    ...
  3. Open PowerPoint that need to convert.
  4. C#
    //
    //open powerpoint document
    //
    pptPresentation = pptApplication.Presentations.Open((string)originalPptPath,
        Microsoft.Office.Core.MsoTriState.msoTrue,Microsoft.Office.Core.MsoTriState.msoTrue,
        Microsoft.Office.Core.MsoTriState.msoFalse);
    
    ...
  5. Export PowerPoint as PDF.
  6. C#
    //
    // save PowerPoint as PDF
    //    
    pptPresentation.ExportAsFixedFormat((string)pdfPath,
        PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF,
        PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentPrint,
        MsoTriState.msoFalse,PowerPoint.PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,
        PowerPoint.PpPrintOutputType.ppPrintOutputSlides,MsoTriState.msoFalse, null,
        PowerPoint.PpPrintRangeType.ppPrintAll, string.Empty,true, true, true,
        true, false, unknownType);
    ...
  7. Release Occupied Object.
  8. C#
    //
    //  Quit PowerPoint and release the ApplicationClass object
    //
    
    finally
    {
        // Close and release the Document object.
        if (pptPresentation != null)
        {
          pptPresentation.Close();
          Util.releaseObject(pptPresentation);
          pptPresentation = null;
        }
        // Quit Word and release the ApplicationClass object.
        pptApplication.Quit();
        Util.releaseObject(pptApplication);
        pptApplication = null;
    }
    ...

IV. Code for Visio to PDF conversion

Method Visio2Pdf have 4 steps to convert Visio to PDF

  1. Start Visio Application in hidden mode
  2. C#
    //
    // Create COM Objects
    //  
        Microsoft.Office.Interop.Visio.ApplicationClass msVisioDoc = null;
        Visio.Document vsdDoc = null;
    //Start application
        msVisioDoc = new Visio.ApplicationClass { Visible = false };
    
    ...
  3. Open Visio that need to convert.
  4. C#
    //
    //Open Visio Document
    //
        vsdDoc = msVisioDoc.Documents.Open(originalVsdPath);
    ...
  5. Export Visio as PDF.
  6. C#
    //
    // Export Visio as PDF
    //
    vsdDoc.ExportAsFixedFormat(Visio.VisFixedFormatTypes.visFixedFormatPDF, pdfPath,
        Visio.VisDocExIntent.visDocExIntentScreen,Visio.VisPrintOutRange.visPrintAll,
        1, vsdDoc.Pages.Count, false, true, true, true, true,System.Reflection.Missing.Value);
    ...
  7. Release occupied Object.
  8. C#
    //
    //  Quit Visio and release the ApplicationClass object
    //
    
    finally
    {
    // Close and release the Document object.
        if (vsdDoc != null)
        {
        vsdDoc.Close();
        Util.releaseObject(vsdDoc);
        }
    
    // Quit Word and release the ApplicationClass object.
        msVisioDoc.Quit();
        Util.releaseObject(msVisioDoc);
    }
    ...

V. Release Object

Method releaseObject have step to release Office COM Object

C#
//
// Create COM Objects
//  
try
{
    System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
    obj = null;
}
catch (Exception exReleaseObject)
{
    obj = null;
    Console.WriteLine("Release of COM Object Fail:"+ exReleaseObject);
}
finally
{
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();
    GC.WaitForPendingFinalizers();
}
...

How to Run Demo Program

  1. Extract "592957/Converter_demo.zip" file, & run "Converter.exe".
  2. New Window will Open, click "Browse" Button.
  3. Image 4

  4. Select Type of File to Convert.
  5. Image 5

  6. Select file & Press "Open".
  7. Image 6

  8. Click "Convert" Button, its will convert input file to PDF & show you Output file of PDF file with Success Message.
  9. Image 7

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) NEC Technology India
India India
Microsoft Certified Professional

Comments and Discussions

 
Questionconverting Excel to pdF with MICROSOFT.interop(password Protected) Pin
Sivachandran R7-Oct-17 4:07
Sivachandran R7-Oct-17 4:07 
QuestionFile in use dialog box apprearing Pin
id8labs26-Sep-17 23:21
id8labs26-Sep-17 23:21 
Questionfile not found ! ms office 2003 Pin
Member 1155636921-Mar-17 16:11
Member 1155636921-Mar-17 16:11 
Questiongreate!! Pin
Member 1155636921-Mar-17 15:00
Member 1155636921-Mar-17 15:00 
QuestionCould it sucess in client pc without office..? Pin
wheep30-May-16 18:45
wheep30-May-16 18:45 
Questionany to png conversion Pin
Member 1229975931-Jan-16 23:31
Member 1229975931-Jan-16 23:31 
QuestionTHANK YOU Pin
Member 119546578-Sep-15 7:26
Member 119546578-Sep-15 7:26 
GeneralThanks a lot Pin
xibeifeijian28-May-15 20:00
xibeifeijian28-May-15 20:00 
QuestionVisio to svg conversion Pin
Member 951780230-Oct-14 19:31
Member 951780230-Oct-14 19:31 
Questionregarding working on web server Pin
checklike14-Jul-14 22:46
checklike14-Jul-14 22:46 
Questionhow to convert word to excel ? can you help Pin
mamujeeb_icss29-Aug-13 2:25
mamujeeb_icss29-Aug-13 2:25 
AnswerRe: how to convert word to excel ? can you help Pin
Member 1233320917-Feb-16 0:08
Member 1233320917-Feb-16 0:08 
QuestionFile not found exception Pin
FILLY862-Jul-13 21:20
FILLY862-Jul-13 21:20 
QuestionAwesome sir Pin
Aravin.it20-Jun-13 9:45
Aravin.it20-Jun-13 9:45 
GeneralMy vote of 4 Pin
Aravin.it20-Jun-13 9:43
Aravin.it20-Jun-13 9:43 
Dear Sir,

Good idea, but these code are not working now a days..

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

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