How to convert and download html(url) to pdf without third part control using C#?
Loading
How to convert and download html(url) to pdf without third part control using C#?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jayraj ChhayaRank #304 · 8.2K reputationPosted Sep 20, 2024, 2:50 AM EDT
To convert HTML from a URL to a PDF in C# without using third-party controls, you can utilize the built-in capabilities of the .NET framework along with the
System.NetandSystem.IOnamespaces. Below is a simple approach using theWebClientclass to fetch the HTML content and thePdfSharplibrary, which is included in .NET Core.using System; using System.IO; using System.Net; using PdfSharp.Pdf; using PdfSharp.Drawing; class Program { static void Main() { string url = "http://example.com"; string htmlContent = GetHtml(url); ConvertHtmlToPdf(htmlContent, "output.pdf"); } static string GetHtml(string url) { using (WebClient client = new WebClient()) { return client.DownloadString(url); } } static void ConvertHtmlToPdf(string html, string outputPath) { PdfDocument document = new PdfDocument(); document.Info.Title = "Converted PDF"; PdfPage page = document.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page); XFont font = new XFont("Verdana", 20, XFontStyle.Bold); gfx.DrawString(html, font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.TopLeft); document.Save(outputPath); } }Jignesh KumarRank #91 · 22.9K reputationPosted Sep 20, 2024, 4:41 AM EDT
Hello,
You can do using below code,
using System; using System.IO; using System.Net; class Program { static void Main(string[] args) { string url = "http://example.com"; // Replace with your URL string tempHtmlFile = Path.Combine(Path.GetTempPath(), "temp.html"); string pdfFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "output.pdf"); using (WebClient webClient = new WebClient()) { webClient.DownloadFile(url, tempHtmlFile); } string wkhtmltopdfPath = @"C:\path\to\wkhtmltopdf.exe"; System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo() { FileName = wkhtmltopdfPath, Arguments = $"\"{tempHtmlFile}\" \"{pdfFilePath}\"", UseShellExecute = false, CreateNoWindow = true, }; using (var process = System.Diagnostics.Process.Start(startInfo)) { process.WaitForExit(); } File.Delete(tempHtmlFile); Console.WriteLine("PDF created at: " + pdfFilePath); } }