2016-03-28 30 views
2

PdfSharp参照ライブラリを使用して、メタデータタグを追加する機能をプログラムに追加しようとしています。ドキュメントにメタデータタグを追加することはできますが、既存のカスタムプロパティのタグを更新する際に問題があります。私のメソッドを使用してカスタムプロパティを更新しようとすると、次の例外が発生します。PdfSharp、C#でのメタデータの更新

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

答えて

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を呼び出す前にファイルのロックを解除するためのツールを使用する必要があります。

+0

ありがとうございます。それはうまくいった。皆さんはこのフォーラムですごく役立ちます。 – Dwayne

関連する問題