C# winform 打印预览

1.第一种方法

使用PrintPreviewDialog控件进行显示

                PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
                printPreviewDialog.ClientSize = new System.Drawing.Size(400, 300);
                printPreviewDialog.Location = new System.Drawing.Point(29, 29);
                printPreviewDialog.Name = "打印预览";
                printPreviewDialog.MinimumSize = new System.Drawing.Size(375, 250);
                printPreviewDialog.UseAntiAlias = true;
                System.Drawing.Printing.PrintDocument document = new System.Drawing.Printing.PrintDocument();
                document.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(document_PrintPage);
                printPreviewDialog.Document = document;
                printPreviewDialog.ShowDialog();

         private void document_PrintPage(object sender,System.Drawing.Printing.PrintPageEventArgs e)
        {
            //显示内容
            string text = "In document_PrintPage method.";
            //设置字体
            System.Drawing.Font printFont = new System.Drawing.Font("Arial", 35, System.Drawing.FontStyle.Regular);
            e.Graphics.DrawString(text, printFont, System.Drawing.Brushes.Black, 0, 0);
        }

其他操作可以参考文档

https://docs.microsoft.com/zh-cn/dotnet/api/system.windows.forms.printpreviewcontrol?view=netframework-4.0

2.如果预览的是Excel文档,则可以如下预览

        public void PrintPriviewExcelFile(string filePath)
        {
            Microsoft.Office.Interop.Excel.ApplicationClass applicationClass = new Microsoft.Office.Interop.Excel.ApplicationClass();
            applicationClass.Visible = true;
            object missing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Workbook xlWorkbook = applicationClass.Workbooks.Open(filePath, 0, true, 5, missing, missing, true, 1, missing, false, false, missing, false, missing, missing);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkbook.Worksheets[1];
            worksheet.PrintPreview(null);
            applicationClass.Visible = false;
            worksheet = null;
        }

若调用这段代码的时候显示“无法嵌入互操作类型ApplicationClass,请改用试用的接口”,将Microsoft.Office.Interop.Excel的嵌入互操作性值改为false

C# winform 打印预览_第1张图片

你可能感兴趣的:(C# winform 打印预览)