星期一, 8月 09, 2010

使用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;
}

沒有留言: