如何向已有的pdf添加书签,

您好,感谢您的查看,以下是我的代码,我想向已有的pdf插入多个书签,我将书签名字存储到list里面,循环获取,添加多个书签,但是问题是,最后保存的pdf只有一个书签,使用pdfOutline.Insert(i, pdfOutline);报错“Invalid index: index should be in the range [1…n] where n equals to the outline items count.”

       //打开文档
        Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(currentpath);
  
        //创建书签对象
        OutlineItemCollection pdfOutline = new OutlineItemCollection(pdfDocument.Outlines);

        for (int i = 1; i <= list6.Count; i++)
        {
            string mz = list6[i];
            //书签名字
            pdfOutline.Title= mz;
   
            //设置目标页码
            pdfOutline.Action = new Aspose.Pdf.Annotations.GoToAction(pdfDocument.Pages[i]);

            //添加新书签   
           // pdfOutline.Insert(i, pdfOutline);

            //在文档的大纲集合中添加书签。
            pdfDocument.Outlines.Add(pdfOutline);

        }

        //保存输出
        pdfDocument.Save(currentpath);

@fhn123456,

感谢您与我们分享示例代码。您能否与我们共享源文件以及环境详细信息,以进一步详细研究此问题。

您好,感谢您的回复及查看,以下是我的代码,再次感谢您的查看。pdf.pdf (141.5 KB)

C#写的程序

这个pdf是通过代码运行存储的只有一个书签的pdf66.pdf (142.4 KB)

        //向list存入3个书签名字
        List<string> list = new List<string>();
        for (int cc=0;cc<3; cc++) {

            String sq = "书签" + cc;

            list.Add(sq);
        
        }
         
         String     currentpath="C:\\Users\\fhn\\Desktop\\123\\pdf.pdf";
         //打开文档
        Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(currentpath);

       //创建书签对象
       OutlineItemCollection pdfOutline = new OutlineItemCollection(pdfDocument.Outlines);
       //循环创建添加多个书签
            for (int i = 0; i < list.Count; i++)
            {
                string mz = list[i];
                //书签名字
                pdfOutline.Title= mz;

                //pdfOutline.Bold = true;
                //设置目标页码
                pdfOutline.Action = new Aspose.Pdf.Annotations.GoToAction(pdfDocument.Pages[i+1]);

                //添加新书签   
                //pdfOutline.Insert(i, pdfOutline);
               

                 // prevBookmarks.Add(pdfOutline);
                 //在文档的大纲集合中添加书签。
                  pdfDocument.Outlines.Add(pdfOutline);

                       }

        //保存输出
        pdfDocument.Save("C:\\Users\\fhn\\Desktop\\123\\66.pdf");

@fhn123456,

我已经处理了您共享的源文件和示例代码,无法观察到该问题。您能否分享指向问题的比较屏幕截图,以便我们进一步调查以帮助您。661.pdf (142.3 KB)

哎,我已经解决了,您身为Aspose公司的技术人员,问题竟然没有找出来,代码写的清清楚楚的,还有pdf附件,您任然找不到问题。

我告诉您 将

   //创建书签对象
   OutlineItemCollection pdfOutline = new OutlineItemCollection(pdfDocument.Outlines);

放入for循环里面。

@fhn123456,

很高兴知道您已经解决了问题。我已生成PDF文件并与您共享,为了进一步调查,请您与我们共享比较屏幕截图。