• Loading embedded resource images into PdfSharp/MigraDoc for non-web projects layers

    Loading embedded resource images into PdfSharp/MigraDoc for non-web projects layers

    There are some cases (for example on Azure) when you can’t really rely on ASP’s Web-layer file resources or “server paths” and file management libraries to access your static resource files. For example if you have a business layer which doesn’t really have a direct access to another layer’s files but you need to generate a PDF using PdfSharp/MigraDoc inside that layer.

    How it can be done is – you need to add an image file to your layer, then right-click on it and go to it’s properties. There you need to set the “Build Action” to Embedded Resource, and the “Copy to Output Directory” to Copy if newer. After that, use these three simple methods to load up the image from the assembly into a Stream, convert it to a byte[] array and then encode it as a base64 string.

    By using the base64 representation of the image, you will be able to embed it into your PDF document.

    Cheers!

  • PdfSharp/MigraDoc to Azure Storage in-memory upload

    PdfSharp/MigraDoc to Azure Storage in-memory upload

    From my (somewhat limited) experience PdfSharp/MigraDoc seems like a pretty fine and powerful library for creating .pdf documents, but it’s documentation – not so much. It’s a bit all over the place and with multiple different NuGet versions/builds and outdated StackOverflow code samples not really helping the situation.

    However, creating a .pdf document in-memory and uploading it straight to Azure is not really that complicated. When might this be useful? For example when you need to generate a report but instead of immediately giving it to the user it just needs to get stored for later access.

    Magic word we’re looking for is MemoryStream. We’ll use two classes – one which will take a MemoryStream and upload it to Azure (AzureProvider.cs), and another one which will create a very simple MigraDoc document (ReportProvider.cs) which you can then build upon and then feed that document to the AzureProvider in the form of MemoryStream.

    The code is pretty straightforward and looks like this:

    Somewhat related – in the next post I’ll explain how to stream a file from Azure Storage private container through .net WebAPI to an AngularJS app.

Back to top