⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pageprinter.cs

📁 arcgis engine地图打印任务的应用
💻 CS
字号:
// Copyright 2006 ESRI
// 
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
// 
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
// 
// See use restrictions at /arcgis/developerkit/userestrictions.
// 

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing.Design;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using ESRI.ArcGIS.ADF.Tasks.Design.Editors;
using ESRI.ArcGIS.ADF.Tasks.Design.Designers;
using ESRI.ArcGIS.ADF.Web;
using ESRI.ArcGIS.ADF.Web.DataSources;
using ESRI.ArcGIS.ADF.Web.Display.Graphics;
using ESRI.ArcGIS.ADF.Web.UI.WebControls;

namespace PrintTask_CSharp
{
    [Serializable()]
    public class PagePrinter
    {
        public PagePrinter(Map mapControl)
        {
            MapControl = mapControl;
            PrintWidth = 0;
            PrintResolution = 96;
            PrintScale = 0;
        }

        public PagePrinter(): this(null) {}

        #region Private fields
        private string _printTitle;
        private int _printWidth;
        private int _printResolution;
        private int _printScale;
        private Map _mapCtrl;
        private ScaleBar _scaleBar;
        private TreeViewPlusNodeCollection _tvpNodes;
        private int _idColumnIndex;
        private int _graphicIdColumnIndex;
        private bool _showIdField;

        private string newlineString = "xxrnxx";
        #endregion

        #region Public properties

        public string PrintTitle
        {
            get { return _printTitle; }
            set { _printTitle = value; }
        }

        /// <summary>
        /// Width of print, in inches. Default is 0, in which case the
        /// print is made at the MapControl's default pixel size.
        /// </summary>
        public int PrintWidth
        {
            get { return _printWidth; }
            set { _printWidth = value; }
        }

        /// <summary>
        /// Print resolution of map, in DPI. Default is 96.
        /// </summary>
        public int PrintResolution
        {
            get { return _printResolution; }
            set { _printResolution = value; }
        }

        /// <summary>
        /// Print scale of map, as denominator of RF scale (e.g., 24000). If zero, uses current map scale.
        /// </summary>
        public int PrintScale
        {
            get { return _printScale; }
            set { _printScale = value; }
        }

        /// <summary>
        /// Map control to print. If null, no map is printed.
        /// </summary>
        public Map MapControl
        {
            get { return _mapCtrl; }
            set { _mapCtrl = value; }
        }

        /// <summary>
        /// Scalebar control to print below map. If null, no scalebar is printed.
        /// </summary>
        public ScaleBar ScaleBarControl
        {
            get { return _scaleBar; }
            set { _scaleBar = value; }
        }

        /// <summary>
        /// Collection of TreeViewPlusNodes (containing feature attributes)
        /// to print. Send only the nodes you want to print.
        /// Currently only nodes that are type GraphicsLayerNode will print. If null, no 
        /// attributes tables will print.
        /// </summary>
        public TreeViewPlusNodeCollection NodesToPrint
        {
            get { return _tvpNodes; }
            set { _tvpNodes = value; }
        }

        /// <summary>
        /// Whether to include the #ID# field in the attributes table.
        /// </summary>
        public bool ShowIdField
        {
            get { return _showIdField; }
            set { _showIdField = value; }
        }

        #endregion

        #region CreatePrintPageContent method

        public string CreatePrintPageContent()
        {
            // get printed page content
            StringBuilder sbPage = new StringBuilder();

            #region Page header and title
            
            sbPage.Append("<html><header>");
            sbPage.Append(newlineString);
            sbPage.AppendFormat("<title>打印预览: {0}</title>", PrintTitle);
            sbPage.Append(newlineString);
            sbPage.Append("<body style='font-family:Verdana,sans-serif,黑体;'>");
            sbPage.Append(newlineString);
            sbPage.AppendFormat("<h1>{0}</h1>", PrintTitle);
            sbPage.Append(newlineString);
            
            #endregion

            #region Map image and/or task results

            sbPage.Append(GenerateAndStoreMap());
            sbPage.Append("<br/>");
            sbPage.Append(newlineString);
            sbPage.Append(GetTaskResultsHtml());
            sbPage.Append(newlineString);

            #endregion

            sbPage.Append("</body></html>");

            return sbPage.ToString();
        }

        #endregion

        #region Private methods

