C#:iTextSharp,如何编辑pdf文档的title属性?

Fab*_*roh 2 c# pdf itextsharp

我在C#项目中使用iTextSharp库来读取和编辑pdf文档.现在我想更改某个pdf文档的标题.我搜索了很多关于这个问题,但没有什么对我有用.我发现的最好的是:

PdfReader pdfReader = new PdfReader(filePath);

using (FileStream fileStream = new FileStream(newFilePath, 
                                              FileMode.Create,
                                              FileAccess.Write))
{
    string title = pdfReader.Info["Title"] as string;
    Trace.WriteLine("Existing title: " + title);

    PdfStamper pdfStamper = new PdfStamper(pdfReader, fileStream);

    // The info property returns a copy of the internal HashTable
    Hashtable newInfo = pdfReader.Info;

    newInfo["Title"] = "New title";

    pdfStamper.MoreInfo = newInfo;

    pdfReader.Close();
    pdfStamper.Close();
}
Run Code Online (Sandbox Code Playgroud)

但Visual Studio表示System.Collection.Hashtable无法将其隐式转换为System.Collections.Generic.IDictionary<string,string>.已有转换.

希望有人能帮助我.或者使用iTextSharp的另一个解决方案来编辑​​标题.

Yuv*_*kov 5

你需要改变这个:

Hashtable newInfo = pdfReader.Info;
Run Code Online (Sandbox Code Playgroud)

对此:

Dictionary<string, string> newInfo = pdfReader.Info;
Run Code Online (Sandbox Code Playgroud)

因为错误说明,pdfReader.Info返回对a的引用IDictionary<string, string>,而不是a Hashtable.

请注意,如果要修改Info,则无需创建额外的局部变量:

var title = "Title";
if (pdfReader.Info.ContainsKey(title))
{
    pdfReader[title] = "NewTitle";
}
Run Code Online (Sandbox Code Playgroud)