Python - wxPython - Impression (example joint).

Ruan - 13 mai 2018 à 18:00
Bonjour,
comment puis-je faire pour prendre en compte/mettre à jour le contenu modifié de mon textCtrl lors de l'impression ou de la prévisualisation ?

Le contenu par défaut est pris en charge, mais dès que je le modifie, le résultat affiché n'est pas le bon.

Source :

--------------------------------------------------------------------------------------------------------------------------

import sys
import os
import wx

BUFFERED = 1

#-------------------------------------------------------------------------------

class My_Canvas(wx.ScrolledWindow):
def __init__(self, parent, txt, id=-1, size=wx.DefaultSize): ########## ICI
wx.ScrolledWindow.__init__(self, parent, id,
pos=(0, 0),
size=size,
style=wx.SUNKEN_BORDER)

#------------

self.parent = parent

#------------

self.maxWidth = 1000
self.maxHeight = 1000
self.x = self.y = 0
self.drawing = False

################################## ICI
self.lines = txt

#------------

self.SetBackgroundColour("WHITE")

#------------

self.SetVirtualSize((self.maxWidth, self.maxHeight))
self.SetScrollRate(30, 30)

#------------

if BUFFERED:
# Initialize the buffer bitmap. No real DC is needed at this point
#self.buffer = wx.EmptyBitmap(self.maxWidth, self.maxHeight)
self.buffer = wx.Bitmap(self.maxWidth, self.maxHeight)
dc = wx.BufferedDC(None, self.buffer)
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
self.DoDrawing(dc)

#------------

# Bind a paint event to an events handler
self.Bind(wx.EVT_PAINT, self.OnPaint)

#---------------------------------------------------------------------------

def GetWidth(self):
return self.maxWidth


def GetHeight(self):
return self.maxHeight


def OnPaint(self, event):
if BUFFERED:
# Create a buffered paint DC. It will create the real
# wx.PaintDC and then blit the bitmap to it when dc is
# deleted. Since we don't need to draw anything else
# here that's all there is to it.
dc = wx.BufferedPaintDC(self, self.buffer, wx.BUFFER_VIRTUAL_AREA)
else:
dc = wx.PaintDC(self)
self.PrepareDC(dc)
# Since we're not buffering in this case, we have to
# (re)paint the all the contents of the window, which can
# be potentially time consuming and flickery depending on
# what is being drawn and how much of it there is.
self.DoDrawing(dc)


def DoDrawing(self, dc, printing=False):
"""
"""

pen = wx.Pen('BLACK', 4, wx.SOLID)

dc.SetTextForeground("BLACK")
dc.SetFont(wx.Font(48, wx.DEFAULT, wx.NORMAL, wx.NORMAL))

##################################################### ICI
dc.DrawText(self.lines, 6, 57)

#-------------------------------------------------------------------------------

class My_Printout(wx.Printout):
"""
"""
def __init__(self, canvas, title):
wx.Printout.__init__(self, title)

#------------

self.canvas = canvas

#---------------------------------------------------------------------------

def OnBeginDocument(self, start, end):
"""
"""

return super(My_Printout, self).OnBeginDocument(start, end)


def OnEndDocument(self):
"""
"""

super(My_Printout, self).OnEndDocument()


def OnBeginPrinting(self):
"""
"""

super(My_Printout, self).OnBeginPrinting()


def OnEndPrinting(self):
"""
"""

super(My_Printout, self).OnEndPrinting()


def OnPreparePrinting(self):
"""
"""

super(My_Printout, self).OnPreparePrinting()


def HasPage(self, page):
"""
"""

if page <= 2:
return True
else:
return False


def GetPageInfo(self):
"""
"""

return (1, 2, 1, 2)


def OnPrintPage(self, page):
"""
"""

dc = self.GetDC()

#------------

# One possible method of setting scaling factors...
maxX = self.canvas.GetWidth()
maxY = self.canvas.GetHeight()

#------------

