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