Printing images through Python

Tim Golden tim.golden at viacom-outdoor.co.uk
Fri Oct 3 04:49:00 EDT 2003


> From: Kevin [mailto:other at cazabon.com]
> Does ANYONE have Python code to print PIL images?

It just so happens that I've been going through the same bit of grief
recently. Depending on just how much control you want, I advocate two
approaches, with several others possible if I had more time to explore the,
frankly arcane, possibilities offered by the Win32 SDK:

1) Use ReportLab's PDF generator to embed the image. Get the ReportLab docs
(http://www.reportlab.com/docs/userguide.pdf) and search for InlineImage. If
you need a code example I can give you one, but it's pretty straightforward.
This has the advantage that you can then call whatever Acrobat viewer you
want in print mode (eg acrord32.exe /p) to give the user the chance to
select the printer, paper size etc. You can even get Acrobat to print using
defaults without asking the user anything (can't remember the switch).

2) If you want quick-and-dirty, make use of the fact that Device-Independent
Bitmaps are *much* easier to work with in Windows than the convention
HBITMAP variety. So (with minimal comments):

<code>
import win32ui
import win32gui
import win32con
from PIL import Image, ImageWin

#
# Constants for GetDeviceCaps 
#
HORZRES = 8
VERTRES = 10

#
# Find the printer resolution to scale to
#
hDC = win32ui.CreateDC ()
hDC.CreatePrinterDC () # can optionally put a printer name in here
printer_resolution = hDC.GetDeviceCaps (HORZRES), hDC.GetDeviceCaps
(VERTRES)
print "printer resolution =", printer_resolution

#
# Open the bitmap and rotate because we know it's
#  really landscape
#
bmp = Image.open ("screen.bmp")
print "original bitmap size =", bmp.size
bmp = bmp.rotate (90)
print "rotated bitmap size =", bmp.size

#
# Resize the image to fit the page but not to overflow
#
ratios = [1.0 * printer_resolution[0] / bmp.size[0], 1.0 *
printer_resolution[1] / bmp.size[1]]
print "ratios =", ratios
scale = min (ratios)
print "scale =", scale

#
# Create the printer document and send the page
#
hDC.StartDoc ("Test")
hDC.StartPage ()

dib = ImageWin.Dib (bmp)
scaled_size = [scale * i for i in bmp.size]
print "scaled bitmap size =", scaled_size
dib.draw (hDC.GetHandleOutput (), [0, 0] + scaled_size)

hDC.EndPage ()
hDC.EndDoc ()
</code>

HTH. 
TJG

________________________________________________________________________
This e-mail has been scanned for all viruses by Star Internet. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
________________________________________________________________________





More information about the Python-list mailing list