> 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/convertprinttest.md).

# Convert File Types with Virtual Printer on Windows - ConvertPrint

Sample code to convert to PDF with virtual printer on Windows. It supports several input formats like docx, xlsx, rtf, txt, html, pub, emf, etc. Samples provided in Python, C++, C#, Java, Node.js (Jav

Sample code to convert to PDF with virtual printer on Windows; provided in Python, C++, C#, Java, Node.js (JavaScript), Go and VB. It supports several input formats like docx, xlsx, rtf, txt, html, pub, emf, etc.

{% 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 ConvertPrintTestCS
{
	/// <summary>
	// The following sample illustrates how to convert to PDF with virtual printer on Windows.
	// It supports several input formats like docx, xlsx, rtf, txt, html, pub, emf, etc. For more details, visit 
	// https://docs.apryse.com/windows/guides/features/conversion/convert-other/
	// 
	// To check if ToPDF (or ToXPS) require that PDFNet printer is installed use Convert::RequiresPrinter(filename). 
	// The installing application must be run as administrator. The manifest for this sample 
	// specifies appropriate the UAC elevation.
	//
	// Note: the PDFNet printer is a virtual XPS printer supported on Vista SP1 and Windows 7, or .NET Framework
	// 3.x or higher. For older versions of .NET Framework running on Windows XP or Vista SP0 you need to install 
	// the XPS Essentials Pack (or equivalent redistributables). 
	//
	// Also note that conversion under ASP.NET can be tricky to configure. Please see the following document for advice: 
	// http://www.pdftron.com/pdfnet/faq_files/Converting_Documents_in_Windows_Service_or_ASP.NET_Application_using_PDFNet.pdf
	/// </summary>
	class Testfile
	{
		public string inputFile, outputFile;
		public Testfile(string inFile, string outFile)
		{
			inputFile = inFile;
			outputFile = outFile;
		}
	};

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

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

		static bool ConvertSpecificFormats()
		{
			//////////////////////////////////////////////////////////////////////////
			bool err = false;
			try
			{
				// Convert MSWord document to XPS
				Console.WriteLine("Converting DOCX to XPS");
				pdftron.PDF.Convert.ToXps(inputPath + "simple-word_2007.docx", outputPath + "simple-word_2007.xps");
				Console.WriteLine("Saved simple-word_2007.xps");
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
				err = true;
			}


			//////////////////////////////////////////////////////////////////////////
			try
			{
				using (PDFDoc pdfdoc = new PDFDoc())
				{
					Console.WriteLine("Converting from EMF");
					pdftron.PDF.Convert.FromEmf(pdfdoc, inputPath + "simple-emf.emf");
					pdfdoc.Save(outputPath + "emf2pdf v2.pdf", SDFDoc.SaveOptions.e_remove_unused);
					Console.WriteLine("Saved emf2pdf v2.pdf");
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
				err = true;
			}

			return err;
		}

		static Boolean ConvertToPdfFromFile()
		{
			System.Collections.ArrayList testfiles = new System.Collections.ArrayList();
			testfiles.Add(new ConvertPrintTestCS.Testfile("simple-powerpoint_2007.pptx", "pptx2pdf.pdf"));
			testfiles.Add(new ConvertPrintTestCS.Testfile("simple-word_2007.docx", "docx2pdf.pdf"));
			testfiles.Add(new ConvertPrintTestCS.Testfile("simple-excel_2007.xlsx", "xlsx2pdf.pdf"));
			testfiles.Add(new ConvertPrintTestCS.Testfile("simple-publisher.pub", "pub2pdf.pdf"));
			testfiles.Add(new ConvertPrintTestCS.Testfile("simple-text.txt", "txt2pdf.pdf"));
			testfiles.Add(new ConvertPrintTestCS.Testfile("simple-rtf.rtf", "rtf2pdf.pdf"));
			testfiles.Add(new ConvertPrintTestCS.Testfile("simple-emf.emf", "emf2pdf.pdf"));
			testfiles.Add(new ConvertPrintTestCS.Testfile("simple-webpage.mht", "mht2pdf.pdf"));
			testfiles.Add(new ConvertPrintTestCS.Testfile("simple-webpage.html", "html2pdf.pdf"));

			bool err = false; 
			try
			{
				if (pdftron.PDF.Convert.Printer.IsInstalled("PDFTron PDFNet"))
				{
					pdftron.PDF.Convert.Printer.SetPrinterName("PDFTron PDFNet");
				}
				else if (!pdftron.PDF.Convert.Printer.IsInstalled())
				{
					try
					{
						Console.WriteLine("Installing printer (requires Windows platform and administrator)");
						pdftron.PDF.Convert.Printer.Install();
						Console.WriteLine("Installed printer " + pdftron.PDF.Convert.Printer.GetPrinterName());
						// the function ConvertToXpsFromFile may require the printer so leave it installed
						// uninstallPrinterWhenDone = true;
					}
					catch (PDFNetException e)
					{
						Console.WriteLine("ERROR: Unable to install printer.");
						Console.WriteLine(e.Message);
						err = true;
					}
					catch
					{
						Console.WriteLine("ERROR: Unable to install printer. Make sure that the package's bitness matches your operating system's bitness and that you are running with administrator privileges.");
					}
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine("ERROR: Unable to install printer.");
				Console.WriteLine(e.Message);
				err = true;
			}
			
			foreach (Testfile file in testfiles)
			{
				try
				{
					using (pdftron.PDF.PDFDoc pdfdoc = new PDFDoc())
					{

						if (pdftron.PDF.Convert.RequiresPrinter(inputPath + file.inputFile))
						{
							Console.WriteLine("Using PDFNet printer to convert file " + file.inputFile);
						}
						pdftron.PDF.Convert.ToPdf(pdfdoc, inputPath + file.inputFile);
						pdfdoc.Save(outputPath + file.outputFile, SDFDoc.SaveOptions.e_linearized);
						Console.WriteLine("Converted file: " + file.inputFile);
						Console.WriteLine("to: " + file.outputFile);
					}
				}
				catch (PDFNetException e)
				{
					Console.WriteLine("ERROR: on input file " + file.inputFile);
					Console.WriteLine(e.Message);
					err = true;
				}
			}

			return err;
		}


		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			if (Environment.OSVersion.Platform == PlatformID.Win32NT)
			{
				PDFNet.Initialize(PDFTronLicense.Key);
				bool err = false;

				err = ConvertToPdfFromFile();
				if (err)
				{
					Console.WriteLine("ConvertFile failed");
				}
				else
				{
					Console.WriteLine("ConvertFile succeeded");
				}

				err = ConvertSpecificFormats();
				if (err)
				{
					Console.WriteLine("ConvertSpecificFormats failed");
				}
				else
				{
					Console.WriteLine("ConvertSpecificFormats succeeded");
				}


				if (pdftron.PDF.Convert.Printer.IsInstalled())
				{
					try
					{
						Console.WriteLine("Uninstalling printer (requires Windows platform and administrator)");
						pdftron.PDF.Convert.Printer.Uninstall();
						Console.WriteLine("Uninstalled Printer " + pdftron.PDF.Convert.Printer.GetPrinterName());
					}
					catch
					{
						Console.WriteLine("Unable to uninstall printer");
					}
				}
			
				PDFNet.Terminate();
				Console.WriteLine("Done.");
			}
			else
			{
				Console.WriteLine("ConvertPrintTest only available on Windows");
			}
		}
	}
}
```

{% endcode %}
{% endtab %}

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

```cpp
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2023 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 "../../LicenseKey/CPP/LicenseKey.h"

//---------------------------------------------------------------------------------------
// The following sample illustrates how to convert to PDF with virtual printer on Windows.
// It supports several input formats like docx, xlsx, rtf, txt, html, pub, emf, etc. For more details, visit 
// https://docs.apryse.com/windows/guides/features/conversion/convert-other/
// 
// To check if ToPDF (or ToXPS) require that PDFNet printer is installed use Convert::RequiresPrinter(filename). 
// The installing application must be run as administrator. The manifest for this sample 
// specifies appropriate the UAC elevation.
//
// Note: the PDFNet printer is a virtual XPS printer supported on Vista SP1 and Windows 7.
// For Windows XP SP2 or higher, or Vista SP0 you need to install the XPS Essentials Pack (or 
// equivalent redistributables). You can download the XPS Essentials Pack from:
//		http://www.microsoft.com/downloads/details.aspx?FamilyId=B8DCFFDD-E3A5-44CC-8021-7649FD37FFEE&displaylang=en
// Windows XP Sp2 will also need the Microsoft Core XML Services (MSXML) 6.0:
// 		http://www.microsoft.com/downloads/details.aspx?familyid=993C0BCF-3BCF-4009-BE21-27E85E1857B1&displaylang=en
//
// Note: Convert.FromEmf and Convert.ToEmf will only work on Windows and require GDI+.
//
// Please contact us if you have any questions.	
//---------------------------------------------------------------------------------------

using namespace pdftron;
using namespace PDF;
using namespace std;

UString inputPath("../../TestFiles/");
UString outputPath("../../TestFiles/Output/");

typedef struct  
{
	UString inputFile, outputFile;
}
Testfile;

Testfile testfiles[] = 
{
	{ "simple-word_2007.docx",		"docx2pdf.pdf"},
	{ "simple-powerpoint_2007.pptx",	"pptx2pdf.pdf"},
	{ "simple-excel_2007.xlsx",		"xlsx2pdf.pdf"},
	{ "simple-publisher.pub",		"pub2pdf.pdf"},
	{ "simple-text.txt",			"txt2pdf.pdf"},
	{ "simple-rtf.rtf",			"rtf2pdf.pdf"},
	{ "simple-emf.emf",			"emf2pdf.pdf"},
	{ "simple-webpage.mht",		"mht2pdf.pdf"},
	{ "simple-webpage.html",		"html2pdf.pdf"}
};

int ConvertSpecificFormats();  // convert to/from PDF, XPS, EMF, SVG
int ConvertToPdfFromFile();	   // convert from a file to PDF automatically

int main(int argc, char *argv[])
{	

//Virtual printer only available on Windows
#if defined(_WIN32)
	// 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 err = 0;

	PDFNet::Initialize(LicenseKey);

	// Demonstrate Convert::ToPdf and Convert::Printer
	err = ConvertToPdfFromFile();
	if (err)
	{
		cout << "ConvertFile failed" << endl;
	}
	else
	{
		cout << "ConvertFile succeeded" << endl;
	}

	// Demonstrate Convert::[FromEmf, FromXps, ToEmf, ToSVG, ToXPS]
	err = ConvertSpecificFormats();
	if (err)
	{
		cout << "ConvertSpecificFormats failed" << endl;
	}
	else
	{
		cout << "ConvertSpecificFormats succeeded" << endl;
	}

	if (Convert::Printer::IsInstalled())
	{
		try 
		{
			cout << "Uninstalling printer (requires Windows platform and administrator)" << endl;
			Convert::Printer::Uninstall();
			cout << "Uninstalled printer " << Convert::Printer::GetPrinterName().ConvertToAscii().c_str() << endl;;
		}
		catch (Common::Exception)
		{
			cout << "Unable to uninstall printer" << endl;
		}
	}

	PDFNet::Terminate();
	cout << "Done.\n";
	return err;
#else
	cout << "ConvertPrintTest only available on Windows\n";
#endif // defined(_WIN32)

}

int ConvertToPdfFromFile()
{
	int ret = 0;

	if( Convert::Printer::IsInstalled("PDFTron PDFNet") )
	{
		Convert::Printer::SetPrinterName("PDFTron PDFNet");
	}
	else if (!Convert::Printer::IsInstalled())
	{
		try
		{
			// This will fail if not run as administrator. Harmless if PDFNet 
			// printer already installed
			cout << "Installing printer (requires Windows platform and administrator)\n";
			Convert::Printer::Install();
			cout << "Installed printer " << Convert::Printer::GetPrinterName().ConvertToAscii().c_str() << endl;
		}
		catch (Common::Exception)
		{
			cout << "Unable to install printer" << endl;
		}
	}

	unsigned int ceTestfiles = sizeof (testfiles) / sizeof (Testfile);

	for (unsigned int i = 0; i < ceTestfiles; i++)
	{
		try
		{
			PDFDoc pdfdoc;
			UString inputFile = inputPath + testfiles[i].inputFile;
			UString outputFile = outputPath + testfiles[i].outputFile;
			if (Convert::RequiresPrinter(inputFile))
			{
				cout << "Using PDFNet printer to convert file " << testfiles[i].inputFile << endl;
			}
			Convert::ToPdf(pdfdoc, inputFile);
			pdfdoc.Save(outputFile, SDF::SDFDoc::e_linearized, NULL);
			cout << "Converted file: " << testfiles[i].inputFile << endl << "to: " << testfiles[i].outputFile << endl;
		}
		catch (Common::Exception& e)
		{
			cout << "Unable to convert file " << testfiles[i].inputFile.ConvertToAscii().c_str() << endl;
			cout << e << endl;
			ret = 1;
		}
		catch (...)
		{
			cout << "Unknown Exception" << endl;
			ret = 1;
		}
	}

	return ret;
}

int ConvertSpecificFormats()
{
	//////////////////////////////////////////////////////////////////////////
	int ret = 0;
	try
	{
		PDFDoc pdfdoc;

		cout << "Converting from EMF" << endl;
		Convert::FromEmf(pdfdoc, inputPath + "simple-emf.emf");
		pdfdoc.Save(outputPath + "emf2pdf v2.pdf", SDF::SDFDoc::e_remove_unused, NULL);
		cout << "Saved emf2pdf v2.pdf" << endl;
	}
	catch (Common::Exception& e)
	{
		cout << e << endl;
		ret = 1;
	}
	catch (...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	//////////////////////////////////////////////////////////////////////////
	try
	{
		// Convert MSWord document to XPS
		cout << "Converting DOCX to XPS" << endl;
		Convert::ToXps(inputPath + "simple-word_2007.docx", outputPath + "simple-word_2007.xps");
		cout << "Saved simple-word_2007.xps" << endl;
	}
	catch (Common::Exception& e)
	{
		cout << e << endl;
		ret = 1;
	}
	catch (...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	return ret;
}
```

{% endcode %}
{% endtab %}

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

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

package main
import (
	"testing"
	"fmt"
	"flag"
	"runtime"
	. "github.com/ApryseSDK/pdftron-go/v2"
)

var licenseKey string
var modulePath string

func init() {
    flag.StringVar(&licenseKey, "license", "", "License key for Apryse SDK")
    flag.StringVar(&modulePath, "modulePath", "", "Module path for Apryse SDK")
}

//---------------------------------------------------------------------------------------
// The following sample illustrates how to convert to PDF with virtual printer on Windows.
// It supports several input formats like docx, xlsx, rtf, txt, html, pub, emf, etc. For more details, visit 
// https://docs.apryse.com/windows/guides/features/conversion/convert-other/
//
// To check if ToPDF (or ToXPS) require that PDFNet printer is installed use Convert::RequiresPrinter(filename). 
// The installing application must be run as administrator. The manifest for this sample 
// specifies appropriate the UAC elevation.
//
// Note: the PDFNet printer is a virtual XPS printer supported on Vista SP1 and Windows 7.
// For Windows XP SP2 or higher, or Vista SP0 you need to install the XPS Essentials Pack (or 
// equivalent redistributables). You can download the XPS Essentials Pack from:
//		http://www.microsoft.com/downloads/details.aspx?FamilyId=B8DCFFDD-E3A5-44CC-8021-7649FD37FFEE&displaylang=en
// Windows XP Sp2 will also need the Microsoft Core XML Services (MSXML) 6.0:
//		http://www.microsoft.com/downloads/details.aspx?familyid=993C0BCF-3BCF-4009-BE21-27E85E1857B1&displaylang=en
//
// Note: Convert.fromEmf and Convert.toEmf will only work on Windows and require GDI+.
//
// 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 ConvertSpecificFormats() bool{
	ret := false

        
	// Convert MSWord document to XPS
	fmt.Println("Converting DOCX to XPS")
	outputFile := "simple-word_2007.xps"
	ConvertToXps(inputPath + "simple-word_2007.docx", outputPath + outputFile)
	fmt.Println("Saved " + outputFile)

    // Start with a PDFDoc to collect the converted documents
    pdfdoc := NewPDFDoc()
    // Convert the EMF document to PDF
    s1 := inputPath + "simple-emf.emf"

    fmt.Println("Converting from EMF")
    ConvertFromEmf(pdfdoc, s1)
    outputFile = "emf2pdf v2.pdf"
    pdfdoc.Save(outputPath + outputFile, uint(SDFDocE_remove_unused))
    fmt.Println("Saved " + outputFile)
        
    return ret
}
func ConvertToPdfFromFile() bool{
	testFiles := [][]string{
	{"simple-word_2007.docx","docx2pdf.pdf"}, 
	{"simple-powerpoint_2007.pptx","pptx2pdf.pdf"}, 
	{"simple-excel_2007.xlsx","xlsx2pdf.pdf"}, 
    {"simple-publisher.pub","pub2pdf.pdf"},
	{"simple-text.txt","txt2pdf.pdf"}, 
    { "simple-rtf.rtf","rtf2pdf.pdf"},
    { "simple-emf.emf","emf2pdf.pdf"},
    { "simple-webpage.mht","mht2pdf.pdf"},
    { "simple-webpage.html","html2pdf.pdf"}}
    ret := false

    if PrinterIsInstalled("PDFTron PDFNet"){
		PrinterSetPrinterName("PDFTron PDFNet")
    }else if ! PrinterIsInstalled(){
		fmt.Println("Installing printer (requires Windows platform and administrator)")
		PrinterInstall()
		fmt.Println("Installed printer " + PrinterGetPrinterName())
	}

	for _, testfile := range testFiles {

        pdfdoc := NewPDFDoc()
        inputFile := testfile[0]
        outputFile := testfile[1]
        if ConvertRequiresPrinter(inputPath + inputFile){
            fmt.Println("Using PDFNet printer to convert file " + inputFile)
		}
        ConvertToPdf(pdfdoc, inputPath + inputFile)
        pdfdoc.Save(outputPath + outputFile, uint(SDFDocE_linearized))
        pdfdoc.Close()
        fmt.Println("Converted file: " + inputFile + "\nto: " + outputFile)
	}
    return ret
}

func TestConvertPrint(t *testing.T){
	if runtime.GOOS == "windows" {
		// 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(licenseKey)

		// Demonstrate Convert.ToPdf and Convert.Printer
		err := ConvertToPdfFromFile()
		if err{
			fmt.Println("ConvertFile failed")
		}else{
			fmt.Println("ConvertFile succeeded")
		}
		// Demonstrate Convert.[FromEmf, FromXps, ToEmf, ToSVG, ToXPS]
		err = ConvertSpecificFormats()
		if err{
			fmt.Println("ConvertSpecificFormats failed")
		}else{
			fmt.Println("ConvertSpecificFormats succeeded")
		}
		fmt.Println("Uninstalling printer (requires Windows platform and administrator)")
		PrinterUninstall()
		fmt.Println("Uninstalled printer " + PrinterGetPrinterName())

		PDFNetTerminate()
		fmt.Println("Done.")
	}else{
		fmt.Println("ConvertPrintTest only available on Windows")
	}
}
```

{% endcode %}
{% endtab %}

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

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

import com.pdftron.common.PDFNetException;
import com.pdftron.pdf.*;
import com.pdftron.sdf.Obj;
import com.pdftron.sdf.ObjSet;
import com.pdftron.sdf.SDFDoc;
import java.util.ArrayList;
//---------------------------------------------------------------------------------------
// The following sample illustrates how to convert to PDF with virtual printer on Windows.
// It supports several input formats like docx, xlsx, rtf, txt, html, pub, emf, etc. For more details, visit 
// https://docs.apryse.com/windows/guides/features/conversion/convert-other/
//
// To check if ToPDF (or ToXPS) require that PDFNet printer is installed use Convert::RequiresPrinter(filename). 
// The installing application must be run as administrator. The manifest for this sample 
// specifies appropriate the UAC elevation.
//
// Note: the PDFNet printer is a virtual XPS printer supported on Vista SP1 and Windows 7.
// For Windows XP SP2 or higher, or Vista SP0 you need to install the XPS Essentials Pack (or 
// equivalent redistributables). You can download the XPS Essentials Pack from:
//		http://www.microsoft.com/downloads/details.aspx?FamilyId=B8DCFFDD-E3A5-44CC-8021-7649FD37FFEE&displaylang=en
// Windows XP Sp2 will also need the Microsoft Core XML Services (MSXML) 6.0:
// 		http://www.microsoft.com/downloads/details.aspx?familyid=993C0BCF-3BCF-4009-BE21-27E85E1857B1&displaylang=en
//
// Note: Convert.fromEmf and Convert.toEmf will only work on Windows and require GDI+.
//
// Please contact us if you have any questions.	
//---------------------------------------------------------------------------------------
class Testfile
{
	public String inputFile, outputFile;
	public Testfile(String inFile, String outFile)
	{
		inputFile = inFile;
		outputFile = outFile;
	}
}

public class ConvertPrintTest 
{
	// Relative path to the folder containing test files.
	static String inputPath = "../../TestFiles/";
	static String outputPath = "../../TestFiles/Output/";

	static boolean ConvertSpecificFormats()
	{
		//////////////////////////////////////////////////////////////////////////
		boolean err = false;
		try (PDFDoc pdfdoc = new PDFDoc())
		{
			System.out.println("Converting from EMF");
			Convert.fromEmf(pdfdoc, inputPath + "simple-emf.emf");
			pdfdoc.save(outputPath + "emf2pdf v2.pdf", SDFDoc.SaveMode.REMOVE_UNUSED, null);
			System.out.println("Saved emf2pdf v2.pdf");
		}
		catch (PDFNetException e)
		{
			System.out.println(e);
			err = true;
		}
		

		//////////////////////////////////////////////////////////////////////////
		try
		{
			// Convert MSWord document to XPS
			System.out.println("Converting DOCX to XPS");
			Convert.toXps(inputPath + "simple-word_2007.docx", outputPath + "simple-word_2007.xps");
			System.out.println("Saved simple-word_2007.xps");
		}
		catch (PDFNetException e)
		{
			System.out.println(e);
			err = true;
		}
		
		return err;
	}

	static boolean ConvertToPdfFromFile()
	{
		ArrayList<Testfile> testfiles = new ArrayList<Testfile>();
		testfiles.add(new Testfile("simple-word_2007.docx", "docx2pdf.pdf"));
		testfiles.add(new Testfile("simple-powerpoint_2007.pptx", "pptx2pdf.pdf"));
		testfiles.add(new Testfile("simple-excel_2007.xlsx", "xlsx2pdf.pdf"));
		testfiles.add(new Testfile("simple-publisher.pub", "pub2pdf.pdf"));
		testfiles.add(new Testfile("simple-text.txt", "txt2pdf.pdf"));
		testfiles.add(new Testfile("simple-rtf.rtf", "rtf2pdf.pdf"));
		testfiles.add(new Testfile("simple-emf.emf", "emf2pdf.pdf"));
		testfiles.add(new Testfile("simple-webpage.mht", "mht2pdf.pdf"));
		testfiles.add(new Testfile("simple-webpage.html", "html2pdf.pdf"));

		boolean err = false;
		try{
			if (ConvertPrinter.isInstalled("PDFTron PDFNet"))
			{
				ConvertPrinter.setPrinterName("PDFTron PDFNet");
			}
			else if (!ConvertPrinter.isInstalled())
			{
				try
				{
					System.out.println("Installing printer (requires Windows platform and administrator)");
					ConvertPrinter.install();
					System.out.println("Installed printer " + ConvertPrinter.getPrinterName());
					// the function ConvertToXpsFromFile may require the printer so leave it installed
					// uninstallPrinterWhenDone = true;
				}
				catch (PDFNetException e)
				{
					System.out.println("ERROR: Unable to install printer.");
					System.out.println(e);
					err = true;
				}
				catch (Exception e)
				{
					System.out.println("ERROR: Unable to install printer. Make sure that the package's bitness matches your operating system's bitness and that you are running with administrator privileges.");
				}
			}
		}
		catch (PDFNetException e)
		{
			System.out.println("ERROR: Unable to install printer.");
			System.out.println(e);
			err = true;
		}
		
		for (Testfile file : testfiles)
		{
			try (PDFDoc pdfdoc = new PDFDoc())
			{
				if (Convert.requiresPrinter(inputPath + file.inputFile))
				{
					System.out.println("Using PDFNet printer to convert file " + file.inputFile);
				}
				Convert.toPdf(pdfdoc, inputPath + file.inputFile);
				pdfdoc.save(outputPath + file.outputFile, SDFDoc.SaveMode.LINEARIZED, null);
				System.out.println("Converted file: " + file.inputFile);
				System.out.println("to: " + file.outputFile);
			}
			catch (PDFNetException e)
			{
				System.out.println("ERROR: on input file " + file.inputFile);
				System.out.println(e);
				err = true;
			}
		}

		return err;
	}

	/// <summary>
	/// The main entry point for the application.
	/// </summary>
	public static void main(String[] args) 
	{
		if (System.getProperty("os.name").startsWith("Windows")) {
			
			PDFNet.initialize(PDFTronLicense.Key());
			boolean err = false;

			err = ConvertToPdfFromFile();
			if (err)
			{
				System.out.println("ConvertFile failed");
			}
			else
			{
				System.out.println("ConvertFile succeeded");
			}

			err = ConvertSpecificFormats();
			if (err)
			{
				System.out.println("ConvertSpecificFormats failed");
			}
			else
			{
				System.out.println("ConvertSpecificFormats succeeded");
			}
			
			try
			{
				System.out.println("Uninstalling printer (requires Windows platform and administrator)");
				ConvertPrinter.uninstall();
				System.out.println("Uninstalled printer " + ConvertPrinter.getPrinterName());
			}
			catch (Exception e)
			{
				System.out.println("Unable to uninstall printer");
				err = true;
			}
			
			System.out.println("Done.");

			PDFNet.terminate();
		}
		else {
			System.out.println("ConvertPrintTest only available on Windows");
		}
	}

}
```

{% 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 convert to PDF with virtual printer on Windows.
// It supports several input formats like docx, xlsx, rtf, txt, html, pub, emf, etc. For more details, visit 
// https://docs.apryse.com/windows/guides/features/conversion/convert-other/
//
// To check if ToPDF (or ToXPS) require that PDFNet printer is installed use Convert::RequiresPrinter(filename). 
// The installing application must be run as administrator. The manifest for this sample 
// specifies appropriate the UAC elevation.
//
// Note: the PDFNet printer is a virtual XPS printer supported on Vista SP1 and Windows 7.
// For Windows XP SP2 or higher, or Vista SP0 you need to install the XPS Essentials Pack (or 
// equivalent redistributables). You can download the XPS Essentials Pack from:
//		http://www.microsoft.com/downloads/details.aspx?FamilyId=B8DCFFDD-E3A5-44CC-8021-7649FD37FFEE&displaylang=en
// Windows XP Sp2 will also need the Microsoft Core XML Services (MSXML) 6.0:
// 		http://www.microsoft.com/downloads/details.aspx?familyid=993C0BCF-3BCF-4009-BE21-27E85E1857B1&displaylang=en
//
// Note: Convert.fromEmf and Convert.toEmf will only work on Windows and require GDI+.
//
// Please contact us if you have any questions.	
//---------------------------------------------------------------------------------------

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

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

  let Testfile = function (inputFile, outputFile) {
    this.inputFile = inputFile;
    this.outputFile = outputFile;
  }

  const testfiles = [
    new Testfile('simple-word_2007.docx', 'docx2pdf.pdf'),
    new Testfile('simple-powerpoint_2007.pptx', 'pptx2pdf.pdf'),
    new Testfile('simple-excel_2007.xlsx', 'xlsx2pdf.pdf'),
    new Testfile('simple-publisher.pub', 'pub2pdf.pdf'),
    new Testfile('simple-text.txt', 'txt2pdf.pdf'),
    new Testfile('simple-rtf.rtf', 'rtf2pdf.pdf'),
    new Testfile('simple-emf.emf', 'emf2pdf.pdf'),
    new Testfile('simple-webpage.mht','mht2pdf.pdf'),
    new Testfile('simple-webpage.html', 'html2pdf.pdf'),
  ]



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

  exports.runConvertPrintTest = () => {

    const main = async () => {
    if (process.platform === 'win32') {	
      try {
        await convertToPdfFromFile();
        console.log('ConvertFile succeeded');
      } catch (err) {
        console.log('ConvertFile failed');
        console.log(err);
      }

      try {
        await convertSpecificFormats();
        console.log('ConvertSpecificFormats succeeded');
      } catch (err) {
        console.log('ConvertSpecificFormats failed');
        console.log(err);
      }
      if (await PDFNet.Convert.printerIsInstalled()) {
        try {
          console.log('Uninstalling printer (requires Windows platform and administrator)');
          await PDFNet.Convert.printerUninstall();
          console.log('Uninstalled printer ' + await PDFNet.Convert.printerGetPrinterName());
        } catch (err) {
          console.log('Unable to uninstall printer');
        }
      }
      console.log('Done.');
    }
    else {
        console.log('ConvertPrintTest only available on Windows');	  
    }
    };

    const convertToPdfFromFile = async () => {
        if (await PDFNet.Convert.printerIsInstalled('PDFTron PDFNet')) {
          await PDFNet.Convert.printerSetPrinterName('PDFTron PDFNet');
        } else if (!(await PDFNet.Convert.printerIsInstalled())) {
          try {
            // This will fail if not run as administrator. Harmless if PDFNet 
            // printer already installed
            console.log('Installing printer (requires Windows platform and administrator)');
            await PDFNet.Convert.printerInstall();
            console.log('Installed printer ' + await PDFNet.Convert.printerGetPrinterName());
          } catch (err) {
            console.log('Unable to install printer');
          }
        }
      for (const testfile of testfiles) {

        try {
          const pdfdoc = await PDFNet.PDFDoc.create();
          await pdfdoc.initSecurityHandler();
          const inputFile = inputPath + testfile.inputFile;
          const outputFile = outputPath + testfile.outputFile;
          if (await PDFNet.Convert.requiresPrinter(inputFile)) {
            console.log('Using PDFNet printer to convert file ' + testfile.inputFile);
          }
          await PDFNet.Convert.toPdf(pdfdoc, inputFile);
          await pdfdoc.save(outputFile, PDFNet.SDFDoc.SaveOptions.e_linearized);
          console.log('Converted file: ' + testfile.inputFile + '\nto: ' + testfile.outputFile);
        } catch (err) {
          console.log('Unable to convert file ' + testfile.inputFile);
          console.log(err);
        }
      }
    };

    const convertSpecificFormats = async () => {

        try {
          // Convert MSWord document to XPS
          console.log('Converting DOCX to XPS');
          await PDFNet.Convert.fileToXps(inputPath + 'simple-word_2007.docx', outputPath + 'simple-word_2007.xps');
          console.log('Saved simple-word_2007.xps');
        } catch (err) {
          console.log(err);
        }
        try {
          const pdfdoc = await PDFNet.PDFDoc.create();
          await pdfdoc.initSecurityHandler();

          console.log('Converting from EMF');
          await PDFNet.Convert.fromEmf(pdfdoc, inputPath + 'simple-emf.emf');
          await pdfdoc.save(outputPath + 'emf2pdf v2.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
          console.log('Saved emf2pdf v2.pdf');
        } catch (err) {
          console.log(err);
        }
    };
    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function(error) {
      console.log('Error: ' + JSON.stringify(error));
    }).then(function(){ return PDFNet.shutdown(); });
  };
  exports.runConvertPrintTest();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=ConvertPrintTest.js
```

{% endcode %}
{% endtab %}

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

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

Imports System
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports pdftron
Imports pdftron.Common
Imports pdftron.Filters
Imports pdftron.SDF
Imports pdftron.PDF

' The following sample illustrates how to convert to PDF with virtual printer on Windows.
' It supports several input formats like docx, xlsx, rtf, txt, html, pub, emf, etc. For more details, visit 
' https://docs.apryse.com/windows/guides/features/conversion/convert-other/
' 
' To check if ToPDF (or ToXPS) require that PDFNet printer is installed use Convert::RequiresPrinter(filename). 
' The installing application must be run as administrator. The manifest for this sample 
' specifies appropriate the UAC elevation.
' 
' Note: the PDFNet printer is a virtual XPS printer supported on Vista SP1 and Windows 7, or .NET Framework
' 3.x or higher. For older versions of .NET Framework running on Windows XP or Vista SP0 you need to install 
' the XPS Essentials Pack (or equivalent redistributables). 
' 
' Also note that conversion under ASP.NET can be tricky to configure. Please see the following document for advice: 
' http://www.pdftron.com/pdfnet/faq_files/Converting_Documents_in_Windows_Service_or_ASP.NET_Application_using_PDFNet.pdf
Module ConvertPrintTestVB
    Class Testfile
        Public inputFile, outputFile As String

        Public Sub New(ByVal inFile As String, ByVal outFile As String)
            inputFile = inFile
            outputFile = outFile
        End Sub
    End Class

    Class Class1
        Shared pdfNetLoader As pdftron.PDFNetLoader = pdftron.PDFNetLoader.Instance()

        Shared Sub New()
        End Sub

        Const inputPath As String = "../../../../TestFiles/"
        Const outputPath As String = "../../../../TestFiles/Output/"

        Private Shared Function ConvertSpecificFormats() As Boolean
            Dim err As Boolean = False
            Try
                Using pdfdoc As PDFDoc = New PDFDoc()
                    Console.WriteLine("Converting from EMF")
                    pdftron.PDF.Convert.FromEmf(pdfdoc, inputPath & "simple-emf.emf")
                    pdfdoc.Save(outputPath & "emf2pdf v2.pdf", SDFDoc.SaveOptions.e_remove_unused)
                    Console.WriteLine("Saved emf2pdf v2.pdf")
                End Using

            Catch e As PDFNetException
                Console.WriteLine(e.Message)
                err = True
            End Try

            Try
                Console.WriteLine("Converting DOCX to XPS")
                pdftron.PDF.Convert.ToXps(inputPath & "simple-word_2007.docx", outputPath & "simple-word_2007.xps")
                Console.WriteLine("Saved simple-word_2007.xps")
            Catch e As PDFNetException
                Console.WriteLine(e.Message)
                err = True
            End Try

            Return err
        End Function

        Private Shared Function ConvertToPdfFromFile() As Boolean
            Dim testfiles As System.Collections.ArrayList = New System.Collections.ArrayList()
            testfiles.Add(New ConvertPrintTestVB.Testfile("simple-powerpoint_2007.pptx", "pptx2pdf.pdf"))
            testfiles.Add(New ConvertPrintTestVB.Testfile("simple-text.txt", "txt2pdf.pdf"))
            testfiles.Add(New ConvertPrintTestVB.Testfile("simple-word_2007.docx", "docx2pdf.pdf"))
            testfiles.Add(New ConvertPrintTestVB.Testfile("simple-rtf.rtf", "rtf2pdf.pdf"))
            testfiles.Add(New ConvertPrintTestVB.Testfile("simple-excel_2007.xlsx", "xlsx2pdf.pdf"))
            testfiles.Add(New ConvertPrintTestVB.Testfile("simple-publisher.pub", "pub2pdf.pdf"))
            testfiles.Add(New ConvertPrintTestVB.Testfile("simple-emf.emf", "emf2pdf.pdf"))
            testfiles.Add(New ConvertPrintTestVB.Testfile("simple-webpage.mht", "mht2pdf.pdf"))
            testfiles.Add(New ConvertPrintTestVB.Testfile("simple-webpage.html", "html2pdf.pdf"))
            Dim err As Boolean = False

            Try
                If pdftron.PDF.Convert.Printer.IsInstalled("PDFTron PDFNet") Then
                    pdftron.PDF.Convert.Printer.SetPrinterName("PDFTron PDFNet")
                ElseIf Not pdftron.PDF.Convert.Printer.IsInstalled() Then

                    Try
                        Console.WriteLine("Installing printer (requires Windows platform and administrator)")
                        pdftron.PDF.Convert.Printer.Install()
                        Console.WriteLine("Installed printer " & pdftron.PDF.Convert.Printer.GetPrinterName())
                    Catch e As PDFNetException
                        Console.WriteLine("ERROR: Unable to install printer.")
                        Console.WriteLine(e.Message)
                        err = True
                    Catch
                        Console.WriteLine("ERROR: Unable to install printer. Make sure that the package's bitness matches your operating system's bitness and that you are running with administrator privileges.")
                    End Try
                End If

            Catch e As PDFNetException
                Console.WriteLine("ERROR: Unable to install printer.")
                Console.WriteLine(e.Message)
                err = True
            End Try

            For Each file As Testfile In testfiles

                Try

                    Using pdfdoc As pdftron.PDF.PDFDoc = New PDFDoc()

                        If pdftron.PDF.Convert.RequiresPrinter(inputPath & file.inputFile) Then
                            Console.WriteLine("Using PDFNet printer to convert file " & file.inputFile)
                        End If

                        pdftron.PDF.Convert.ToPdf(pdfdoc, inputPath & file.inputFile)
                        pdfdoc.Save(outputPath & file.outputFile, SDFDoc.SaveOptions.e_linearized)
                        Console.WriteLine("Converted file: " & file.inputFile)
                        Console.WriteLine("to: " & file.outputFile)
                    End Using

                Catch e As PDFNetException
                    Console.WriteLine("ERROR: on input file " & file.inputFile)
                    Console.WriteLine(e.Message)
                    err = True
                End Try
            Next

            Return err
        End Function

        <STAThread>
        Shared Sub Main(ByVal args As String())
            ' Virtual printer only available on Windows
            If Environment.OSVersion.Platform = PlatformID.Win32NT Then
                PDFNet.Initialize(PDFTronLicense.Key)
                Dim err As Boolean = False
                err = ConvertToPdfFromFile()

                If err Then
                    Console.WriteLine("ConvertFile failed")
                Else
                    Console.WriteLine("ConvertFile succeeded")
                End If

                err = ConvertSpecificFormats()

                If err Then
                    Console.WriteLine("ConvertSpecificFormats failed")
                Else
                    Console.WriteLine("ConvertSpecificFormats succeeded")
                End If

                If pdftron.PDF.Convert.Printer.IsInstalled() Then
                    Try
                        Console.WriteLine("Uninstalling printer (requires Windows platform and administrator)")
                        pdftron.PDF.Convert.Printer.Uninstall()
                        Console.WriteLine("Uninstalled Printer " & pdftron.PDF.Convert.Printer.GetPrinterName())
                    Catch
                        Console.WriteLine("Unable to uninstall printer")
                    End Try
                End If

                PDFNet.Terminate()
                Console.WriteLine("Done.")
            Else
                Console.WriteLine("ConvertPrintTest only available on Windows")
            End If
        End Sub
    End Class
End Module
```

{% 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 *
	
import platform

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

#---------------------------------------------------------------------------------------
# The following sample illustrates how to convert to PDF with virtual printer on Windows.
# It supports several input formats like docx, xlsx, rtf, txt, html, pub, emf, etc. For more details, visit 
# https://docs.apryse.com/windows/guides/features/conversion/convert-other/
#
# To check if ToPDF (or ToXPS) require that PDFNet printer is installed use Convert::RequiresPrinter(filename). 
# The installing application must be run as administrator. The manifest for this sample 
# specifies appropriate the UAC elevation.
#
# Note: the PDFNet printer is a virtual XPS printer supported on Vista SP1 and Windows 7.
# For Windows XP SP2 or higher, or Vista SP0 you need to install the XPS Essentials Pack (or 
# equivalent redistributables). You can download the XPS Essentials Pack from:
#		http://www.microsoft.com/downloads/details.aspx?FamilyId=B8DCFFDD-E3A5-44CC-8021-7649FD37FFEE&displaylang=en
# Windows XP Sp2 will also need the Microsoft Core XML Services (MSXML) 6.0:
# 		http://www.microsoft.com/downloads/details.aspx?familyid=993C0BCF-3BCF-4009-BE21-27E85E1857B1&displaylang=en
#
# Note: Convert.fromEmf and Convert.toEmf will only work on Windows and require GDI+.
#
# Please contact us if you have any questions.	
#---------------------------------------------------------------------------------------

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



def ConvertSpecificFormats():
    ret = 0
    try:
        # Convert MSWord document to XPS
        print("Converting DOCX to XPS")
        outputFile = "simple-word_2007.xps"
        Convert.ToXps(inputPath + "simple-word_2007.docx", outputPath + outputFile)
        print("Saved " + outputFile)
    except:
        ret = 1

    try:
        # Start with a PDFDoc to collect the converted documents
        pdfdoc = PDFDoc() 
        # Convert the EMF document to PDF
        s1 = inputPath + "simple-emf.emf"
        print("Converting from EMF")
        Convert.FromEmf(pdfdoc, s1)
        outputFile = "emf2pdf v2.pdf"
        pdfdoc.Save(outputPath + outputFile, SDFDoc.e_remove_unused)
        print("Saved " + outputFile)
    except:
        ret = 1
    return ret

# convert from a file to PDF automatically
def ConvertToPdfFromFile():
    testfiles = [
    [ "simple-word_2007.docx","docx2pdf.pdf"],
    [ "simple-powerpoint_2007.pptx","pptx2pdf.pdf"],
    [ "simple-excel_2007.xlsx","xlsx2pdf.pdf"],
    [ "simple-publisher.pub","pub2pdf.pdf"],
    [ "simple-text.txt","txt2pdf.pdf"],
    [ "simple-rtf.rtf","rtf2pdf.pdf"],
    [ "simple-emf.emf","emf2pdf.pdf"],
    [ "simple-webpage.mht","mht2pdf.pdf"],
    [ "simple-webpage.html","html2pdf.pdf"]
    ]
    ret = 0

    try:
        if ConvertPrinter.IsInstalled("PDFTron PDFNet"):
            ConvertPrinter.SetPrinterName("PDFTron PDFNet")
        elif not ConvertPrinter.isInstalled():
            try:
                print("Installing printer (requires Windows platform and administrator)")
                ConvertPrinter.Install()
                print("Installed printer " + ConvertPrinter.getPrinterName())
                # the function ConvertToXpsFromFile may require the printer so leave it installed
                # uninstallPrinterWhenDone = true;
            except:
                print("ERROR: Unable to install printer.")
    except:
        print("ERROR: Unable to install printer.")

    for testfile in testfiles:
        try:
            pdfdoc = PDFDoc()
            inputFile = testfile[0]
            outputFile = testfile[1]
            if Convert.RequiresPrinter(inputPath + inputFile):
                print("Using PDFNet printer to convert file " + inputFile)
            Convert.ToPdf(pdfdoc, inputPath + inputFile)
            pdfdoc.Save(outputPath + outputFile, SDFDoc.e_compatibility)
            pdfdoc.Close()
            print("Converted file: " + inputFile + "\nto: " + outputFile)
        except:
            ret = 1
            print("ERROR: on input file " + inputFile)
    return ret


def main():
    if platform.system() == 'Windows':
        # 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)
        
        # Demonstrate Convert.ToPdf and Convert.Printer
        err = ConvertToPdfFromFile()
        if err:
            print("ConvertFile failed")
        else:
            print("ConvertFile succeeded")

        # Demonstrate Convert.[FromEmf, FromXps, ToEmf, ToSVG, ToXPS]
        err = ConvertSpecificFormats()
        if err:
            print("ConvertSpecificFormats failed")
        else:
            print("ConvertSpecificFormats succeeded")

        try:
            print("Uninstalling printer (requires Windows platform and administrator)")
            ConvertPrinter.Uninstall()
            print("Uninstalled printer " + ConvertPrinter.getPrinterName())
        except:
            print("Unable to uninstall printer")

        PDFNet.Terminate()
        print("Done.")
    else:
        print("ConvertPrintTest only available on Windows")

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

{% 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/convertprinttest.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.
