noob to C# here, using iTextSharp examples from around SO I’ve made a basic exe to change title, description and keywords to an existing PDF. Using MS Visual C# 2010, I don’t understand all this ‘Generic’ change to C#, so I’m getting this error:
Cannot implicitly convert type 'System.Collections.Generic.Dictionary<string,string>' to 'System.Collections.Hashtable'
and
Cannot implicitly convert type 'System.Collections.Hashtable' to 'System.Collections.Generic.IDictionary<string,string>'. An explicit conversion exists (are you missing a cast?)
The Code:
using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
if ((args == null) || (args.Length < 3))
{
Console.WriteLine("args: PDFProp [fileName] [outputPath] [Title] [Description] [Keywords]");
Console.WriteLine();
Console.Write("<Continue>");
Console.ReadLine();
return;
}
string filePath = args[0];
string newFilePath = args[1];
string title = args[2];
string desc = "";
string keywords = "";
if (args.Length > 3)
desc = args[3];
if (args.Length > 4)
keywords = args[4];
Console.Write(filePath + "->" + newFilePath + " title: " + title + " description: " + desc + " keywords: " + keywords);
Console.WriteLine();
Console.ReadLine();
PdfReader pdfReader = new PdfReader(filePath);
using (FileStream fileStream = new FileStream(newFilePath, FileMode.Create, FileAccess.Write))
{
// string title = pdfReader.Info["Title"] as string;
PdfStamper pdfStamper = new PdfStamper(pdfReader, fileStream);
// The info property returns a copy of the internal HashTable
Hashtable newInfo = pdfReader.Info; // error 1
newInfo["Title"] = title;
if (args.Length > 3)
newInfo["Description"] = desc;
if (args.Length > 4)
newInfo["Keywords"] = keywords;
pdfStamper.MoreInfo = newInfo; // error 2
pdfReader.Close();
pdfStamper.Close();
}
}
}
}
Change the below line:
instead of
Should fix both errors.
The reason why this is happening is because you are trying to cast from a Hashtable to a Generic Dictionary and the hashtable does not have an implicit type conversion available for this. look here to see the difference between a hashtable and a Dictionary.