我們知道,在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");
}
}
}
感謝您的浏覽,希望本文能給您帶來一定的幫助。