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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With