C#: iTextSharp, how can i edit the title property of a pdf-document?

4.3k Views Asked by At

I use the iTextSharp Library in my C# project to read and edit pdf documents. Now I want to change the title of a certain pdf-document. I searched a lot about this issue, but nothing really works for me. Best I found is following:

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();
}

But Visual Studio says that System.Collection.Hashtable can't be converted implicit into System.Collections.Generic.IDictionary<string,string>. There is already an existing conversion.

Hope anyone can help me with that. Or has another solution with iTextSharp to edit the title.

1

There are 1 best solutions below

0
On

You need to change this:

Hashtable newInfo = pdfReader.Info;

To this:

Dictionary<string, string> newInfo = pdfReader.Info;

Because as the error says, pdfReader.Info returns a reference to a IDictionary<string, string>, not a Hashtable.

Note that if you want to modify Info, there's no need to create an extra local variable:

var title = "Title";
if (pdfReader.Info.ContainsKey(title))
{
    pdfReader.Info[title] = "NewTitle";
}