> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/core/get-started/samples/officetopdftest.md).

# MS Office to PDF Conversion - OfficeToPDF

Sample code for using Apryse Server SDK to convert Office documents to PDF (including Word, Excel, PowerPoint and Publisher) without needing any external dependencies or MS Office licenses.  Samples p

{% hint style="info" %}
**Requirements**

*These packages are required to use these features in production. Trial keys have unlimited access to all features*

<a href="/core/get-started/get-started.md" class="button primary">Server SDK</a><a href="https://apryse.com/capabilities#OfficeConversion" class="button primary">Package: Office Conversion</a><a href="https://showcase.apryse.com/office-to-pdf" class="button primary">Live demo</a>
{% endhint %}

Sample code for using Apryse Server SDK to convert Office documents to PDF (including Word, Excel, PowerPoint, RTF, MSG, and EML) without needing any external dependencies or MS Office licenses. Office to PDF conversion can be performed on a Linux or Windows server to automate Office-centric workflows, or entirely in the user's client (web browser, mobile device). The conversion functionality can be combined with our Viewer to display or annotate Office files (docx, xlsx, pptx) on all major platforms, including Web, Android, iOS, Xamarin, UWP, and Windows. Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB.

To run this sample, you will need:

1. [Get started with Server SDK](/core/get-started/get-started.md) in your language/framework
2. Add the sample code provided below

