天天看點

C# 将多個office檔案轉換及合并為一個PDF檔案

PDF檔案介紹

PDF(Portable Document Format )檔案源于20世紀90年代初期,如今早已成為了一種最流行的的檔案格式之一。因為PDF檔案有很多優點:

  • 支援跨平台和跨裝置共享
  • 可以通過密碼保護方式來阻止複制和編輯
  • 将各種文本文檔、圖檔、音頻、三維地圖等合并為一個PDF檔案時,依然可以完好的儲存所有的源檔案資訊等

是以,有些時候為了友善共享檔案,你可能需要把其他格式的檔案如Word,Excel以及 PowerPoint檔案轉換為PDF格式。本文将向你介紹如何使用Spire.Office軟體,通過C#程式設計的方式,

将多個office檔案轉換及合并到一個PDF檔案。并且在轉換過程中,你還可以根據自己的需要來改變PDF檔案的尺寸。

Spire.Office簡介 

Spire.Office是一款強大的.NET類庫,通過它,程式設計者可以在任何一個.NET平台上操作MS Word,Excel,PowerPoint和PDF文檔。首先,請在e-iceblue website上下載下傳Spire.Office軟

件,其次添加相關的.dll檔案引用至Visual Studio。

C# 将多個office檔案轉換及合并為一個PDF檔案

下面我們就來看看怎樣通過這款軟體來實作上述要求的功能。

代碼片段:

第一步:建立一個winform應用程式,定義Form1并像下圖這樣設定;

C# 将多個office檔案轉換及合并為一個PDF檔案

第二步:定義btnAdd_Click方法,通過OpenFileDialog、添加檔案路徑到listbox來選擇目标檔案;

private void btnAdd_Click(object sender, EventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Filter = "All files (*.docx, *.pdf, *.pptx, *.pdf)|*.docx;*.pdf;*.pptx;*.xlsx";
    ofd.Multiselect=true;
    if (DialogResult.OK == ofd.ShowDialog())
    {
        string[] files = ofd.FileNames;
        listBox1.Items.AddRange(files);
    }
}      

第三步:通過MemoryStream将不同格式的檔案轉換為PDF檔案,然後把它們合并為一個PDF檔案。

值得指出的是,當你将不同類型的檔案合并為一個PDF檔案時,你會發現不同類型的檔案大小也不相同。例如,PowerPoint檔案的頁面大小和Word或Excel檔案的頁面大小完全不同。如果你

想保持合并文檔的整潔美觀,可以建立一個新的、頁面大小固定的PDF檔案,然後複制合并檔案的内容到這個新的PDF檔案裡面。

C# 将多個office檔案轉換及合并為一個PDF檔案
C# 将多個office檔案轉換及合并為一個PDF檔案
private void btnMerge_Click(object sender, EventArgs e)
{
    //将其他格式的檔案轉換為PDF檔案
    string ext=string.Empty;
    foreach (object item in listBox1.Items)
    {
        ext=Path.GetExtension(item.ToString());
        switch (ext)
        {
            case ".docx":
                using (MemoryStream ms = new MemoryStream())
                {
                    Document doc = new Document(item.ToString());
                    doc.SaveToStream(ms, Spire.Doc.FileFormat.PDF);
                    PdfFiles.Add(new PdfDocument(ms));
                }
                break;
            case ".pdf":
                PdfFiles.Add(new PdfDocument(item.ToString()));
                break;
            case ".pptx":
                using (MemoryStream ms = new MemoryStream())
                {
                    Presentation ppt = new Presentation(item.ToString(),Spire.Presentation.FileFormat.Auto);
                    ppt.SaveToFile(ms,Spire.Presentation.FileFormat.PDF);
                    PdfFiles.Add(new PdfDocument(ms));
                }
                break;
            case ".xlsx":
                using (MemoryStream ms = new MemoryStream())
                {
                    Workbook xls = new Workbook();
                    xls.LoadFromFile(item.ToString());
                    xls.SaveToStream(ms, Spire.Xls.FileFormat.PDF);
                    PdfFiles.Add(new PdfDocument(ms));
                }
                break;
            default:
                break;
        }              
    }
    //将多個PDF檔案合并為一個PDF檔案
    PdfDocument newPdf1 = new PdfDocument();
    foreach (PdfDocument doc in PdfFiles)
    {
        newPdf1.AppendPage(doc);
    }
    //建立一個新的、頁面大小固定的PDF檔案,複制合并檔案的内容到該新的PDF檔案
    PdfDocument newPdf2 = new PdfDocument();
    foreach (PdfPageBase page in newPdf1.Pages)
    {
        PdfPageBase newPage = newPdf2.Pages.Add(PdfPageSize.A4, new PdfMargins(0));
        PdfTextLayout loLayout = new PdfTextLayout();
        loLayout.Layout = PdfLayoutType.OnePage;
        page.CreateTemplate().Draw(newPage, new PointF(0, 0), loLayout);
    }
    //儲存目标PDF檔案
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "Pdf files(*.pdf)|*.pdf";
    if (DialogResult.OK == sfd.ShowDialog())
    {
        newPdf2.SaveToFile(sfd.FileName);
    }
}      

