c# - 合并 pdf 列表并创建新书签 (C#)

标签 c# itext

该项目使用 C# 并使用 iTextSharp。

我有一个带有标题(字符串)和文件内容(字节数组)的字典。我遍历这本字典并将所有文件合并在一起。我现在需要的是将书签添加到每个文件第一页的开头,但我不应该向最终文档添加任何新页面或文本。我尝试了不同的解决方案,但似乎都添加了目录页、每页前的新页或页首的一些文本。

所有文件最初都没有书签。

我正在寻找看起来像这样的书签结构:

  • 文件1
  • 文件2
  • 一些类别
    • 文件3
    • 文件4

如果有人能指出正确的方向,我将不胜感激。

我合并文件的函数如下所示:

/// <summary>
/// Merge PDF files, and stamp certificates. This is a modified version of the example in the link below.
/// See: http://www.codeproject.com/Articles/28283/Simple-NET-PDF-Merger for more information.            
/// </summary>
/// <param name="sourceFiles">Files to be merged</param>
/// <returns>Byte array with the combined files.</returns>
public static byte[] MergeFiles(Dictionary<string, byte[]> sourceFiles)
    {
        var document = new Document();
        var output = new MemoryStream();

        try
        {
            // Initialize pdf writer
            var writer = PdfWriter.GetInstance(document, output);
            writer.PageEvent = new PdfPageEvents();

            // Open document to write
            document.Open();
            var content = writer.DirectContent;

            // Iterate through all pdf documents
            foreach (var sourceFile in sourceFiles)
            {
                // Create pdf reader
                var reader = new PdfReader(sourceFile.Value);
                var numberOfPages = reader.NumberOfPages;

                // Iterate through all pages
                for (var currentPageIndex = 1; currentPageIndex <=
                                   numberOfPages; currentPageIndex++)
                {
                    // Determine page size for the current page
                    document.SetPageSize(
                       reader.GetPageSizeWithRotation(currentPageIndex));

                    // Create page
                    document.NewPage();

                    var importedPage =
                      writer.GetImportedPage(reader, currentPageIndex);

                    // Determine page orientation
                    var pageOrientation = reader.GetPageRotation(currentPageIndex);
                    if ((pageOrientation == 90) || (pageOrientation == 270))
                    {
                        content.AddTemplate(importedPage, 0, -1f, 1f, 0, 0,
                           reader.GetPageSizeWithRotation(currentPageIndex).Height);
                    }
                    else
                    {
                        content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
                    }
                    // Add stamp to certificates
                    if (sourceFile.Key.IsValidDocumentReference())
                        AddStamp(content, document, sourceFile.Key, currentPageIndex, numberOfPages);

                }
            }
        }
        catch (Exception exception)
        {
            throw new Exception("An unexpected exception occured during the merging process", exception);
        }
        finally
        {
            document.Close();
        }
        return output.GetBuffer();
    }

最佳答案

感谢Bruno Lowagie谁指出了我正确的方向,我就能够为我的问题提供解决方案。

这是我的解决方案:

public static byte[] MergeFilesAndAddBookmarks(Dictionary<PrintDocument, byte[]> sourceFiles)
    {
        using (var ms = new MemoryStream())
        {
            using (var document = new Document())
            {
                using (var copy = new PdfCopy(document, ms))
                {
                    //Order the files by chapternumber
                    var files = sourceFiles.GroupBy(f => f.Key.ChapterNumber);

                    document.Open();

                    var outlines = new List<Dictionary<string, object>>();

                    var pageIndex = 1; 

                    foreach (var chapterGroup in files)
                    {
                        var map = new Dictionary<string, object>();
                        outlines.Add(map);
                        map.Add("Title", chapterGroup.First().Key.ChapterName);
                        var kids = new List<Dictionary<string, object>>();
                        map.Add("Kids", kids);

                        foreach (var sourceFile in chapterGroup)
                        {
                            using (var reader = new PdfReader(sourceFile.Value))
                            {
                                // add the pages
                                var n = reader.NumberOfPages;

                                for (var page = 0; page < n;)
                                {
                                    if (page == 0)
                                    {
                                        var kid = new Dictionary<string, object>();
                                        kids.Add(kid);
                                        kid["Title"] = sourceFile.Key.Title;
                                        kid["Action"] = "GoTo";
                                        kid["Page"] = String.Format("{0} Fit", pageIndex);
                                    }
                                    copy.AddPage(copy.GetImportedPage(reader, ++page));
                                }

                                pageIndex += n;
                                reader.Close();
                            }
                        }
                    }

                    copy.Outlines = outlines;
                    document.Close();
                    copy.Close();
                    ms.Close();
                }
            }
            return ms.ToArray();
        }
    } 
}

public class PrintDocument
{
    public string Title { get; set; }
    public string ChapterName { get; set; }
    public int ChapterNumber { get; set; }
}

关于c# - 合并 pdf 列表并创建新书签 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20636690/

相关文章:

c# - 来自 WPF 的异步 Web 服务请求

c# - AWS Lambda C# CloudFormation 配置

c# - 重构乐趣 - 素数

pdf - iText PDF : replace/transform colours

c# - 检查 Excel 文件是否在 .NET Core 中受密码保护

c# - 无法从 CLI 读取数据

android - iText 库 - 不显示西里尔文(俄语)符号

c# - 使用 itextsharp 突出显示 PDF 文件时出现数字超出范围错误

java - 使用 itext 编辑 pdf 时出现异常

java - 如何在下一页重复表格的最后 5 行?