Convert File Types with Virtual Printer on Windows - Python Sample Code

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.

1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6import site
7site.addsitedir("../../../PDFNetC/Lib")
8import sys
9from PDFNetPython import *
10
11import platform
12
13sys.path.append("../../LicenseKey/PYTHON")
14from LicenseKey import *
15
16#---------------------------------------------------------------------------------------
17# The following sample illustrates how to convert to PDF with virtual printer on Windows.
18# It supports several input formats like docx, xlsx, rtf, txt, html, pub, emf, etc. For more details, visit
19# https://docs.apryse.com/windows/guides/features/conversion/convert-other/
20#
21# To check if ToPDF (or ToXPS) require that PDFNet printer is installed use Convert::RequiresPrinter(filename).
22# The installing application must be run as administrator. The manifest for this sample
23# specifies appropriate the UAC elevation.
24#
25# Note: the PDFNet printer is a virtual XPS printer supported on Vista SP1 and Windows 7.
26# For Windows XP SP2 or higher, or Vista SP0 you need to install the XPS Essentials Pack (or
27# equivalent redistributables). You can download the XPS Essentials Pack from:
28# http://www.microsoft.com/downloads/details.aspx?FamilyId=B8DCFFDD-E3A5-44CC-8021-7649FD37FFEE&displaylang=en
29# Windows XP Sp2 will also need the Microsoft Core XML Services (MSXML) 6.0:
30# http://www.microsoft.com/downloads/details.aspx?familyid=993C0BCF-3BCF-4009-BE21-27E85E1857B1&displaylang=en
31#
32# Note: Convert.fromEmf and Convert.toEmf will only work on Windows and require GDI+.
33#
34# Please contact us if you have any questions.
35#---------------------------------------------------------------------------------------
36
37# Relative path to the folder containing the test files.
38inputPath = "../../TestFiles/"
39outputPath = "../../TestFiles/Output/"
40
41
42
43def ConvertSpecificFormats():
44 ret = 0
45 try:
46 # Convert MSWord document to XPS
47 print("Converting DOCX to XPS")
48 outputFile = "simple-word_2007.xps"
49 Convert.ToXps(inputPath + "simple-word_2007.docx", outputPath + outputFile)
50 print("Saved " + outputFile)
51 except:
52 ret = 1
53
54 try:
55 # Start with a PDFDoc to collect the converted documents
56 pdfdoc = PDFDoc()
57 # Convert the EMF document to PDF
58 s1 = inputPath + "simple-emf.emf"
59 print("Converting from EMF")
60 Convert.FromEmf(pdfdoc, s1)
61 outputFile = "emf2pdf v2.pdf"
62 pdfdoc.Save(outputPath + outputFile, SDFDoc.e_remove_unused)
63 print("Saved " + outputFile)
64 except:
65 ret = 1
66 return ret
67
68# convert from a file to PDF automatically
69def ConvertToPdfFromFile():
70 testfiles = [
71 [ "simple-word_2007.docx","docx2pdf.pdf"],
72 [ "simple-powerpoint_2007.pptx","pptx2pdf.pdf"],
73 [ "simple-excel_2007.xlsx","xlsx2pdf.pdf"],
74 [ "simple-publisher.pub","pub2pdf.pdf"],
75 [ "simple-text.txt","txt2pdf.pdf"],
76 [ "simple-rtf.rtf","rtf2pdf.pdf"],
77 [ "simple-emf.emf","emf2pdf.pdf"],
78 [ "simple-webpage.mht","mht2pdf.pdf"],
79 [ "simple-webpage.html","html2pdf.pdf"]
80 ]
81 ret = 0
82
83 try:
84 if ConvertPrinter.IsInstalled("PDFTron PDFNet"):
85 ConvertPrinter.SetPrinterName("PDFTron PDFNet")
86 elif not ConvertPrinter.isInstalled():
87 try:
88 print("Installing printer (requires Windows platform and administrator)")
89 ConvertPrinter.Install()
90 print("Installed printer " + ConvertPrinter.getPrinterName())
91 # the function ConvertToXpsFromFile may require the printer so leave it installed
92 # uninstallPrinterWhenDone = true;
93 except:
94 print("ERROR: Unable to install printer.")
95 except:
96 print("ERROR: Unable to install printer.")
97
98 for testfile in testfiles:
99 try:
100 pdfdoc = PDFDoc()
101 inputFile = testfile[0]
102 outputFile = testfile[1]
103 if Convert.RequiresPrinter(inputPath + inputFile):
104 print("Using PDFNet printer to convert file " + inputFile)
105 Convert.ToPdf(pdfdoc, inputPath + inputFile)
106 pdfdoc.Save(outputPath + outputFile, SDFDoc.e_compatibility)
107 pdfdoc.Close()
108 print("Converted file: " + inputFile + "\nto: " + outputFile)
109 except:
110 ret = 1
111 print("ERROR: on input file " + inputFile)
112 return ret
113
114
115def main():
116 if platform.system() == 'Windows':
117 # The first step in every application using PDFNet is to initialize the
118 # library. The library is usually initialized only once, but calling
119 # Initialize() multiple times is also fine.
120 PDFNet.Initialize(LicenseKey)
121
122 # Demonstrate Convert.ToPdf and Convert.Printer
123 err = ConvertToPdfFromFile()
124 if err:
125 print("ConvertFile failed")
126 else:
127 print("ConvertFile succeeded")
128
129 # Demonstrate Convert.[FromEmf, FromXps, ToEmf, ToSVG, ToXPS]
130 err = ConvertSpecificFormats()
131 if err:
132 print("ConvertSpecificFormats failed")
133 else:
134 print("ConvertSpecificFormats succeeded")
135
136 try:
137 print("Uninstalling printer (requires Windows platform and administrator)")
138 ConvertPrinter.Uninstall()
139 print("Uninstalled printer " + ConvertPrinter.getPrinterName())
140 except:
141 print("Unable to uninstall printer")
142
143 PDFNet.Terminate()
144 print("Done.")
145 else:
146 print("ConvertPrintTest only available on Windows")
147
148if __name__ == '__main__':
149 main()

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales