Print preview and print PDF in PyQT5

paolo at paolodestefani.it paolo at paolodestefani.it
Sun Jun 14 09:33:11 BST 2020


Il 12/06/2020 13:08 Justin Giffard ha scritto:
> Good afternoon
> 
> I'm looking for a way to make a print preview and print a PDF. I've
> tried various things including trying to use a webview and print from
> there without much success.
> 
> Currently I am generating a PDF with reportlab but ideally what I want
> is to be able view the document after the pdf is generated (based on
> data fetched from a database) and then if need be press cancel to
> alter the parameters and then view it again then chose which printer I
> want to print to and then print. Thus far I haven't had much luck
> other than making the app open the document in an external browser /
> external PDF viewer and then printing from there or blindly printing
> to the default printer.
> 
> I appreciate any advice
> 
> Justin

For printing in PyQt basically you can:
- use the print method of QTextDocument, you can use setHtml method to 
put your text in the document or create a QTextDocument programmatically 
using a QTextCursor
- use a QPainter to draw in a QPaintDevice

I use the second approach in my PyQt applications. For generating a PDF 
file you ca use QPdfWriter as a paint device.

Creating a page in this way means doing something like:

painter = QPainter()
painter.begin(printer)
painter.drawImage(QRectF(self.left,
                                      top,
                                      self.width,
                                      height),
                               self.value,
                               source)

painter.drawText(QRectF(self.left,
                                 top,
                                 self.width,
                                 height),
                          flags,
                          text)

painter.end()

For a print preview a QPrintPreviewDialog is available.

I think a lot of information and examples are available in the net just 
use google...
For example:
https://stackoverflow.com/questions/8193920/how-to-use-qprinter-and-qprintpreviewdialog
https://www.pythonstudio.us/pyqt-programming/printing-documents-using-qpainter.html



More information about the PyQt mailing list