我们知道,在MS word中,默认的页面大小是letter(8.5’’x11’’),除此之外,word还提供了其他一些预定义的页面大小,如Legal (5.4’’x14’’),A3 (11.69’’x16.54’’),A4(8.27’’x11.69’’)等,使用户可以根据自己的需求来选择页面大小。而且,如果我们想设置的页面大小不在下拉列表中,还可以通过点击页面设置按钮从中选择自定义大小来定义页面的宽度和高度,非常方便。
那么怎样使用编程的方式来实现这些功能呢?E-iceblue提供了一款软件Spire.Doc,它给编程者提供了一种类似的方法来设置页面的大小。下面就让我们一起来探讨如何使用Spire.Doc 软件, 通过C#编程的方式来选择页面大小或自定义页面大小。
首先,从
e-iceblue 上下载并安装Spire.Doc软件,其次从BIN文件夹中选择相应的.dll文件添加引用至Visual Studio。
下面是代码片段:
步骤1:创建一个新的word文档,添加一个空白Section;
Document doc = new Document();
Section section = doc.AddSection();
步骤2:设置页面大小为A4。在页面大小类中,有很多预定义的页面大小;
section.PageSetup.PageSize = PageSize.A4;
如果你想自定义页面的大小,用下面这两行代码替换上面的代码:
section.PageSetup.PageSize = new System.Drawing.SizeF(500, 800);
section.PageSetup.Orientation = PageOrientation.Portrait;
步骤3:添加一些文本到section;
Paragraph Para = section.AddParagraph();
Para.AppendText("朝 辞 白 帝 彩 云 间 ,"
+ "千 里 江 陵 一 日 还 。"
+ "两 岸 猿 声 啼 不 尽 ,"
+ "轻 舟 已 过 万 重 山 。");
步骤4:保存文档并重新打开;
doc.SaveToFile("result.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("result.docx");
效果图:
1.选择一个预定义的页面大小
2.自定义页面大小
全部代码:
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace set_page_size_of_word_document
{
class Program
{
static void Main(string[] args)
{
Document doc = new Document();
Section section = doc.AddSection();
section.PageSetup.PageSize = PageSize.A4;
//section.PageSetup.PageSize = new System.Drawing.SizeF(550, 800);
//section.PageSetup.Orientation = PageOrientation.Portrait;
Paragraph Para = section.AddParagraph();
Para.AppendText("朝 辞 白 帝 彩 云 间 ,"
+ "千 里 江 陵 一 日 还 。"
+ "两 岸 猿 声 啼 不 尽 ,"
+ "轻 舟 已 过 万 重 山 。");
doc.SaveToFile("result.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("result.docx");
}
}
}
感谢您的浏览,希望本文能给您带来一定的帮助。