This is a migrated thread and some comments may be shown as answers.

Problem of printing in LandScape

12 Answers 192 Views
RichTextBox
This is a migrated thread and some comments may be shown as answers.
Guy
Top achievements
Rank 1
Guy asked on 13 Dec 2011, 09:38 PM
Hi,

I have a problem of printing in LandScape a document i created using a RadRichTextBox.
I customized my RadDocument by setting different properties ( defaultPageLayoutSettings, sectionDefaultPageOrientation,  sectionDefaultPageMargin, etc).
When SectionDefaultPageOrientation is set to LandScape PageOrientation, this setting doesn't affect when printing (using native PrintMode) but if i export the same document in PDF, the exported document is done in LandScape.
Is there any trick to overcome this misbehaviour.

thank you for your support.

12 Answers, 1 is accepted

Sort by
0
Boby
Telerik team
answered on 19 Dec 2011, 12:36 PM
Hi Guy,
Unfortunately this is bug which cannot be workarounded. We will add it to our TODO list and will try to fix it for the next release.

Please, excuse us for the inconvenience. We have added points to your account for the report. Don't hesitate to contact us if you have other questions.


All the best,
Boby
the Telerik team

Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

0
Guy
Top achievements
Rank 1
answered on 07 Mar 2012, 04:53 PM
Hi Boby,

I checked in the latest versions of both RadControls of silverlight 4 and 5 and  the RadRichTextBox still not printing in LandScape.. Is there any workaround i can do because i really need it.

Thank u for your Help.

Guy 
 
0
Vasil
Telerik team
answered on 12 Mar 2012, 03:45 PM
Hi Guy,

We have scheduled to resolve this problem for the upcoming 2012 Q1 SP1 release, expected at the end of March.

I hope this sounds good for you.

Greetings,
Vasil
the Telerik team
Sharpen your .NET Ninja skills! Attend Q1 webinar week and get a chance to win a license! Book your seat now >>
0
Jaco De Villiers
Top achievements
Rank 2
answered on 11 May 2012, 10:14 AM
I have the same problem in Silverlight.  I have the following code (below).  If you set your printer paper orientation to landscape; then the pages are printed as portrait rotated on the landscape pages.  I need to set the both the orientation and the paper size 

Please help

GalaSoft.MvvmLight.Threading.DispatcherHelper.UIDispatcher.BeginInvoke((Action)(() =>
{
        rtb.Document.SectionDefaultPageMargin = new Telerik.Windows.Documents.Layout.Padding(0);
    rtb.Document.SectionDefaultPageOrientation = PageOrientation.Landscape;
    rtb.Document.Measure(RadDocument.MAX_DOCUMENT_SIZE);
    rtb.Document = CreateDocument(package);
}));
rtb.Print(package.Name, Telerik.Windows.Documents.UI.PrintMode.Native);
0
Vasil
Telerik team
answered on 16 May 2012, 08:08 AM
Hi Jaco De Villiers,
We have fixed this failure in 2012 Q1 SP1 version of the controls, so you could upgrade your project and this problem should not persist any more.

I hope this helps. Don't hesitate to contact us if you have other questions.

Kind regards,
Vasil
the Telerik team

Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

0
Jaco De Villiers
Top achievements
Rank 2
answered on 16 May 2012, 10:58 AM
I think I am on the latest version (2012.1.326.1050).
0
Vasil
Telerik team
answered on 21 May 2012, 11:30 AM
Hello Jaco De Villiers,
Maybe not all references Telerik assemblies are 2012 Q1 SP1 version (2012.1.326.1050) - could you please verify this? Otherwise, you just need to change the page orientation of the document and send it to the printer as follows:
this.radRichTextBox.Document.SectionDefaultPageOrientation = PageOrientation.Landscape;
this.radRichTextBox.Print("document", PrintMode.Native);
If the problem continues, please send us a sample project using a support ticket, so we can further investigate it and provide a resolution.

Kind regards,
Vasil
the Telerik team

Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

0
Jaco De Villiers
Top achievements
Rank 2
answered on 30 May 2012, 06:25 PM
I have confirmed that I am on the latest version.

Unfortunately the application is part of a MEF application and need to be broken up to get a sample working.  I am attaching the actual print helper, but will try and get a sample going by isolating the print code and serializing the data

Regards
Jaco
using System.Windows;
using System.Linq;
using System.Collections.ObjectModel;
using Sym.Entities.PM;
using Telerik.Windows.Documents.Model;
using System.Collections.Generic;
using Sym.Entities.Shared;
using Telerik.Windows.Controls;
using System;
using System.Windows.Controls;
using Telerik.Windows.Documents.FormatProviders.Pdf;
using System.IO;
 
namespace Sym.SL.BSC.ViewModel
{
    /// <summary>
    ///
    /// </summary>
    public class PrintHelper : Sym.Entities.EntityBase
    {
        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="PrintHelper" /> class.
        /// </summary>
        public PrintHelper()
        {
            this.DocumentReady += new EventHandler<PrintDocumentArgs>((sender, args) =>
            {
                GalaSoft.MvvmLight.Threading.DispatcherHelper.UIDispatcher.BeginInvoke((Action)(() =>
                {
                    args.RichTextBoxContainer.Document.SectionDefaultPageMargin = new Telerik.Windows.Documents.Layout.Padding(0);
                    args.RichTextBoxContainer.Document.SectionDefaultPageOrientation = PageOrientation.Landscape;
                    args.RichTextBoxContainer.Document.Measure(RadDocument.MAX_DOCUMENT_SIZE);
                    args.RichTextBoxContainer.Document = args.DocumentToPrint;
                }));
                args.RichTextBoxContainer.Print(args.DocumentName, Telerik.Windows.Documents.UI.PrintMode.Native);
            });
        }
 
        #endregion
 
        #region Private member variables
        private static Dictionary<string, string> _kpiLegends = new Dictionary<string, string>();
        #endregion
 
