You can specify which permission you want to use in the constructor when creating QPrinter. Then, after you set the page size, you can use the width
, height
and resolution
on the printer to crop these values, this is what I got for the letters (the dpi values โโmay be different, they depend on the screen or printer):
QPrinter(QPrinter.ScreenResolution) # 96dpi, 752x992 QPrinter(QPrinter.PrinterResolution) # 72dpi, 564x744 QPrinter(QPrinter.HighResolution) # 1200dpi, 9400x12400
You can also configure dpi with setResolution
. The size returned in width and height is the page size (the same as pageRect (). Size ()), which does not match the paper size - since the page also has margins that you can set as follows:
printer.setPageMargins(12, 16, 12, 20, QPrinter.Millimeter)
this sets the left and right margins to 12 mm, from above to 16 mm and from below to 20 mm - for example, if you want less free space, you can simply use smaller values. And you should set the size of the document to the size of the resulting size:
document.setPageSize(QSizeF(printer.pageRect().size()))
as you noticed yourself, a subset of html and css is allowed very limited, especially for formatting tables. But instead of using the bottom border on the table, you can just use hr, which will probably look the way you want. At least it doesn't look so bad if I test it like this:
from PyQt4.QtGui import * from PyQt4.QtCore import * a=QApplication([]) document = QTextDocument() html = """ <head> <title>Report</title> <style> </style> </head> <body> <table width="100%"> <tr> <td><img src="{}" width="30"></td> <td><h1>REPORT</h1></td> </tr> </table> <hr> <p align=right><img src="{}" width="300"></p> <p align=right>Sample</p> </body> """.format('', '') document.setHtml(html) printer = QPrinter() printer.setResolution(96) printer.setPageSize(QPrinter.Letter) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName("test.pdf") printer.setPageMargins(12, 16, 12, 20, QPrinter.Millimeter) document.setPageSize(QSizeF(printer.pageRect().size())) print(document.pageSize(), printer.resolution(), printer.pageRect()) document.print_(printer)