Overriding XtraReport or print preview toolbar commands

I happened upon a cool question on the Support Center the other day, asking how to override the default functionality in the Print Preview window to email a document via Gmail. If you look at the default Print Preview (in either ribbon or standard toolbar configuration), you’ll see that you’re given the option to email the document in various formats (Pdf, Xls, RTF etc…): Print Preview window Doing so will typically open a dialog window which prompts you to save the file to your computer before your default email program is opened and the file is attached. This is all done via MAPI, which may not be the method you want to take. It opens the user’s default email client and constructs a blank message with the file attached. Historically, DevExpress used the 32-bit version of MAPI which causes issues if you were to build your application to 64 bit. Additionally, you may not want to save the file to your computer before sending it because then you’ll need to delete it afterwards. And if your end user doesn’t have a default email program set up on their PC, they’ll be prompted with the Windows email wizard which attempts to walk them through the process of setting up an email account. So what if you’d prefer the document to be emailed through your server or a third-party server like Gmail? At first glance you have a couple of options:

  • Create a form, place a DocumentViewer component on the form and then create your own toolbar. You’ll have to provide your own implementation for each of the various commands that are offered by the built-in Document Viewer toolbar.
  • Do the same as above, but create the default Document Viewer toolbar (or ribbon control) via the smart tag. Then, assign an ItemClick event handler to the functions you’d like to control. The problem is that your code will run first and then the default button command will run afterwards. Hardly ideal.
  • Again, create a form with a Document Viewer but remove the BarButtomItems that you want to override. Insert your own BarButtonItems for the commands that you’d like to control. There’s nothing inherently wrong with this approach unless you want to use the built-in print-preview methods offered by controls like the XtraGrid or the XtraTreeList. In this case, they’ll use the default print preview window rather than your custom one.

So it can be done, but I’m not sure if any of these options are really optimal. Fortunately for us, all of the BarButtomItems in the Document Viewer window implement an ICommandHandler interface which, when implemented, tells the Document Viewer window two important things:

  1. Can I handle this command? (done by implementing the CanHandleCommand method)
  2. How should I handle this command? (done by implementing the HandleCommand method)

All of this is detailed in the documentation topic for How to: Execute and Modify Commands in a Print Preview. So how can we apply this to the topic that was originally presented?

Assuming we have a simple project containing an XtraReport and we want to send a Pdf copy via Gmail through the standard toolbar, we’ll need to first create our own CommandHandler.

To create your own CommandHandler, create a new class in Visual Studio and name it “MyCommandHandler”. Your class will need to implement ICommandHandler. You can then tell Visual Studio to implement the interface, which will automatically insert a CanHandleCommand and a HandleCommand method.

Let’s start with the CanHandleCommand method:

public virtual bool CanHandleCommand(PrintingSystemCommand command, IPrintControl control)
    //This handler overrides the Send Pdf command.
    return command == PrintingSystemCommand.SendPdf;

This crux of this method is to tell the Document Viewer (or printing system) if this handler can process the provided command. The PrintingSystemCommand enum contains all of the commands that are available by the default toolbar/ribbon control. In this case, we’re telling the printing system that we can handle the SendPdf command ourselves and no default action is necessary.

That being said, we now have to do the heavy lifting ourselves and actually do something when the button is clicked. To do that, we provide an implementation for the HandleCommand method.

public virtual void HandleCommand(PrintingSystemCommand command, object[] args, IPrintControl control, ref bool handled)

    const string Username = "YOUR_GMAIL_USERNAME_HERE";   //your username here
    const string Password = "YOUR_GMAIL_PASSWORD_HERE"; ///your password here

    if (CanHandleCommand(command, control) == false)

    using (MailMessage mailMessage = new MailMessage())
        //Set to/from
        mailMessage.From = new MailAddress("email address here");
        mailMessage.To.Add(new MailAddress("email address here"));
        mailMessage.Subject = "Test message";
        mailMessage.Body = "This is my test email!";

        //Create an attachment
        using (MemoryStream ms = new MemoryStream())
            ms.Position = 0;
            mailMessage.Attachments.Add(new Attachment(ms, "MyFile.pdf", "application/pdf"));

            using (SmtpClient client = new SmtpClient())
                client.Host = "smtp.gmail.com";
                client.Port = 587;
                client.EnableSsl = true;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(Username, Password);


    //Ensure the default action isn't fired by setting Handled to True
    handled = true;

So here we’ve created a nice implementation that sends a Pdf copy of the document via email.

Note that I’ve decided to user a MemoryStream here instead of saving the Pdf file to the user’s PC first. This alleviates the need to save a file to the disk, but it does remove the ability to customize the Pdf. If you want to change some of the Pdf properties upon export, you can use the PdfExportOptions class offered by the ExportToPdf overload.

The only thing left to do is tell our PrintPreview window to actually use this CommandHandler. We do that via the PrintingSystem.AddCommandHandler method:

// Create a report instance, assigned to a Print Tool.
ReportPrintTool pt = new ReportPrintTool(new XtraReport1());

// Generate the report's document. This step is required
// to activate its PrintingSystem and access it later.

// Override the Send Pdf command.
pt.PrintingSystem.AddCommandHandler(new SendToGmailCommandHandler());

// Show the report's print preview.

And just like that, we’ve overrided the default behavior and created our own implementation.

Going forward, we can also use this CommandHandler for print previewing other DevExpress controls such as the GridControl. By handling the GridView’s PrintInitialize event, we can insert our CommandHandler and reuse the same implementation:

private void gridView1_PrintInitialize(object sender, DevExpress.XtraGrid.Views.Base.PrintInitializeEventArgs e)
    (e.PrintingSystem as PrintingSystemBase).AddCommandHandler(new MyCommandHandler());

The full source code is available here: CustomCommandHandler

Overriding XtraReport or print preview toolbar commands

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s