CSharp之打印设置与打印预览

依赖包

  • FreeSpire.XLS

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using Spire.Xls;
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PrintPreviewTest
{
class Program
{
static void Main(string[] args)
{
//打印参数对话框
PrintDialog printdialog = new PrintDialog();

//使用Spire加载文档
Workbook workbook = new Workbook();
workbook.LoadFromFile(args[0]);

//预设参数
Worksheet sheet = workbook.Worksheets[0];
//设置打印纸张大小
sheet.PageSetup.PaperSize = PaperSizeType.PaperA4;
//设置打印方向
sheet.PageSetup.Orientation = PageOrientationType.Portrait;
//设置打印区域
sheet.PageSetup.PrintArea = "B2:F8";
//打印标题
sheet.PageSetup.PrintTitleColumns = "$A:$B";
sheet.PageSetup.PrintTitleRows = "$1:$2";
//打印顺序
sheet.PageSetup.Order = OrderType.DownThenOver;
sheet.PageSetup.Order = OrderType.OverThenDown;
//设置打印对话框属性
PrintDialog dialog = new PrintDialog();
dialog.AllowPrintToFile = true; dialog.AllowCurrentPage = true;
dialog.AllowSomePages = true;
//设置单面打印
dialog.PrinterSettings.Duplex = Duplex.Simplex;
//设置打印页面范围
dialog.PrinterSettings.FromPage = 0;
dialog.PrinterSettings.ToPage = 8;
dialog.PrinterSettings.PrintRange = PrintRange.SomePages;
//设置打印份数
dialog.PrinterSettings.Copies = 5;
//设置打印机名称
dialog.PrinterSettings.PrinterName = "HP LasterJet P1007";


//关联
printdialog.Document = workbook.PrintDocument;

if(printdialog.ShowDialog() == DialogResult.OK)
{
//根据对话框重设参数
workbook.PrintDocument.PrinterSettings = printdialog.PrinterSettings;
PrintPreviewDialog previewDialog = new PrintPreviewDialog();
previewDialog.Document = workbook.PrintDocument;
previewDialog.ShowDialog();
}
}
}
}

预览