        #region Enums
        private enum ParagrapStyles
        {
            DefaultText,
            TableCellHeaderParagraph,
            ModuleName,
            SectionName,
            KPAGrouping,
            KPA
        }
        #endregion
 
        #region Static Properties
        private static Dictionary<ParagrapStyles, Telerik.Windows.Documents.Model.Styles.StyleDefinition> _documentStyles;
        private static Dictionary<string, FrameworkElement[]> _moduleCharts = new Dictionary<string, FrameworkElement[]>();
        /// <summary>
        /// Gets or sets the module charts.
        /// </summary>
        /// <value>
        /// The module charts.
        /// </value>
        public static Dictionary<string, FrameworkElement[]> ModuleCharts
        {
            get { return PrintHelper._moduleCharts; }
            set { PrintHelper._moduleCharts = value; }
        }
 
        #endregion
 
        #region Static Methods
 
        /// <summary>
        /// Loads the styles shared in the document.
        /// </summary>
        private static void _loadStyles()
        {
            if (_documentStyles == null) _documentStyles = new Dictionary<ParagrapStyles, Telerik.Windows.Documents.Model.Styles.StyleDefinition>();
            _documentStyles.Clear();
 
            #region Default Text
            var defaultText = new Telerik.Windows.Documents.Model.Styles.StyleDefinition(Telerik.Windows.Documents.Model.Styles.StyleType.Paragraph)
            {
                Name = ParagrapStyles.DefaultText.ToString(),
                DisplayName = ParagrapStyles.DefaultText.ToString(),
            };
            defaultText.SpanProperties.FontFamily = new System.Windows.Media.FontFamily("Trebuche MS");
            defaultText.SpanProperties.FontSize = 6;
            _documentStyles.Add(ParagrapStyles.DefaultText, defaultText);
            #endregion
 
            #region TableCellHeaderParagraph
            var tableCellHeaderP = new Telerik.Windows.Documents.Model.Styles.StyleDefinition(Telerik.Windows.Documents.Model.Styles.StyleType.Paragraph)
            {
                BasedOn = defaultText,
                Name = ParagrapStyles.TableCellHeaderParagraph.ToString(),
                DisplayName = ParagrapStyles.TableCellHeaderParagraph.ToString()
            };
            tableCellHeaderP.SpanProperties.FontWeight = FontWeights.Bold;
            _documentStyles.Add(ParagrapStyles.TableCellHeaderParagraph, tableCellHeaderP);
            #endregion
 
            #region Section Name
            var sectionName = new Telerik.Windows.Documents.Model.Styles.StyleDefinition(Telerik.Windows.Documents.Model.Styles.StyleType.Paragraph)
            {
                BasedOn = defaultText,
                Name = ParagrapStyles.SectionName.ToString(),
                DisplayName = ParagrapStyles.SectionName.ToString()
            };
            sectionName.SpanProperties.ForeColor = System.Windows.Media.Colors.Blue;
            sectionName.SpanProperties.FontSize = 12;
            sectionName.SpanProperties.FontWeight = FontWeights.Bold;
            sectionName.SpanProperties.FontStyle = FontStyles.Italic;
            _documentStyles.Add(ParagrapStyles.SectionName, sectionName);
            #endregion
 
            #region Grouping Name
            var groupingName = new Telerik.Windows.Documents.Model.Styles.StyleDefinition(Telerik.Windows.Documents.Model.Styles.StyleType.Paragraph)
            {
                BasedOn = sectionName,
                Name = ParagrapStyles.KPAGrouping.ToString(),
                DisplayName = ParagrapStyles.KPAGrouping.ToString()
            };
            _documentStyles.Add(ParagrapStyles.KPAGrouping, groupingName);
            #endregion
 
            #region KPA Name
            var kpa = new Telerik.Windows.Documents.Model.Styles.StyleDefinition(Telerik.Windows.Documents.Model.Styles.StyleType.Paragraph)
            {
                BasedOn = sectionName,
                Name = ParagrapStyles.KPA.ToString(),
                DisplayName = ParagrapStyles.KPA.ToString()
            };
            kpa.SpanProperties.FontSize = 10;
            _documentStyles.Add(ParagrapStyles.KPA, kpa);
            #endregion
        }
 
