Convert HTML to PDF in .NET

后端 未结 30 1905
不知归路
不知归路 2020-11-22 00:28

I want to generate a PDF by passing HTML contents to a function. I have made use of iTextSharp for this but it does not perform well when it encounters tables and the layout

30条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 00:45

    You can use Google Chrome print-to-pdf feature from its headless mode. I found this to be the simplest yet the most robust method.

    var url = "https://stackoverflow.com/questions/564650/convert-html-to-pdf-in-net";
    var chromePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
    var output = Path.Combine(Environment.CurrentDirectory, "printout.pdf");
    using (var p = new Process())
        {
            p.StartInfo.FileName = chromePath;
            p.StartInfo.Arguments = $"--headless --disable-gpu --print-to-pdf={output} {url}";
            p.Start();
            p.WaitForExit();
        }
    
    

提交回复
热议问题