# Let's have at least 50 device units margin.
marginX = 180
marginY = 180

#------------

# Add the margin to the graphic size.
maxX = maxX + (2 * marginX)
maxY = maxY + (2 * marginY)

#------------

# Get the size of the DC in pixels.
#(w, h) = dc.GetSizeTuple()
(w, h) = dc.GetSize()

# Calculate a suitable scaling factor.
scaleX = float(w) / maxX
scaleY = float(h) / maxY

# Use x or y scaling factor, whichever fits on the DC.
actualScale = min(scaleX, scaleY)

# Calculate the position on the DC for centering the graphic.
posX = (w - (self.canvas.GetWidth() * actualScale)) / 2.0
posY = (h - (self.canvas.GetHeight() * actualScale)) / 2.0

# Set the scale and origin.
dc.SetUserScale(actualScale, actualScale)
dc.SetDeviceOrigin(int(posX), int(posY))

#------------

self.canvas.DoDrawing(dc, True)

return True

#-------------------------------------------------------------------------------

class My_Frame(wx.Frame):
"""
"""
def __init__(self, parent, id, title=""):
wx.Frame.__init__(self,
parent,
id,
title,
size=(600, 367),
style=wx.DEFAULT_FRAME_STYLE)

#------------

# Simplified init method.
self.CreateCtrls()
self.CreatePrintData()
self.BindEvents()
self.DoLayout()

#------------

self.CenterOnScreen()

#---------------------------------------------------------------------------

def CreateCtrls(self):
"""
Make widgets for my app.
"""

font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
font.SetWeight(wx.BOLD)
font.SetPointSize(10)

#------------

# First create the controls.
self.panel = wx.Panel(self,
id=-1,
style=wx.BORDER_THEME|
wx.TAB_TRAVERSAL)

##################################################### ICI

self.tc = wx.TextCtrl(self.panel,
id=-1,
size=(200, -1),
value="Hello, World ! A sample text.")
text = self.tc.GetValue()

self.canvas = My_Canvas(self.panel, text, size=(0, 0))

#####################################################

self.btnSetup = wx.Button(self.panel,
id=wx.ID_PAGE_SETUP,
label="Page set&up")

self.btnPreview = wx.Button(self.panel,
id=wx.ID_PREVIEW,
label="Print Pre&view")

self.btnPrint = wx.Button(self.panel,
id=wx.ID_PRINT,
label="&Print")

self.btnClose = wx.Button(self.panel,
id=wx.ID_CLOSE,
label="E&xit")


def CreatePrintData(self):
"""
Create printing data.
"""

self.printdata = wx.PrintData()

self.printdata.SetPrinterName('')
self.printdata.SetOrientation(wx.PORTRAIT)
self.printdata.SetPaperId(wx.PAPER_A4)
self.printdata.SetQuality(wx.PRINT_QUALITY_DRAFT)
# Black and white printing if (False) :
self.printdata.SetColour(True)
self.printdata.SetNoCopies(1)
self.printdata.SetCollate(True)
# self.printData.SetPrintMode(wx.PRINT_MODE_PRINTER)


def BindEvents(self):
"""
Bind all the events related to my application.
"""

# Bind some menu events to an events handler.
self.Bind(wx.EVT_MENU, self.OnBtnPageSetup, id=wx.ID_PAGE_SETUP)
self.Bind(wx.EVT_MENU, self.OnBtnPreview, id=wx.ID_PREVIEW)
self.Bind(wx.EVT_MENU, self.OnBtnPrint, id=wx.ID_PRINT)
self.Bind(wx.EVT_MENU, self.OnBtnClose, id=wx.ID_EXIT)

# Bind the close event to an event handler.
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

# Bind some buttons events to an events handler.
self.Bind(wx.EVT_BUTTON, self.OnBtnPageSetup, self.btnSetup)
self.Bind(wx.EVT_BUTTON, self.OnBtnPreview, self.btnPreview)
self.Bind(wx.EVT_BUTTON, self.OnBtnPrint, self.btnPrint)
self.Bind(wx.EVT_BUTTON, self.OnBtnClose, self.btnClose)


