You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用iText7设置PDF创建日期?原iText5方法已不可用

iText7 设置PDF创建日期的解决思路

核心逻辑

iText7中不管是新建还是修改PDF,都通过PdfDocumentInfo类管理文档元数据(包括创建日期),无需依赖旧版的PdfStamper,直接通过PdfDocument对象操作即可。


场景1:新建PDF时设置创建日期

创建PdfDocument后,获取其PdfDocumentInfo实例,调用专门的SetCreationDate方法(自动处理PDF标准日期格式):

using iText.Kernel.Pdf;
using System;

PdfWriter writer = new PdfWriter("new_document.pdf");
PdfDocument pdfDoc = new PdfDocument(writer);
PdfDocumentInfo docInfo = pdfDoc.GetDocumentInfo();

// 设置创建日期为当前时间
docInfo.SetCreationDate(DateTime.Now);

// 也可以指定具体日期
// docInfo.SetCreationDate(new DateTime(2023, 11, 15, 9, 30, 0));

pdfDoc.Close();

场景2:修改已有PDF的创建日期

通过PdfReader读取原文档,结合PdfWriter输出修改后的文档,同样通过PdfDocumentInfo更新日期:

using iText.Kernel.Pdf;
using System;

PdfReader reader = new PdfReader("existing_document.pdf");
PdfWriter writer = new PdfWriter("updated_document.pdf");
PdfDocument pdfDoc = new PdfDocument(reader, writer);
PdfDocumentInfo docInfo = pdfDoc.GetDocumentInfo();

// 更新创建日期为指定时间
docInfo.SetCreationDate(new DateTime(2022, 5, 20, 14, 0, 0));

pdfDoc.Close();
reader.Close();
writer.Close();

补充说明

  • 若需手动设置符合PDF标准的日期字符串(格式为D:YYYYMMDDHHmmSS±HHmm),可使用SetMoreInfo方法:
    // 示例:手动拼接带时区的PDF日期
    string timeZoneOffset = TimeZoneInfo.Local.GetUtcOffset(DateTime.Now).ToString(@"\+hhmm");
    string pdfDate = $"D:{DateTime.Now:yyyyMMddHHmmss}{timeZoneOffset}";
    docInfo.SetMoreInfo("CreationDate", pdfDate);
    
  • 优先使用SetCreationDate(DateTime)方法,它会自动处理时区和格式转换,避免手动拼接出错。

内容的提问来源于stack exchange,提问作者mark gamache

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:12:54