1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="highlight.min.css">
<script src="highlight.min.js"></script><script>
hljs.configure({languages: ['cpp']});
hljs.highlightAll();
</script><title>Examples</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="generator" content="DocBook XSL Stylesheets Vsnapshot">
<link rel="home" href="index.html" title="Programming with gtkmm 4">
<link rel="up" href="chapter-printing.html" title="Chapter 21. Printing">
<link rel="prev" href="sec-printing-printdialog.html" title="PrintDialog">
<link rel="next" href="chapter-recent-documents.html" title="Chapter 22. Recently Used Documents">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr><th colspan="3" align="center">Examples</th></tr>
<tr>
<td width="20%" align="left">
<a accesskey="p" href="sec-printing-printdialog.html"><img src="icons/prev.png" alt="Prev"></a> </td>
<th width="60%" align="center">Chapter 21. Printing</th>
<td width="20%" align="right"> <a accesskey="n" href="chapter-recent-documents.html"><img src="icons/next.png" alt="Next"></a>
</td>
</tr>
</table>
<hr>
</div>
<div class="section">
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
<a name="sec-printing-examples"></a>Examples</h2></div></div></div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="sec-printing-examples-simple"></a>Simple</h3></div></div></div>
<p>
The following example demonstrates how to print some input from a user interface
using <code class="classname">PrintOperation</code>. It shows how to implement
<code class="literal">on_begin_print</code> and <code class="literal">on_draw_page</code>,
as well as how to track print status and update the print settings.
</p>
<div class="figure">
<a name="figure-printing-simple"></a><p class="title"><b>Figure 21.1. Printing - Simple</b></p>
<div class="figure-contents">
<div class="screenshot">
<div class="mediaobject"><img src="figures/printing_simple.png" alt="Printing - Simple"></div>
</div>
</div>
</div>
<br class="figure-break">
<p><a class="ulink" href="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/printing/simple/" target="_top">Source Code</a></p>
<p>File: <code class="filename">examplewindow.h</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
// This file is part of the printing/simple and printing/advanced examples
#include <gtkmm.h>
class PrintFormOperation;
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow(const Glib::RefPtr<Gtk::Application>& app);
virtual ~ExampleWindow();
protected:
void build_main_menu(const Glib::RefPtr<Gtk::Application>& app);
void print_or_preview(Gtk::PrintOperation::Action print_action);
//PrintOperation signal handlers.
//We handle these so can get necessary information to update the UI or print settings.
//Our derived PrintOperation class also overrides some default signal handlers.
void on_printoperation_status_changed();
void on_printoperation_done(Gtk::PrintOperation::Result result);
//Action signal handlers:
void on_menu_file_new();
void on_menu_file_page_setup();
void on_menu_file_print_preview();
void on_menu_file_print();
void on_menu_file_quit();
//Printing-related objects:
Glib::RefPtr<Gtk::PageSetup> m_refPageSetup;
Glib::RefPtr<Gtk::PrintSettings> m_refSettings;
Glib::RefPtr<PrintFormOperation> m_refPrintFormOperation;
//Child widgets:
Gtk::Box m_VBox;
Gtk::Grid m_Grid;
Gtk::Label m_NameLabel;
Gtk::Entry m_NameEntry;
Gtk::Label m_SurnameLabel;
Gtk::Entry m_SurnameEntry;
Gtk::Label m_CommentsLabel;
Gtk::ScrolledWindow m_ScrolledWindow;
Gtk::TextView m_TextView;
Glib::RefPtr<Gtk::TextBuffer> m_refTextBuffer;
Gtk::Label m_Statusbar;
Glib::RefPtr<Gtk::Builder> m_refBuilder;
Glib::RefPtr<Gtk::AlertDialog> m_refDialog;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</code></pre>
<p>File: <code class="filename">printformoperation.h</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#ifndef GTKMM_PRINT_FORM_OPERATION_H
#define GTKMM_PRINT_FORM_OPERATION_H
#include <gtkmm.h>
#include <pangomm.h>
#include <vector>
//We derive our own class from PrintOperation,
//so we can put the actual print implementation here.
class PrintFormOperation : public Gtk::PrintOperation
{
public:
static Glib::RefPtr<PrintFormOperation> create();
virtual ~PrintFormOperation();
void set_name(const Glib::ustring& name) { m_Name = name; }
void set_comments(const Glib::ustring& comments) { m_Comments = comments; }
protected:
PrintFormOperation();
//PrintOperation default signal handler overrides:
void on_begin_print(const Glib::RefPtr<Gtk::PrintContext>& context) override;
void on_draw_page(const Glib::RefPtr<Gtk::PrintContext>& context, int page_nr) override;
Glib::ustring m_Name;
Glib::ustring m_Comments;
Glib::RefPtr<Pango::Layout> m_refLayout;
std::vector<int> m_PageBreaks; // line numbers where a page break occurs
};
#endif // GTKMM_PRINT_FORM_OPERATION_H
</code></pre>
<p>File: <code class="filename">examplewindow.cc</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "examplewindow.h"
#include "printformoperation.h"
#include <iostream>
ExampleWindow::ExampleWindow(const Glib::RefPtr<Gtk::Application>& app)
: m_VBox(Gtk::Orientation::VERTICAL),
m_NameLabel("Name"),
m_SurnameLabel("Surname"),
m_CommentsLabel("Comments")
{
m_refPageSetup = Gtk::PageSetup::create();
m_refSettings = Gtk::PrintSettings::create();
set_title("gtkmm Printing Example");
set_default_size(400, 300);
set_child(m_VBox);
build_main_menu(app);
m_VBox.append(m_Grid);
//Arrange the widgets inside the grid:
m_Grid.set_expand(true);
m_Grid.set_row_spacing(5);
m_Grid.set_column_spacing(5);
m_Grid.attach(m_NameLabel, 0, 0);
m_Grid.attach(m_NameEntry, 1, 0);
m_Grid.attach(m_SurnameLabel, 0, 1);
m_Grid.attach(m_SurnameEntry, 1, 1);
//Add the TextView, inside a ScrolledWindow:
m_ScrolledWindow.set_child(m_TextView);
//Only show the scrollbars when they are necessary:
m_ScrolledWindow.set_policy(Gtk::PolicyType::AUTOMATIC, Gtk::PolicyType::AUTOMATIC);
m_Grid.attach(m_CommentsLabel, 0, 2);
m_Grid.attach(m_ScrolledWindow, 1, 2);
m_ScrolledWindow.set_expand(true);
m_refTextBuffer = Gtk::TextBuffer::create();
m_TextView.set_buffer(m_refTextBuffer);
m_Statusbar.set_hexpand(true);
m_VBox.append(m_Statusbar);
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::build_main_menu(const Glib::RefPtr<Gtk::Application>& app)
{
//Create actions for menus and toolbars:
auto refActionGroup = Gio::SimpleActionGroup::create();
//File menu:
refActionGroup->add_action("new",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_new));
refActionGroup->add_action("pagesetup",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_page_setup));
refActionGroup->add_action("printpreview",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_print_preview));
refActionGroup->add_action("print",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_print));
refActionGroup->add_action("quit",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_quit));
insert_action_group("example", refActionGroup);
// When the menubar is a child of a Gtk::Window, keyboard accelerators are not
// automatically fetched from the Gio::Menu.
// See the examples/book/menus/main_menu example for an alternative way of
// adding the menubar when using Gtk::ApplicationWindow.
app->set_accel_for_action("example.new", "<Primary>n");
app->set_accel_for_action("example.print", "<Primary>p");
app->set_accel_for_action("example.quit", "<Primary>q");
m_refBuilder = Gtk::Builder::create();
// Layout the actions in a menubar:
Glib::ustring ui_menu_info =
"<interface>"
" <menu id='menu-example'>"
" <submenu>"
" <attribute name='label' translatable='yes'>_File</attribute>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>_New</attribute>"
" <attribute name='action'>example.new</attribute>"
" </item>"
" </section>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>Page _Setup...</attribute>"
" <attribute name='action'>example.pagesetup</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>Print Preview</attribute>"
" <attribute name='action'>example.printpreview</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>_Print...</attribute>"
" <attribute name='action'>example.print</attribute>"
" </item>"
" </section>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>_Quit</attribute>"
" <attribute name='action'>example.quit</attribute>"
" </item>"
" </section>"
" </submenu>"
" </menu>"
"</interface>";
try
{
m_refBuilder->add_from_string(ui_menu_info);
}
catch(const Glib::Error& ex)
{
std::cerr << "building menus failed: " << ex.what();
}
// Layout the actions in a toolbar:
Glib::ustring ui_toolbar_info =
"<!-- Generated with glade 3.18.3 and then changed manually -->"
"<interface>"
"<object class='GtkBox' id='toolbar'>"
"<property name='can_focus'>False</property>"
"<property name='spacing'>3</property>"
"<child>"
"<object class='GtkButton' id='toolbutton_new'>"
"<property name='can_focus'>False</property>"
"<property name='tooltip_text' translatable='yes'>New</property>"
"<property name='action_name'>example.new</property>"
"<property name='icon_name'>document-new</property>"
"<property name='hexpand'>False</property>"
"<property name='vexpand'>False</property>"
"</object>"
"</child>"
"<child>"
"<object class='GtkButton' id='toolbutton_print'>"
"<property name='can_focus'>False</property>"
"<property name='tooltip_text' translatable='yes'>Print</property>"
"<property name='action_name'>example.print</property>"
"<property name='icon_name'>document-print</property>"
"<property name='hexpand'>False</property>"
"<property name='vexpand'>False</property>"
"</object>"
"</child>"
"<child>"
"<object class='GtkSeparator' id='separator1'>"
"<property name='can_focus'>False</property>"
"<property name='hexpand'>False</property>"
"<property name='vexpand'>False</property>"
"</object>"
"</child>"
"<child>"
"<object class='GtkButton' id='toolbutton_quit'>"
"<property name='can_focus'>False</property>"
"<property name='tooltip_text' translatable='yes'>Quit</property>"
"<property name='action_name'>example.quit</property>"
"<property name='icon_name'>application-exit</property>"
"<property name='hexpand'>False</property>"
"<property name='vexpand'>False</property>"
"</object>"
"</child>"
"</object>"
"</interface>";
try
{
m_refBuilder->add_from_string(ui_toolbar_info);
}
catch(const Glib::Error& ex)
{
std::cerr << "building toolbar failed: " << ex.what();
}
// Get the menubar and add it to a container widget:
auto object = m_refBuilder->get_object("menu-example");
auto gmenu = std::dynamic_pointer_cast<Gio::Menu>(object);
if (!gmenu)
g_warning("GMenu not found");
else
{
auto pMenuBar = Gtk::make_managed<Gtk::PopoverMenuBar>(gmenu);
// Add the PopoverMenuBar to the window:
m_VBox.append(*pMenuBar);
}
// Get the toolbar and add it to a container widget:
auto toolbar = m_refBuilder->get_widget<Gtk::Box>("toolbar");
if (!toolbar)
g_warning("toolbar not found");
else
m_VBox.append(*toolbar);
}
void ExampleWindow::on_printoperation_status_changed()
{
Glib::ustring status_msg;
if (m_refPrintFormOperation->is_finished())
{
status_msg = "Print job completed.";
}
else
{
//You could also use get_status().
status_msg = m_refPrintFormOperation->get_status_string();
}
m_Statusbar.set_text(status_msg);
}
void ExampleWindow::on_printoperation_done(Gtk::PrintOperation::Result result)
{
//Printing is "done" when the print data is spooled.
if (result == Gtk::PrintOperation::Result::ERROR)
{
if (!m_refDialog)
m_refDialog = Gtk::AlertDialog::create("Error printing form");
m_refDialog->show(*this);
}
else if (result == Gtk::PrintOperation::Result::APPLY)
{
//Update PrintSettings with the ones used in this PrintOperation:
m_refSettings = m_refPrintFormOperation->get_print_settings();
}
if (!m_refPrintFormOperation->is_finished())
{
//We will connect to the status-changed signal to track status
//and update a status bar. In addition, you can, for example,
//keep a list of active print operations, or provide a progress dialog.
m_refPrintFormOperation->signal_status_changed().connect(sigc::mem_fun(*this,
&ExampleWindow::on_printoperation_status_changed));
}
}
void ExampleWindow::print_or_preview(Gtk::PrintOperation::Action print_action)
{
//Create a new PrintOperation with our PageSetup and PrintSettings:
//(We use our derived PrintOperation class)
m_refPrintFormOperation = PrintFormOperation::create();
m_refPrintFormOperation->set_name(m_NameEntry.get_text() + " " + m_SurnameEntry.get_text());
m_refPrintFormOperation->set_comments(m_refTextBuffer->get_text(false /*Don't include hidden*/));
// In the printing/advanced example, the font will be set through a custom tab
// in the print dialog.
m_refPrintFormOperation->set_track_print_status();
m_refPrintFormOperation->set_default_page_setup(m_refPageSetup);
m_refPrintFormOperation->set_print_settings(m_refSettings);
m_refPrintFormOperation->signal_done().connect(sigc::mem_fun(*this,
&ExampleWindow::on_printoperation_done));
try
{
m_refPrintFormOperation->run(print_action /* print or preview */, *this);
}
catch (const Gtk::PrintError& ex)
{
//See documentation for exact Gtk::PrintError error codes.
std::cerr << "An error occurred while trying to run a print operation:"
<< ex.what() << std::endl;
}
}
void ExampleWindow::on_menu_file_new()
{
//Clear entries and textview:
m_NameEntry.set_text("");
m_SurnameEntry.set_text("");
m_refTextBuffer->set_text("");
m_TextView.set_buffer(m_refTextBuffer);
}
void ExampleWindow::on_menu_file_page_setup()
{
//Show the page setup dialog, asking it to start with the existing settings:
auto new_page_setup =
Gtk::run_page_setup_dialog(*this, m_refPageSetup, m_refSettings);
//Save the chosen page setup dialog for use when printing, previewing, or
//showing the page setup dialog again:
m_refPageSetup = new_page_setup;
}
void ExampleWindow::on_menu_file_print_preview()
{
print_or_preview(Gtk::PrintOperation::Action::PREVIEW);
}
void ExampleWindow::on_menu_file_print()
{
print_or_preview(Gtk::PrintOperation::Action::PRINT_DIALOG);
}
void ExampleWindow::on_menu_file_quit()
{
set_visible(false);
}
</code></pre>
<p>File: <code class="filename">main.cc</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char* argv[])
{
auto app = Gtk::Application::create("org.gtkmm.example");
// Shows the window and returns when it is closed.
return app->make_window_and_run<ExampleWindow>(argc, argv, app);
}
</code></pre>
<p>File: <code class="filename">printformoperation.cc</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "printformoperation.h"
PrintFormOperation::PrintFormOperation()
{
}
PrintFormOperation::~PrintFormOperation()
{
}
Glib::RefPtr<PrintFormOperation> PrintFormOperation::create()
{
return Glib::make_refptr_for_instance<PrintFormOperation>(new PrintFormOperation());
}
void PrintFormOperation::on_begin_print(
const Glib::RefPtr<Gtk::PrintContext>& print_context)
{
//Create and set up a Pango layout for PrintData based on the passed
//PrintContext: We then use this to calculate the number of pages needed, and
//the lines that are on each page.
m_refLayout = print_context->create_pango_layout();
Pango::FontDescription font_desc("sans 12");
m_refLayout->set_font_description(font_desc);
const double width = print_context->get_width();
const double height = print_context->get_height();
m_refLayout->set_width(static_cast<int>(width * Pango::SCALE));
//Set and mark up the text to print:
Glib::ustring marked_up_form_text;
marked_up_form_text += "<b>Name</b>: " + m_Name + "\n\n";
marked_up_form_text += "<b>Comments</b>: " + m_Comments;
m_refLayout->set_markup(marked_up_form_text);
//Set the number of pages to print by determining the line numbers
//where page breaks occur:
const int line_count = m_refLayout->get_line_count();
Glib::RefPtr<Pango::LayoutLine> layout_line;
double page_height = 0;
for (int line = 0; line < line_count; ++line)
{
Pango::Rectangle ink_rect, logical_rect;
layout_line = m_refLayout->get_line(line);
layout_line->get_extents(ink_rect, logical_rect);
const double line_height = logical_rect.get_height() / 1024.0;
if (page_height + line_height > height)
{
m_PageBreaks.push_back(line);
page_height = 0;
}
page_height += line_height;
}
set_n_pages(m_PageBreaks.size() + 1);
}
void PrintFormOperation::on_draw_page(
const Glib::RefPtr<Gtk::PrintContext>& print_context, int page_nr)
{
//Decide which lines we need to print in order to print the specified page:
int start_page_line = 0;
int end_page_line = 0;
if(page_nr == 0)
{
start_page_line = 0;
}
else
{
start_page_line = m_PageBreaks[page_nr - 1];
}
if(page_nr < static_cast<int>(m_PageBreaks.size()))
{
end_page_line = m_PageBreaks[page_nr];
}
else
{
end_page_line = m_refLayout->get_line_count();
}
//Get a Cairo Context, which is used as a drawing board:
Cairo::RefPtr<Cairo::Context> cairo_ctx = print_context->get_cairo_context();
//We'll use black letters:
cairo_ctx->set_source_rgb(0, 0, 0);
//Render Pango LayoutLines over the Cairo context:
auto iter = m_refLayout->get_iter();
double start_pos = 0;
int line_index = 0;
do
{
if(line_index >= start_page_line)
{
auto layout_line = iter.get_line();
auto logical_rect = iter.get_line_logical_extents();
int baseline = iter.get_baseline();
if (line_index == start_page_line)
{
start_pos = logical_rect.get_y() / 1024.0;
}
cairo_ctx->move_to(logical_rect.get_x() / 1024.0,
baseline / 1024.0 - start_pos);
layout_line->show_in_cairo_context(cairo_ctx);
}
line_index++;
}
while(line_index < end_page_line && iter.next_line());
}
</code></pre>
</div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="sec-printing-examples-printdialog"></a>PrintDialog</h3></div></div></div>
<p>
The following example demonstrates how to print some input from a user
interface using <code class="classname">PrintDialog</code>. The user interface is
similar to the previous example.
</p>
<div class="figure">
<a name="figure-printing-printdialog"></a><p class="title"><b>Figure 21.2. Printing - PrintDialog</b></p>
<div class="figure-contents">
<div class="screenshot">
<div class="mediaobject"><img src="figures/printing_printdialog.png" alt="Printing - PrintDialog"></div>
</div>
</div>
</div>
<br class="figure-break">
<p><a class="ulink" href="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/printing/print_dialog/" target="_top">Source Code</a></p>
<p>File: <code class="filename">examplewindow.h</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class PrintFormDialog;
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow(const Glib::RefPtr<Gtk::Application>& app);
~ExampleWindow() override;
protected:
void build_main_menu(const Glib::RefPtr<Gtk::Application>& app);
// Action signal handlers:
void on_menu_file_new();
void on_menu_file_print_setup();
void on_menu_file_print();
void on_menu_file_quit();
// Printing-related objects:
Glib::RefPtr<PrintFormDialog> m_refPrintFormDialog;
// Child widgets:
Gtk::Box m_VBox;
Gtk::Grid m_Grid;
Gtk::Label m_NameLabel;
Gtk::Entry m_NameEntry;
Gtk::Label m_SurnameLabel;
Gtk::Entry m_SurnameEntry;
Gtk::Label m_CommentsLabel;
Gtk::ScrolledWindow m_ScrolledWindow;
Gtk::TextView m_TextView;
Glib::RefPtr<Gtk::TextBuffer> m_refTextBuffer;
Glib::RefPtr<Gtk::Builder> m_refBuilder;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</code></pre>
<p>File: <code class="filename">printformdialog.h</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#ifndef GTKMM_PRINT_FORM_DIALOG_H
#define GTKMM_PRINT_FORM_DIALOG_H
#include <gtkmm.h>
#include <pangomm.h>
#include <vector>
#define HAS_PRINT_DIALOG GTKMM_CHECK_VERSION(4,13,1)
#if HAS_PRINT_DIALOG
// We derive our own class from PrintDialog,
// so we can put the actual print implementation here.
class PrintFormDialog : public Gtk::PrintDialog
{
public:
static Glib::RefPtr<PrintFormDialog> create();
virtual ~PrintFormDialog();
void set_name(const Glib::ustring& name) { m_Name = name; }
void set_comments(const Glib::ustring& comments) { m_Comments = comments; }
void do_setup(Gtk::Window* parent);
void do_print(Gtk::Window* parent);
protected:
PrintFormDialog();
// PrintDialog callback slots:
void on_setup_finish(const Glib::RefPtr<Gio::AsyncResult>& result);
void on_print_finish(const Glib::RefPtr<Gio::AsyncResult>& result);
Cairo::ErrorStatus write_func(const unsigned char* data, unsigned int length,
Glib::RefPtr<Gio::OutputStream>& stream);
void do_printing(const Cairo::RefPtr<Cairo::Context>& cairo_ctx);
Glib::ustring m_Name;
Glib::ustring m_Comments;
Glib::RefPtr<Pango::Layout> m_refLayout;
Glib::RefPtr<Gtk::PrintSetup> m_refPrintSetup;
};
#endif // HAS_PRINT_DIALOG
#endif // GTKMM_PRINT_FORM_DIALOG_H
</code></pre>
<p>File: <code class="filename">examplewindow.cc</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "examplewindow.h"
#include "printformdialog.h"
#include <iostream>
ExampleWindow::ExampleWindow(const Glib::RefPtr<Gtk::Application>& app)
: m_VBox(Gtk::Orientation::VERTICAL),
m_NameLabel("Name"),
m_SurnameLabel("Surname"),
m_CommentsLabel("Comments")
{
set_title("gtkmm PrintDialog Example");
set_default_size(400, 300);
#if HAS_PRINT_DIALOG
// Create a PrintDialog. (We use our derived PrintDialog class.)
m_refPrintFormDialog = PrintFormDialog::create();
#endif // HAS_PRINT_DIALOG
set_child(m_VBox);
build_main_menu(app);
m_VBox.append(m_Grid);
// Arrange the widgets inside the grid:
m_Grid.set_expand(true);
m_Grid.set_row_spacing(5);
m_Grid.set_column_spacing(5);
m_Grid.attach(m_NameLabel, 0, 0);
m_Grid.attach(m_NameEntry, 1, 0);
m_Grid.attach(m_SurnameLabel, 0, 1);
m_Grid.attach(m_SurnameEntry, 1, 1);
// Add the TextView, inside a ScrolledWindow:
m_ScrolledWindow.set_child(m_TextView);
// Only show the scrollbars when they are necessary:
m_ScrolledWindow.set_policy(Gtk::PolicyType::AUTOMATIC, Gtk::PolicyType::AUTOMATIC);
m_Grid.attach(m_CommentsLabel, 0, 2);
m_Grid.attach(m_ScrolledWindow, 1, 2);
m_ScrolledWindow.set_expand(true);
m_refTextBuffer = Gtk::TextBuffer::create();
m_TextView.set_buffer(m_refTextBuffer);
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::build_main_menu(const Glib::RefPtr<Gtk::Application>& app)
{
// Create actions for menus and toolbars:
auto refActionGroup = Gio::SimpleActionGroup::create();
// File menu:
refActionGroup->add_action("new",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_new));
refActionGroup->add_action("printsetup",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_print_setup));
refActionGroup->add_action("print",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_print));
refActionGroup->add_action("quit",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_quit));
insert_action_group("example", refActionGroup);
// When the menubar is a child of a Gtk::Window, keyboard accelerators are not
// automatically fetched from the Gio::Menu.
// See the examples/book/menus/main_menu example for an alternative way of
// adding the menubar when using Gtk::ApplicationWindow.
app->set_accel_for_action("example.new", "<Primary>n");
app->set_accel_for_action("example.print", "<Primary>p");
app->set_accel_for_action("example.quit", "<Primary>q");
m_refBuilder = Gtk::Builder::create();
// Layout the actions in a menubar:
Glib::ustring ui_menu_info =
"<interface>"
" <menu id='menu-example'>"
" <submenu>"
" <attribute name='label' translatable='yes'>_File</attribute>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>_New</attribute>"
" <attribute name='action'>example.new</attribute>"
" </item>"
" </section>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>Print _Setup...</attribute>"
" <attribute name='action'>example.printsetup</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>_Print...</attribute>"
" <attribute name='action'>example.print</attribute>"
" </item>"
" </section>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>_Quit</attribute>"
" <attribute name='action'>example.quit</attribute>"
" </item>"
" </section>"
" </submenu>"
" </menu>"
"</interface>";
try
{
m_refBuilder->add_from_string(ui_menu_info);
}
catch(const Glib::Error& ex)
{
std::cerr << "building menus failed: " << ex.what();
}
// Layout the actions in a toolbar:
Glib::ustring ui_toolbar_info =
"<!-- Generated with glade 3.18.3 and then changed manually -->"
"<interface>"
"<object class='GtkBox' id='toolbar'>"
"<property name='can_focus'>False</property>"
"<property name='spacing'>3</property>"
"<child>"
"<object class='GtkButton' id='toolbutton_new'>"
"<property name='can_focus'>False</property>"
"<property name='tooltip_text' translatable='yes'>New</property>"
"<property name='action_name'>example.new</property>"
"<property name='icon_name'>document-new</property>"
"<property name='hexpand'>False</property>"
"<property name='vexpand'>False</property>"
"</object>"
"</child>"
"<child>"
"<object class='GtkButton' id='toolbutton_print'>"
"<property name='can_focus'>False</property>"
"<property name='tooltip_text' translatable='yes'>Print</property>"
"<property name='action_name'>example.print</property>"
"<property name='icon_name'>document-print</property>"
"<property name='hexpand'>False</property>"
"<property name='vexpand'>False</property>"
"</object>"
"</child>"
"<child>"
"<object class='GtkSeparator' id='separator1'>"
"<property name='can_focus'>False</property>"
"<property name='hexpand'>False</property>"
"<property name='vexpand'>False</property>"
"</object>"
"</child>"
"<child>"
"<object class='GtkButton' id='toolbutton_quit'>"
"<property name='can_focus'>False</property>"
"<property name='tooltip_text' translatable='yes'>Quit</property>"
"<property name='action_name'>example.quit</property>"
"<property name='icon_name'>application-exit</property>"
"<property name='hexpand'>False</property>"
"<property name='vexpand'>False</property>"
"</object>"
"</child>"
"</object>"
"</interface>";
try
{
m_refBuilder->add_from_string(ui_toolbar_info);
}
catch(const Glib::Error& ex)
{
std::cerr << "building toolbar failed: " << ex.what();
}
// Get the menubar and add it to a container widget:
auto object = m_refBuilder->get_object("menu-example");
auto gmenu = std::dynamic_pointer_cast<Gio::Menu>(object);
if (!gmenu)
g_warning("GMenu not found");
else
{
auto pMenuBar = Gtk::make_managed<Gtk::PopoverMenuBar>(gmenu);
// Add the PopoverMenuBar to the window:
m_VBox.append(*pMenuBar);
}
// Get the toolbar and add it to a container widget:
auto toolbar = m_refBuilder->get_widget<Gtk::Box>("toolbar");
if (!toolbar)
g_warning("toolbar not found");
else
m_VBox.append(*toolbar);
}
void ExampleWindow::on_menu_file_new()
{
// Clear entries and textview:
m_NameEntry.set_text("");
m_SurnameEntry.set_text("");
m_refTextBuffer->set_text("");
m_TextView.set_buffer(m_refTextBuffer);
}
void ExampleWindow::on_menu_file_print_setup()
{
#if HAS_PRINT_DIALOG
m_refPrintFormDialog->do_setup(this);
#else
std::cout << "Gtk::PrintDialog is not available.\n";
#endif // HAS_PRINT_DIALOG
}
void ExampleWindow::on_menu_file_print()
{
#if HAS_PRINT_DIALOG
m_refPrintFormDialog->set_name(m_NameEntry.get_text() + " " + m_SurnameEntry.get_text());
m_refPrintFormDialog->set_comments(m_refTextBuffer->get_text(false /*Don't include hidden*/));
m_refPrintFormDialog->do_print(this);
#else
std::cout << "Gtk::PrintDialog is not available.\n";
#endif // HAS_PRINT_DIALOG
}
void ExampleWindow::on_menu_file_quit()
{
set_visible(false);
}
</code></pre>
<p>File: <code class="filename">main.cc</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char* argv[])
{
auto app = Gtk::Application::create("org.gtkmm.example");
// Shows the window and returns when it is closed.
return app->make_window_and_run<ExampleWindow>(argc, argv, app);
}
</code></pre>
<p>File: <code class="filename">printformdialog.cc</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "printformdialog.h"
#include <iostream>
#if HAS_PRINT_DIALOG
PrintFormDialog::PrintFormDialog()
{
set_page_setup(Gtk::PageSetup::create());
set_print_settings(Gtk::PrintSettings::create());
}
PrintFormDialog::~PrintFormDialog()
{
}
Glib::RefPtr<PrintFormDialog> PrintFormDialog::create()
{
return Glib::make_refptr_for_instance<PrintFormDialog>(new PrintFormDialog());
}
void PrintFormDialog::do_setup(Gtk::Window* parent)
{
set_title("Print setup");
if (parent)
setup(*parent, sigc::mem_fun(*this, &PrintFormDialog::on_setup_finish));
else
setup(sigc::mem_fun(*this, &PrintFormDialog::on_setup_finish));
}
void PrintFormDialog::do_print(Gtk::Window* parent)
{
set_title("Printing");
if (parent)
print(*parent, sigc::mem_fun(*this, &PrintFormDialog::on_print_finish));
else
print(sigc::mem_fun(*this, &PrintFormDialog::on_print_finish));
}
void PrintFormDialog::on_setup_finish(const Glib::RefPtr<Gio::AsyncResult>& result)
{
try
{
m_refPrintSetup = setup_finish(result);
if (m_refPrintSetup)
{
set_page_setup(m_refPrintSetup->get_page_setup());
set_print_settings(m_refPrintSetup->get_print_settings());
}
}
catch (const Gtk::DialogError& err)
{
// Can be thrown by setup_finish(result).
std::cout << "No setup selected. " << err.what() << std::endl;
}
catch (const Glib::Error& err)
{
std::cout << "Unexpected exception. " << err.what() << std::endl;
}
}
void PrintFormDialog::on_print_finish(const Glib::RefPtr<Gio::AsyncResult>& result)
{
Glib::RefPtr<Gio::OutputStream> outputStream;
try
{
outputStream = print_finish(result);
}
catch (const Gtk::DialogError& err)
{
// Can be thrown by print_finish(result).
std::cout << "No output stream. " << err.what() << std::endl;
return;
}
catch (const Glib::Error& err)
{
std::cout << "Unexpected exception. " << err.what() << std::endl;
return;
}
const double paper_width = get_page_setup()->get_paper_width(Gtk::Unit::POINTS);
const double paper_height = get_page_setup()->get_paper_height(Gtk::Unit::POINTS);
auto cairo_surface = Cairo::PdfSurface::create_for_stream(
sigc::bind(sigc::mem_fun(*this, &PrintFormDialog::write_func), outputStream),
paper_width, paper_height);
auto cairo_ctx = Cairo::Context::create(cairo_surface);
do_printing(cairo_ctx);
// cairo_surface->finish() calls write_func(),
// which must be done before the stream is closed.
cairo_surface->finish();
try
{
outputStream->close();
}
catch (const Glib::Error& err)
{
std::cout << "Error closing stream. " << err.what() << std::endl;
}
}
Cairo::ErrorStatus PrintFormDialog::write_func(const unsigned char* data,
unsigned int length, Glib::RefPtr<Gio::OutputStream>& stream)
{
try
{
gsize bytes_written = 0;
stream->write_all(data, length, bytes_written);
}
catch (const Glib::Error& err)
{
std::cout << "Error writing to stream. " << err.what() << std::endl;
return CAIRO_STATUS_WRITE_ERROR;
}
return CAIRO_STATUS_SUCCESS;
}
void PrintFormDialog::do_printing(const Cairo::RefPtr<Cairo::Context>& cairo_ctx)
{
m_refLayout = Pango::Layout::create(cairo_ctx);
m_refLayout->set_font_description(Pango::FontDescription("sans 12"));
const auto page_setup = get_page_setup();
const double page_width = page_setup->get_page_width(Gtk::Unit::POINTS);
const double page_height = page_setup->get_page_height(Gtk::Unit::POINTS);
const double left_margin = page_setup->get_left_margin(Gtk::Unit::POINTS);
const double top_margin = page_setup->get_top_margin(Gtk::Unit::POINTS);
m_refLayout->set_width(static_cast<int>(page_width * Pango::SCALE));
m_refLayout->set_wrap(Pango::WrapMode::WORD_CHAR);
cairo_ctx->translate(left_margin, top_margin);
// Set and mark up the text to print:
Glib::ustring marked_up_form_text =
"<b>Name</b>: " + m_Name + "\n\n" +
"<b>Comments</b>: " + m_Comments;
m_refLayout->set_markup(marked_up_form_text);
// We'll use black letters:
cairo_ctx->set_source_rgb(0, 0, 0);
// Render Pango LayoutLines over the Cairo context:
const double inverse_pango_scale = 1.0 / Pango::SCALE;
double page_y = 0.0;
auto iter = m_refLayout->get_iter();
double start_y_pos = iter.get_line_logical_extents().get_y() * inverse_pango_scale;
do
{
const auto layout_line = iter.get_line();
const auto logical_rect = iter.get_line_logical_extents();
const double line_height = logical_rect.get_height() * inverse_pango_scale;
if (page_y + line_height > page_height)
{
// Start a new page.
cairo_ctx->show_page();
page_y = 0.0;
start_y_pos = logical_rect.get_y() * inverse_pango_scale;
}
page_y += line_height;
cairo_ctx->move_to(logical_rect.get_x() * inverse_pango_scale,
iter.get_baseline() * inverse_pango_scale - start_y_pos);
layout_line->show_in_cairo_context(cairo_ctx);
}
while (iter.next_line());
cairo_ctx->show_page();
}
#endif // HAS_PRINT_DIALOG
</code></pre>
</div>
</div>
<div class="navfooter">
<hr>
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left">
<a accesskey="p" href="sec-printing-printdialog.html"><img src="icons/prev.png" alt="Prev"></a> </td>
<td width="20%" align="center"><a accesskey="u" href="chapter-printing.html"><img src="icons/up.png" alt="Up"></a></td>
<td width="40%" align="right"> <a accesskey="n" href="chapter-recent-documents.html"><img src="icons/next.png" alt="Next"></a>
</td>
</tr>
<tr>
<td width="40%" align="left" valign="top">PrintDialog </td>
<td width="20%" align="center"><a accesskey="h" href="index.html"><img src="icons/home.png" alt="Home"></a></td>
<td width="40%" align="right" valign="top"> Chapter 22. Recently Used Documents</td>
</tr>
</table>
</div>
</body>
</html>
|