        private string GenerateAndStoreMap()
        {
            string printImageTag = String.Empty;

            if (MapControl != null)
            {
                MapPrinter mapPrinter = new MapPrinter(MapControl);

                // default map size - modified if higher width or resolution
                //  (can't use Map.Width/Height because if they're set as percentages,
                //   as in WMA template, doesn't work, esp. when browser resized)
                int printWidthPix = (int)MapControl.TilingScheme.ViewWidth; //.Width.Value;
                int printHeightPix = (int)MapControl.TilingScheme.ViewHeight; //.Height.Value;

                // width/height values for <img> tag - changed if resolution is higher
                int tagWidth = printWidthPix;
                int tagHeight = printHeightPix;

                // change print size if non-default size or resolution requested
                if (PrintWidth > 0 || PrintResolution != 96)
                {
                    // ratio used later to calculate new height
                    double hwRatio = (double)printHeightPix / printWidthPix;

                    // if only printresolution changed,
                    //   just increase pixel size to account for higher resolution
                    if (PrintWidth <= 0)
                    {
                        double pw = printWidthPix * PrintResolution / 96;
                        printWidthPix = (int)Math.Round(pw);
                    }
                    else
                    {
                        // only width changed from default, or
                        //  both width and resolution changed
                        printWidthPix = PrintWidth * PrintResolution;
                        tagWidth = PrintWidth * 96;
                        tagHeight = (int)Math.Round(tagWidth * hwRatio);
                    }

                    // scale height based on width
                    printHeightPix =
                        (int)Math.Round(hwRatio * printWidthPix);

                    mapPrinter.Dpi = PrintResolution;
                    mapPrinter.MapHeight = printHeightPix;
                    mapPrinter.MapWidth = printWidthPix;
                }

                // set scale if specified
                if (PrintScale > 0)
                {
                    mapPrinter.MapScale = PrintScale;
                }

                // add scalebar to map, if added to the page printer
                if (this.ScaleBarControl != null)
                    mapPrinter.ScaleBarControl = this.ScaleBarControl;

                // Generate the map bitmap
                System.Drawing.Bitmap mapImage = mapPrinter.GeneratePrintImage();

                if (mapImage != null)
                {
                    // save map image in session and generate id
                    string mapBitmapId = String.Concat(
                        "MapBitmap_" + MapControl.UniqueID);

                    // ?use StateManager - works but Session may be more appropriate
                    MapControl.Page.Session[mapBitmapId] = mapImage;
                    //MapControl.StateManager.Add(mapBitmapId, mapImage);

                    // Compose URL for map image
                    string printImageUrl = String.Concat(
                        MapControl.Page.Request.Url.AbsoluteUri,
                        "?getMap=", mapBitmapId);

                    printImageTag = String.Format("<img src=\"{0}\" width=\"{1}\" height=\"{2}\" >", 
                        printImageUrl, tagWidth, tagHeight);
                }
                else
                    printImageTag = "(Error generating map. Try again or contact site administrator.";
            }
            
            return printImageTag;
        }

        private string GetTaskResultsHtml()
        {
            StringBuilder sbTaskResults = new StringBuilder();

            if (NodesToPrint != null)
            {
                // Each node is a top-level node in TaskResults
                foreach (TreeViewPlusNode taskNode in NodesToPrint)
                {
                    // Each node is a layer/dataset node
                    foreach (TreeViewPlusNode node in taskNode.Nodes)

                        if (node is GraphicsLayerNode)
                        {
                            GraphicsLayerNode glNode = (GraphicsLayerNode)node;
                            GraphicsLayer grLayer = glNode.Layer;

                            // reset ID column index - used in rowdatabound event handler
                            _idColumnIndex = -1;
                            _graphicIdColumnIndex = -1;

                            GridView gv = new GridView();
                            gv.Caption = node.Text;
                            gv.CaptionAlign = TableCaptionAlign.Left;

                            // Since GraphicsLayer extends DataTable, we can bind it to the gridview
                            gv.DataSource = grLayer;

                            // Add event handler to do column hiding and aliasing
                            gv.RowDataBound += new 
                                GridViewRowEventHandler(resultsGridView_RowDataBound);

                            gv.DataBind();

                            string htmlContent = Utilities.RenderControlHtml(gv);
                            //htmlContent =  System.Web.HttpUtility.HtmlEncode(htmlContent);
                            htmlContent = htmlContent.Replace("\r\n", newlineString);

                            sbTaskResults.Append(htmlContent);

                            sbTaskResults.Append("<br/><br/>");
                        }

                        // TODO: Handle other types of nodes/data??
                }
            }

            return sbTaskResults.ToString();
        }

        // Must do column hiding at rowdatabound event - don't have columns populated before this
        private void resultsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            GridViewRow row = e.Row;

            if (row.RowType == DataControlRowType.Header)
            {
                for (int i = 0; i < row.Cells.Count; i++)
                    // get position of graphics id column
                    if (row.Cells[i].Text == "GRAPHICS_ID")
                        _graphicIdColumnIndex = i;
                    else if ((row.Cells[i].Text == "#ID#" || row.Cells[i].Text.ToUpper() == "OBJECTID")
                        && !this.ShowIdField)
                        // find ID field index in header row if will be hiding the field
                        _idColumnIndex = i;
                    else
                        // use initial caps for other columns
                        row.Cells[i].Text = Utilities.CapText(row.Cells[i].Text);

                // doesn't work right in IE if text is all caps (do above instead)
                //row.Style["text-transform"] = "capitalize"; 
            }

            // hide graphicid column
            if (_graphicIdColumnIndex >= 0)
                row.Cells[_graphicIdColumnIndex].Visible = false;

            // hide feature ID column (ShowIdField) if requested
            if (!this.ShowIdField && _idColumnIndex >= 0)
            {
                e.Row.Cells[_idColumnIndex].Visible = false;
            }

        }

        #endregion

    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -