跳到主要內容

使用iTextSharp合併PDF

本文只是簡單做個紀錄,因為同事有需求,所以就簡單地Google一下合併PDF的程式。
先找到iTextSharp合併PDF檔,後來又比對Merge PDF Files using iTextSharpMerge PDFs using ITextSharp,覺得老外參考現在已不存在的原網站Example比較好用,因此採用改寫以上兩位的版本,原始碼版權....依照iTextSharp的版權應該是GPL。




public static string MergePDFs(string destinationFile, string[] sourceFiles)
{
    string ret = "ok";
    try
    {
        int f = 0;
        // we create a reader for a certain document
        PdfReader reader = new PdfReader(sourceFiles[f]);
        // we retrieve the total number of pages
        int n = reader.NumberOfPages;
        Console.WriteLine("There are " + n + " pages in the original file.");
        // step 1: creation of a document-object
        Document document = new Document(reader.GetPageSizeWithRotation(1));
        // step 2: we create a writer that listens to the document
        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
        // step 3: we open the document
        document.Open();
        PdfContentByte cb = writer.DirectContent;
        PdfImportedPage page;
        int rotation;
        // step 4: we add content
        while (f < sourceFiles.Length)
        {
            int i = 0;
            while (i < n)
            {
                i++;
                document.SetPageSize(reader.GetPageSizeWithRotation(i));
                document.NewPage();
                page = writer.GetImportedPage(reader, i);
                rotation = reader.GetPageRotation(i);
                if (rotation == 90 || rotation == 270)
                {
                    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                }
                else
                {
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
                Console.WriteLine("Processed page " + i);
            }
            f++;
            if (f < sourceFiles.Length)
            {
                reader = new PdfReader(sourceFiles[f]);
                // we retrieve the total number of pages
                n = reader.NumberOfPages;
                Console.WriteLine("There are " + n + " pages in the original file.");
            }
        }
        // step 5: we close the document
        document.Close();
    }
    catch (Exception e)
    {
        Console.Error.WriteLine(e.Message);
        Console.Error.WriteLine(e.StackTrace);
        ret = e.Message;
    }
    return ret;
}

留言

這個網誌中的熱門文章

DBeaver 介面語言

DBeaver是我個人頗常用的一套跨平台Database管理工具,最近升級後發現Windows版本居然變成簡體中文,而且無法切換為英文。

自然人憑證讀卡機驅動程式

鳥毅用的是第一代的自然人憑證讀卡機,EZ100PU(後來有同事買EZmini可以讀SIM卡似乎更好),每年報稅時用一次。 本來只是要申請些政府業務,一時之間找不到光碟,沒想到在 驅動程式下載 居然看到Linux和Mac的驅動程式,剩下的就是政府單位的網頁和程式應該改版了吧!!!

如何將較高版本SQL Server複製到低版本SQL Server (降級為舊版)並保留權限及資料庫圖表

一般若是要將SQL Server裡的Database轉往其他Server時,最簡單的方式就是備份(Backup)後再還原(Restore),或者是䣃離(detach)後附加(attach)。 但是很不幸地,若是由較低版本(e.g. 2008)到較高版本(e.g. 2012)要怎麼辦呢?