25.4 mm to the inch, not 25.1
[wxWidgets.git] / samples / printing / printing.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: printing.cpp
3 // Purpose: Printing demo for wxWidgets
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 1995
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation
14 #endif
15
16 // For compilers that support precompilation, includes "wx/wx.h".
17 #include "wx/wxprec.h"
18
19 #ifdef __BORLANDC__
20 #pragma hdrstop
21 #endif
22
23 #ifndef WX_PRECOMP
24 #include "wx/wx.h"
25 #endif
26
27 #if !wxUSE_PRINTING_ARCHITECTURE
28 #error "You must set wxUSE_PRINTING_ARCHITECTURE to 1 in setup.h, and recompile the library."
29 #endif
30
31 // Set this to 1 if you want to test PostScript printing under MSW.
32 // However, you'll also need to edit src/msw/makefile.nt.
33 #define wxTEST_POSTSCRIPT_IN_MSW 0
34
35 #include <ctype.h>
36 #include "wx/metafile.h"
37 #include "wx/print.h"
38 #include "wx/printdlg.h"
39 #include "wx/image.h"
40 #include "wx/accel.h"
41
42 #if wxTEST_POSTSCRIPT_IN_MSW
43 #include "wx/generic/printps.h"
44 #include "wx/generic/prntdlgg.h"
45 #endif
46
47 #include "printing.h"
48
49 #ifndef __WXMSW__
50 #include "mondrian.xpm"
51 #endif
52
53 #if wxUSE_LIBGNOMEPRINT
54 #include "wx/html/forcelnk.h"
55 FORCE_LINK(gnome_print)
56 #endif
57
58
59 // Declare a frame
60 MyFrame *frame = (MyFrame *) NULL;
61 // int orientation = wxPORTRAIT;
62
63 // Global print data, to remember settings during the session
64 wxPrintData *g_printData = (wxPrintData*) NULL ;
65
66 // Global page setup data
67 wxPageSetupData* g_pageSetupData = (wxPageSetupData*) NULL;
68
69 // Main proc
70 IMPLEMENT_APP(MyApp)
71
72 // Writes a header on a page. Margin units are in millimetres.
73 bool WritePageHeader(wxPrintout *printout, wxDC *dc, wxChar *text, float mmToLogical);
74
75 // The `main program' equivalent, creating the windows and returning the
76 // main frame
77
78 bool MyApp::OnInit(void)
79 {
80 wxInitAllImageHandlers();
81
82 m_testFont.Create(10, wxSWISS, wxNORMAL, wxNORMAL);
83
84 g_printData = new wxPrintData;
85 g_pageSetupData = new wxPageSetupDialogData;
86
87 // Create the main frame window
88 frame = new MyFrame((wxFrame *) NULL, _T("wxWidgets Printing Demo"), wxPoint(0, 0), wxSize(400, 400));
89
90 #if wxUSE_STATUSBAR
91 // Give it a status line
92 frame->CreateStatusBar(2);
93 #endif // wxUSE_STATUSBAR
94
95 // Load icon and bitmap
96 frame->SetIcon( wxICON( mondrian) );
97
98 // Make a menubar
99 wxMenu *file_menu = new wxMenu;
100
101 file_menu->Append(WXPRINT_PRINT, _T("&Print..."), _T("Print"));
102 file_menu->Append(WXPRINT_PAGE_SETUP, _T("Page Set&up..."), _T("Page setup"));
103 file_menu->Append(WXPRINT_PREVIEW, _T("Print Pre&view"), _T("Preview"));
104
105 #if wxUSE_ACCEL
106 // Accelerators
107 wxAcceleratorEntry entries[1];
108 entries[0].Set(wxACCEL_CTRL, (int) 'V', WXPRINT_PREVIEW);
109 wxAcceleratorTable accel(1, entries);
110 frame->SetAcceleratorTable(accel);
111 #endif
112
113 #if defined(__WXMSW__) && wxTEST_POSTSCRIPT_IN_MSW
114 file_menu->AppendSeparator();
115 file_menu->Append(WXPRINT_PRINT_PS, _T("Print PostScript..."), _T("Print (PostScript)"));
116 file_menu->Append(WXPRINT_PAGE_SETUP_PS, _T("Page Setup PostScript..."), _T("Page setup (PostScript)"));
117 file_menu->Append(WXPRINT_PREVIEW_PS, _T("Print Preview PostScript"), _T("Preview (PostScript)"));
118 #endif
119 file_menu->AppendSeparator();
120 file_menu->Append(WXPRINT_ANGLEUP, _T("Angle up\tAlt-U"), _T("Raise rotated text angle"));
121 file_menu->Append(WXPRINT_ANGLEDOWN, _T("Angle down\tAlt-D"), _T("Lower rotated text angle"));
122 file_menu->AppendSeparator();
123 file_menu->Append(WXPRINT_QUIT, _T("E&xit"), _T("Exit program"));
124
125 wxMenu *help_menu = new wxMenu;
126 help_menu->Append(WXPRINT_ABOUT, _T("&About"), _T("About this demo"));
127
128 wxMenuBar *menu_bar = new wxMenuBar;
129
130 menu_bar->Append(file_menu, _T("&File"));
131 menu_bar->Append(help_menu, _T("&Help"));
132
133 // Associate the menu bar with the frame
134 frame->SetMenuBar(menu_bar);
135
136 MyCanvas *canvas = new MyCanvas(frame, wxPoint(0, 0), wxSize(100, 100), wxRETAINED|wxHSCROLL|wxVSCROLL);
137
138 // Give it scrollbars: the virtual canvas is 20 * 50 = 1000 pixels in each direction
139 canvas->SetScrollbars(20, 20, 50, 50);
140
141 frame->canvas = canvas;
142
143 frame->Centre(wxBOTH);
144 frame->Show();
145
146 #if wxUSE_STATUSBAR
147 frame->SetStatusText(_T("Printing demo"));
148 #endif // wxUSE_STATUSBAR
149
150 SetTopWindow(frame);
151
152 return true;
153 }
154
155 int MyApp::OnExit()
156 {
157 delete g_printData;
158 delete g_pageSetupData;
159 return 1;
160 }
161
162 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
163 EVT_MENU(WXPRINT_QUIT, MyFrame::OnExit)
164 EVT_MENU(WXPRINT_PRINT, MyFrame::OnPrint)
165 EVT_MENU(WXPRINT_PREVIEW, MyFrame::OnPrintPreview)
166 EVT_MENU(WXPRINT_PAGE_SETUP, MyFrame::OnPageSetup)
167 EVT_MENU(WXPRINT_ABOUT, MyFrame::OnPrintAbout)
168 #if defined(__WXMSW__) && wxTEST_POSTSCRIPT_IN_MSW
169 EVT_MENU(WXPRINT_PRINT_PS, MyFrame::OnPrintPS)
170 EVT_MENU(WXPRINT_PREVIEW_PS, MyFrame::OnPrintPreviewPS)
171 EVT_MENU(WXPRINT_PAGE_SETUP_PS, MyFrame::OnPageSetupPS)
172 #endif
173 EVT_MENU(WXPRINT_ANGLEUP, MyFrame::OnAngleUp)
174 EVT_MENU(WXPRINT_ANGLEDOWN, MyFrame::OnAngleDown)
175 END_EVENT_TABLE()
176
177 // Define my frame constructor
178 MyFrame::MyFrame(wxFrame *frame, const wxString& title, const wxPoint& pos, const wxSize& size):
179 wxFrame(frame, wxID_ANY, title, pos, size)
180 {
181 canvas = NULL;
182 m_angle = 30;
183 #if 0
184 wxImage image( wxT("test.jpg") );
185 image.SetAlpha();
186 int i,j;
187 for (i = 0; i < image.GetWidth(); i++)
188 for (j = 0; j < image.GetHeight(); j++)
189 image.SetAlpha( i, j, 50 );
190 m_bitmap = image;
191 #endif
192 }
193
194 void MyFrame::OnExit(wxCommandEvent& WXUNUSED(event))
195 {
196 Close(true /*force closing*/);
197 }
198
199 void MyFrame::OnPrint(wxCommandEvent& WXUNUSED(event))
200 {
201 wxPrintDialogData printDialogData(* g_printData);
202
203 wxPrinter printer(& printDialogData);
204 MyPrintout printout(_T("My printout"));
205 if (!printer.Print(this, &printout, true /*prompt*/))
206 {
207 if (wxPrinter::GetLastError() == wxPRINTER_ERROR)
208 wxMessageBox(_T("There was a problem printing.\nPerhaps your current printer is not set correctly?"), _T("Printing"), wxOK);
209 else
210 wxMessageBox(_T("You canceled printing"), _T("Printing"), wxOK);
211 }
212 else
213 {
214 (*g_printData) = printer.GetPrintDialogData().GetPrintData();
215 }
216 }
217
218 void MyFrame::OnPrintPreview(wxCommandEvent& WXUNUSED(event))
219 {
220 // Pass two printout objects: for preview, and possible printing.
221 wxPrintDialogData printDialogData(* g_printData);
222 wxPrintPreview *preview = new wxPrintPreview(new MyPrintout, new MyPrintout, & printDialogData);
223 if (!preview->Ok())
224 {
225 delete preview;
226 wxMessageBox(_T("There was a problem previewing.\nPerhaps your current printer is not set correctly?"), _T("Previewing"), wxOK);
227 return;
228 }
229
230 wxPreviewFrame *frame = new wxPreviewFrame(preview, this, _T("Demo Print Preview"), wxPoint(100, 100), wxSize(600, 650));
231 frame->Centre(wxBOTH);
232 frame->Initialize();
233 frame->Show();
234 }
235
236 void MyFrame::OnPageSetup(wxCommandEvent& WXUNUSED(event))
237 {
238 (*g_pageSetupData) = *g_printData;
239
240 wxPageSetupDialog pageSetupDialog(this, g_pageSetupData);
241 pageSetupDialog.ShowModal();
242
243 (*g_printData) = pageSetupDialog.GetPageSetupData().GetPrintData();
244 (*g_pageSetupData) = pageSetupDialog.GetPageSetupData();
245 }
246
247 #if defined(__WXMSW__) && wxTEST_POSTSCRIPT_IN_MSW
248 void MyFrame::OnPrintPS(wxCommandEvent& WXUNUSED(event))
249 {
250 wxPostScriptPrinter printer(g_printData);
251 MyPrintout printout(_T("My printout"));
252 printer.Print(this, &printout, true/*prompt*/);
253
254 (*g_printData) = printer.GetPrintData();
255 }
256
257 void MyFrame::OnPrintPreviewPS(wxCommandEvent& WXUNUSED(event))
258 {
259 // Pass two printout objects: for preview, and possible printing.
260 wxPrintDialogData printDialogData(* g_printData);
261 wxPrintPreview *preview = new wxPrintPreview(new MyPrintout, new MyPrintout, & printDialogData);
262 wxPreviewFrame *frame = new wxPreviewFrame(preview, this, _T("Demo Print Preview"), wxPoint(100, 100), wxSize(600, 650));
263 frame->Centre(wxBOTH);
264 frame->Initialize();
265 frame->Show();
266 }
267
268 void MyFrame::OnPageSetupPS(wxCommandEvent& WXUNUSED(event))
269 {
270 (*g_pageSetupData) = * g_printData;
271
272 wxGenericPageSetupDialog pageSetupDialog(this, g_pageSetupData);
273 pageSetupDialog.ShowModal();
274
275 (*g_printData) = pageSetupDialog.GetPageSetupData().GetPrintData();
276 (*g_pageSetupData) = pageSetupDialog.GetPageSetupData();
277 }
278 #endif
279
280
281 void MyFrame::OnPrintAbout(wxCommandEvent& WXUNUSED(event))
282 {
283 (void)wxMessageBox(_T("wxWidgets printing demo\nAuthor: Julian Smart"),
284 _T("About wxWidgets printing demo"), wxOK|wxCENTRE);
285 }
286
287 void MyFrame::OnAngleUp(wxCommandEvent& WXUNUSED(event))
288 {
289 m_angle += 5;
290 canvas->Refresh();
291 }
292
293 void MyFrame::OnAngleDown(wxCommandEvent& WXUNUSED(event))
294 {
295 m_angle -= 5;
296 canvas->Refresh();
297 }
298
299 void MyFrame::Draw(wxDC& dc)
300 {
301 dc.SetBackground(*wxWHITE_BRUSH);
302 dc.Clear();
303 dc.SetFont(wxGetApp().m_testFont);
304
305 dc.SetBackgroundMode(wxTRANSPARENT);
306
307 dc.SetBrush(*wxCYAN_BRUSH);
308 dc.SetPen(*wxRED_PEN);
309
310 dc.DrawRoundedRectangle(0, 30, 200, 100, 20);
311
312 dc.DrawText( wxT("Rectangle 200 by 100"), 40, 40);
313
314 dc.SetPen( wxPen(*wxBLACK,0,wxDOT_DASH) );
315 dc.DrawEllipse(50, 140, 100, 50);
316 dc.SetPen(*wxRED_PEN);
317
318 dc.DrawText( wxT("Test message: this is in 10 point text"), 10, 180);
319
320 #if wxUSE_UNICODE
321 char *test = "Hebrew שלום -- Japanese (日本語)";
322 wxString tmp = wxConvUTF8.cMB2WC( test );
323 dc.DrawText( tmp, 10, 200 );
324 #endif
325
326 wxString str;
327 int i = 0;
328 str.Printf( wxT("---- Text at angle %d ----"), i );
329 dc.DrawRotatedText( str, 100, 300, i );
330
331 i = m_angle;
332 str.Printf( wxT("---- Text at angle %d ----"), i );
333 dc.DrawRotatedText( str, 100, 300, i );
334
335 dc.SetPen(* wxBLACK_PEN);
336 dc.DrawLine(0, 0, 200, 200);
337 dc.DrawLine(200, 0, 0, 200);
338
339 wxIcon my_icon = wxICON(mondrian) ;
340
341 dc.DrawIcon( my_icon, 100, 100);
342
343 if (m_bitmap.Ok())
344 dc.DrawBitmap( m_bitmap, 10, 10 );
345 }
346
347 void MyFrame::OnSize(wxSizeEvent& event )
348 {
349 wxFrame::OnSize(event);
350 }
351
352 BEGIN_EVENT_TABLE(MyCanvas, wxScrolledWindow)
353 EVT_MOUSE_EVENTS(MyCanvas::OnEvent)
354 END_EVENT_TABLE()
355
356 // Define a constructor for my canvas
357 MyCanvas::MyCanvas(wxFrame *frame, const wxPoint& pos, const wxSize& size, long style):
358 wxScrolledWindow(frame, wxID_ANY, pos, size, style)
359 {
360 SetBackgroundColour(* wxWHITE);
361 }
362
363 // Define the repainting behaviour
364 void MyCanvas::OnDraw(wxDC& dc)
365 {
366 frame->Draw(dc);
367 }
368
369 void MyCanvas::OnEvent(wxMouseEvent& WXUNUSED(event))
370 {
371 }
372
373 bool MyPrintout::OnPrintPage(int page)
374 {
375 wxDC *dc = GetDC();
376 if (dc)
377 {
378 if (page == 1)
379 DrawPageOne(dc);
380 else if (page == 2)
381 DrawPageTwo(dc);
382
383 dc->SetDeviceOrigin(0, 0);
384 dc->SetUserScale(1.0, 1.0);
385
386 wxChar buf[200];
387 wxSprintf(buf, wxT("PAGE %d"), page);
388 dc->DrawText(buf, 10, 10);
389
390 return true;
391 }
392 else
393 return false;
394 }
395
396 bool MyPrintout::OnBeginDocument(int startPage, int endPage)
397 {
398 if (!wxPrintout::OnBeginDocument(startPage, endPage))
399 return false;
400
401 return true;
402 }
403
404 void MyPrintout::GetPageInfo(int *minPage, int *maxPage, int *selPageFrom, int *selPageTo)
405 {
406 *minPage = 1;
407 *maxPage = 2;
408 *selPageFrom = 1;
409 *selPageTo = 2;
410 }
411
412 bool MyPrintout::HasPage(int pageNum)
413 {
414 return (pageNum == 1 || pageNum == 2);
415 }
416
417 void MyPrintout::DrawPageOne(wxDC *dc)
418 {
419 // You might use THIS code if you were scaling
420 // graphics of known size to fit on the page.
421
422 // We know the graphic is 200x200. If we didn't know this,
423 // we'd need to calculate it.
424 float maxX = 200;
425 float maxY = 200;
426
427 // Let's have at least 50 device units margin
428 float marginX = 50;
429 float marginY = 50;
430
431 // Add the margin to the graphic size
432 maxX += (2*marginX);
433 maxY += (2*marginY);
434
435 // Get the size of the DC in pixels
436 int w, h;
437 dc->GetSize(&w, &h);
438
439 // Calculate a suitable scaling factor
440 float scaleX=(float)(w/maxX);
441 float scaleY=(float)(h/maxY);
442
443 // Use x or y scaling factor, whichever fits on the DC
444 float actualScale = wxMin(scaleX,scaleY);
445
446 // Calculate the position on the DC for centring the graphic
447 float posX = (float)((w - (200*actualScale))/2.0);
448 float posY = (float)((h - (200*actualScale))/2.0);
449
450 // Set the scale and origin
451 dc->SetUserScale(actualScale, actualScale);
452 dc->SetDeviceOrigin( (long)posX, (long)posY );
453
454 frame->Draw(*dc);
455 }
456
457 void MyPrintout::DrawPageTwo(wxDC *dc)
458 {
459 // You might use THIS code to set the printer DC to ROUGHLY reflect
460 // the screen text size. This page also draws lines of actual length
461 // 5cm on the page.
462
463 // Get the logical pixels per inch of screen and printer
464 int ppiScreenX, ppiScreenY;
465 GetPPIScreen(&ppiScreenX, &ppiScreenY);
466 int ppiPrinterX, ppiPrinterY;
467 GetPPIPrinter(&ppiPrinterX, &ppiPrinterY);
468
469 // This scales the DC so that the printout roughly represents the
470 // the screen scaling. The text point size _should_ be the right size
471 // but in fact is too small for some reason. This is a detail that will
472 // need to be addressed at some point but can be fudged for the
473 // moment.
474 float scale = (float)((float)ppiPrinterX/(float)ppiScreenX);
475
476 // Now we have to check in case our real page size is reduced
477 // (e.g. because we're drawing to a print preview memory DC)
478 int pageWidth, pageHeight;
479 int w, h;
480 dc->GetSize(&w, &h);
481 GetPageSizePixels(&pageWidth, &pageHeight);
482
483 // If printer pageWidth == current DC width, then this doesn't
484 // change. But w might be the preview bitmap width, so scale down.
485 float overallScale = scale * (float)(w/(float)pageWidth);
486 dc->SetUserScale(overallScale, overallScale);
487
488 // Calculate conversion factor for converting millimetres into
489 // logical units.
490 // There are approx. 25.4 mm to the inch. There are ppi
491 // device units to the inch. Therefore 1 mm corresponds to
492 // ppi/25.4 device units. We also divide by the
493 // screen-to-printer scaling factor, because we need to
494 // unscale to pass logical units to DrawLine.
495
496 // Draw 50 mm by 50 mm L shape
497 float logUnitsFactor = (float)(ppiPrinterX/(scale*25.4));
498 float logUnits = (float)(50*logUnitsFactor);
499 dc->SetPen(* wxBLACK_PEN);
500 dc->DrawLine(50, 250, (long)(50.0 + logUnits), 250);
501 dc->DrawLine(50, 250, 50, (long)(250.0 + logUnits));
502
503 dc->SetBackgroundMode(wxTRANSPARENT);
504 dc->SetBrush(*wxTRANSPARENT_BRUSH);
505
506 { // GetTextExtent demo:
507 wxString words[7] = {_T("This "), _T("is "), _T("GetTextExtent "), _T("testing "), _T("string. "), _T("Enjoy "), _T("it!")};
508 long w, h;
509 long x = 200, y= 250;
510 wxFont fnt(15, wxSWISS, wxNORMAL, wxNORMAL);
511
512 dc->SetFont(fnt);
513
514 for (int i = 0; i < 7; i++)
515 {
516 wxString word = words[i];
517 word.Remove( word.Len()-1, 1 );
518 dc->GetTextExtent(word, &w, &h);
519 dc->DrawRectangle(x, y, w, h);
520 dc->GetTextExtent(words[i], &w, &h);
521 dc->DrawText(words[i], x, y);
522 x += w;
523 }
524
525 }
526
527 dc->SetFont(wxGetApp().m_testFont);
528
529 dc->DrawText(_T("Some test text"), 200, 300 );
530
531 // TESTING
532
533 int leftMargin = 20;
534 int rightMargin = 20;
535 int topMargin = 20;
536 int bottomMargin = 20;
537
538 int pageWidthMM, pageHeightMM;
539 GetPageSizeMM(&pageWidthMM, &pageHeightMM);
540
541 float leftMarginLogical = (float)(logUnitsFactor*leftMargin);
542 float topMarginLogical = (float)(logUnitsFactor*topMargin);
543 float bottomMarginLogical = (float)(logUnitsFactor*(pageHeightMM - bottomMargin));
544 float rightMarginLogical = (float)(logUnitsFactor*(pageWidthMM - rightMargin));
545
546 dc->SetPen(* wxRED_PEN);
547 dc->DrawLine( (long)leftMarginLogical, (long)topMarginLogical,
548 (long)rightMarginLogical, (long)topMarginLogical);
549 dc->DrawLine( (long)leftMarginLogical, (long)bottomMarginLogical,
550 (long)rightMarginLogical, (long)bottomMarginLogical);
551
552 WritePageHeader(this, dc, _T("A header"), logUnitsFactor);
553 }
554
555 // Writes a header on a page. Margin units are in millimetres.
556 bool WritePageHeader(wxPrintout *printout, wxDC *dc, wxChar *text, float mmToLogical)
557 {
558 /*
559 static wxFont *headerFont = (wxFont *) NULL;
560 if (!headerFont)
561 {
562 headerFont = wxTheFontList->FindOrCreateFont(16, wxSWISS, wxNORMAL, wxBOLD);
563 }
564 dc->SetFont(headerFont);
565 */
566
567 int pageWidthMM, pageHeightMM;
568
569 printout->GetPageSizeMM(&pageWidthMM, &pageHeightMM);
570 wxUnusedVar(pageHeightMM);
571
572 int leftMargin = 10;
573 int topMargin = 10;
574 int rightMargin = 10;
575
576 float leftMarginLogical = (float)(mmToLogical*leftMargin);
577 float topMarginLogical = (float)(mmToLogical*topMargin);
578 float rightMarginLogical = (float)(mmToLogical*(pageWidthMM - rightMargin));
579
580 long xExtent, yExtent;
581 dc->GetTextExtent(text, &xExtent, &yExtent);
582 float xPos = (float)(((((pageWidthMM - leftMargin - rightMargin)/2.0)+leftMargin)*mmToLogical) - (xExtent/2.0));
583 dc->DrawText(text, (long)xPos, (long)topMarginLogical);
584
585 dc->SetPen(* wxBLACK_PEN);
586 dc->DrawLine( (long)leftMarginLogical, (long)(topMarginLogical+yExtent),
587 (long)rightMarginLogical, (long)topMarginLogical+yExtent );
588
589 return true;
590 }