BeerBaron BeerBaron -4 years ago 185
C# Question

Read custom property value from XMP with itextsharp 5.5.9

I'm having difficulties in reading a specific custom property from the XMP section of a PDF file, using itextsharp v. 5.5.9.

When I try to use the XmpReader class, it gets marked as obsolete, and it does not contain any public method that seems to be useful for reading purposes.

I can convert the Metadata section to an XML, and then parse it in some way (a workaround consists in using XmpCore library that has convenient methods for reading properties by name) but I'm sure I'm missing something...

I think it should be possible to just access some properties with just one library.

PdfReader reader = new PdfReader(inFile);
PdfStamper stamper = new PdfStamper(reader, new FileStream(outFile, FileMode.Create));
MemoryStream ms = null;

if (reader.Metadata != null)
ms = new MemoryStream(reader.Metadata);
ms = new MemoryStream();

XmpWriter xw = new XmpWriter(ms);

xw.XmpMeta.GetPropertyString(XmpConst.NS_DC, "MyProperty"); // -> not found, but it's ok for the first time...
xw.SetProperty(XmpConst.NS_DC, "MyProperty", "MyValue"); // -> OK
xw.XmpMeta.GetPropertyString(XmpConst.NS_DC, "MyProperty"); // -> OK

stamper.XmpMetadata = ms.ToArray();

If I run the program on the same file twice (so the property is saved in the file) the property is still not found..

How can I read the presence and value of MyProperty?

Answer Source

I ended up with this solution.

It requires XmpCore library, but it's easy and fast to implement, avoiding the explicit management of many details, such as encodings:

string result = null;
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(inFile);
if (reader.Metadata != null)
    XmpCore.IXmpMeta meta = XmpCore.XmpMetaFactory.ParseFromBuffer(reader.Metadata);
    result = meta.GetPropertyString(XmpConst.NS_DC, "MyProperty");
return result;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download