        /// <summary>
        /// Loads the kpi values row.
        /// </summary>
        /// <param name="kpiTable">The kpi table.</param>
        /// <param name="visibleColumnNames">The visible column names.</param>
        /// <param name="row">The row.</param>
        /// <param name="columns">The columns.</param>
        /// <param name="moduleName">Name of the module.</param>
        /// <param name="scaleId">The scale id.</param>
        private static void _loadKpiRow(Table kpiTable, List<string> visibleColumnNames, DataRow row, List<LabelAndValue> columns, string moduleName, string scaleId)
        {
            // Do not add the row if not scored is set
            if (row["Not_Scored"] != null)
            {
                // Check if the row is marked as notscored.  if so, exit: row should not be printed
                bool? notScored = (bool?)row["Not_Scored"];
                if (notScored.HasValue && notScored.Value == true) return;
            }
 
            TableRow kpiValueRow = new TableRow();
            kpiTable.AddRow(kpiValueRow);
            foreach (var columnName in visibleColumnNames)
            {
                TableCell kpiValueCell = new TableCell();
                var col = columns.Where(w => w.Label.Equals(columnName)).FirstOrDefault();
                if (col != null)
                {
                    kpiValueCell.PreferredWidth = new TableWidthUnit(TableWidthUnitType.Percent, 0);
                }
                kpiValueRow.Cells.Add(kpiValueCell);
 
                string spanValue = _getSpanValue(row[columnName]);
                if (columnName.Equals("Rating1", StringComparison.OrdinalIgnoreCase) || columnName.Equals("Rating2", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        string newSpanValue = Globals.RatingScales[scaleId].Where(w => w.Value.ToString().Equals(spanValue)).Select(s => s.Label).FirstOrDefault();
                        if (string.IsNullOrEmpty(newSpanValue))
                        {
                            decimal valueToFind = decimal.Parse(spanValue);
                            foreach (var item in Globals.RatingScales[scaleId])
                            {
                                decimal itemValue = decimal.Parse(item.Value.ToString());
                                if (valueToFind.Equals(itemValue))
                                {
                                    newSpanValue = item.Label;
                                    break;
                                }
                            }
                            if (!string.IsNullOrEmpty(newSpanValue))
                            {
                                spanValue = newSpanValue;
                            }
                            //if (spanValue.Contains(".00"))
                            //{
                            //  string valueToFind = spanValue.Replace(".00", "");
                            //  spanValue = Globals.RatingScales[scaleId].Where(w => w.Value.ToString().Equals(valueToFind)).Select(s => s.Display).FirstOrDefault();
                            //}
                            //else if (spanValue.Contains(".50"))
                            //{
                            //  string valueToFind = spanValue.Replace(".50", ".5");
                            //  spanValue = Globals.RatingScales[scaleId].Where(w => w.Value.ToString().Equals(valueToFind)).Select(s => s.Display).FirstOrDefault();
                            //}
                        }
                        else
                        {
                            spanValue = newSpanValue;
                        }
                    }
                    catch { }
                }
                if (!string.IsNullOrEmpty(spanValue))
                {
                    Paragraph kpiValueParagraph = new Paragraph();
                    kpiValueParagraph.Style = _documentStyles[ParagrapStyles.DefaultText];
                    kpiValueCell.Blocks.Add(kpiValueParagraph);
 
                    Span kpiValueSpan = new Span(spanValue);
                    kpiValueParagraph.Inlines.Add(kpiValueSpan);
                }
            }
        }
 
        /// <summary>
        /// Loads the KPI headings.
        /// </summary>
        /// <param name="columns">The columns.</param>
        /// <param name="kpiTable">The kpi table.</param>
        /// <param name="grouping">The grouping.</param>
        /// <param name="kpa">The kpa.</param>
        /// <param name="moduleName">Name of the module.</param>
        /// <param name="visibleColumnNames">The visible column names.</param>
        private static void _loadKPIHeadings(List<LabelAndValue> columns, Table kpiTable, KPAGrouping grouping, KPA kpa, string moduleName, bool addGroupingHeader, out List<string> visibleColumnNames)
        {
            #region Add Grouping Row
            TableCell groupingCell = new TableCell();
            if (addGroupingHeader)
            {
 
                TableRow groupingHeaderRow = new TableRow();
                kpiTable.AddRow(groupingHeaderRow);
 
                groupingCell.Background = System.Windows.Media.Colors.Gray;
                groupingHeaderRow.Cells.Add(groupingCell);
 
                Paragraph groupingParagraph = new Paragraph();
                groupingParagraph.Style = _documentStyles[ParagrapStyles.KPAGrouping];
                groupingCell.Blocks.Add(groupingParagraph);
 
                string groupingHeaderText = grouping.Name;
                if (moduleName.Equals("Balance Scorecard", StringComparison.OrdinalIgnoreCase))
                {
                    groupingHeaderText += string.Format("\tSelf Rating: {0:0.00}\t\tManager Rating: {1:0.00}\t\tWeight: {2}%", grouping.Score1, grouping.Score2, grouping.Weight);
                }
 
                Span groupingHeaderSpan = new Span(groupingHeaderText);
                groupingParagraph.Inlines.Add(groupingHeaderSpan);
            }
            #endregion
 
            #region Add KPA Row
            TableRow kpaHeaderRow = new TableRow();
            kpiTable.AddRow(kpaHeaderRow);
 
            TableCell kpaHeaderCell = new TableCell();
            kpaHeaderCell.Background = System.Windows.Media.Colors.LightGray;
            kpaHeaderRow.Cells.Add(kpaHeaderCell);
 
            Paragraph kpaHeaderParagraph = new Paragraph();
            kpaHeaderParagraph.Style = _documentStyles[ParagrapStyles.KPA];
            kpaHeaderCell.Blocks.Add(kpaHeaderParagraph);
 
            string kpaHeaderText = kpa.Name;
            if (moduleName.Equals("Balance Scorecard", StringComparison.OrdinalIgnoreCase))
            {
                kpaHeaderText += string.Format("\tSelf Rating: {0:0.00}\t\tManager Rating: {1:0.00}\t\tWeight: {2}%", kpa.Score1, kpa.Score2, kpa.Weight);
            }
 
            Span kpaHeaderSpan = new Span(kpaHeaderText);
            kpaHeaderParagraph.Inlines.Add(kpaHeaderSpan);
            #endregion
 
            TableRow kpiHeaderRow = new TableRow();
            kpiTable.AddRow(kpiHeaderRow);
            visibleColumnNames = new List<string>();
 
            foreach (var col in columns.Where(w => w.IsVisible))
            {
                TableCell kpiHeaderCell = new TableCell();
                kpiHeaderCell.Background = System.Windows.Media.Colors.LightGray;
                kpiHeaderCell.PreferredWidth = new TableWidthUnit(TableWidthUnitType.Percent, col.DisplayWidthPercentage.HasValue ? (float)col.DisplayWidthPercentage.Value : 0);
                kpiHeaderRow.Cells.Add(kpiHeaderCell);
 
                Paragraph kpiHeaderParagraph = new Paragraph();
                kpiHeaderParagraph.Style = _documentStyles[ParagrapStyles.TableCellHeaderParagraph];
                kpiHeaderCell.Blocks.Add(kpiHeaderParagraph);
                kpiHeaderParagraph.TextAlignment = Telerik.Windows.Documents.Layout.RadTextAlignment.Center;
 
                Span kpiHeaderSpan = new Span(col.Display);
                kpiHeaderParagraph.Inlines.Add(kpiHeaderSpan);
                visibleColumnNames.Add(col.Label);
            }
 
            // Update the column span
            groupingCell.ColumnSpan = visibleColumnNames.Count;
            kpaHeaderCell.ColumnSpan = visibleColumnNames.Count;
        }
 
