2013-04-24 75 views
0

打印完整的文档目前我正忙着与发展中国家其中PDF转换成PNG,并使用PNG图像打印出来到打印机的应用程序。与PySide/QT

的问题是,我可以打印出的图像,但我不知道如何调整它的方式,它总是在纸上全尺寸。 Offcourse我想设置一些边距,但图像必须按照适合的方式重新调整大小。

的问题是,我真的没有线索如何做到这一点,因为文档是非常有限的。

这是我当前的代码打印的图像:

#set up printer 
printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution) 
printer.setPrinterName('Adobe PDF') #I print to my Adobe PDF software printer 
#set up image 
image = QtGui.QImage(pngFiles[0]) 
#paint & print 
painter = QtGui.QPainter() 
painter.begin(printer) 
painter.drawImage(100,100, image) 
painter.end() 

我认为解决的办法是在这一行: painter.drawImage(100,100,图像)

它使图像的保证金100从侧面,但它不缩放。如何以适合文档的方式缩放图像?我特别寻找一种解决方案,它看起来像打印机的默认文档大小。

回答

0

根据与Sashoalm谈话,我可以做调整图像大小,并很好地适应到纸张上进行打印。我已经剥离了我的expirmental代码,它应该像这样工作。

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. 
0

可以使用QPrinter::paperSize获取文档的大小。

对于调整大小绘制时它的图像,使用的QPainter::drawImage重载的版本,这需要QRectF,而不是一个QPoint。图像将被缩放以适合目的QRectF。

+0

我真的不明白你说的是什么,对不起。顺便说一下,我只有有限的python经验,我使用Qt与C++。为什么这些功能不适合你? – sashoalm 2013-04-24 15:28:18

+0

我在您回答的同时删除了我的评论。 我完全不理解你。当我这样做时:papersize = QtGui.QPrinter.paperSize(打印机)。纸张大小是PySide.QtGui.QPrinter.PageSize.A4 ..一直到现在呢?还是我必须执行它不同? 也许你可以告诉我你将如何在C++代码中完成它,也许我可以将它翻译成Python。 – Ecno92 2013-04-24 16:32:21

+0

所以你的问题解决了 - paperSize给了你PageSize - 它是A4。你还需要什么? A4是标准纸张尺寸,您知道吗?请参阅http://en.wikipedia.org/wiki/Paper_size – sashoalm 2013-04-24 16:34:55