Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt print multiple pages to PDF only get last page

I am have a problem where I am trying to print out a QWebView/QTextDocument to a multi-page PDF, however no matter what I do I only get a single page PDF with the last page. I am using the printer.newPage() command as most examples show, yet I always get the same result. This program exhibits the problem for me (using QTextDocument, QWebView gives the same result):

from PyQt4.QtGui import QTextDocument, QPrinter, QApplication

import sys
app = QApplication(sys.argv)

doc = QTextDocument()
doc.setHtml('''
<html>
<body>
<h1>Page 1</h1>
</body>
</html>
''')

printer = QPrinter()
printer.setOutputFileName("foo.pdf")
printer.setOutputFormat(QPrinter.PdfFormat)
doc.print_(printer)

doc.setHtml('''
<html>
<body>
<h1>Page 2</h1>
</body>
</html>
''')
printer.newPage()
doc.print_(printer)

print "done!"

Am I making some obvious mistake, or am I misunderstanding the use of newPage() and the ability to make multiple print_ calls on the same printer?

like image 225
aaa90210 Avatar asked Oct 26 '25 08:10

aaa90210


1 Answers

You can't call QPrinter::newPage() without an active QPainter. It should return False in your case.

You can use a QPainter to solve this problem:

doc = QTextDocument()
doc.setHtml('''
<html>
<body>
<h1>Page 1</h1>
</body>
</html>
''')

printer = QPrinter()
printer.setOutputFileName("foo.pdf")
printer.setOutputFormat(QPrinter.PdfFormat)
doc.print_(printer)

# Create a QPainter to draw our content    
painter = QPainter()
painter.begin( printer )

# Draw the first page removing the pageRect offset due to margins.
doc.drawContents(painter, printer.pageRect().translated( -printer.pageRect().x(), -    printer.pageRect().y() ))

doc.setHtml('''
<html>
<body>
<h1>Page 2</h1>
</body>
</html>
''')

# A new page
printer.newPage()

# The second page
doc.drawContents(painter, printer.pageRect().translated( -printer.pageRect().x(), -printer.pageRect().y() ))

# Done.
painter.end()
like image 143
Dimitry Ernot Avatar answered Oct 29 '25 08:10

Dimitry Ernot