Convert HTML to PDF file in Mac using C#

13 Jan 20232 minutes to read

The Syncfusion HTML to PDF converter is a .NET library for converting webpages, SVG, MHTML, and HTML to PDF using C#. It is reliable and accurate. Using this library, you can convert HTML to PDF document in Mac.

Steps to convert HTML to PDF in ASP.NET Core MVC

Step 1: Create a new C# ASP.NET Core Web Application project.
Mac_step1
Step 2: Select the Target Framework of your project.
Mac_step2

Step 3: Configure your application and click Create.
Mac_step3

Step 4: Install the Syncfusion.HtmlToPdfConverter.Net.Mac NuGet package as reference to your .NET Standard applications from NuGet.org.
Mac_step4

Step 5: A default controller with name HomeController.cs gets added on creation of ASP.NET MVC project. Include the following namespaces in that HomeController.cs file.

  • C#
  • using Syncfusion.Pdf;
    using Syncfusion.HtmlConverter;
    using System.IO;
    using Microsoft.AspNetCore.Hosting;

    Step 6: A default action method named Index will be present in HomeController.cs. Right click on Index method and select Go To View where you will be directed to its associated view page Index.cshtml. Add a new button in the Index.cshtml as shown below.

  • C#
  • @{Html.BeginForm("ExportToPDF", "Home", FormMethod.Post);
        {
            <div>
                <input type="submit" value="Convert PDF" style="width:150px;height:27px" />
            </div>
         }
            Html.EndForm();
     }

    Step 7: Add a new action method ExportToPDF in HomeController.cs and include the below code example to convert HTML to PDF file using Convert method in HtmlToPdfConverter class.

  • C#
  • public IActionResult ExportToPDF()
    {
        //Initialize HTML to PDF converter.
        HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();
        //Convert URL to PDF.
        PdfDocument document = htmlConverter.Convert("https://www.syncfusion.com");
        MemoryStream stream = new MemoryStream();
        document.Save(stream);
        //Download the PDF document in the browser
        return File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf, "HTML-to-PDF.pdf");
    }

    Step 8: Right click the project and select Build.
    Mac_step5

    NOTE

    Once the build succeeded, unzip the chromium.app file in bin folder (bin -> Debug ->net6.0 -> BlinkBinariesMac -> Chromium.app)`

    Step 9: Run the application.
    Mac_step6

    By executing the program, you will get the PDF document as follows.
    HTMLtoPDF

    A complete working sample can be downloaded from Github.