noob to C#here,使用来自各地的iTextSharp示例我已经制作了一个基本的exe来将标题,描述和关键字更改为现有的PDF。使用MS Visual C#2010,我不明白所有这些对C#的“通用”更改,所以我收到了这个错误:
Cannot implicitly convert type 'System.Collections.Generic.Dictionary<string,string>' to 'System.Collections.Hashtable'
和
Cannot implicitly convert type 'System.Collections.Hashtable' to 'System.Collections.Generic.IDictionary<string,string>'. An explicit conversion exists (are you missing a cast?)
守则:
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();
}
}
}
}
答案 0 :(得分:2)
更改以下行:
Dictionary<string,string> newInfo = pdfReader.Info;
而不是
Hashtable newInfo = pdfReader.Info;
应该修复这两个错误。
之所以发生这种情况,是因为您正在尝试从Hashtable转换为通用字典,并且哈希表没有可用的implicit类型转换。查看here以查看散列表和字典之间的区别。
答案 1 :(得分:1)
我想这一行
Hashtable newInfo = pdfReader.Info;
抛出错误,然后是这个:
pdfStamper.MoreInfo = newInfo;
pdfStamper.MoreInfo似乎是System.Collections.Generic.Dictionary类型,所以你要做的就是替换
Hashtable newInfo = pdfReader.Info;
通过
System.Collections.Generic.Dictionary<string,string> newInfo = pdfReader.Info;
类型必须匹配。我不能测试这个,所以我不知道我是否找到了正确的线条,但是这样的东西会起作用。