C# 設置word文檔頁面大小

 我們知道,在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");

        }

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章