def DoLayout(self):
"""
"""

mainSizer = wx.BoxSizer(wx.VERTICAL)

#------------

hBox2 = wx.BoxSizer(wx.HORIZONTAL)
hBox2.Add(self.btnSetup, 0, wx.ALL, 10)
hBox2.Add(self.btnPreview, 0, wx.ALL, 10)
hBox2.Add(self.btnPrint, 0, wx.ALL, 10)
hBox2.Add(self.btnClose, 0, wx.ALL, 10)

#------------

mainSizer.Add(wx.StaticLine(self.panel),
0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)
mainSizer.Add(self.tc, 0, wx.ALL, 15)
mainSizer.Add(hBox2, 0, wx.ALL, 5)

#------------

self.panel.SetSizer(mainSizer)


def OnBtnPageSetup(self, event):
"""
"""

psdd = wx.PageSetupDialogData(self.printdata)

psdd.EnablePrinter(True)

#------------

dlg = wx.PageSetupDialog(self, psdd)
dlg.ShowModal()

#------------

# This makes a copy of the wx.PrintData instead of just saving
# a reference to the one inside the PrintDialogData that will
# be destroyed when the dialog is destroyed
self.printdata = wx.PrintData(dlg.GetPageSetupData().GetPrintData())

dlg.Destroy()


def OnBtnPreview(self, event):
"""
"""

data = wx.PrintDialogData(self.printdata)

printout1 = My_Printout(self.canvas, "- Mon document")
printout2 = My_Printout(self.canvas, "- Mon document")

printPreview = wx.PrintPreview(printout1, printout2, data)

# Initial zoom value.
if "__WXMAC__" in wx.PlatformInfo:
printPreview.SetZoom(50)
else:
printPreview.SetZoom(35)

if not printPreview.IsOk():
wx.MessageBox(("Il y a un problème d'impression.\nPeut-être "\
"que votre imprimante n'est \npas "\
"réglée correctement ?"),
("Impression"),
wx.OK)
return

else:
previewFrame = wx.PreviewFrame(printPreview, None, "Prévisualisation")

previewFrame.Initialize()
previewFrame.SetPosition(self.GetPosition())
previewFrame.SetSize(self.GetSize())
previewFrame.Show(True)
previewFrame.Layout()


def OnBtnPrint(self, event):
"""
"""

pdd = wx.PrintDialogData(self.printdata)
pdd.SetPrintData(self.printdata)
pdd.SetMinPage(1)
pdd.SetMaxPage(1)
pdd.SetFromPage(1)
pdd.SetToPage(1)
pdd.SetPrintToFile(False)

#------------

printer = wx.Printer(pdd)

myPrintout = My_Printout(self.canvas, "- Mon document")

if not printer.Print(self, myPrintout, True):
wx.MessageBox(("Il y a un problème d'impression.\nPeut-être "\
"que votre imprimante n'est \npas "\
"réglée correctement ?"),
("Impression"),
wx.OK)
return

else:
self.printData = wx.PrintData(printer.GetPrintDialogData().GetPrintData())
myPrintout.Destroy()


def OnBtnClose(self, event):
"""
"""

self.Close(True)


def OnCloseWindow(self, event):
"""
"""

self.Destroy()

#-------------------------------------------------------------------------------

class My_App(wx.App):
"""
"""
def OnInit(self):

self.locale = wx.Locale(wx.LANGUAGE_FRENCH)

#------------

frame = My_Frame(None, id=-1, title="test")
self.SetTopWindow(frame)
frame.Show(True)

return True

#-------------------------------------------------------------------------------

def main():
app = My_App(False)
app.MainLoop()

#-------------------------------------------------------------------------------

if __name__ == "__main__" :
main()

--------------------------------------------------------------------------------------------------------------------------

Merci d'avance.
Afficher la suite 

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.