        /// <summary>
        /// Adds the heading paragraph.
        /// </summary>
        /// <param name="documentSection">The document section.</param>
        /// <param name="headingContent">Content of the heading.</param>
        /// <param name="fontSize">Size of the font.</param>
        private static void _addHeadingParagraph(Section documentSection, string headingContent, int fontSize)
        {
            Paragraph p = new Paragraph();
 
            documentSection.Blocks.Add(p);
            Span span = new Span(headingContent)
            {
                FontFamily = new System.Windows.Media.FontFamily("Trebuche MS"),
                FontWeight = FontWeights.Bold,
                FontSize = fontSize,
                ForeColor = System.Windows.Media.Colors.Blue
            };
            p.Inlines.Add(span);
        }
 
        /// <summary>
        /// Builds the section data.
        /// </summary>
        /// <param name="section">The section.</param>
        /// <param name="sectionTable">The section table.</param>
        /// <param name="startIndex">The start index.</param>
        /// <param name="endIndex">The end index.</param>
        private static void _buildSectionData(Entities.Shared.LabelAndValueGroup groupedItem, Telerik.Windows.Documents.Model.Table sectionTable, int startIndex, int endIndex)
        {
            // Add data headings and data values rows
            Telerik.Windows.Documents.Model.TableRow sectionHeaderRow = new TableRow();
            sectionTable.Rows.Add(sectionHeaderRow);
            Telerik.Windows.Documents.Model.TableRow sectionValueRow = new TableRow();
            sectionTable.Rows.Add(sectionValueRow);
 
            var orderedList = groupedItem.Data.OrderBy(o => o.Sequence).ToList();
            if (endIndex > orderedList.Count) endIndex = orderedList.Count;
            for (int i = startIndex; i < endIndex; i++)
            {
                // Create the section name as header
 
                var item = orderedList[i];
                #region Add Cell Header
                TableCell sectionHeaderCell = new TableCell();
                sectionHeaderCell.Background = System.Windows.Media.Colors.LightGray;
                sectionHeaderRow.Cells.Add(sectionHeaderCell);
                Paragraph sectionHeaderParagraph = new Paragraph();
                sectionHeaderParagraph.Style = _documentStyles[ParagrapStyles.TableCellHeaderParagraph];
                sectionHeaderCell.Blocks.Add(sectionHeaderParagraph);
                Span sectionHeaderSpan = new Span(string.IsNullOrEmpty(item.Display) ? item.Label : item.Display);
                sectionHeaderParagraph.Inlines.Add(sectionHeaderSpan);
                #endregion
 
                #region Add Section Value
                TableCell sectionValueCell = new TableCell();
                sectionValueRow.Cells.Add(sectionValueCell);
 
                string spanValue = _getSpanValue(item.Value);
                if (!string.IsNullOrEmpty(spanValue))
                {
                    Paragraph sectionValueParagraph = new Paragraph();
                    sectionValueParagraph.Style = _documentStyles[ParagrapStyles.DefaultText];
                    sectionValueCell.Blocks.Add(sectionValueParagraph);
 
                    Span sectionValueSpan = new Span(spanValue);
                    sectionValueParagraph.Inlines.Add(sectionValueSpan);
                }
                #endregion
            }
        }
 
        /// <summary>
        /// Gets the span value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        private static string _getSpanValue(object value)
        {
            if (value == null || string.IsNullOrEmpty(value.ToString()))
            {
                return null;
            }
            if (value is DateTime)
            {
                return ((DateTime)value).ToString("dd MMM yyyy");
            }
            if (value is Boolean)
            {
                return ((bool)value) ? "Yes" : "No";
            }
            return value.ToString();
        }
 
