How to set QTextDocument margins and other properties (setHTML, print to pdf)?

后端 未结 1 895
梦毁少年i
梦毁少年i 2020-12-16 19:46

I have the following certificate class for producing pdf document out of some images and data. After setting image sources, I call generate() funct

相关标签:
1条回答
  • 2020-12-16 20:24

    You can specify what resolution you want to use in the constructor when you create the QPrinter. Then after you've set the pagesize, you can use width, height and resolution on the printer to fint out that values, here's what I got for Letter (dpi-values can be different, they depend on the screen or the printer):

    QPrinter(QPrinter.ScreenResolution)   #   96dpi,  752x992
    QPrinter(QPrinter.PrinterResolution)  #   72dpi,  564x744
    QPrinter(QPrinter.HighResolution)     # 1200dpi, 9400x12400
    

    You can also set the dpi directly using setResolution. The size returned by width and height is the page size (same as pageRect().size()), which ist not the same as the paper size - as the page also has margins, which you can set like this:

    printer.setPageMargins(12, 16, 12, 20, QPrinter.Millimeter)
    

    this sets left and right margins to 12mm, top to 16mm and bottom to 20mm - just for example, if you want less white space you can obviously just use smaller values. And you should set the document size to the size of the resulting size:

    document.setPageSize(QSizeF(printer.pageRect().size()))
    

    as you've noticed yourself, the subset of html and css allowed is very limited, specially for formatting tables. But instead of using a lower border on the table you could just use a hr, which probably will look like you want it. At least it doesn't look that 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)
    
    0 讨论(0)
提交回复
热议问题