user1032355
user1032355

Reputation: 355

How do I print a PDF file to a printer in landscape from Python?

I'm using Mac OSX but I need a platform independent method to print a pdf file. I created a graph in Matplotlib and want to print it to my printer.

I can set the orientation of the canvas to fit a portrait layout with:

fig.set_size_inches(  8.27,11.69) # set the figure size in inches

but using:

fig.set_size_inches( 11.69, 8.27) 

prints a cropped portrait oriented figure

I found this on another post here:

import subprocess
import shlex

printfile='test.pdf'
fig.savefig(printfile)
proc=subprocess.Popen(shlex.split('lpr {f}'.format(f=printfile)))

Can anyone help me with the format of the code to set the print orientation to landscape?

Upvotes: 3

Views: 4240

Answers (1)

David Alber
David Alber

Reputation: 18091

I have seen lpr -o landscape, but do not have enough experience with it to know if it works for all printers.

Rather than changing orientation while printing, you can do it when generating the image (if it fits with your workflow). The matplotlib savefig command allows you to specify saving in landscape orientation, but currently only for postscript. That is not a problem, however, since we can easily convert the postscript file to PDF format. Below is an example.

In Python:

from pylab import *
import numpy as np

x = np.arange(0, 10, 0.1)
y = np.sin(x)
plot(x, y)
xlabel('x')
ylabel('y')
savefig('img.eps', orientation='landscape')

I left out the canvas size for convenience and brevity.

Now we have a file named img.eps. In the shell do the following.

epstopdf img.eps

Here is what the resulting img.pdf file looks like: Landscape image.

One downside to keep in mind with this approach is that postscript does not like transparency, so if you want transparency this is not the approach for you. To see what I mean take the matplotlib patch_collection.py example. Replace the pylab.show() on the last line with pylab.savefig('patch.pdf'), run it, and then look at the resulting PDF file. It will look like the image in the example. If, however, you do pylab.savefig('patch.eps'), you will see that the objects are all opaque.

Upvotes: 2

Related Questions