Calling Prince from Python

Prince can be called from Python using the command-line interface, like this:

import subprocess

subprocess.call(["prince","foo.xml","bar.pdf"]);

It is possible to write XML to Prince directly from the Python script rather than have Prince read it from an external file:

from subprocess import *

p = Popen(["prince","-","out.pdf"], stdin=PIPE)

p.stdin.write("<html><body><h1>Hello, world!</h1></body></html>")
p.stdin.close()

(The first filename argument of "-" instructs Prince to read the XML from its standard input stream rather than from a file).

For Python CGI scripts, the PDF output can be written to the standard output stream so that it is returned to the browser:

from subprocess import *

p = Popen(["prince","-"], stdin=PIPE)

p.stdin.write("<html><body><h1>Hello, world!</h1></body></html>")
p.stdin.close()

(Because the second filename argument has been omitted and the XML is being read from standard input, the PDF will be written to standard output. Be careful to redirect the output of this script if you try running it from the terminal).

Alternatively, it is possible for the Python script to read the PDF output directly rather than have Prince save it to an external file:

from subprocess import *

p = Popen(["prince","-"], stdin=PIPE, stdout=PIPE)

p.stdin.write("<html><body><h1>Hello, world!</h1></body></html>")
p.stdin.close()

pdf = p.stdout.read()

print("PDF is "+str(len(pdf))+" bytes in size")