        /// <summary>
        /// Prints the module.
        /// </summary>
        /// <param name="packageDoc">The package doc.</param>
        /// <param name="module">The module.</param>
        private void _printModule(RadDocument packageDoc, PMModule module, string packageName, string period)
        {
            Section moduleHeaderSection = new Section();
            packageDoc.Sections.Add(moduleHeaderSection);
            packageDoc.SectionDefaultPageMargin = new Telerik.Windows.Documents.Layout.Padding(5, 5, 5, 5);
            _addHeadingParagraph(moduleHeaderSection, string.Format("{0} -- {2}", module.Name, period, packageName), 16);
 
            if (_moduleCharts.ContainsKey(module.Name))
            {
                CreateChartDocumentPart(moduleHeaderSection, _moduleCharts[module.Name].ToArray());
            }
 
            // Loop through all sections in the module
            if (module.Sections != null)
            {
                foreach (var section in module.Sections)
                {
                    #region Add sections to document
                    Telerik.Windows.Documents.Model.Table sectionTable = new Telerik.Windows.Documents.Model.Table();
                    moduleHeaderSection.Blocks.Add(sectionTable);
                    #region ### Section Heading ###
 
                    Telerik.Windows.Documents.Model.TableRow sectionHeadingRow = new TableRow();
                    sectionTable.Rows.Add(sectionHeadingRow);
                    Telerik.Windows.Documents.Model.TableCell sectionHeadingCell = new TableCell();
                    sectionHeadingRow.Cells.Add(sectionHeadingCell);
                    Span sectionHeadingSpan = new Span(section.Name);
                    Paragraph sectionHeadingParagraph = new Paragraph();
                    sectionHeadingParagraph.Style = _documentStyles[ParagrapStyles.SectionName];
                    sectionHeadingParagraph.Inlines.Add(sectionHeadingSpan);
                    sectionHeadingCell.Blocks.Add(sectionHeadingParagraph);
                    int columnSpan = section.Data.Count < _fieldsPerRowInSection ? section.Data.Count : _fieldsPerRowInSection;
                    sectionHeadingCell.ColumnSpan = columnSpan;
                    #endregion
 
                    _buildGroupedSectionData(section, sectionTable, columnSpan);
                    #endregion
                }
            }
 
            // Loop through the kpa groupings
            if (module.Contract != null)
            {
                #region ### Section Heading ###
                if (module.Name.Equals("Balance Scorecard"))
                {
                    Table scoresTable = new Table();
                    moduleHeaderSection.Blocks.Add(scoresTable);
                    Telerik.Windows.Documents.Model.TableRow scoresHeadingRow = new TableRow();
                    scoresTable.Rows.Add(scoresHeadingRow);
                    Telerik.Windows.Documents.Model.TableCell scoresHeadingCell = new TableCell();
                    scoresHeadingRow.Cells.Add(scoresHeadingCell);
 
                    string scoresText = string.Format("Self Rating: {0:0.00}\t\tManager Rating: {1:0.00}", module.Contract.Score1, module.Contract.Score2);
 
                    Span scoresHeadingSpan = new Span(scoresText);
                    Paragraph scoresHeadingParagraph = new Paragraph();
                    scoresHeadingParagraph.Style = _documentStyles[ParagrapStyles.KPAGrouping];
                    scoresHeadingParagraph.Inlines.Add(scoresHeadingSpan);
                    scoresHeadingCell.Blocks.Add(scoresHeadingParagraph);
                }
                #endregion
 
                foreach (var grouping in module.Contract.KPAGroupings)
                {
                    if (!grouping.NotScored)
                    {
                        // Add seperator
                        moduleHeaderSection.Blocks.Add(new Paragraph());
 
                        // Add Grouping to Document
                        #region Grouping Heading
                        //_addHeadingParagraph(moduleHeaderSection, grouping.Name, 12);
                        #endregion
 
                        bool addGrouping = true;
                        foreach (var kpa in grouping.KPAs)
                        {
                            // Add Kpas to document
                            if (!kpa.NotScored)
                            {
                                string scaleId = kpa.ScaleId;
                                #region KPA Heading
                                //_addHeadingParagraph(moduleHeaderSection, kpa.Name, 10);
                                #endregion
 
                                Table kpiTable = new Table();
                                moduleHeaderSection.Blocks.Add(kpiTable);
 
                                #region KPI Headings
                                List<string> visibleColumnNames;
                                _loadKPIHeadings(Sym.Entities.Shared.DataTable.ColumnDefinitionsPerModule[module.Name].Values.ToList(), kpiTable, grouping, kpa, module.Name, addGrouping, out visibleColumnNames);
                                addGrouping = false;
                                #endregion
 
                                #region Add the KPI Values rows
                                foreach (var kpi in kpa.KPIs.Rows)
                                {
                                    // Add the KPI Data Table
                                    _loadKpiRow(kpiTable, visibleColumnNames, kpi, Sym.Entities.Shared.DataTable.ColumnDefinitionsPerModule[module.Name].Values.ToList(), module.Name, scaleId);
                                }
                                #endregion
 
                                #region Add Legend
                                //_loadKPILegend(kpiTable, scaleId, visibleColumnNames.Count);
                                #endregion
                            }
                        }
                    }
                }
            }
            #region Create Signatures
            // Create space after last KPA
            moduleHeaderSection.Blocks.Add(new Paragraph());
 
            Table signatureTable = new Table();
            signatureTable.Borders = new TableBorders(new Telerik.Windows.Documents.Model.Border(BorderStyle.None));
            moduleHeaderSection.Blocks.Add(signatureTable);
 
            TableRow signatureRow = new TableRow();
            signatureTable.Rows.Add(signatureRow);
 
            TableCell employeeSignatureCell = new TableCell();
            employeeSignatureCell.TextAlignment = Telerik.Windows.Documents.Layout.RadTextAlignment.Justify;
            signatureRow.Cells.Add(employeeSignatureCell);
 
            TableCell managerSignatureCell = new TableCell();
            employeeSignatureCell.TextAlignment = Telerik.Windows.Documents.Layout.RadTextAlignment.Justify;
            signatureRow.Cells.Add(managerSignatureCell);
 
            Paragraph employeeSignatureParagraph = new Paragraph();
            employeeSignatureParagraph.Inlines.Add(new Span("___________________________\r\n"));
            employeeSignatureParagraph.Inlines.Add(new Span("___________________ ( Date )\r\n"));
            employeeSignatureParagraph.Style = _documentStyles[ParagrapStyles.DefaultText];
            employeeSignatureParagraph.Inlines.Add(new Span(module.Contract != null ? module.Contract.ContractEmployee.Name : "Employee"));
 
            Paragraph managerSignatureParagraph = new Paragraph();
            managerSignatureParagraph.Inlines.Add(new Span("___________________________\r\n"));
            managerSignatureParagraph.Inlines.Add(new Span("___________________ ( Date )\r\n"));
            managerSignatureParagraph.Style = _documentStyles[ParagrapStyles.DefaultText];
            managerSignatureParagraph.Inlines.Add(new Span(module.Contract != null ? module.Contract.Creator.Name : "Manager"));
 
            employeeSignatureCell.Blocks.Add(employeeSignatureParagraph);
            managerSignatureCell.Blocks.Add(managerSignatureParagraph);
            #endregion
 
        }
 
