合并带书签的pdf和向pdf里加图片
using iTextSharp;
using iText = iTextSharp.text;
using iTextSharp.text.pdf;
private void addPicToPdf() { var pgSize = new iText.Rectangle(1664, 2400); var doc = new iText.Document(pgSize, 50, 50, 50, 50); string existingPdf = @"c:\temp\foo.pdf"; string newPdf = @"c:\temp\bar.pdf"; string imagePath = @"c:\temp\images"; PdfReader reader = null; if (File.Exists(existingPdf)) { reader = new PdfReader(existingPdf); } var files = (new DirectoryInfo(imagePath)).GetFiles().OrderBy(p => p.Name).ToList(); string bookmarkName = ""; PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(newPdf, FileMode.Create)); doc.Open(); float totalHeight = 0; //读入已有文件 if (reader != null) { for (int page = 0; page < reader.NumberOfPages; page++) { doc.SetPageSize(pgSize); doc.NewPage(); var pg = writer.GetImportedPage(reader, page + 1); writer.DirectContent.AddTemplate(pg, 1f, 0, 0, 1f, 0, 0);//这里不考虑旋转,否则需要稍微调整一下 } //导入书签,这里不考虑多级书签,只考虑单级,多级的话要检测Kid这个key,递归实现,稍微麻烦些 IList<Dictionary<string, object>> book_mark = SimpleBookmark.GetBookmark(reader); foreach (Dictionary<string, object> bk in book_mark) { string title = bk["Title"].ToString(); string[] words = Convert.ToString(bk["Page"]).Split(' '); int page = 0; if (!object.Equals(words, null)) { page = Convert.ToInt32(words[0]);//如果是合并多个pdf文件,需要调整page,下面的pos则不需要调整 } int pos = Convert.ToInt32(words[2]); PdfAction obja3lvl = PdfAction.GotoLocalPage(page, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH, pos), writer); PdfOutline objoutline3lvl = new PdfOutline(writer.RootOutline, obja3lvl, title, true); } } //原pdf导入完成,开始添加新图片 for (int i = 0; i < files.Count; i++) { iText.Image jpg = iText.Image.GetInstance(files[i].FullName); string newBookmarkName = Regex.Replace(Path.GetFileNameWithoutExtension(files[i].Name), "[0-9]+", "");//文件名如:foo1.png, foo2.png, bar1.png...... totalHeight += jpg.Height; if (totalHeight > 2290) { doc.NewPage(); totalHeight = jpg.Height; } if (newBookmarkName != bookmarkName) { bookmarkName = newBookmarkName; var bookmark = new PdfOutline(writer.RootOutline, new PdfDestination(PdfDestination.FITH, writer.GetVerticalPosition(true)), newBookmarkName); } doc.Add(jpg); } doc.Close(); MessageBox.Show("finish"); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律