This blog is subject the DISCLAIMER below.

Thursday, March 06, 2008

Save As PDF using C#

Welcome guys , this day we will display an esay way to convert files from any format that Microsoft Office open to PDF file format using simple C# code.

Frist of all you should to install 2007 Microsoft Office Add-in: Microsoft Save as PDF (very small about 934 KB) .

Click here to download it from Microsoft site

After you have finished your setup , you should to have new save as option like the picture .

saveasPDF


Secondly : add this two reference to your DotNet project as you see in this picture .

refrences

Then insert the required namespaces in the project ..

Like here :

using System;

using System.Data;

using System.Text;

using System.IO;

using Microsoft.Office.Interop.Word;

finally : here is the class called Doc2PDFAtServerClass , this class have only one static function word2PdfFcih which have two paramters .

this is a example :

object SourceFileName = “Fci-H.doc” ;

object newFileName = “Fci-H.pdf” ;

static public class Doc2PDFAtServerClass

{

static public void word2PdfFcih(object SourceFileName, object newFileName)

{

//Pid++;

Microsoft.Office.Interop.Word.ApplicationClass MSdoc = null;

//object Source = "d:\\Document" + Pid.ToString(System.Globalization.CultureInfo.CurrentCulture) + ".doc";

object Source = SourceFileName;

object readOnly = false;

object Unknown = System.Reflection.Missing.Value; //Type.Missing;

object missing = Type.Missing;

try

{

//Creating the instance of Word Application

if (MSdoc == null)

MSdoc = new Microsoft.Office.Interop.Word.ApplicationClass();

MSdoc.Visible = false;

MSdoc.Documents.Open(ref Source, ref Unknown,

ref readOnly, 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);

MSdoc.Application.Visible = false;

MSdoc.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateMinimize;

object FileName = newFileName;

object FileFormat = WdSaveFormat.wdFormatPDF;

object LockComments = false;

object AddToRecentFiles = false;

object ReadOnlyRecommended = false;

object EmbedTrueTypeFonts = true;

object SaveNativePictureFormat = false;

object SaveFormsData = false;

object SaveAsAOCELetter = false;

//object Encoding = MsoEncoding.msoEncodingUSASCII;

object InsertLineBreaks = false;

object AllowSubstitutions = false;

object LineEnding = WdLineEndingType.wdCRLF;

object AddBiDiMarks = false;

/*

to get more details about SaveAs(...) function and it's parameter ,read this microsoft's link

http://msdn2.microsoft.com/en-us/library/aa662158(office.10).aspx

*/

MSdoc.ActiveDocument.SaveAs(ref FileName, ref FileFormat, ref LockComments,

ref missing, ref AddToRecentFiles, ref missing,

ref ReadOnlyRecommended, ref EmbedTrueTypeFonts,

ref SaveNativePictureFormat, ref SaveFormsData,

ref SaveAsAOCELetter, ref /*Encoding*/missing, ref InsertLineBreaks,

ref AllowSubstitutions, ref LineEnding, ref AddBiDiMarks);

}

catch (FileLoadException e)

{

Console.WriteLine(e.Message + "Error" );

}

catch (FileNotFoundException e)

{

Console.WriteLine(e.Message + "Error");

}

catch (FormatException e)

{

Console.WriteLine(e.Message + "Error");

}

finally

{

if (MSdoc != null)

{

MSdoc.Documents.Close(ref Unknown, ref Unknown, ref Unknown);

//WordDoc.Application.Quit(ref Unknown, ref Unknown, ref Unknown);

}

// for closing the application

// WordDoc.Quit(ref Unknown, ref Unknown, ref Unknown);

MSdoc.Quit(ref Unknown, ref Unknown, ref Unknown);

MSdoc = null;

}

}

}

Have fun ;) ..

9 comments:

Anonymous said...

Thanks for the article.
A small question: don't you know how can we specify the PDF options when saving. These options we can see when manually open Word and selecting "Save As -> PDF or XPS" menu item. Then there is "Options" button with additional options. Specifically I need the "ISO 19005-1 compliant (PDF/A)" option. It seems that when saving PDF programmatically, this option is unchecked. And this causes problems on some documents. Some software (e.g. Ghostscript) cannot operate with such PDF.

Thanks, Constantine

Anonymous said...

Im in the same boat, how would one go about saving in PDF/A in this case. Would it be possible to pass some kind of argument or set some properties throught programming?

Frank

Anonymous said...

I had the same problem, save a document in PDF/A format. So I started the macro recored of word, I saved the document with the PDF/A option and stopped the macro recored. The output was:

Sub Macro1()
'
' Macro1 Macro
'
'
ActiveDocument.ExportAsFixedFormat OutputFileName:= _
"C:\temp\test.pdf", ExportFormat:= _
wdExportFormatPDF, OpenAfterExport:=True, OptimizeFor:= _
wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=True
End Sub

I have VB!!! So the C# version is:

document.ExportAsFixedFormat("C:\temp\test.pdf", WdExportFormat.wdExportFormatPDF, false,
WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 1, 1,
WdExportItem.wdExportDocumentContent, true, true,
WdExportCreateBookmarks.wdExportCreateNoBookmarks, true, true, true, ref missing);

Aquilax

balu said...

its nice article using microsoft office

Anonymous said...

But it is not working in iis server. It is working locally why?

Please mail to me aneesh.malasani@gmai.com

Ahmed Essawy said...

@venkat
it's working with me. check that you have installed the office with that add-on in your server

TONY :D said...

it's work for me!
wonderful!

TONY :D said...
This comment has been removed by the author.
Bhavana said...

I use Aspose.Words for .NET Library for this purpose and its a very good library, offers many code example that i can use in my .net application.