【问题标题】:PdfSharp, Updating Metadata in C# ErrorPdfSharp,在 C# 错误中更新元数据
【发布时间】:2016-03-28 09:47:43
【问题描述】:

我正在使用PdfSharp 参考库来尝试向我的程序添加添加元数据标签的功能。我能够成功地将元数据标签添加到文档中,但是在更新现有自定义属性上的标签时遇到了问题。每当我尝试使用我的方法更新自定义属性时,都会收到以下异常:

“'System.Collections.Generic.KeyValuePair' 不包含 'Name' 的定义。”

你们能否告诉我,我是否正在编写下面 foreach 循环中的 if 语句,以正确循环 PDF 文档中的所有自定义元素,以查看它是否存在并需要更新?谢谢。

public void AddMetaDataPDF(string property, string propertyValue, string    
                                                                   path)
{
    PdfDocument document = PdfReader.Open(path);
    bool propertyFound = false;

    try {
           dynamic properties = document.Info.Elements;
           foreach(dynamic p in properties)
           {
               //Check to see if the property exists. If it does, update   
                   value.
               if(string.Equals(p.Name, property,  
                StringComparison.InvariantCultureIgnoreCase))
               {
                   document.Info.Elements.SetValue("/" + property, new   
                           PdfString(propertyValue));
               }
           }
           // the property doesn't exist so add it
           if(!propertyFound)
           {
               document.Info.Elements.Add(new KeyValuePair<String, PdfItem>   
                   ("/"+ property, new PdfString(propertyValue)));
           }
      }

      catch (Exception ex)
      {
          MessageBox.Show(path + "\n" + ex.Message);
          document.Close();

      }
      finally
      {
          if(document != null)
          {
              document.Save(path);
              document.Close();
          }
      }
}

【问题讨论】:

    标签: c# metadata pdfsharp


    【解决方案1】:

    我没有尝试您的代码,但使用此库时的一个常见问题是您需要在属性名称之前添加一个斜杠才能找到它。下面的代码会成功的。

    PdfDocument document = PdfReader.Open(path);
    var properties = document.Info.Elements;
    if (properties.ContainsKey("/" + propertyName))
    {
        properties.SetValue("/" + propertyName, new PdfString(propertyValue));
    }
    else
    {
        properties.Add(new KeyValuePair<String, PdfItem>("/" + propertyName, new PdfString(propertyValue)));
    }
    document.Save(path);
    document.Close();
    

    PDF 文件也不应该被写保护。否则,您需要在调用 PdfSharp 之前使用解锁文件的工具。

    【讨论】:

    • 非常感谢先生。那行得通。你们在这个论坛上很棒而且乐于助人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多