Convert (Export) URL (HTML string) to PDF in ASP.Net MVC

paulrajmca
 
on Mar 26, 2021 12:01 AM
Sample_137691.zip
4837 Views

Hi Developers,

I need Export a PDF Using Existing HTML URL using Asp.Net MVC

Am trying with google, but can’t get exact output

Html File Existing Url : https://fastag.indusind.com/Bankadmin/GenericReport/ProofOfFitmentCopy?Orderid=GI1802202115095210491515970209

If anyone know kindly suggest me to done this task.

Regards,

Paul.S

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Mar 27, 2021 04:06 AM

Hi paulrajmca,

Use Aspose.PDF library to sxport html to pdf.

Check this example. Now please take its reference and correct your code.

use below to install Aspose.PDF from nuget.

Install-Package Aspose.Pdf -Version 21.3.0

Namespaces

using System.IO;
using System.Net;
using Aspose.Pdf;

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Export(string url)
    {
        return File(ConvertUrlToBytes(url), "application/pdf", "Html.pdf");
    }

    private byte[] ConvertUrlToBytes(string url)
    {
        byte[] bytes;
        ServicePointManager.Expect100Continue = true;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        using (Stream stream = WebRequest.Create(url).GetResponse().GetResponseStream())
        {
            HtmlLoadOptions htmloptions = new HtmlLoadOptions(url);
            Document pdfDocument = new Document(stream, htmloptions);
            using (MemoryStream ms = new MemoryStream())
            {
                pdfDocument.Save(ms);
                bytes = ms.ToArray();
            }
        }

        return bytes;
    }
}

View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Export", "Home", FormMethod.Post))
    {
        <input type="text" name="url" />
        <input type="submit" id="btnSubmit" value="Export" />
    }
</body>
</html>

Screenshots

The Form

Exported PDF

For more details on Aspose.PDF refer below link.

HTML to PDF C# Conversion using .NET API