private void MergePdfTogeter(bool createBookmarks = false)
{
if (listBox1.Items.Count > 0)
{
Document document = new Document();
//存放书签的页面
List ints = new List();
int currentPage = 1;
foreach (var item in fileNameWithPostfix)
{
Document tempDoc = new Document(item);
document.Pages.Add(tempDoc.Pages);
if (createBookmarks == true)
{
string bookmarkTitle = System.IO.Path.GetFileNameWithoutExtension(item);
OutlineItemCollection bookmark = new OutlineItemCollection(document.Outlines)
{
Title = bookmarkTitle,
Action = new GoToAction(document.Pages[currentPage])
};
ints.Add(currentPage);
document.Outlines.Add(bookmark);
currentPage += document.Pages.Count;
}
}
if (string.IsNullOrEmpty(fileNameSaveAs))
{
MessageBox.Show("请输入要保存的文件名");
}
else
{
document.Save(fileNameSaveAs);
}
if (createBookmarks == true)
{
// 创建新文档并插入目录页
Document newdocument = new Document(fileNameSaveAs);
Aspose.Pdf.Page tocPage = newdocument.Pages.Insert(1);
TocInfo tocInfo = new TocInfo();
// 创建目录标题
TextFragment title = new TextFragment("目录")
{
TextState = { FontSize = 20, FontStyle = FontStyles.Bold, Font = FontRepository.FindFont("SimSun") }
};
title.TextState.Font.IsEmbedded = true;
tocInfo.Title = title;
tocPage.TocInfo = tocInfo;
// 创建目录项
for (int i = 0; i < fileNameWithPostfix.Length; i++)
{
var heading = new Aspose.Pdf.Heading(1)
{ TocPage = tocPage, DestinationPage = newdocument.Pages[i + 2], Top = newdocument.Pages[i + 2].Rect.Height };
var segment = new TextSegment
{
Text = Path.GetFileNameWithoutExtension(fileNameWithPostfix[i]),
TextState = { Font = FontRepository.FindFont("SimSun"), FontSize = 12 }
};
heading.Segments.Add(segment);
tocPage.Paragraphs.Add(heading);
}
newdocument.Save("mergedOutput_withToc.pdf");
// 保存输出
}
MessageBox.Show($"Pdf合并完成,共合并{listBox1.Items.Count}份文件");
}
}