How to use printing framework - Part 4 (Phoenix)
Keywords : Printing, Printout, Preview, Printer, PrintData, PrintDialogData, PageSetupDialogData, PageSetupDialog, PrintPreview, PreviewFrame, Canvas, Grid, HtmlEasyPrinting, PDFViewer, PDFWindow, ReportLab.
Contents
Introduction
The Printer framework for wx.Windows / wx.Python is quite complicated.
Because of this, wx.HtmlEasyPrinting is provided to help simplify basic printing functionality.
This Recipe covers a simplified approach to using both wx.HtmlEasyPrinting and the more complicated wx.Printout.
What Objects are Involved
The following classes will be used in these recipes :
wx.HtmlEasyPrinting -- The simple way to print
wx.Printout -- Base printing class that will be inherited from. Various control functions handling printing events are defined here.
wx.PrintData -- Printer / page configuration data
wx.PrintDialogData -- (same as (wx.PrintData) except what is used by Page Setup window ??)
wx.Printer -- Software interface to the printer
wx.MessageBox -- Used for alerting the user to any problems
wx.PrintPreview -- Used for print preview
wx.PrintDialog -- Window that pops up, asking how many pages to print, etc..
Demonstrating :
Tested py3.x, wx4.x and Win10.
Printing is an essential element for your programs, here we show you how to print.
Are you ready to use some samples ?
Test, modify, correct, complete, improve and share your discoveries !
Special concerns or comments about the Easy Printing approach :
- Very simple to use.
- As powerful as HTML
- Seems to be limited around the capabilities of HTML (e.g. seems to have less control over printing configuration. Please correct me if I'm wrong).
Change the GetHtmlText code to be more appropriate with the kind of text you will be using.
Easy html direct printing
1 # sample_one_a.py
2
3 import os
4 import wx
5 from wx.html import HtmlEasyPrinting
6 from wx.html import HtmlWindow
7
8 # class MyHtmlPrinter
9 # class MyFrame
10 # class MyApp
11
12 #-------------------------------------------------------------------------------
13
14 if os.name == "posix":
15 print("\nPlatform : UNIX - Linux")
16 elif os.name in ['nt', 'dos', 'ce']:
17 print("\nPlatform : Windows")
18 else:
19 print("\nPlatform : ", platform.system())
20
21 #-------------------------------------------------------------------------------
22
23 # Sample html.
24 sample_html = """<html>
25 <body>
26 <h2><FONT COLOR=\"blue\">Sample printing </FONT></h2>
27 <p><B>Vestibulum</B> in tellus non nunc mollis sagittis sit amet ac purus.
28 Nam convallis vulputate tortor nec elementum. Nunc dictum accumsan
29 arcu ut lacinia. Nullam enim neque, consequat quis bibendum vitae,
30 gravida nec arcu. Nullam molestie dapibus sapien quis consectetur.
31 Donec lacinia, ante non faucibus ornare, purus sapien venenatis
32 turpis, ut eleifend lorem purus eu nisl. Pellentesque eget leo a augue
33 ullamcorper interdum at et nibh. Sed aliquet convallis dui, id
34 condimentum orci viverra ac. Morbi quis mauris nisl, vel malesuada
35 libero. Nam eleifend odio velit. Nulla vulputate facilisis mi
36 tincidunt tempus. Nam eu metus elit. <B>Vestibulum</B> ante ipsum primis in
37 faucibus orci luctus et ultrices posuere cubilia Curae; <B>Vestibulum</B> eu
38 risus accumsan leo egestas rutrum vitae in urna. Morbi diam orci,
39 eleifend a tempor sit amet, cursus sit amet est.</p>
40 <p><FONT COLOR=\"red\">WxPython </FONT><B>HtmlEasyPrinting </B>test.</p>
41 </body>
42 </html>"""
43
44 #-------------------------------------------------------------------------------
45
46 class MyHtmlPrinter(HtmlEasyPrinting):
47 """
48 ...
49 """
50 def __init__(self, parent):
51
52 # Get the window name.
53 name = "My document"
54
55 # Init the HtmlEasyPrinting.
56 HtmlEasyPrinting.__init__(self, name, parent)
57
58 # Get the current script directory.
59 self.current_dir = os.path.normpath(os.path.dirname(__file__))
60
61 # Set some default printer and page options.
62 self.GetPrintData().SetPaperId(wx.PAPER_LETTER) # wx.PAPER_A4
63 self.GetPrintData().SetOrientation(wx.LANDSCAPE) # wx.PORTRAIT
64 # Black and white printing if False.
65 self.GetPrintData().SetColour(True)
66 self.GetPageSetupData().SetMarginTopLeft((20, 20))
67 self.GetPageSetupData().SetMarginBottomRight((20, 20))
68
69 #---------------------------------------------------------------------------
70
71 def page_setup(self):
72 """
73 Show page setup.
74 """
75
76 self.PageSetup()
77
78
79 def print_text(self, text):
80 """
81 Print the text.
82 """
83
84 return self.PrintText(text, basepath=self.current_dir)
85
86
87 def preview_text(self, text):
88 """
89 Preview html text.
90 """
91
92 # @DATE @ is replaced by the current date in default format.
93 # @PAGENUM@ is replaced by page number.
94 # @PAGESCNT@ is replaced by total number of pages.
95 # @TIME @ is replaced by the current time in default format.
96 # @TITLE@ is replaced with the title of the document.
97
98 header = "My document"
99 footer = "Page @PAGENUM@ of @PAGESCNT@"
100
101 self.SetHeader(header)
102 self.SetFooter(footer)
103
104 return self.PreviewText(text, basepath=self.current_dir)
105
106
107 def print_file(self, file):
108 """
109 Print the text.
110 """
111
112 return self.PrintFile(file)
113
114
115 def preview_file(self, file):
116 """
117 Preview html file.
118 """
119
120 return self.PreviewFile(file)
121
122 #-------------------------------------------------------------------------------
123
124 class MyFrame(wx.Frame):
125 """
126 Create a main frame for my application.
127 """
128 def __init__ (self, parent, id, title=""):
129 wx.Frame.__init__(self,
130 parent,
131 id,
132 title,
133 size=(600, 610),
134 style=wx.DEFAULT_FRAME_STYLE)
135
136 #------------
137
138 # Simplified init method.
139 self.SetProperties()
140 self.CreateMenu()
141 self.CreateCtrls()
142 self.CreatePrinter()
143 self.BindEvents()
144 self.DoLayout()
145
146 #------------
147
148 self.CenterOnScreen()
149
150 #---------------------------------------------------------------------------
151
152 def SetProperties(self):
153 """
154 Set the main frame properties (title, icon...).
155 """
156
157 frameicon = wx.Icon("Icons/wxWidgets.ico")
158 self.SetIcon(frameicon)
159
160 #------------
161
162 self.SetTitle("Html easy printing...")
163
164
165 def CreateMenu(self):
166 """
167 Make the frame menus.
168 """
169
170 menub = wx.MenuBar()
171
172 fmenu = wx.Menu()
173 fmenu.Append(wx.ID_PAGE_SETUP, "Page set&up\tCtrl+U")
174 fmenu.Append(wx.ID_PREVIEW, "Print pre&view\tCtrl+V")
175 fmenu.Append(wx.ID_PRINT, "&Print\tCtrl+P")
176 fmenu.AppendSeparator()
177 fmenu.Append(wx.ID_EXIT, "E&xit\tCtrl+X")
178 menub.Append(fmenu, "&File")
179
180 self.SetMenuBar(menub)
181
182
183 def CreateCtrls(self):
184 """
185 Make widgets for my application.
186 """
187
188 font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
189 font.SetWeight(wx.BOLD)
190 font.SetPointSize(10)
191
192 #------------
193
194 # First create the controls.
195 self.panel = wx.Panel(self,
196 id=-1,
197 style=wx.BORDER_THEME|
198 wx.TAB_TRAVERSAL)
199
200 self.demo = wx.StaticText(self.panel,
201 id=-1,
202 label="Demonstrating :")
203 self.demo.SetFont(font)
204
205 self.winHtml = HtmlWindow(self.panel,
206 id=-1,
207 style=wx.BORDER_THEME|
208 wx.NO_FULL_REPAINT_ON_RESIZE)
209 self.winHtml.SetPage(sample_html)
210
211 self.info = wx.StaticText(self.panel,
212 id=-1,
213 label="1) Direct printing,\n"
214 "2) HtmlWindow,\n"
215 "3) HtmlEasyPrinting class,\n"
216 "4) Preview,\n"
217 "5) Menu,\n"
218 "6) Page setup.")
219 self.info.SetForegroundColour("red")
220 font.SetWeight(wx.NORMAL)
221 self.info.SetFont(font)
222
223 self.btnSetup = wx.Button(self.panel,
224 id=wx.ID_PAGE_SETUP,
225 label="Page set&up")
226
227 self.btnPreview = wx.Button(self.panel,
228 wx.ID_PREVIEW,
229 label="Pre&view text")
230 self.btnPreview.SetFocus()
231
232 self.btnPrint = wx.Button(self.panel,
233 id=wx.ID_PRINT,
234 label="&Print")
235
236 self.btnClose = wx.Button(self.panel,
237 id=wx.ID_CLOSE,
238 label="E&xit")
239
240
241 def CreatePrinter(self):
242 """
243 Create the printer.
244 """
245
246 self.printer = MyHtmlPrinter(self)
247
248
249 def BindEvents(self):
250 """
251 Bind all the events related to my application.
252 """
253
254 # Bind some menu events to an events handler.
255 self.Bind(wx.EVT_MENU, self.OnBtnPageSetup, id=wx.ID_PAGE_SETUP)
256 self.Bind(wx.EVT_MENU, self.OnBtnPreview, id=wx.ID_PREVIEW)
257 self.Bind(wx.EVT_MENU, self.OnBtnPrint, id=wx.ID_PRINT)
258 self.Bind(wx.EVT_MENU, self.OnBtnClose, id=wx.ID_EXIT)
259
260 # Bind some buttons events to an events handler.
261 self.Bind(wx.EVT_BUTTON, self.OnBtnPageSetup, self.btnSetup)
262 self.Bind(wx.EVT_BUTTON, self.OnBtnPreview, self.btnPreview)
263 self.Bind(wx.EVT_BUTTON, self.OnBtnPrint, self.btnPrint)
264 self.Bind(wx.EVT_BUTTON, self.OnBtnClose, self.btnClose)
265
266 # Bind the close event to an event handler.
267 self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
268
269
270 def DoLayout(self):
271 """
272 Manage widgets Layout.
273 """
274
275 # MainSizer is the top-level one that manages everything.
276 mainSizer = wx.BoxSizer(wx.VERTICAL)
277
278 #------------
279
280 hBox1 = wx.BoxSizer(wx.HORIZONTAL)
281 hBox1.Add(self.info, 0, wx.ALL, 15)
282
283 #------------
284
285 hBox2 = wx.BoxSizer(wx.HORIZONTAL)
286 hBox2.Add(self.btnSetup, 0, wx.ALL, 10)
287 hBox2.Add(self.btnPreview, 0, wx.ALL, 10)
288 hBox2.Add(self.btnPrint, 0, wx.ALL, 10)
289 hBox2.Add(self.btnClose, 0, wx.ALL, 10)
290
291 #------------
292
293 mainSizer.Add(self.demo, 0, wx.ALL, 10)
294 mainSizer.Add(wx.StaticLine(self.panel),
295 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)
296 mainSizer.Add(self.winHtml, 1, wx.EXPAND | wx.ALL, 15)
297 mainSizer.Add(hBox1, 0, wx.ALL, 5)
298 mainSizer.Add(hBox2, 0, wx.ALL, 5)
299
300 #------------
301
302 # Finally, tell the panel to use the mainSizer for layout.
303 self.panel.SetSizer(mainSizer)
304
305
306 def OnBtnPageSetup(self, event):
307 """
308 Page setup click.
309 """
310
311 # Page setup dialog.
312 self.printer.page_setup()
313
314
315 def OnBtnPreview(self, event):
316 """
317 Print preview click.
318 """
319
320 # Preview html text.
321 print("Preview result :", self.printer.preview_text(sample_html))
322
323
324 def OnBtnPrint(self, event):
325 """
326 Print click.
327 """
328
329 # Print html text.
330 print("Print result :", self.printer.print_text(sample_html))
331
332
333 def OnBtnClose(self, event):
334 """
335 Close application.
336 """
337
338 self.Close(True)
339
340
341 def OnCloseWindow(self, event):
342 """
343 Destroy application.
344 """
345
346 self.Destroy()
347
348 #-------------------------------------------------------------------------------
349
350 class MyApp(wx.App):
351 """
352 wx.App sub-class that is the example application.
353 """
354 def OnInit(self):
355 """
356 Init MyApp instance.
357 """
358
359 #------------
360
361 self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)
362
363 #------------
364
365 frame = MyFrame(None, id=-1)
366 self.SetTopWindow(frame)
367 frame.Show(True)
368
369 return True
370
371 #-------------------------------------------------------------------------------
372
373 def main():
374 app = MyApp(False)
375 app.MainLoop()
376
377 #-------------------------------------------------------------------------------
378
379 if __name__ == "__main__" :
380 main()
Easy html multilines printing
1 # sample_one_b.py
2
3 import os
4 import wx
5 from wx.html import HtmlEasyPrinting
6
7 # class MyHtmlPrinter
8 # class MyFrame
9 # class MyApp
10
11 #-------------------------------------------------------------------------------
12
13 if os.name == "posix":
14 print("\nPlatform : UNIX - Linux")
15 elif os.name in ['nt', 'dos', 'ce']:
16 print("\nPlatform : Windows")
17 else:
18 print("\nPlatform : ", platform.system())
19
20 #-------------------------------------------------------------------------------
21
22 class MyHtmlPrinter(HtmlEasyPrinting):
23 """
24 ...
25 """
26 def __init__(self, parent):
27
28 # Get the window name.
29 name = "My document"
30
31 # Init the HtmlEasyPrinting.
32 HtmlEasyPrinting.__init__(self, name, parent)
33
34 # Get the current script directory.
35 self.current_dir = os.path.normpath(os.path.dirname(__file__))
36
37 # Set some default printer and page options.
38 self.GetPrintData().SetPaperId(wx.PAPER_LETTER) # wx.PAPER_A4
39 self.GetPrintData().SetOrientation(wx.LANDSCAPE) # wx.PORTRAIT
40 # Black and white printing if False.
41 self.GetPrintData().SetColour(True)
42 self.GetPageSetupData().SetMarginTopLeft((20, 20))
43 self.GetPageSetupData().SetMarginBottomRight((20, 20))
44
45 #---------------------------------------------------------------------------
46
47 def GetHtmlText(self, text):
48 """
49 Simple conversion of text.
50 Use a more powerful version.
51 """
52
53 html_text = text.replace("\n\n", "<P>")
54 html_text = text.replace("\n", "<BR>")
55
56 return html_text
57
58
59 def page_setup(self):
60 """
61 Show page setup.
62 """
63
64 self.PageSetup()
65
66
67 def print_text(self, text):
68 """
69 Print the text.
70 """
71
72 return self.PrintText(self.GetHtmlText(text), basepath=self.current_dir)
73
74
75 def preview_text(self, text):
76 """
77 Preview html text.
78 """
79
80 # @DATE @ is replaced by the current date in default format.
81 # @PAGENUM@ is replaced by page number.
82 # @PAGESCNT@ is replaced by total number of pages.
83 # @TIME @ is replaced by the current time in default format.
84 # @TITLE@ is replaced with the title of the document.
85
86 header = "My document"
87 footer = "Page @PAGENUM@ of @PAGESCNT@"
88
89 self.SetHeader(header)
90 self.SetFooter(footer)
91
92 return self.PreviewText(self.GetHtmlText(text), basepath=self.current_dir)
93
94
95 def print_file(self, file):
96 """
97 Print the text.
98 """
99
100 return self.PrintFile(file)
101
102
103 def preview_file(self, file):
104 """
105 Preview html file.
106 """
107
108 return self.PreviewFile(file)
109
110 #-------------------------------------------------------------------------------
111
112 class MyFrame(wx.Frame):
113 """
114 Create a main frame for my application.
115 """
116 def __init__ (self, parent, id, title=""):
117 wx.Frame.__init__(self,
118 parent,
119 id,
120 title,
121 size=(600, 450),
122 style=wx.DEFAULT_FRAME_STYLE)
123
124 #------------
125
126 # Simplified init method.
127 self.SetProperties()
128 self.CreateMenu()
129 self.CreateCtrls()
130 self.CreatePrinter()
131 self.BindEvents()
132 self.DoLayout()
133
134 #------------
135
136 self.CenterOnScreen()
137
138 #---------------------------------------------------------------------------
139
140 def SetProperties(self):
141 """
142 Set the main frame properties (title, icon...).
143 """
144
145 frameicon = wx.Icon("Icons/wxWidgets.ico")
146 self.SetIcon(frameicon)
147
148 #------------
149
150 self.SetTitle("Html easy printing...")
151
152
153 def CreateMenu(self):
154 """
155 Make the frame menus.
156 """
157
158 menub = wx.MenuBar()
159
160 fmenu = wx.Menu()
161 fmenu.Append(wx.ID_PAGE_SETUP, "Page set&up\tCtrl+U")
162 fmenu.Append(wx.ID_PREVIEW, "Print pre&view\tCtrl+V")
163 fmenu.Append(wx.ID_PRINT, "&Print\tCtrl+P")
164 fmenu.AppendSeparator()
165 fmenu.Append(wx.ID_EXIT, "E&xit\tCtrl+X")
166 menub.Append(fmenu, "&File")
167
168 self.SetMenuBar(menub)
169
170
171 def CreateCtrls(self):
172 """
173 Make widgets for my application.
174 """
175
176 font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
177 font.SetWeight(wx.BOLD)
178 font.SetPointSize(10)
179
180 #------------
181
182 # First create the controls.
183 self.panel = wx.Panel(self,
184 id=-1,
185 style=wx.BORDER_THEME|
186 wx.TAB_TRAVERSAL)
187
188 self.demo = wx.StaticText(self.panel,
189 id=-1,
190 label="Demonstrating :")
191 self.demo.SetFont(font)
192
193 self.info = wx.StaticText(self.panel,
194 id=-1,
195 label="1) Direct printing,\n"
196 "2) HtmlEasyPrinting class,\n"
197 "3) Preview,\n"
198 "4) Menu,\n"
199 "5) Page setup.")
200 self.info.SetForegroundColour("red")
201 font.SetWeight(wx.NORMAL)
202 self.info.SetFont(font)
203
204 text = ('This the first line of text.\n'\
205 'This is the second line\nand the third. The fourth will be the number 4.0.\n'\
206 '4.0\n'\
207 'This is the fifth line, but by design it is too long to fit in the width of a standard'\
208 'page, so it will be forced to wrap around in order to fit without having'\
209 'some of its verbose verbage truncated.\n'\
210 'Here we have the final line.')
211
212 self.tc = wx.TextCtrl(self.panel,
213 id=-1,
214 size=(200, -1),
215 value=text,
216 style=wx.TE_MULTILINE|wx.TE_DONTWRAP)
217
218 self.btnSetup = wx.Button(self.panel,
219 id=wx.ID_PAGE_SETUP,
220 label="Page set&up")
221
222 self.btnPreview = wx.Button(self.panel,
223 wx.ID_PREVIEW,
224 label="Pre&view text")
225 self.btnPreview.SetFocus()
226
227 self.btnPrint = wx.Button(self.panel,
228 id=wx.ID_PRINT,
229 label="&Print")
230
231 self.btnClose = wx.Button(self.panel,
232 id=wx.ID_CLOSE,
233 label="E&xit")
234
235
236 def CreatePrinter(self):
237 """
238 Create the printer.
239 """
240
241 self.printer = MyHtmlPrinter(self)
242
243
244 def BindEvents(self):
245 """
246 Bind all the events related to my application.
247 """
248
249 # Bind some menu events to an events handler.
250 self.Bind(wx.EVT_MENU, self.OnBtnPageSetup, id=wx.ID_PAGE_SETUP)
251 self.Bind(wx.EVT_MENU, self.OnBtnPreview, id=wx.ID_PREVIEW)
252 self.Bind(wx.EVT_MENU, self.OnBtnPrint, id=wx.ID_PRINT)
253 self.Bind(wx.EVT_MENU, self.OnBtnClose, id=wx.ID_EXIT)
254
255 # Bind some buttons events to an events handler.
256 self.Bind(wx.EVT_BUTTON, self.OnBtnPageSetup, self.btnSetup)
257 self.Bind(wx.EVT_BUTTON, self.OnBtnPreview, self.btnPreview)
258 self.Bind(wx.EVT_BUTTON, self.OnBtnPrint, self.btnPrint)
259 self.Bind(wx.EVT_BUTTON, self.OnBtnClose, self.btnClose)
260
261 # Bind the close event to an event handler.
262 self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
263
264
265 def DoLayout(self):
266 """
267 Manage widgets Layout.
268 """
269
270 # MainSizer is the top-level one that manages everything.
271 mainSizer = wx.BoxSizer(wx.VERTICAL)
272
273 #------------
274
275 hBox1 = wx.BoxSizer(wx.HORIZONTAL)
276 hBox1.Add(self.info, 0, wx.ALL, 15)
277
278 #------------
279
280 hBox2 = wx.BoxSizer(wx.HORIZONTAL)
281 hBox2.Add(self.btnSetup, 0, wx.ALL, 10)
282 hBox2.Add(self.btnPreview, 0, wx.ALL, 10)
283 hBox2.Add(self.btnPrint, 0, wx.ALL, 10)
284 hBox2.Add(self.btnClose, 0, wx.ALL, 10)
285
286 #------------
287
288 mainSizer.Add(self.demo, 0, wx.ALL, 10)
289 mainSizer.Add(wx.StaticLine(self.panel),
290 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)
291 mainSizer.Add(self.tc, 1, wx.EXPAND | wx.ALL, 15)
292 mainSizer.Add(hBox1, 0, wx.ALL, 5)
293 mainSizer.Add(hBox2, 0, wx.ALL, 5)
294
295 #------------
296
297 # Finally, tell the panel to use the mainSizer for layout.
298 self.panel.SetSizer(mainSizer)
299
300
301 def OnBtnPageSetup(self, event):
302 """
303 Page setup click.
304 """
305
306 # Page setup dialog.
307 self.printer.page_setup()
308
309
310 def OnBtnPreview(self, event):
311 """
312 Print preview click.
313 """
314
315 self.sample_html = self.tc.GetValue()
316
317 # Preview html text.
318 print("Preview result :", self.printer.preview_text(self.sample_html))
319
320
321 def OnBtnPrint(self, event):
322 """
323 Print click.
324 """
325
326 self.sample_html = self.tc.GetValue()
327
328 # Print html text.
329 print("Print result :", self.printer.print_text(self.sample_html))
330
331
332 def OnBtnClose(self, event):
333 """
334 Close application.
335 """
336
337 self.Close(True)
338
339
340 def OnCloseWindow(self, event):
341 """
342 Destroy application.
343 """
344
345 self.Destroy()
346
347 #-------------------------------------------------------------------------------
348
349 class MyApp(wx.App):
350 """
351 wx.App sub-class that is the example application.
352 """
353 def OnInit(self):
354 """
355 Init MyApp instance.
356 """
357
358 #------------
359
360 self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)
361
362 #------------
363
364 frame = MyFrame(None, id=-1)
365 self.SetTopWindow(frame)
366 frame.Show(True)
367
368 return True
369
370 #-------------------------------------------------------------------------------
371
372 def main():
373 app = MyApp(False)
374 app.MainLoop()
375
376 #-------------------------------------------------------------------------------
377
378 if __name__ == "__main__" :
379 main()
Easy html grid printing
HTML file : template.html
1 <!doctype html>
2 <html>
3 <head>
4 <meta http-equiv="Content-Type" content="text/html" charset="utf-8">
5 </head>
6 <body>
7 <table width="50%" cellspacing='2' cellpadding='0' border='0' bgcolor="black">
8 <tr>
9 <td align=center colspan="2" rowspan="1" width="20%" bgcolor="red">
10 <table cellspacing="7" cellpadding="0" border="0"><tr><td align=center><b><font face="Tahoma" color="white" size="3"> FIRSTNAME </font></b></td></tr></table>
11 </td>
12 <td align=center colspan="2" rowspan="1" width="80%" bgcolor="yellow">
13 <table cellspacing="7" cellpadding="0" border="0"><tr><td align=center><b><font face="Tahoma" color="black" size="3"> {{FIRSTNAME}} </font></b></td></tr></table>
14 </td>
15 </tr>
16 <tr>
17 <td align=center colspan="2" rowspan="1" width="20%" bgcolor="red">
18 <table cellspacing="7" cellpadding="0" border="0"><tr><td align=center><b><font face="Tahoma" color="white" size="3"> SURNAME </font></b></td></tr></table>
19 </td>
20 <td align=center colspan="2" rowspan="1" width="80%" bgcolor="yellow">
21 <table cellspacing="7" cellpadding="0" border="0"><tr><td align=center><b><font face="Tahoma" color="black" size="3"> {{SURNAME}} </font></b></td></tr></table>
22 </td>
23 </tr>
24 <tr>
25 <td align=center colspan="2" rowspan="1" width="20%" bgcolor="red">
26 <table cellspacing="7" cellpadding="0" border="0"><tr><td align=center><b><font face="Tahoma" color="white" size="3"> AGE </font></b></td></tr></table>
27 </td>
28 <td align=center colspan="2" rowspan="1" width="80%" bgcolor="yellow">
29 <table cellspacing="7" cellpadding="0" border="0"><tr><td align=center><b><font face="Tahoma" color="black" size="3"> {{AGE}} </font></b></td></tr></table>
30 </td>
31 </tr>
32 </table>
33 </body>
34 </html>
1 # sample_one_c.py
2
3 import os
4 import sys
5 import wx
6 from wx.html import HtmlEasyPrinting
7 from wx.html import HtmlWindow
8
9 # class MyHtmlPrinter
10 # class MyFrame
11 # class MyApp
12
13 app_dir = os.path.split(os.path.abspath(sys.argv[0]))[0]
14 html_file = os.path.join(app_dir, "template.html")
15
16 #-------------------------------------------------------------------------------
17
18 if os.name == "posix":
19 print("\nPlatform : UNIX - Linux")
20 elif os.name in ['nt', 'dos', 'ce']:
21 print("\nPlatform : Windows")
22 else:
23 print("\nPlatform : ", platform.system())
24
25 #-------------------------------------------------------------------------------
26
27 class MyHtmlPrinter(HtmlEasyPrinting):
28 """
29 ...
30 """
31 def __init__(self, parent):
32
33 # Get the window name.
34 name = "Person"
35
36 # Init the HtmlEasyPrinting.
37 HtmlEasyPrinting.__init__(self, name, parent)
38
39 # Get the current script directory.
40 self.current_dir = os.path.normpath(os.path.dirname(__file__))
41
42 # Set some default printer and page options.
43 self.GetPrintData().SetPaperId(wx.PAPER_LETTER) # wx.PAPER_A4
44 self.GetPrintData().SetOrientation(wx.LANDSCAPE) # wx.PORTRAIT
45 # Black and white printing if False.
46 self.GetPrintData().SetColour(True)
47 self.GetPageSetupData().SetMarginTopLeft((20, 20))
48 self.GetPageSetupData().SetMarginBottomRight((20, 20))
49
50 #---------------------------------------------------------------------------
51
52 def page_setup(self):
53 """
54 Show page setup.
55 """
56
57 self.PageSetup()
58
59
60 def print_text(self, text):
61 """
62 Print the text.
63 """
64
65 return self.PrintText(text, basepath=self.current_dir)
66
67
68 def preview_text(self, text):
69 """
70 Preview html text.
71 """
72
73 # @DATE @ is replaced by the current date in default format.
74 # @PAGENUM@ is replaced by page number.
75 # @PAGESCNT@ is replaced by total number of pages.
76 # @TIME @ is replaced by the current time in default format.
77 # @TITLE@ is replaced with the title of the document.
78
79 header = "Person :"
80 footer = "Page @PAGENUM@ of @PAGESCNT@"
81
82 self.SetHeader(header)
83 self.SetFooter(footer)
84
85 return self.PreviewText(text, basepath=self.current_dir)
86
87
88 def print_file(self, file):
89 """
90 Print the text.
91 """
92
93 return self.PrintFile(file)
94
95
96 def preview_file(self, file):
97 """
98 Preview html file.
99 """
100
101 return self.PreviewFile(file)
102
103 #-------------------------------------------------------------------------------
104
105 class MyFrame(wx.Frame):
106 """
107 Create a main frame for my application.
108 """
109 def __init__ (self, parent, id, title=""):
110 wx.Frame.__init__(self,
111 parent,
112 id,
113 title,
114 size=(600, 417),
115 style=wx.DEFAULT_FRAME_STYLE)
116
117 #------------
118
119 # Sample html.
120 self.sample_html = None
121
122 #------------
123
124 # Simplified init method.
125 self.SetProperties()
126 self.CreateMenu()
127 self.CreateCtrls()
128 self.CreatePrinter()
129 self.BindEvents()
130 self.DoLayout()
131
132 #------------
133
134 self.CenterOnScreen()
135
136 #---------------------------------------------------------------------------
137
138 def SetProperties(self):
139 """
140 Set the main frame properties (title, icon...).
141 """
142
143 frameicon = wx.Icon("Icons/wxWidgets.ico")
144 self.SetIcon(frameicon)
145
146 #------------
147
148 self.SetTitle("Html easy printing...")
149
150
151 def CreateMenu(self):
152 """
153 Make the frame menus.
154 """
155
156 menub = wx.MenuBar()
157
158 fmenu = wx.Menu()
159 fmenu.Append(wx.ID_PAGE_SETUP, "Page set&up\tCtrl+U")
160 fmenu.Append(wx.ID_PREVIEW, "Print pre&view\tCtrl+V")
161 fmenu.Append(wx.ID_PRINT, "&Print\tCtrl+P")
162 fmenu.AppendSeparator()
163 fmenu.Append(wx.ID_EXIT, "E&xit\tCtrl+X")
164 menub.Append(fmenu, "&File")
165
166 self.SetMenuBar(menub)
167
168
169 def CreateCtrls(self):
170 """
171 Make widgets for my application.
172 """
173
174 font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
175 font.SetWeight(wx.BOLD)
176 font.SetPointSize(10)
177
178 #------------
179
180 # First create the controls.
181 self.panel = wx.Panel(self,
182 id=-1,
183 style=wx.BORDER_THEME|
184 wx.TAB_TRAVERSAL)
185
186 self.demo = wx.StaticText(self.panel,
187 id=-1,
188 label="Demonstrating :")
189 self.demo.SetFont(font)
190
191 self.stFirstname = wx.StaticText(self.panel,
192 id=-1,
193 label="Firstname : ")
194
195 self.tcFirstname = wx.TextCtrl(self.panel,
196 id=-1,
197 size=(200, -1),
198 value="John")
199
200 self.stSurname = wx.StaticText(self.panel,
201 id=-1,
202 label="Surname : ")
203
204 self.tcSurname = wx.TextCtrl(self.panel,
205 id=-1,
206 size=(200, -1),
207 value="Doe")
208
209 self.stAge = wx.StaticText(self.panel,
210 id=-1,
211 label="Age : ")
212
213 self.tcAge = wx.TextCtrl(self.panel,
214 id=-1,
215 size=(200, -1),
216 value="32")
217
218 self.info = wx.StaticText(self.panel,
219 id=-1,
220 label="1) Direct printing,\n"
221 "2) HtmlEasyPrinting class,\n"
222 "3) Html file loading,\n"
223 "4) Preview,\n"
224 "5) Menu,\n"
225 "6) Page setup.")
226 self.info.SetForegroundColour("red")
227 font.SetWeight(wx.NORMAL)
228 self.info.SetFont(font)
229
230 self.btnSetup = wx.Button(self.panel,
231 id=wx.ID_PAGE_SETUP,
232 label="Page set&up")
233
234 self.btnPreview = wx.Button(self.panel,
235 wx.ID_PREVIEW,
236 label="Pre&view text")
237 self.btnPreview.SetFocus()
238
239 self.btnPrint = wx.Button(self.panel,
240 id=wx.ID_PRINT,
241 label="&Print")
242
243 self.btnClose = wx.Button(self.panel,
244 id=wx.ID_CLOSE,
245 label="E&xit")
246
247
248 def CreatePrinter(self):
249 """
250 Create the printer.
251 """
252
253 self.printer = MyHtmlPrinter(self)
254
255
256 def LoadTemplate(self, event):
257 """
258 Load html template.
259 """
260
261
262 sSurname = self.tcSurname.GetValue()
263 sFirstname = self.tcFirstname.GetValue()
264 sAge = self.tcAge.GetValue()
265
266 #------------
267
268 # Thanks to Pascal Faut.
269 # Returns html file ("template.html").
270 with open(html_file, "r") as MyTemplate:
271 strTemplate = MyTemplate.read()
272 self.sample_html = strTemplate
273
274 self.sample_html = self.sample_html.replace("{{SURNAME}}", sSurname)
275 self.sample_html = self.sample_html.replace("{{FIRSTNAME}}", sFirstname)
276 self.sample_html = self.sample_html.replace("{{AGE}}", sAge)
277
278
279 def BindEvents(self):
280 """
281 Bind all the events related to my application.
282 """
283
284 # Bind some menu events to an events handler.
285 self.Bind(wx.EVT_MENU, self.OnBtnPageSetup, id=wx.ID_PAGE_SETUP)
286 self.Bind(wx.EVT_MENU, self.OnBtnPreview, id=wx.ID_PREVIEW)
287 self.Bind(wx.EVT_MENU, self.OnBtnPrint, id=wx.ID_PRINT)
288 self.Bind(wx.EVT_MENU, self.OnBtnClose, id=wx.ID_EXIT)
289
290 # Bind some buttons events to an events handler.
291 self.Bind(wx.EVT_BUTTON, self.OnBtnPageSetup, self.btnSetup)
292 self.Bind(wx.EVT_BUTTON, self.OnBtnPreview, self.btnPreview)
293 self.Bind(wx.EVT_BUTTON, self.OnBtnPrint, self.btnPrint)
294 self.Bind(wx.EVT_BUTTON, self.OnBtnClose, self.btnClose)
295
296 # Bind the close event to an event handler.
297 self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
298
299
300 def DoLayout(self):
301 """
302 Manage widgets Layout.
303 """
304
305 # MainSizer is the top-level one that manages everything.
306 mainSizer = wx.BoxSizer(wx.VERTICAL)
307
308 #------------
309
310 hBox1 = wx.BoxSizer(wx.HORIZONTAL)
311 hBox1.Add(self.info, 0, wx.ALL, 15)
312
313 #------------
314
315 hBox2 = wx.BoxSizer(wx.HORIZONTAL)
316 hBox2.Add(self.btnSetup, 0, wx.ALL, 10)
317 hBox2.Add(self.btnPreview, 0, wx.ALL, 10)
318 hBox2.Add(self.btnPrint, 0, wx.ALL, 10)
319 hBox2.Add(self.btnClose, 0, wx.ALL, 10)
320
321 #------------
322
323 # wx.GridBagSizer(vgap=0, hgap=0).
324 gSizer = wx.GridBagSizer(2, 2)
325 gSizer.Add(self.stFirstname, (0, 0), span=(wx.DefaultSpan),
326 flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
327 gSizer.Add(self.tcFirstname, (0, 1), span=wx.DefaultSpan)
328
329 gSizer.Add(self.stSurname, (1, 0), span=wx.DefaultSpan,
330 flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
331 gSizer.Add(self.tcSurname, (1, 1), span=wx.DefaultSpan)
332
333 gSizer.Add(self.stAge, (2, 0), span=wx.DefaultSpan,
334 flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
335 gSizer.Add(self.tcAge, (2, 1), span=wx.DefaultSpan)
336
337 #------------
338
339 mainSizer.Add(self.demo, 0, wx.ALL, 10)
340 mainSizer.Add(wx.StaticLine(self.panel),
341 0, wx.EXPAND|wx.TOP, 5)
342 mainSizer.Add(gSizer, 0, wx.ALL, 20)
343 mainSizer.Add(hBox1, 0, wx.LEFT|wx.BOTTOM, 5)
344 mainSizer.Add(hBox2, 0, wx.ALL, 5)
345
346 #------------
347
348 # Finally, tell the panel to use the mainSizer for layout.
349 self.panel.SetSizer(mainSizer)
350
351
352 def OnBtnPageSetup(self, event):
353 """
354 Page setup click.
355 """
356
357 # Page setup dialog.
358 self.printer.page_setup()
359
360
361 def OnBtnPreview(self, event):
362 """
363 Print preview click.
364 """
365
366 # Load template.
367 self.LoadTemplate(event)
368
369 if self.sample_html is not None:
370 # Preview html text.
371 print("Preview result:", self.printer.preview_text(self.sample_html))
372
373
374 def OnBtnPrint(self, event):
375 """
376 Print click.
377 """
378
379 # Load template.
380 self.LoadTemplate(event)
381
382 if self.sample_html is not None:
383 # Print html text.
384 print("Print result:", self.printer.print_text(self.sample_html))
385
386
387 def OnBtnClose(self, event):
388 """
389 Close application.
390 """
391
392 self.Close(True)
393
394
395 def OnCloseWindow(self, event):
396 """
397 Destroy application.
398 """
399
400 self.Destroy()
401
402 #-------------------------------------------------------------------------------
403
404 class MyApp(wx.App):
405 """
406 wx.App sub-class that is the example application.
407 """
408 def OnInit(self):
409 """
410 Init MyApp instance.
411 """
412
413 #------------
414
415 self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)
416
417 #------------
418
419 frame = MyFrame(None, id=-1)
420 self.SetTopWindow(frame)
421 frame.Show(True)
422
423 return True
424
425 #-------------------------------------------------------------------------------
426
427 def main():
428 app = MyApp(False)
429 app.MainLoop()
430
431 #-------------------------------------------------------------------------------
432
433 if __name__ == "__main__" :
434 main()
Download source
Additional Information
Link :
https://wiki.wxpython.org/MoreCommentsOnPrinting
https://wiki.wxpython.org/PrintingWithReportGenerators
http://www.blog.pythonlibrary.org/2010/05/15/manipulating-pdfs-with-python-and-pypdf/
https://www.blog.pythonlibrary.org/2010/02/14/python-windows-and-printers/
- - - - -
https://wiki.wxpython.org/TitleIndex
Thanks to
Lorne White, Jeff Grimmett, Vernon Cole, Robin Dunn, Andy Robinson / Robin Becker / The ReportLab team, David Hughe (PDFViewer), Ruikai Liu / Jorj X. McKie (PyMuPDF), Cody Precord, Mike Driscoll, Pascal Faut., Dietmar Schwertberger, Chris Barker, the wxPython community...
Thanks also to all known contributors or anonymous that I forgot.
And finally, congratulations to the many forums and blogs for all the available examples and the help which is the strength of wxPython.
About this page
Date (d/m/y) Person (bot) Comments :
00/00/00 - Sean McKay (originally Created).
10/10/18 - Ecco (Updated page and published examples for wxPython Phoenix).
Comments
- blah, blah, blah....