1

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'.
scapegoat17
  • 5,509
  • 14
  • 55
  • 90

1 Answers1

6

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);
}
  • really smart use of the base class. This is the problem we are solving: https://stackoverflow.com/questions/5240143/invalidcastexception-unable-to-cast-objects-of-type-base-to-type-subclass – Stephanie Sep 28 '21 at 03:01
  • 2
    this is good. doc.Steam will make the document identical. –  Sep 28 '21 at 03:26
  • 1
    Hello and thank you for the answer. This is essentially what i did to resolve my issue. – scapegoat17 Oct 01 '21 at 12:17
  • If we open a Stream, please Dispose() it. `System.IO.Stream : IDisposable` – Stephanie Oct 08 '21 at 06:14