        /// <summary>
        /// Loads the KPI Rating legend.
        /// </summary>
        /// <param name="kpiTable">The kpi table.</param>
        /// <param name="scaleId">The scale id.</param>
        private void _loadKPILegend(Table kpiTable, string scaleId, int colSpan)
        {
            if (Globals.RatingScales.ContainsKey(scaleId))
            {
                TableRow kpiValueRow = new TableRow();
                kpiTable.AddRow(kpiValueRow);
                TableCell kpiValueCell = new TableCell();
                kpiValueCell.ColumnSpan = colSpan;
                kpiValueRow.Cells.Add(kpiValueCell);
 
                if (_kpiLegends == null) _kpiLegends = new Dictionary<string, string>();
                if (!_kpiLegends.ContainsKey(scaleId))
                {
                    _kpiLegends.Add(scaleId, string.Join(", ", Globals.RatingScales[scaleId].Select(s => s.Display).ToArray()));
                }
                string legend = _kpiLegends[scaleId];
 
                string spanValue = _getSpanValue(legend);
                if (!string.IsNullOrEmpty(spanValue))
                {
                    Paragraph kpiValueParagraph = new Paragraph();
                    kpiValueParagraph.Style = _documentStyles[ParagrapStyles.TableCellHeaderParagraph];
                    kpiValueCell.Blocks.Add(kpiValueParagraph);
 
                    Span kpiValueSpan = new Span(spanValue);
                    kpiValueParagraph.Inlines.Add(kpiValueSpan);
                }
            }
        }
 
        /// <summary>
        /// Builds the grouped section data.
        /// </summary>
        /// <param name="section">The section.</param>
        /// <param name="sectionTable">The section table.</param>
        /// <param name="columnSpan">The column span.</param>
        private void _buildGroupedSectionData(PMSection section, Telerik.Windows.Documents.Model.Table sectionTable, int columnSpan)
        {
            foreach (var groupedItem in section.Data)
            {
                if (!string.IsNullOrEmpty(groupedItem.GroupName))
                {
                    Telerik.Windows.Documents.Model.TableRow groupedHeadingRow = new TableRow();
                    sectionTable.Rows.Add(groupedHeadingRow);
                    Telerik.Windows.Documents.Model.TableCell groupedHeadingCell = new TableCell();
                    groupedHeadingRow.Cells.Add(groupedHeadingCell);
                    Span groupedHeadingSpan = new Span(groupedItem.GroupName);
                    Paragraph groupedHeadingParagraph = new Paragraph();
                    groupedHeadingParagraph.Style = _documentStyles[ParagrapStyles.TableCellHeaderParagraph];
                    groupedHeadingParagraph.Inlines.Add(groupedHeadingSpan);
                    groupedHeadingCell.Blocks.Add(groupedHeadingParagraph);
                    groupedHeadingCell.ColumnSpan = columnSpan;
                }
 
                if (groupedItem.Data.Count <= _fieldsPerRowInSection)
                {
                    _buildSectionData(groupedItem, sectionTable, 0, _fieldsPerRowInSection);
                }
                else
                {
                    int sectionRows = groupedItem.Data.Count / _fieldsPerRowInSection;
                    for (int i = 0; i < sectionRows; i++)
                    {
                        _buildSectionData(groupedItem, sectionTable, i * sectionRows, (i * sectionRows) + _fieldsPerRowInSection);
                    }
                    var res = groupedItem.Data.Count - (sectionRows * _fieldsPerRowInSection);
                    if (res > 0)
                    {
                        _buildSectionData(groupedItem, sectionTable, sectionRows * _fieldsPerRowInSection, (sectionRows * _fieldsPerRowInSection) + res + 1);
                    }
                }
 
            }
        }
 
        /// <summary>
        /// Creates the doc header.
        /// </summary>
        /// <param name="packageDoc">The package doc.</param>
        /// <param name="packageName">Name of the package.</param>
        private static void _createDocHeader(RadDocument packageDoc, string packageName)
        {
            Header header = new Header();
            RadDocument headerDoc = new RadDocument();
            Section headerSection = new Section();
            headerDoc.Sections.Add(headerSection);
            Paragraph headerParagraph = new Paragraph();
            headerSection.Blocks.Add(headerParagraph);
            Span headerSpan = new Span(packageName);
            headerParagraph.Inlines.Add(headerSpan);
            headerParagraph.TextAlignment = Telerik.Windows.Documents.Layout.RadTextAlignment.Right;
            headerDoc.MeasureAndArrangeInDefaultSize();
 
            header.Body = headerDoc;
            packageDoc.Sections.First.Headers.Default = header;
            packageDoc.Sections.First.HeaderTopMargin = 5;
        }
 
        /// <summary>
        /// Creates the doc footer.
        /// </summary>
        /// <param name="packageDoc">The package doc.</param>
        private static void _createDocFooter(RadDocument packageDoc)
        {
            Footer footer = new Footer();
            RadDocument footerDoc = new RadDocument();
            Section footerSection = new Section();
            Paragraph footerParagraph = new Paragraph();
            footerParagraph.TextAlignment = Telerik.Windows.Documents.Layout.RadTextAlignment.Right;
 
 
            FieldRangeStart fieldStart = new FieldRangeStart();
            FieldRangeEnd fieldEnd = new FieldRangeEnd();
 
            fieldEnd.PairWithStart(fieldStart);
            fieldStart.Field = new PageField();
            fieldStart.Field.DisplayMode = FieldDisplayMode.Result;
 
            footerParagraph.Children.Add(fieldStart);
            //footerParagraph.Children.Add(new Span(" of "));
            footerParagraph.Children.Add(fieldEnd);
            footerParagraph.RightIndent = 20;
 
            footerSection.Children.Add(footerParagraph);
            footerDoc.Sections.Add(footerSection);
            footer.Body = footerDoc;
 
            footerDoc.MeasureAndArrangeInDefaultSize();
 
            packageDoc.Sections.First.Footers.Default = footer;
            packageDoc.Sections.First.FooterBottomMargin = 2;
        }
 