點選加号檢視全部代碼

第四步:運作程式,點選“Add Files” 按鈕來添加目标檔案到listbox;

C# 将多個office檔案轉換及合并為一個PDF檔案

第五步:點選“Merge”按鈕來轉換和合并不同格式的檔案至一個PDF檔案,然後儲存該檔案;

C# 将多個office檔案轉換及合并為一個PDF檔案

全部代碼:

using System.Drawing;
using System.Windows.Forms;
using Spire.Pdf;
using Spire.Doc;
using Spire.Xls;
using Spire.Presentation;
using System.IO;
using Spire.Pdf.Graphics;

namespace ConvertAndMerge
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            PdfFiles = new List();
        }
        public List PdfFiles { get; set;}

        //添加檔案到 listbox
        private void btnAdd_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "All files (*.docx, *.pdf, *.pptx, *.pdf)|*.docx;*.pdf;*.pptx;*.xlsx";
            ofd.Multiselect=true;
            if (DialogResult.OK == ofd.ShowDialog())
            {
                string[] files = ofd.FileNames;
                listBox1.Items.AddRange(files);
            }
        }

        private void btnMerge_Click(object sender, EventArgs e)
        {
            //将其他格式的檔案轉換為PDF檔案
            string ext=string.Empty;
            foreach (object item in listBox1.Items)
            {
                ext=Path.GetExtension(item.ToString());
                switch (ext)
                {
                    case ".docx":
                        using (MemoryStream ms = new MemoryStream())
                        {
                            Document doc = new Document(item.ToString());
                            doc.SaveToStream(ms, Spire.Doc.FileFormat.PDF);
                            PdfFiles.Add(new PdfDocument(ms));
                        }
                        break;
                    case ".pdf":
                        PdfFiles.Add(new PdfDocument(item.ToString()));
                        break;
                    case ".pptx":
                        using (MemoryStream ms = new MemoryStream())
                        {
                            Presentation ppt = new Presentation(item.ToString(),Spire.Presentation.FileFormat.Auto);
                            ppt.SaveToFile(ms,Spire.Presentation.FileFormat.PDF);
                            PdfFiles.Add(new PdfDocument(ms));
                        }
                        break;
                    case ".xlsx":
                        using (MemoryStream ms = new MemoryStream())
                        {
                            Workbook xls = new Workbook();
                            xls.LoadFromFile(item.ToString());
                            xls.SaveToStream(ms, Spire.Xls.FileFormat.PDF);
                            PdfFiles.Add(new PdfDocument(ms));
                        }
                        break;
                    default:
                        break;
                }              
            }
            //将多個PDF檔案合并為一個PDF檔案
            PdfDocument newPdf1 = new PdfDocument();
            foreach (PdfDocument doc in PdfFiles)
            {
                newPdf1.AppendPage(doc);
            }
            //建立一個新的、頁面大小固定的PDF檔案,複制合并檔案的内容到該新的PDF檔案
            PdfDocument newPdf2 = new PdfDocument();
            foreach (PdfPageBase page in newPdf1.Pages)
            {
                PdfPageBase newPage = newPdf2.Pages.Add(PdfPageSize.A4, new PdfMargins(0));
                PdfTextLayout loLayout = new PdfTextLayout();
                loLayout.Layout = PdfLayoutType.OnePage;
                page.CreateTemplate().Draw(newPage, new PointF(0, 0), loLayout);
            }
            //儲存目标PDF檔案
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Pdf files(*.pdf)|*.pdf";
            if (DialogResult.OK == sfd.ShowDialog())
            {
                newPdf2.SaveToFile(sfd.FileName);
            }
        }
    }
}      

注意:

使用此方法來将多個office檔案合并到一個PDF檔案,排版可能會改變,因為不同檔案的所有内容都會顯示在一個固定的大小的頁面上(例如A4)。如果你想儲存原來的排版格式,隻需要先把

它們轉換成PDF檔案然後再合并到一起。