To use this feature in production, your license key will need the [Office Conversion Package](https://apryse.com/capabilities#OfficeConversion). Trial keys already include this package.

Most MSG and EML conversions require the [HTML2PDF ](/core/learn-more/modules.md#html2pdf-module)module to be installed. No HTML2PDF license is required for the conversions.

Learn more about our [Server SDK](/core/get-started/get-started.md) and [Office Document Conversion Library](https://apryse.com/products/core-sdk/office).

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
//
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
//

using System;
using System.Drawing;
using System.Drawing.Drawing2D;

using pdftron;
using pdftron.Common;
using pdftron.Filters;
using pdftron.SDF;
using pdftron.PDF;

namespace OfficeToPDFTestCS
{
    /// <summary>
    ///---------------------------------------------------------------------------------------
    /// The following sample illustrates how to use the PDF::Convert utility class to convert 
    /// .docx files to PDF
    ///
    /// This conversion is performed entirely within the PDFNet and has *no* external or
    /// system dependencies dependencies
    ///
    /// Please contact us if you have any questions.    
    ///---------------------------------------------------------------------------------------
    /// </summary>



    class Class1
    {
        private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
        static Class1() {}

        static String input_path = "../../../../TestFiles/";
        static String output_path = "../../../../TestFiles/Output/";

        static void SimpleConvert(String input_filename, String output_filename)
        {
            // Start with a PDFDoc (the conversion destination)
            using (PDFDoc pdfdoc = new PDFDoc())
            {
                // perform the conversion with no optional parameters
                pdftron.PDF.Convert.OfficeToPDF(pdfdoc, input_path + input_filename, null);

                // save the result
                pdfdoc.Save(output_path + output_filename, SDFDoc.SaveOptions.e_linearized);

                // And we're done!
                Console.WriteLine("Saved " + output_filename);
            }   
        }

        static void FlexibleConvert(String input_filename, String output_filename)
        {
            // Start with a PDFDoc (the conversion destination)
            using (PDFDoc pdfdoc = new PDFDoc())
            {
                OfficeToPDFOptions options = new OfficeToPDFOptions();
                options.SetSmartSubstitutionPluginPath(input_path);
                // create a conversion object -- this sets things up but does not yet
                // perform any conversion logic.
                // in a multithreaded environment, this object can be used to monitor
                // the conversion progress and potentially cancel it as well
                DocumentConversion conversion = pdftron.PDF.Convert.StreamingPDFConversion(
                    pdfdoc, input_path + input_filename, options);

                // actually perform the conversion
                // this particular method will not throw on conversion failure, but will
                // return an error status instead
                if (conversion.TryConvert() == DocumentConversionResult.e_document_conversion_success)
                {
                    int num_warnings = conversion.GetNumWarnings();

                    // print information about the conversion 
                    for (int i = 0; i < num_warnings; ++i)
                    {
                        Console.WriteLine("Warning: " + conversion.GetWarningString(i));
                    }

                    // save the result
                    pdfdoc.Save(output_path + output_filename, SDFDoc.SaveOptions.e_linearized);
                    // done
                    Console.WriteLine("Saved " + output_filename);
                }
                else
                {
                    Console.WriteLine("Encountered an error during conversion: " + conversion.GetErrorString());
                }
            }
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            PDFNet.Initialize(PDFTronLicense.Key);

            try
            {
                // first the one-line conversion method
                SimpleConvert("Fishermen.docx", "Fishermen.pdf");

                // then the more flexible line-by-line conversion API
                FlexibleConvert("the_rime_of_the_ancient_mariner.docx", "the_rime_of_the_ancient_mariner.pdf");

                // conversion of RTL content
                FlexibleConvert("factsheet_Arabic.docx", "factsheet_Arabic.pdf");
            }
            catch (pdftron.Common.PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unrecognized Exception: " + e.Message );
            }

            PDFNet.Terminate();
            Console.WriteLine("Done.");
        }
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code lineNumbers="true" %}

```cpp
//------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//------------------------------------------------------------------------------

#include <iostream>
#include <sstream>
#include <PDF/PDFNet.h>
#include <PDF/Convert.h>
#include <PDF/OfficeToPDFOptions.h>
#include "../../LicenseKey/CPP/LicenseKey.h"

//------------------------------------------------------------------------------
// The following sample illustrates how to use the PDF::Convert utility class 
// to convert MS Office files to PDF
//
// This conversion is performed entirely within the PDFNet and has *no* 
// external or system dependencies dependencies -- Conversion results will be
// the same whether on Windows, Linux or Android.
//
// Please contact us if you have any questions.	
//------------------------------------------------------------------------------

using namespace pdftron;
using namespace PDF;

UString input_path = "../../TestFiles/";
UString output_path = "../../TestFiles/Output/";

void SimpleDocxConvert(UString input_filename, UString output_filename)
{
	// Start with a PDFDoc (the conversion destination)
	PDFDoc pdfdoc;

	// perform the conversion with no optional parameters
	Convert::OfficeToPDF(pdfdoc, input_path + input_filename, NULL);

	// save the result
	pdfdoc.Save(output_path + output_filename, SDF::SDFDoc::e_linearized, NULL);
	
	// And we're done!
	std::cout << "Saved " << output_filename << std::endl;
}

void FlexibleDocxConvert(UString input_filename, UString output_filename)
{
	// Start with a PDFDoc (the conversion destination)
	PDFDoc pdfdoc;

	OfficeToPDFOptions options;

	// set up smart font substitutions to improve conversion results
	// in situations where the original fonts are not available
	options.SetSmartSubstitutionPluginPath(input_path);

	// create a conversion object -- this sets things up but does not yet
	// perform any conversion logic.
	// in a multithreaded environment, this object can be used to monitor
	// the conversion progress and potentially cancel it as well
	DocumentConversion conversion = Convert::StreamingPDFConversion(
		pdfdoc, input_path + input_filename, &options);
	
	// Print the progress of the conversion.
	/*
	std::cout << "Status: " << conversion.GetProgress()*100 << "%, "
			<< conversion.GetProgressLabel() << std::endl;
	*/

	// actually perform the conversion
	// this particular method will not throw on conversion failure, but will
	// return an error status instead
		
	while (conversion.GetConversionStatus() == DocumentConversion::eIncomplete)
	{
		conversion.ConvertNextPage();
		// print out the progress status as we go
		/*
		std::cout << "Status: " << conversion.GetProgress()*100 << "%, "
			<< conversion.GetProgressLabel() << std::endl;
		*/
	}

	if(conversion.GetConversionStatus() == DocumentConversion::eSuccess)
	{
		int num_warnings = conversion.GetNumWarnings();
		
		// print information about the conversion 
		for (int i = 0; i < num_warnings; ++i)
		{
			std::cout << "Conversion Warning: " 
				<< conversion.GetWarningString(i) << std::endl;
		}

		// save the result
		pdfdoc.Save(output_path + output_filename, SDF::SDFDoc::e_linearized, NULL);
		// done
		std::cout << "Saved " << output_filename << std::endl;
	}
	else
	{
		std::cout << "Encountered an error during conversion: " 
			<< conversion.GetErrorString() << std::endl;
	}

	
}


int main(int argc, char *argv[])
{	
	// The first step in every application using PDFNet is to initialize the 
	// library. The library is usually initialized only once, but calling 
	// Initialize() multiple times is also fine.
	int ret = 0;

	PDFNet::Initialize(LicenseKey);
	PDFNet::SetResourcesPath("../../../Resources");

	try
	{
		// first the one-line conversion function
		SimpleDocxConvert("Fishermen.docx", "Fishermen.pdf");

		// then the more flexible line-by-line conversion API
		FlexibleDocxConvert("the_rime_of_the_ancient_mariner.docx",
			"the_rime_of_the_ancient_mariner.pdf");

		// conversion of RTL content
		FlexibleDocxConvert("factsheet_Arabic.docx", "factsheet_Arabic.pdf");
	}
	catch (Common::Exception& e)
	{
		std::cout << e << std::endl;
		ret = 1;
	}
	catch (...)
	{
		std::cout << "Unknown Exception" << std::endl;
		ret = 1;
	}

	PDFNet::Terminate();
	std::cout << "Done.\n";
	return ret;
}
```

{% endcode %}
{% endtab %}

{% tab title="Go" %}
{% code lineNumbers="true" %}

```go
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------

package main
import (
	"fmt"
	. "pdftron"
)

import  "pdftron/Samples/LicenseKey/GO"

//------------------------------------------------------------------------------
// The following sample illustrates how to use the PDF.Convert utility class 
// to convert MS Office files to PDF
//
// This conversion is performed entirely within the PDFNet and has *no* 
// external or system dependencies dependencies -- Conversion results will be
// the same whether on Windows, Linux or Android.
//
// Please contact us if you have any questions.
//------------------------------------------------------------------------------

// Relative path to the folder containing the test files.
var inputPath = "../../TestFiles/"
var outputPath = "../../TestFiles/Output/"

func SimpleDocxConvert(inputFileName string, outputFileName string){
	// Start with a PDFDoc (the conversion destination)
    pdfdoc := NewPDFDoc()

    // perform the conversion with no optional parameters
    ConvertOfficeToPDF(pdfdoc, inputPath + inputFileName, NewConversionOptions())

    // save the result
    pdfdoc.Save(outputPath + outputFileName, uint(SDFDocE_linearized))

    // And we're done!
    fmt.Println("Saved " + outputFileName )
}

func FlexibleDocxConvert(inputFileName string , outputFileName string){
    // Start with a PDFDoc (the conversion destination)
    pdfdoc :=  NewPDFDoc()

    options :=  NewOfficeToPDFOptions() 

    // set up smart font substitutions to improve conversion results
    // in situations where the original fonts are not available
    options.SetSmartSubstitutionPluginPath(inputPath)

    // create a conversion object -- this sets things up but does not yet
    // perform any conversion logic.
    // in a multithreaded environment, this object can be used to monitor
    // the conversion progress and potentially cancel it as well
    conversion := ConvertStreamingPDFConversion(pdfdoc, inputPath + inputFileName, options)

    // Print the progress of the conversion.
    // print( "Status: " + str(conversion.GetProgress()*100) +"%, " +
    //        conversion.GetProgressLabel())

    // actually perform the conversion
    // this particular method will not throw on conversion failure, but will
    // return an error status instead
	for {
		if (conversion.GetConversionStatus() != DocumentConversionEIncomplete){
			break
		}
		conversion.ConvertNextPage()
		// print out the progress status as we go
		// print("Status: " + str(conversion.GetProgress()*100) + "%, " +
		//     conversion.GetProgressLabel() )
	}

    if(conversion.GetConversionStatus() == DocumentConversionESuccess){
        numWarnings := conversion.GetNumWarnings()
        // print information about the conversion
        for i := uint(0); i < numWarnings; i++ {
            fmt.Println("Conversion Warning: " + conversion.GetWarningString(i) )
            i = i + 1
		}
        // save the result
        pdfdoc.Save(outputPath + outputFileName, uint(SDFDocE_linearized))
        // done
        fmt.Println("Saved " + outputFileName )
	}else{
        fmt.Println("Encountered an error during conversion: " + conversion.GetErrorString() )
	}
}

func main(){
    // The first step in every application using PDFNet is to initialize the 
    // library. The library is usually initialized only once, but calling 
    // Initialize() multiple times is also fine.
    PDFNetInitialize(PDFTronLicense.Key)
    PDFNetSetResourcesPath("../../Resources")

    // first the one-line conversion function
    SimpleDocxConvert("simple-word_2007.docx", "simple-word_2007.pdf")

    // then the more flexible line-by-line conversion API
    FlexibleDocxConvert("the_rime_of_the_ancient_mariner.docx", "the_rime_of_the_ancient_mariner.pdf")
    PDFNetTerminate()

}
```

{% endcode %}
{% endtab %}

{% tab title="Java" %}
{% code lineNumbers="true" %}

```java
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

import com.pdftron.common.PDFNetException;
import com.pdftron.pdf.Convert;
import com.pdftron.pdf.DocumentConversion;
import com.pdftron.pdf.PDFDoc;
import com.pdftron.pdf.PDFNet;
import com.pdftron.pdf.OfficeToPDFOptions;
import com.pdftron.sdf.SDFDoc;

//---------------------------------------------------------------------------------------
// The following sample illustrates how to use the PDF.Convert utility class to convert 
// MS Office files to PDF
//
// This conversion is performed entirely within the PDFNet and has *no* external or
// system dependencies dependencies -- Conversion results will be the same whether
// on Windows, Linux or Android.
//
// Please contact us if you have any questions. 
//---------------------------------------------------------------------------------------
public class OfficeToPDFTest {

    static String input_path = "../../TestFiles/";
    static String output_path = "../../TestFiles/Output/";

    public static void main(String[] args) {
        PDFNet.initialize(PDFTronLicense.Key());
        PDFNet.setResourcesPath("../../../Resources");

        // first the one-line conversion interface
        simpleDocxConvert("Fishermen.docx", "Fishermen.pdf");

        // then the more flexible line-by-line interface
        flexibleDocxConvert("the_rime_of_the_ancient_mariner.docx", "the_rime_of_the_ancient_mariner.pdf");
       
        // conversion of RTL content
        flexibleDocxConvert("factsheet_Arabic.docx", "factsheet_Arabic.pdf");

        PDFNet.terminate();
    }

    public static void simpleDocxConvert(String inputFilename, String outputFilename) {
        try (PDFDoc pdfdoc = new PDFDoc()) {

            // perform the conversion with no optional parameters
            Convert.officeToPdf(pdfdoc, input_path + inputFilename, null);

            // save the result
            pdfdoc.save(output_path + outputFilename, SDFDoc.SaveMode.INCREMENTAL, null);
            // output PDF pdfdoc

            // And we're done!
            System.out.println("Done conversion " + output_path + outputFilename);
        } catch (PDFNetException e) {
            System.out.println("Unable to convert MS Office document, error:");
            e.printStackTrace();
            System.out.println(e);
        }
    }

    public static void flexibleDocxConvert(String inputFilename, String outputFilename) {
        try {
            OfficeToPDFOptions options = new OfficeToPDFOptions();
            options.setSmartSubstitutionPluginPath(input_path);

            // create a conversion object -- this sets things up but does not yet
            // perform any conversion logic.
            // in a multithreaded environment, this object can be used to monitor
            // the conversion progress and potentially cancel it as well
            DocumentConversion conversion = Convert.streamingPdfConversion(
                    input_path + inputFilename, options);

            System.out.println(inputFilename + ": " + Math.round(conversion.getProgress() * 100.0)
                    + "% " + conversion.getProgressLabel());

            // actually perform the conversion
            while (conversion.getConversionStatus() == DocumentConversion.e_incomplete) {
                conversion.convertNextPage();
                System.out.println(inputFilename + ": " + Math.round(conversion.getProgress() * 100.0)
                        + "% " + conversion.getProgressLabel());
            }

            if (conversion.tryConvert() == DocumentConversion.e_success) {
                int num_warnings = conversion.getNumWarnings();

                // print information about the conversion
                for (int i = 0; i < num_warnings; ++i) {
                    System.out.println("Warning: " + conversion.getWarningString(i));
                }

                // save the result
                try (PDFDoc doc = conversion.getDoc()) {
                    doc.save(output_path + outputFilename, SDFDoc.SaveMode.INCREMENTAL, null);
                }

                // done
                System.out.println("Done conversion " + output_path + outputFilename);
            } else {
                System.out.println("Encountered an error during conversion: " + conversion.getErrorString());
            }
        } catch (PDFNetException e) {
            System.out.println("Unable to convert MS Office document, error:");
            e.printStackTrace();
            System.out.println(e);
        }
    }

}
```

{% endcode %}
{% endtab %}

{% tab title="JavaScript" %}
{% code lineNumbers="true" %}

```js
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// The following sample illustrates how to use the PDF::Convert utility class 
// to convert MS Office files to PDF
//
// This conversion is performed entirely within the PDFNet and has *no* 
// external or system dependencies dependencies -- Conversion results will be
// the same whether on Windows, Linux or Android.
//
// Please contact us if you have any questions.	
//------------------------------------------------------------------------------

const { PDFNet } = require('@pdftron/pdfnet-node');
const PDFTronLicense = require('../LicenseKey/LicenseKey');

((exports) => {
  'use strict';

  exports.runOfficeToPDF = () => {

    const inputPath = '../TestFiles/';
    const outputPath = inputPath + 'Output/';

    const simpleDocxConvert = async (inputFilename, outputFilename) => {
      // perform the conversion with no optional parameters
      const pdfdoc = await PDFNet.Convert.officeToPdfWithPath(inputPath + inputFilename);

      // save the result
      await pdfdoc.save(outputPath + outputFilename, PDFNet.SDFDoc.SaveOptions.e_linearized);

      // And we're done!
      console.log('Saved ' + outputFilename);
    }

    const flexibleDocxConvert = async (inputFilename, outputFilename) => {
      // Start with a PDFDoc (the conversion destination)
      const pdfdoc = await PDFNet.PDFDoc.create();
      pdfdoc.initSecurityHandler();

      const options = new PDFNet.Convert.OfficeToPDFOptions();

      // set up smart font substitutions to improve conversion results
      // in situations where the original fonts are not available
      options.setSmartSubstitutionPluginPath(inputPath);

      // create a conversion object -- this sets things up but does not yet
      // perform any conversion logic.
      // in a multithreaded environment, this object can be used to monitor
      // the conversion progress and potentially cancel it as well
      const conversion = await PDFNet.Convert.streamingPdfConversionWithPdfAndPath(
        pdfdoc, inputPath + inputFilename, options);

      // Print the progress of the conversion.
      /*
            console.log('Status: ' + await conversion.getProgress() * 100 + '%, '
              + await conversion.getProgressLabel());
      */

      // actually perform the conversion
      // this particular method will not throw on conversion failure, but will
      // return an error status instead

      while (await conversion.getConversionStatus() === PDFNet.DocumentConversion.Result.e_Incomplete) {
        await conversion.convertNextPage();
        // print out the progress status as we go
        /*
                console.log('Status: ' + await conversion.getProgress() * 100 + '%, '
                  + await conversion.getProgressLabel());
        */
      }

      if (await conversion.getConversionStatus() === PDFNet.DocumentConversion.Result.e_Success) {
        const num_warnings = await conversion.getNumWarnings();

        // print information about the conversion 
        for (let i = 0; i < num_warnings; ++i) {
          console.log('Conversion Warning: ' + await conversion.getWarningString(i));
        }

        // save the result
        await pdfdoc.save(outputPath + outputFilename, PDFNet.SDFDoc.SaveOptions.e_linearized);
        // done
        console.log('Saved ' + outputFilename);
      }
      else {
        console.log('Encountered an error during conversion: '
          + await conversion.getErrorString());
      }
    }


    const main = async () => {

      PDFNet.addResourceSearchPath('../Resources');

      try {
        // first the one-line conversion function
        await simpleDocxConvert('Fishermen.docx', 'Fishermen.pdf');

        // then the more flexible line-by-line conversion API
        await flexibleDocxConvert('the_rime_of_the_ancient_mariner.docx',
          'the_rime_of_the_ancient_mariner.pdf');

        // conversion of RTL content
        await flexibleDocxConvert('factsheet_Arabic.docx', 'factsheet_Arabic.pdf');
      } catch (err) {
        console.log(err);
      }

      console.log('Done.');
    };

    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function (error) {
      console.log('Error: ' + JSON.stringify(error));
    }).then(function () { return PDFNet.shutdown(); });

  };
  exports.runOfficeToPDF();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=OfficeToPDFTest.js
```

{% endcode %}
{% endtab %}

{% tab title="PHP" %}
{% code lineNumbers="true" %}

```php
<?php
//------------------------------------------------------------------------------
// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//------------------------------------------------------------------------------
if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
include("../../../PDFNetC/Lib/PDFNetPHP.php");
include("../../LicenseKey/PHP/LicenseKey.php");

// Relative path to the folder containing the test files.
$input_path = getcwd()."/../../TestFiles/";
$output_path = $input_path."Output/";

//------------------------------------------------------------------------------
// The following sample illustrates how to use the PDF::Convert utility class 
// to convert MS Office files to PDF
//
// This conversion is performed entirely within the PDFNet and has *no* 
// external or system dependencies dependencies -- Conversion results will be
// the same whether on Windows, Linux or Android.
//
// Please contact us if you have any questions.
//------------------------------------------------------------------------------


function SimpleDocxConvert($input_filename, $output_filename)
{
	global $input_path, $output_path;

	// Start with a PDFDoc (the conversion destination)
	$pdfdoc = new PDFDoc();

	// perform the conversion with no optional parameters
	Convert::OfficeToPDF($pdfdoc, $input_path.$input_filename, NULL);

	// save the result
	$pdfdoc->Save($output_path.$output_filename, SDFDoc::e_linearized);
	
	// And we're done!
	echo nl2br("Saved ".$output_filename . "\n");
}


function FlexibleDocxConvert($input_filename, $output_filename)
{
	global $input_path, $output_path;

	// Start with a PDFDoc (the conversion destination)
	$pdfdoc = new PDFDoc();

	$options = new OfficeToPDFOptions(); //ConversionOptions();

	// set up smart font substitutions to improve conversion results
	// in situations where the original fonts are not available
	$options->SetSmartSubstitutionPluginPath($input_path);

	// create a conversion object -- this sets things up but does not yet
	// perform any conversion logic.
	// in a multithreaded environment, this object can be used to monitor
	// the conversion progress and potentially cancel it as well
	$conversion = Convert::StreamingPDFConversion($pdfdoc, $input_path.$input_filename, $options);

	// Print the progress of the conversion.
	/*
	echo "Status: "$conversion->GetProgress()*100 . "%, ".
			$conversion->GetProgressLabel();
	*/

	// actually perform the conversion
	// this particular method will not throw on conversion failure, but will
	// return an error status instead
	while ($conversion->GetConversionStatus() == DocumentConversion::eIncomplete)
	{
		$conversion->ConvertNextPage();
		// print out the progress status as we go
		/*
		echo (nl2br("Status: " . $conversion->GetProgress()*100 . "%, ".
			 $conversion->GetProgressLabel() ));
		*/
	}

 	if($conversion->GetConversionStatus() == DocumentConversion::eSuccess)
	{
		$num_warnings = $conversion->GetNumWarnings();
		
		// print information about the conversion 
		for ($i = 0; $i < $num_warnings; ++$i)
		{
			echo(nl2br("Conversion Warning: ".$conversion->GetWarningString($i) ));
		}

		// save the result
		$pdfdoc->Save($output_path . $output_filename, SDFDoc::e_linearized);
		// done
		echo(nl2br("Saved " . $output_filename ."\n"));
	}
	else
	{
		echo(nl2br("Encountered an error during conversion: " . $conversion->GetErrorString() ));
	}

}




function main()
{
	// The first step in every application using PDFNet is to initialize the 
	// library. The library is usually initialized only once, but calling 
	// Initialize() multiple times is also fine.

	global $LicenseKey;
	PDFNet::Initialize($LicenseKey);
	PDFNet::SetResourcesPath("../../../Resources");

	// first the one-line conversion function
	SimpleDocxConvert("simple-word_2007.docx", "simple-word_2007.pdf");

	// then the more flexible line-by-line conversion API
	FlexibleDocxConvert("the_rime_of_the_ancient_mariner.docx", "the_rime_of_the_ancient_mariner.pdf");
	PDFNet::Terminate();
	echo(nl2br("Done.\n"));
}

main()

?>
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code lineNumbers="true" %}

```python
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

import site
site.addsitedir("../../../PDFNetC/Lib")
import sys
from PDFNetPython import *

sys.path.append("../../LicenseKey/PYTHON")
from LicenseKey import *

# Relative path to the folder containing the test files.
input_path = "../../TestFiles/"
output_path = "../../TestFiles/Output/"

#------------------------------------------------------------------------------
# The following sample illustrates how to use the PDF.Convert utility class 
# to convert MS Office files to PDF
#
# This conversion is performed entirely within the PDFNet and has *no* 
# external or system dependencies dependencies -- Conversion results will be
# the same whether on Windows, Linux or Android.
#
# Please contact us if you have any questions.
#------------------------------------------------------------------------------

def SimpleDocxConvert(input_filename, output_filename):
    # Start with a PDFDoc (the conversion destination)
    pdfdoc = PDFDoc()

    # perform the conversion with no optional parameters
    Convert.OfficeToPDF(pdfdoc, input_path + input_filename, None)

    # save the result
    pdfdoc.Save(output_path + output_filename, SDFDoc.e_linearized)

    # And we're done!
    print("Saved " + output_filename )

def FlexibleDocxConvert(input_filename, output_filename):
    # Start with a PDFDoc (the conversion destination)
    pdfdoc =  PDFDoc()

    options =  OfficeToPDFOptions() 

    # set up smart font substitutions to improve conversion results
    # in situations where the original fonts are not available
    options.SetSmartSubstitutionPluginPath(input_path)

    # create a conversion object -- this sets things up but does not yet
    # perform any conversion logic.
    # in a multithreaded environment, this object can be used to monitor
    # the conversion progress and potentially cancel it as well
    conversion = Convert.StreamingPDFConversion(pdfdoc, input_path + input_filename, options)

    # Print the progress of the conversion.
    # print( "Status: " + str(conversion.GetProgress()*100) +"%, " +
    #        conversion.GetProgressLabel())

    # actually perform the conversion
    # this particular method will not throw on conversion failure, but will
    # return an error status instead
    while (conversion.GetConversionStatus() == DocumentConversion.eIncomplete):
        conversion.ConvertNextPage()
        # print out the progress status as we go
        # print("Status: " + str(conversion.GetProgress()*100) + "%, " +
        #     conversion.GetProgressLabel() )

    if(conversion.GetConversionStatus() == DocumentConversion.eSuccess):
        num_warnings = conversion.GetNumWarnings()
        # print information about the conversion
        i = 0
        for i in range(num_warnings):
            print("Conversion Warning: " + conversion.GetWarningString(i) )
            i = i + 1

        # save the result
        pdfdoc.Save(output_path + output_filename, SDFDoc.e_linearized)
        # done
        print("Saved " + output_filename )
    else:
        print("Encountered an error during conversion: " + conversion.GetErrorString() )

def main():
    # The first step in every application using PDFNet is to initialize the 
    # library. The library is usually initialized only once, but calling 
    # Initialize() multiple times is also fine.
    PDFNet.Initialize(LicenseKey)
    PDFNet.SetResourcesPath("../../../Resources")

    # first the one-line conversion function
    SimpleDocxConvert("simple-word_2007.docx", "simple-word_2007.pdf")

    # then the more flexible line-by-line conversion API
    FlexibleDocxConvert("the_rime_of_the_ancient_mariner.docx", "the_rime_of_the_ancient_mariner.pdf")
    PDFNet.Terminate()

    print("Done.")

if __name__ == '__main__':
    main()
```

{% endcode %}
{% endtab %}

{% tab title="Ruby" %}
{% code lineNumbers="true" %}

```ruby
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

require '../../../PDFNetC/Lib/PDFNetRuby'
include PDFNetRuby
require '../../LicenseKey/RUBY/LicenseKey'

$stdout.sync = true

#------------------------------------------------------------------------------
# The following sample illustrates how to use the PDF.Convert utility class 
# to convert MS Office files to PDF
#
# This conversion is performed entirely within the PDFNet and has *no* 
# external or system dependencies dependencies -- Conversion results will be
# the same whether on Windows, Linux or Android.
#
# Please contact us if you have any questions.
#------------------------------------------------------------------------------

# Relative path to the folder containing the test files.
$inputPath = "../../TestFiles/"
$outputPath = "../../TestFiles/Output/"

def SimpleDocxConvert(input_filename, output_filename)
    # Start with a PDFDoc (the conversion destination)
    pdfdoc = PDFDoc.new()

    # perform the conversion with no optional parameters
    inputFile = $inputPath + input_filename
    Convert.OfficeToPDF(pdfdoc, inputFile, nil)

    # save the result
    outputFile = $outputPath + output_filename
    pdfdoc.Save(outputFile, SDFDoc::E_linearized)

    # And we're done!
    puts "Saved " + output_filename
end

def FlexibleDocxConvert(input_filename, output_filename)
    # Start with a PDFDoc (the conversion destination)
    pdfdoc = PDFDoc.new()

    options = OfficeToPDFOptions.new() 

    # set up smart font substitutions to improve conversion results
    # in situations where the original fonts are not available
    inputFile = $inputPath 
    options.SetSmartSubstitutionPluginPath(inputFile)

    # create a conversion object -- this sets things up but does not yet
    # perform any conversion logic.
    # in a multithreaded environment, this object can be used to monitor
    # the conversion progress and potentially cancel it as well
    inputFile = $inputPath + input_filename
    conversion = Convert.StreamingPDFConversion(pdfdoc, inputFile, options)

    # Print the progress of the conversion.
    # puts  "Status " + (conversion.GetProgress()*100).to_s + "%, " +
    #        conversion.GetProgressLabel()

    # actually perform the conversion
    # this particular method will not throw on conversion failure, but will
    # return an error status instead
    while (conversion.GetConversionStatus() == DocumentConversion::EIncomplete)
        conversion.ConvertNextPage()
        # print out the progress status as we go
        # puts "Status " + (conversion.GetProgress()*100).to_s + "%, " +
        #     conversion.GetProgressLabel()
    end

    if(conversion.GetConversionStatus() == DocumentConversion::ESuccess)
        num_warnings = conversion.GetNumWarnings()
        # print information about the conversion
        for i in 0..num_warnings-1 
            puts "Conversion Warning " + conversion.GetWarningString(i)
        end

        # save the result
        outputFile = $outputPath + output_filename
        pdfdoc.Save(outputFile, SDFDoc::E_linearized)
        # done
        puts "Saved " + output_filename 
    else
        puts "Encountered an error during conversion " + conversion.GetErrorString()
    end
    
end


def main()
    # The first step in every application using PDFNet is to initialize the 
    # library. The library is usually initialized only once, but calling 
    # Initialize() multiple times is also fine.
    PDFNet.Initialize(PDFTronLicense.Key)
    PDFNet.SetResourcesPath("../../../Resources")

    # first the one-line conversion function
    SimpleDocxConvert("simple-word_2007.docx", "simple-word_2007.pdf")

    # then the more flexible line-by-line conversion API
    FlexibleDocxConvert("the_rime_of_the_ancient_mariner.docx", "the_rime_of_the_ancient_mariner.pdf")
    PDFNet.Terminate
    puts "Done."
end

main()
```

{% endcode %}
{% endtab %}

{% tab title="VB" %}
{% code lineNumbers="true" %}

```vb
'
' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
'

Imports System

Imports pdftron
Imports pdftron.Common
Imports pdftron.Filters
Imports pdftron.SDF
Imports pdftron.PDF


' The following sample illustrates how to use the PDF::Convert utility class to convert 
' .docx files to PDF
'
' This conversion is performed entirely within the PDFNet and has *no* external or
' system dependencies dependencies 
'
' Please contact us if you have any questions.	
Module OfficeToPDFTestVB
    Dim pdfNetLoader As PDFNetLoader
    Sub New()
        pdfNetLoader = pdftron.PDFNetLoader.Instance()
    End Sub

    ' Relative path to the folder containing test files.
    Dim input_path As String = "../../../../TestFiles/"
    Dim output_path As String = "../../../../TestFiles/Output/"

    Private Sub SimpleConvert(ByVal input_filename As String, ByVal output_filename As String)
        ' Start with a PDFDoc (the conversion destination)
        Using pdfdoc As PDFDoc = New PDFDoc

            ' perform the conversion with no optional parameters
            pdftron.PDF.Convert.OfficeToPDF(pdfdoc, input_path + input_filename, Nothing)

            ' save the result
            pdfdoc.Save(output_path + output_filename, SDFDoc.SaveOptions.e_linearized)

            ' And we're done!
            Console.WriteLine("Saved " + (output_path + output_filename))
        End Using
    End Sub

    Private Sub FlexibleConvert(ByVal input_filename As String, ByVal output_filename As String)
        ' Start with a PDFDoc (the conversion destination)
        Using pdfdoc As PDFDoc = New PDFDoc
            Dim options As OfficeToPDFOptions = New OfficeToPDFOptions
            options.SetResourceDocPath("SomePath")
            ' perform the conversion with no optional parameters
            Using conversion As DocumentConversion = pdftron.PDF.Convert.StreamingPDFConversion(pdfdoc, input_path + input_filename, options)

                If conversion.TryConvert() = DocumentConversionResult.e_document_conversion_success Then
                    Dim num_warnings As Integer = conversion.GetNumWarnings()
                    For i As Integer = 0 To num_warnings - 1
                        Console.WriteLine("Warning: " + conversion.GetWarningString(i))
                    Next i

                    ' save the result
                    pdfdoc.Save(output_path + output_filename, SDFDoc.SaveOptions.e_linearized)

                    ' And we're done!
                    Console.WriteLine("Saved " + (output_path + output_filename))
                Else
                    Console.WriteLine("Error: " + conversion.GetErrorString())
                End If
            End Using
        End Using
    End Sub



    Sub Main()

        PDFNet.Initialize(PDFTronLicense.Key)

        Try
            ' first the one-line conversion method
            SimpleConvert("Fishermen.docx", "Fishermen.pdf")

            ' Then the more flexible conversion process
            FlexibleConvert("simple-word_2007.docx", "simple-word_2007_b.pdf")

            ' conversion of RTL content
            FlexibleConvert("factsheet_Arabic.docx", "factsheet_Arabic.pdf")

        Catch ex As PDFNetException

            Console.WriteLine(ex.Message)

        Catch ex As Exception

            MsgBox(ex.Message)

        End Try

        PDFNet.Terminate()

    End Sub

End Module
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/core/get-started/samples/officetopdftest.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
