打印代碼片斷

//當前打印的行的索引,用於遍歷ListBox.Items
        private int listPrintIndex;
        private void btnPrintList_Click(object sender, RoutedEventArgs e)
        {
            //初始值爲0
            listPrintIndex = 0;
            PrintDocument document = new PrintDocument();
            document.PrintPage += new EventHandler<PrintPageEventArgs>(document_PrintPage);
            document.Print("Print List");
        }

        //設置每一項之間的間距
        private int extraMargin = 50;
        void document_PrintPage(object sender, PrintPageEventArgs e)
        {
            //定義一個打印的元素
            Canvas printSurface = new Canvas();
            e.PageVisual = printSurface;
            //獲得最頂端位置
            double topPosition = e.PageMargins.Top + extraMargin;

            //遍歷當前的ListBox.Items
            while (listPrintIndex<lstPrint.Items.Count)
            {
                //實例化TextBlock用來存放ListItem的值
                TextBlock txt = new TextBlock();
                txt.FontSize = 30;
                //獲得ListBox每一項的值
                txt.Text = lstPrint.Items[listPrintIndex].ToString();
                double measuredHeight = txt.ActualHeight;
                //若是打印的當前行高度不合適的話,則進行分頁
                if (measuredHeight>(e.PrintableArea.Height- topPosition- extraMargin))
                {
                    e.HasMorePages = true;
                    return ;
                }

                //設置TextBlock在Canvas中的位置
                txt.SetValue(Canvas.TopProperty, topPosition);
                txt.SetValue(Canvas.LeftProperty, e.PageMargins.Left + extraMargin);
                //將TextBlock添加到打印的元素中去
                printSurface.Children.Add(txt);

                listPrintIndex++;
                //追加高度
                topPosition = topPosition + measuredHeight;
            }
            e.HasMorePages = false;
        }
相關文章
相關標籤/搜索