        /// <summary>
        /// Saves the PDF to file.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="dialog">The dialog.</param>
        /// <param name="document">The document.</param>
        /// <returns></returns>
        private static string _savePDFToFile(string fileName, SaveFileDialog dialog, RadDocument document)
        {
            if (dialog.ShowDialog() == true)
            {
                document.LayoutMode = DocumentLayoutMode.Paged;
                document.Measure(RadDocument.MAX_DOCUMENT_SIZE);
                document.Arrange(new RectangleF(PointF.Empty, document.DesiredSize));
 
                PdfFormatProvider provider = new PdfFormatProvider();
 
                using (Stream output = dialog.OpenFile())
                {
                    provider.Export(document, output);
 
                    var fs = output as System.IO.FileStream;
                    if (fs != null)
                    {
                        fileName = fs.Name;
                    }
                    else
                    {
                        fileName = dialog.SafeFileName;
                    }
                }
            }
            return fileName;
        }
 
        /// <summary>
        /// Gets the save dialog.
        /// </summary>
        /// <param name="package">The package.</param>
        /// <param name="module">The module.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="dialog">The dialog.</param>
        private static void _getSaveDialog(PMPackage package, PMModule module, out string fileName, out SaveFileDialog dialog)
        {
            dialog = new SaveFileDialog();
            dialog.DefaultExt = "*.pdf";
            dialog.Filter = "Adobe PDF Document (*.pdf)|*.pdf";
            if (module == null)
            {
                fileName = string.Format("{0}.pdf", package.Name);
            }
            else
            {
                fileName = string.Format("{0} - {1}.pdf", package.Name, module.Name);
            }
            dialog.DefaultFileName = fileName;
        }
 
        #endregion
 
        #region || Properties ||
        private PMPackage _package;
        /// <summary>
        /// Gets or Sets the Package instance
        /// </summary>     
        public PMPackage Package
        {
            get { return _package; }
            set
            {
                SetValue(ref _package, value, "Package");
            }
        }
 
        private ObservableCollection<FrameworkElement> _graphs;
        /// <summary>
        /// Gets or Sets the Graphs instance
        /// </summary>     
        public ObservableCollection<FrameworkElement> Graphs
        {
            get { return _graphs; }
            set
            {
                SetValue(ref _graphs, value, "Graphs");
            }
        }
 
        private int _fieldsPerRowInSection = 6;
        /// <summary>
        /// Gets or Sets the FieldsPerRowInSection instance
        /// </summary>     
        public int FieldsPerRowInSection
        {
            get { return _fieldsPerRowInSection; }
            set
            {
                SetValue(ref _fieldsPerRowInSection, value, "FieldsPerRowInSection");
            }
        }
        #endregion
 
        #region Events
        private event EventHandler<PrintDocumentArgs> DocumentReady;
        /// <summary>
        /// Called when [document ready for printing] .
        /// </summary>
        /// <param name="documentToPrint">The document to print.</param>
        /// <param name="richTextBoxContainer">The rich text box container.</param>
        /// <param name="documentName">Name of the document.</param>
        private void OnDocumentReady(RadDocument documentToPrint, RadRichTextBox richTextBoxContainer, string documentName)
        {
            if (DocumentReady != null)
            {
                DocumentReady(this, new PrintDocumentArgs(documentToPrint, richTextBoxContainer, documentName));
            }
        }
 
        #endregion
 
        #region Async Delegates
        private delegate void CreateDocumentWithModuleBegin(PMPackage package, PMModule selectedModule, RadRichTextBox rtb);
        private delegate void CreateDocumentBegin(PMPackage package, RadRichTextBox rtb);
        #endregion
 
        #region Private member methods
        /// <summary>
        /// Creates the document.
        /// </summary>
        /// <param name="package">The package.</param>
        /// <param name="richTextBoxContainer">The rich text box container.</param>
        private void CreateDocument(PMPackage package, RadRichTextBox richTextBoxContainer)
        {
            // Persist the passed in package
            Package = package;
            RadDocument packageDoc = new RadDocument();
 
            if (_documentStyles == null || _documentStyles.Count == 0)
            {
                _loadStyles();
            }
            foreach (var style in _documentStyles.Values)
            {
                packageDoc.StyleRepository.Add(style);
            }
 
            // Loop through the modules in the package
            foreach (var module in _package.Modules)
            {
                string period = module.Contract == null ? package.Period : module.Contract.Period;
                _printModule(packageDoc, module, package.Name, period);
                // Add signatures
            }
 
            // Create the header and the footer
            _createDocHeader(packageDoc, package.Name);
            _createDocFooter(packageDoc);
            packageDoc.UpdateAllFields();
            OnDocumentReady(packageDoc, richTextBoxContainer, package.Name);
        }
        /// <summary>
        /// Creates the document.
        /// </summary>
        /// <param name="module">The module.</param>
        /// <param name="package">The package.</param>
        /// <param name="richTextBoxContainer">The rich text box container.</param>
        private void CreateDocumentWithModule(PMModule module, PMPackage package, RadRichTextBox richTextBoxContainer)
        {
            // Persist the passed in package
            RadDocument packageDoc = new RadDocument();
 
            if (_documentStyles == null || _documentStyles.Count == 0)
            {
                _loadStyles();
            }
            foreach (var style in _documentStyles.Values)
            {
                packageDoc.StyleRepository.Add(style);
            }
 
            // Loop through the modules in the package
            string period = module.Contract == null ? package.Period : module.Contract.Period;
            _printModule(packageDoc, module, package.Name, period);
 
            // Create the header and the footer
            _createDocHeader(packageDoc, package.Name);
            _createDocFooter(packageDoc);
            OnDocumentReady(packageDoc, richTextBoxContainer, module.Name);
        }
        /// <summary>
        /// Creates the chart document part.
        /// </summary>
        /// <param name="currentSection">The current section.</param>
        /// <param name="charts">The charts.</param>
        private void CreateChartDocumentPart(Section currentSection, FrameworkElement[] charts)
        {
            MemoryStream ms = null;
            Table graphTable = new Table();
            currentSection.Blocks.Add(graphTable);
            TableRow graphRow = new TableRow();
            graphTable.Rows.Add(graphRow);
 
            foreach (var chart in charts)
            {
                TableCell graphCell = new TableCell();
                graphRow.Cells.Add(graphCell);
                Paragraph paragraph = new Paragraph();
                graphCell.Blocks.Add(paragraph);
 
                ms = new MemoryStream();
                Telerik.Windows.Media.Imaging.ExportExtensions.ExportToImage(chart, ms, new Telerik.Windows.Media.Imaging.PngBitmapEncoder());
 
                double imageWidth = chart.ActualWidth / 2;
                double imageHeight = chart.ActualHeight / 2;
 
                ImageInline image = new ImageInline(ms, new Size(imageWidth, imageHeight), "png");
 
                paragraph.Inlines.Add(image);
                ms.Close();
            }
        }
 
