ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-06-29 06:54:24  阅读:274  来源: 互联网

标签:c itextsharp


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

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

这些文件都没有最初的书签.

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

> File1
> File2
> SomeCategory

> File3
> File4

如果有人能指出我正确的方向,我将非常感激.

我合并文件的功能如下所示:

/// <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,itextsharp
来源: https://codeday.me/bug/20190629/1323974.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有