I am having an issue wrapping my head around how to properly wrap a PDF library I am using called IronPDF
.
IronPDF
has a PdfDocument
object.
My thought was to create a IronPdfDocument
object that looks like this:
public class IronPdfDocument : PdfDocument, IPdfDocument
{
public IronPdfDocument(string filePath) : base(filePath) { }
public IronPdfDocument(Stream stream) : base(stream) { }
public IronPdfDocument(byte[] data) : base(data) { }
public Stream GetSTream() => base.Stream;
}
IronPDF
also has a Rendering object that is called HtmlToPdf
and my thougth was to create an IronPdfRenderer
that looks like this:
public class IronPdfRenderer : HtmlToPdf, IPdfRenderer
{
public IronPdfRenderer() : base() { }
public IPdfDocument RenderHtmlAsPdf(string html)
=> (IronPdfDocument)base.RenderHtmlAsPdf(html);
}
Then utilizing the interface objects in code like so:
public IPdfDocument Execute()
{
IPdfRenderer renderer = new IronPdfRenderer();
return renderer.RenderHtmlAsPdf(myHtmlString);
}
However, I am getting an error in my IronPdfRenderer
object when calling RenderHtmlAsPdf
trying to convert IronPDF
's PdfDocument
to my wrapped object of IronPdfDocument
.
I understand that at face value a PdfDocument
may not be able to be casted to my IronPdfDocument
, but I would like to create a more generic structure in my code that would help future proof my business logic as different Pdf Libraries can come and go. I was wondering if anyone could provide any help/insight into what I am doing wrong here?
Here is the error for anyone interested:
Unable to cast object of type 'IronPdf.PdfDocument' to type 'MyNamespace.Merge.IronPdfDocument'.
CodePudding user response:
you can't cast to IronPdfDocument directly because it's not implemented the same interface that PdfDocument implements, as a workaround, you can create a new object and pass the resulted stream to the constructor to create a new object and return it as following
public IPdfDocument RenderHtmlAsPdf(string html)
{
var doc= base.RenderHtmlAsPdf(html);
return new IronPdfDocument(doc.Stream);
}