根据与 Sashoalm 的对话,我可以调整图像的大小并将其很好地贴合在纸上进行打印。我已经剥离了我的实验代码,它应该像这样工作。
from PIL import Image
imagefile = 'image.png'
def scale(w, h, x, y, maximum=True):
nw = y * w / h
nh = x * h / w
if maximum ^ (nw >= x):
return nw or 1, y
return x, nh or 1
#set up print printer.
printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)
#dlg = QtGui.QPrintDialog(printer, self)
printer.setPrinterName('Adobe PDF')
#check image size with PIL:
image = Image.open(imagefile)
imageWidth, imageHeight = image.size
paperPixels = printer.pageRect(QtGui.QPrinter.DevicePixel)
paperPixels = paperPixels.getRect() #get tuple of the "pixels on the paper"
paperWidth = paperPixels[2]
paperHeight = paperPixels[3]
#set margins for paper
paperMargin = 100
#find out the image size
paperWidth = paperWidth - (paperMargin*2) #times two, for left and right..
paperHeight = paperHeight - (paperMargin*2)
#scale image within a rectangle.
paintWidth, paintHeight = scale(imageWidth, imageHeight, paperWidth, paperHeight, True)
#construct the paint dimensions area
paintRect = QtCore.QRectF(paperMargin, paperMargin, paintWidth, paintHeight)
#start painting
image = QtGui.QImage(imagefile)
painter = QtGui.QPainter()
painter.begin(printer)
painter.drawImage(paintRect, image)
painter.end()
#now the page gets printed out and the image should fit the paper.