使用PDFSharp合并PDF时如何避免PDF中已添加的注释丢失
注释丢失原因
PDF 格式中注释是独立于页面内容流、挂载在页面对象 /Annots 属性下的独立对象,现有代码调用的 PdfDocument.AddPage() 方法默认仅复制页面的基础渲染内容流,不会自动迁移页面对应的注释集合,因此合并后注释会丢失。
修复后的代码
仅需要修改 CopyPages 方法,在添加页面后额外克隆迁移所有注释即可,同时可根据需求补充表单域合并逻辑:
public string CombinePdf(List<string> files) { PdfDocument outDoc = new PdfDocument(); // 若需要保留表单域,先初始化输出文档的AcroForm outDoc.AcroForm = new PdfAcroForm(outDoc); foreach(string file in files) { using (PdfDocument pdfDocument = PdfReader.Open(FormatPath(file), PdfDocumentOpenMode.Import, PdfReadAccuracy.Strict)) { CopyPages(pdfDocument, outDoc); } } string outPdfFileName = $"{Guid.NewGuid()}.pdf"; string outPdfPath = Path.Combine(Path.GetTempPath(), outPdfFileName); outDoc.Save(outPdfPath); outDoc.Close(); return outPdfPath; } private void CopyPages(PdfDocument from, PdfDocument to) { // 合并源文档的表单域(如果存在),不需要可删除本段 if (from.AcroForm != null && from.AcroForm.Fields.Count > 0) { foreach (var field in from.AcroForm.Fields) { var clonedField = (PdfAcroField)field.Clone(); to.AcroForm.Fields.Add(clonedField); } } for (int i = 0; i < from.PageCount; i++) { var sourcePage = from.Pages[i]; var targetPage = to.AddPage(sourcePage); // 迁移页面级注释 if (sourcePage.Annotations != null && sourcePage.Annotations.Count > 0) { foreach (var annot in sourcePage.Annotations) { var clonedAnnot = (PdfAnnotation)annot.Clone(); targetPage.Annotations.Add(clonedAnnot); } } } }
注意事项
如果使用的是1.5.x及更早版本的PDFSharp,部分特殊类型注释的克隆可能存在兼容问题,建议升级到最新稳定版测试。
内容的提问来源于stack exchange,提问作者GoozMeister
相关产品推荐
相关产品推荐

