From 31224f02cb3ae2ad2fe23637c02c7f01d5371c41 Mon Sep 17 00:00:00 2001 From: wiz78 Date: Tue, 19 Mar 2019 14:54:11 +0100 Subject: [PATCH] Make it possible to provide custom XMP metadata The PdfMetadata class is now inheritable. PdfDocument has a new delegate that can be used to provide a different implementation of that class that creates custom metadata. e.g.: class XMPMetadata : PdfMetadata { private readonly XmpCore xmp; public XMPMetadata( PdfDocument document, XmpCore xmpCore ) : base( document ) { xmp = xmpCore; SetupStream(); } protected override byte[] GenerateXmp() { return xmp?.SerializeToRDF(); } } --- src/PdfSharp/Pdf/PdfDocument.cs | 12 +++++++++++- src/PdfSharp/Pdf/PdfMetadata.cs | 12 ++++++------ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/PdfSharp/Pdf/PdfDocument.cs b/src/PdfSharp/Pdf/PdfDocument.cs index fe1b9af5..eb801d36 100644 --- a/src/PdfSharp/Pdf/PdfDocument.cs +++ b/src/PdfSharp/Pdf/PdfDocument.cs @@ -491,7 +491,10 @@ internal override void PrepareForSave() // @PDF/UA // Create PdfMetadata now to include the final document information in XMP generation. - Catalog.Elements.SetReference(PdfCatalog.Keys.Metadata, new PdfMetadata(this)); + if( MetadataProvider != null ) + Catalog.Elements.SetReference(PdfCatalog.Keys.Metadata, MetadataProvider(this)); + else + Catalog.Elements.SetReference(PdfCatalog.Keys.Metadata, new PdfMetadata(this)); } /// @@ -808,6 +811,13 @@ internal PdfCatalog Catalog } PdfCatalog _catalog; // never changes if once created + public delegate PdfMetadata PdfMetadataProvider(PdfDocument document); + + /// + /// Gets or sets the delegate that will return the PdfMetadata object to use when saving the document + /// + public PdfMetadataProvider MetadataProvider { get; set; } + /// /// Gets the PdfInternals object of this document, that grants access to some internal structures /// which are not part of the public interface of PdfDocument. diff --git a/src/PdfSharp/Pdf/PdfMetadata.cs b/src/PdfSharp/Pdf/PdfMetadata.cs index 6b4eafa9..29ef55cd 100644 --- a/src/PdfSharp/Pdf/PdfMetadata.cs +++ b/src/PdfSharp/Pdf/PdfMetadata.cs @@ -35,7 +35,7 @@ namespace PdfSharp.Pdf /// /// Represents an XML Metadata stream. /// - public sealed class PdfMetadata : PdfDictionary + public class PdfMetadata : PdfDictionary { /// /// Initializes a new instance of the class. @@ -60,15 +60,15 @@ public PdfMetadata(PdfDocument document) SetupStream(); } - void SetupStream() + protected void SetupStream() { var stream = GenerateXmp(); - byte[] bytes = PdfEncoders.RawEncoding.GetBytes(stream); - CreateStream(bytes); + if(stream != null) + CreateStream(stream); } - string GenerateXmp() + protected virtual byte[] GenerateXmp() { var instanceId = Guid.NewGuid().ToString(); var documentId = Guid.NewGuid().ToString(); @@ -123,7 +123,7 @@ string GenerateXmp() " \n" + "\n"; - return str; + return PdfEncoders.RawEncoding.GetBytes(str); } ///