Word-> pdf

Source: Internet
Author: User

Download saveaspdf.exe and install To programmatically save a Word 2007 document to either the PDF format or the XPS format
  1. Add a reference to the Word 12.0 Object Library.

  2. Import the Word 2007 interop assembly namespace.

  3. Create an instance ofApplicationClassObject.

  4. Declare the appropriate variables

  5. Implement the conversion code.

1. Add a Reference to the Word 12.0 Object Library

First, add a reference to the Microsoft Word 12.0 Object Library to the Visual Studio project. To do this, right-click the project inVisual Studio Solution ExplorerAnd selectAdd Reference...Menu item. SelectCOMTab inAdd ReferenceDialog box, then scroll down toMicrosoft Word 12.0 Object LibraryComponent, select it, and then clickOKTo add the reference.

Figure 1. Adding a Reference

2. Import the Word Interop Namespace

Next, importMicrosoft. Office. Interop. WordNamespace. this allows objects that are defined in that namespace to be referred to without having to specify the fully qualified namespace path. to import the namespace, add the following line to the top of the source file.

VBC # C ++ F # JScriptCopy
using Microsoft.Office.Interop.Word;

For Microsoft Visual Basic projects, you can also import the namespace by right-clicking the project inVisual Studio Solution ExplorerAnd selectingPropertiesMenu item. On the project properties page, selectReferencesTab and then select the check box next toMicrosoft. Office. Interop. WordEntry in the list of imported namespaces.

3. Create an Instance of the Word ApplicationClass Object

To work with the Word 2007 object model, create an instance of the Word 2007 top-levelApplicationClassObject and declare a variable to hold the reference to the document.

VBC # C ++ F # JScriptCopy
ApplicationClass wordApplication = new ApplicationClass();Document wordDocument = null;

4. Declare Appropriate Variables

The following code blocks declare variables that help to make the parameters that are passed to methods used in the conversion code easier to read. The following variables are used withDocuments. OpenMethod andApplicationClass. QuitMethod.

UseparamSourceDocPathVariable to specify the path and filename of the Word 2007 document that is to be exported to either the PDF format or the XPS format.

UseparamMissingVariable when calling methods that accept optional parameters. Optional parameters are only optional when you use Microsoft Visual Basic. You must specify a value for optional parameters when you use Microsoft Visual C #. UsingType. MissingAs the value for an optional parameter indicates that the parameter is not specified and that the method should use the parameter's default value.

VBC # C ++ F # JScriptCopy
object paramSourceDocPath = @"C:\Temp\Test.docx";object paramMissing = Type.Missing;

The following variables are used withDocument. ExportAsFixedFormatMethod.paramExportFormat Variable is important because it is used to specify the format in which to export the document.paramExportFormat Variable is ofWdExportFormatType. It is an enumerated type which has two values,WdExportFormatXPSAndWdExportFormatPDF. The following sample code setsparamExportFormat Variable toWdExportFormat. wdExportFormatXPSValue to export a document to the XPS format. To change the code to export a document in the PDF format, set the variable toWdExportFormat. wdExportFormatPDFValue. For more information onExportAsFixedFormatMethod and the parameters that it accepts, seeDocment. ExportAsFixedFormat.

VBC # C ++ F # JScriptCopy
string paramExportFilePath = @"C:\Temp\Test.xps";WdExportFormat paramExportFormat = WdExportFormat.wdExportFormatXPS;bool paramOpenAfterExport = false;WdExportOptimizeFor paramExportOptimizeFor =    WdExportOptimizeFor.wdExportOptimizeForPrint;WdExportRange paramExportRange = WdExportRange.wdExportAllDocument;int paramStartPage = 0;int paramEndPage = 0;WdExportItem paramExportItem = WdExportItem.wdExportDocumentContent;bool paramIncludeDocProps = true;bool paramKeepIRM = true;WdExportCreateBookmarks paramCreateBookmarks =     WdExportCreateBookmarks.wdExportCreateWordBookmarks;bool paramDocStructureTags = true;bool paramBitmapMissingFonts = true;bool paramUseISO19005_1 = false;

5. Implement the Conversion Code

Next add code that opens the source document, exports it to the specified format, and exits Word 2007. Making the call toDocument. ExportAsFixedFormatMethod throws an exception if the add-in for the format is not currently installed. To handle this situation, the conversion code is wrapped inTry... CatchBlock. The code that exits Word 2007, which allows it to unload from memory, is located inFinallyBlock. the shutdown-related code closes the Word 2007 document, exits the Word 2007 application, releases references to the underlying Word 2007 COM objects, and makes callto. NET garbage collector. for more information about how to release COM objects when you use managed code, see Chapter 2: Basics of Office Interoperability (Part 2 of 3) from the book Microsoft. NET Development for Microsoft Office.

VBC # C ++ F # JScriptCopy
try{    // Open the source document.    wordDocument = wordApplication.Documents.Open(        ref paramSourceDocPath, ref paramMissing, ref paramMissing,        ref paramMissing, ref paramMissing, ref paramMissing,        ref paramMissing, ref paramMissing, ref paramMissing,        ref paramMissing, ref paramMissing, ref paramMissing,        ref paramMissing, ref paramMissing, ref paramMissing,        ref paramMissing);    // Export it in the specified format.    if (wordDocument != null)        wordDocument.ExportAsFixedFormat(paramExportFilePath,            paramExportFormat, paramOpenAfterExport,             paramExportOptimizeFor, paramExportRange, paramStartPage,            paramEndPage, paramExportItem, paramIncludeDocProps,             paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,             paramBitmapMissingFonts, paramUseISO19005_1,            ref paramMissing);}catch (Exception ex){    // Respond to the error}finally{    // Close and release the Document object.    if (wordDocument != null)    {        wordDocument.Close(ref paramMissing, ref paramMissing,            ref paramMissing);        wordDocument = null;    }    // Quit Word and release the ApplicationClass object.    if (wordApplication != null)    {        wordApplication.Quit(ref paramMissing, ref paramMissing,            ref paramMissing);        wordApplication = null;    }        GC.Collect();    GC.WaitForPendingFinalizers();    GC.Collect();    GC.WaitForPendingFinalizers();}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.