C# iTextSharp 带书签合并多个PDF

本文介绍了一种使用iTextSharp库合并多个PDF文件的方法,并在此过程中保留了原始PDF文件中的书签结构。通过逐个读取源PDF文件,合并页面内容及书签,最终生成一个包含所有源文件内容及书签的新PDF文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    private void MergePdfFilesWithBookMark(string[] sourcePdfs, string outputPdf)
    {
        PdfReader reader = null;
        Document document = new Document();
        PdfImportedPage page = null;
        PdfCopy pdfCpy = null;
        int n = 0;
        int totalPages = 0;
        int page_offset = 0;
        List<Dictionary<string, object>> bookmarks = new List<Dictionary<string, object>>();
        IList<Dictionary<string, object>> tempBookmarks;
        for (int i = 0; i <= sourcePdfs.GetUpperBound(0); i++)
        {
            reader = new PdfReader(sourcePdfs[i]);
            reader.ConsolidateNamedDestinations();
            n = reader.NumberOfPages;
            tempBookmarks = SimpleBookmark.GetBookmark(reader);

            if (i == 0)
            {
                document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1));
                pdfCpy = new PdfCopy(document, new FileStream(outputPdf, FileMode.Create));
                document.Open();
                SimpleBookmark.ShiftPageNumbers(tempBookmarks, page_offset, null);
                page_offset += n;
                if (tempBookmarks != null)
                    bookmarks.AddRange(tempBookmarks);
                //  MessageBox.Show(n.ToString());
                totalPages = n;
            }
            else
            {
                SimpleBookmark.ShiftPageNumbers(tempBookmarks, page_offset, null);
                if (tempBookmarks != null)
                    bookmarks.AddRange(tempBookmarks);

                page_offset += n;
                totalPages += n;
            }

            for (int j = 1; j <= n; j++)
            {
                page = pdfCpy.GetImportedPage(reader, j);
                pdfCpy.AddPage(page);

            }
            reader.Close();

        }
        pdfCpy.Outlines = bookmarks;
        document.Close();
    }

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值