Tuesday 30 April 2019

Convert HTML text to PDF stream in D365

In D365, out of the box HTML to PDF converter is not available using X++ code. So we need to use NuGet package "HTMLRenderer.PDFSharp" which is open source. 

  • Create a new console application VS project
  • Right click on the project and select "Manage NuGet package"

  • New NuGet window opens, Search for "HTMLRenderer.PDFSharp" and install it.
  • After installing you can see the installed references in the project
  •  To convert HTML to PDF we required only 3 references
    • HTMLRenderer
    • HTMLRenderer.PDFSharp
    • PDFSharp
  • Copy the .dll's file from the reference path for all the 3 references which is available in the properties
  • Create a new D365 project and add the 3 references .dll's to the D365 project reference as image shown below unser D365 project

Now here is the ready made code for you to convert HTML to PDF and PDF will be as a stream:
     public static System.IO.Stream converttopdffile(str _html)
    {
        PdfSharp.Pdf.PdfDocument pdf =                                                               TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator::GeneratePdf(_html, PdfSharp.PageSize::A4,       10, null, null);
        
        System.IO.Stream stream = new System.IO.MemoryStream();
        pdf.Save(stream, false);
        
        System.IO.StreamWriter writer = new System.IO.StreamWriter(stream);
        
        return stream;
    }

Here your HTML is now converted :)

Thanks,
DAXBuddy

No comments:

Post a Comment