        #endregion
 
        #region Public member methods
        /// <summary>
        /// Prints the specified package.
        /// </summary>
        /// <param name="package">The package.</param>
        public void Print(PMPackage package, RadRichTextBox rtb)
        {
            CreateDocument(package, rtb);
        }
        /// <summary>
        /// Prints the specified package.
        /// </summary>
        /// <param name="package">The package.</param>
        /// <param name="selectedModule">The selected module.</param>
        /// <param name="rtb">The RTB.</param>
        public void Print(PMPackage package, PMModule selectedModule, RadRichTextBox rtb)
        {
            CreateDocumentWithModule(selectedModule, package, rtb);
        }
        /// <summary>
        /// Exports the specified package.
        /// </summary>
        /// <param name="package">The package.</param>
        public void Export(PMPackage package, out string fileName)
        {
            throw new NotImplementedException();
 
            //// Create the dialog to be presented to the user
            //SaveFileDialog dialog;
            //_getSaveDialog(package, null, out fileName, out dialog);
 
            //// Create the print document
            //RadDocument document = CreateDocument(package);
 
            //// Save PDF to file and return the selected file name
            //fileName = _savePDFToFile(fileName, dialog, document);
        }
        /// <summary>
        /// Exports the specified package.
        /// </summary>
        /// <param name="package">The package.</param>
        /// <param name="module">The module.</param>
        /// <param name="fileName">Name of the file.</param>
        public void Export(PMPackage package, PMModule module, out string fileName)
        {
            throw new NotImplementedException();
            //// Create the dialog to be presented to the user
            //SaveFileDialog dialog;
            //_getSaveDialog(package, module, out fileName, out dialog);
 
            //// Create the print document
            //RadDocument document = CreateDocument(module, package);
 
            //// Save PDF to file and return the selected file name
            //fileName = _savePDFToFile(fileName, dialog, document);
        }
        /// <summary>
        /// Converts a frameworkelement to image object.
        /// </summary>
        /// <param name="element"> The FrameworkElement object to save to PNG format graphic file. </param>
        public static System.Windows.Media.Imaging.BitmapImage SaveFrameworkElementToImage(FrameworkElement element)
        {
            System.Windows.Media.Imaging.BitmapImage w = new System.Windows.Media.Imaging.BitmapImage();
            using (MemoryStream stream = new MemoryStream())
            {
                Telerik.Windows.Media.Imaging.ExportExtensions.ExportToImage(element, stream, new Telerik.Windows.Media.Imaging.PngBitmapEncoder());
                w.SetSource(stream);
            }
            return w;
        }
        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return ToString();
        }
        #endregion
    }
 
    /// <summary>
    /// Event args passed when the print document is raised
    /// </summary>
    public class PrintDocumentArgs : EventArgs
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PrintDocumentArgs" /> class.
        /// </summary>
        public PrintDocumentArgs()
        {
        }
 
        /// <summary>
        /// Initializes a new instance of the <see cref="PrintDocumentArgs" /> class.
        /// </summary>
        /// <param name="documentToPrint">The document to print.</param>
        public PrintDocumentArgs(RadDocument documentToPrint, RadRichTextBox richTextBoxContainer, string documentName)
        {
            DocumentToPrint = documentToPrint;
            RichTextBoxContainer = richTextBoxContainer;
            DocumentName = documentName;
        }
 
        /// <summary>
        /// Gets or sets the document to print.
        /// </summary>
        /// <value>The document to print.</value>
        public RadDocument DocumentToPrint { get; set; }
 
        /// <summary>
        /// Gets or sets the rich text box container control.
        /// </summary>
        /// <value>The rich text box container.</value>
        public RadRichTextBox RichTextBoxContainer { get; set; }
 
        /// <summary>
        /// Gets or sets the name of the document.
        /// </summary>
        /// <value>The name of the document.</value>
        public string DocumentName { get; set; }
    }
}
 
0
Boby
Telerik team
answered on 04 Jun 2012, 12:32 PM
Hi Jaco
,
We were not able to run the sample code you sent us, as it has a lot of external references. Could you please try to isolate the problem in a sample runnable project, and send it to us through a support ticket, so that we can investigate the issue further?

Greetings,
Boby
the Telerik team

Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

0
Jaco De Villiers
Top achievements
Rank 2
answered on 08 Jun 2012, 05:26 AM
I will test on the Q2 release.  If the problem persists then I will create a sample application that simulates the problem
Regards
Jaco
0
Anbu
Top achievements
Rank 1
answered on 18 Sep 2014, 07:46 AM
Wher can i get the latest version of the dll?
0
Mihail
Telerik team
answered on 22 Sep 2014, 12:49 PM
Hello Anbu,

 All required dll's are available under your account.

Regards,
Mihail
Telerik
 
Check out Telerik Analytics, the service which allows developers to discover app usage patterns, analyze user data, log exceptions, solve problems and profile application performance at run time. Watch the videos and start improving your app based on facts, not hunches.
 
Tags
RichTextBox
Asked by
Guy
Top achievements
Rank 1
Answers by
Boby
Telerik team
Guy
Top achievements
Rank 1
Vasil
Telerik team
Jaco De Villiers
Top achievements
Rank 2
Anbu
Top achievements
Rank 1
Mihail
Telerik team
Share this question
or