Control Rendering in Print Document
Often times we want to display a control, rendered on a Windows form, in a C1PrintDocument. However, being that there is no direct method to achieve this, we can follow the approach mentioned in this blog. The idea is to capture the control's state as an image object and then render it the same in a Print Document. The implementation, though, is something that makes this worth reading. We will use C1Flexgrid control with a bound image column and then render it on a C1PrintDocument.
Step 1: Display Bound Images in C1FlexGrid
Step One is carried out by binding C1FlexGrid with a datasource. For simplicity we are using Category table of C1Nwind database. //Binding C1FlexGrid categoriesTableAdapter.Connection = new OleDbConnection(GetConnectionString()); categoriesTableAdapter.Fill(this.c1NWindDataSet.Categories); _flex.DataSource = c1NWindDataSet.Tables[0]; The GetConnectionString() method here would return the path for the C1Nwind.mdb :
To view images rendered within a flexgrid column, it is necessary to make some changes. By default, the visibility of the image column is set as false. Set the visibility of Picture column to True. Furthermore, we need to set the custom cell drawing, which is done by setting the DrawMode property of the grid to OwnerDraw and subscribing the OwnerDrawCell event. Finally, making all the preceding revisions would require the following code which we have added in the Form_Load event :
Within the OwnerDrawCell event we parse the image column of the grid by converting each cell into an individual image object :
The LoadImage() method is a subroutine to convert the Byte[] array to Bitmap images :
At the end of step one, we have a bound Flexgrid with an image column.
Step 2: Capture an image of C1FlexGrid
Now we will capture the image of C1FlexGrid using a GetControlImage() method. This is a simple method that uses the ClientRectangle of the control and the DrawToBitmap() method of Control class to convert it into a bitmap image with a zoom-like speed.
We will use this method when opening a form containing C1PrintPreviewControl :
Step 3: Render Captured Image in C1PrintDocument
The last step is to render the captured image in a C1PrintDocunment. We will add 2 objects to the document -- RenderText and RenderImage. RenderText renders text on the PrintDocument whereas RenderImage renders the captured C1FlexGrid image. We also define the default unit and page margins for the document in this step. The code should look as follows :
When we run the application, C1FlexGrid is displayed on the form. Click on the Render To PrintDocument button and the flexgrid will appear on the C1PrintPreviewControl. Download Sample