使用 C# 将 HTML 文档转换为 PDF 文档
2026/04/08
"C:\Program Files\Google\Chrome\Application\chrome.exe" --headless --disable-gpu —run-all-compositor-stages-before-draw --no-margins --printBackground=true --no-pdf-header-footer --print-to-pdf="D:\result.pdf" "https://www.vintasoft.com/index.html"
using System.Diagnostics;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
string chromePath = @"C:\Program Files\Google\Chrome\Application\chrome.exe";
string sourceUrl = "https://www.vintasoft.com/index.html";
string resultPdfFilePath = @"D:\result.pdf";
string chromeArgsTemplate =
"--headless --no-pdf-header-footer --no-margins --disable-gpu --run-all-compositor-stages-before-draw --printBackground=true --print-to-pdf=\"{0}\" {1}";
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = chromePath,
Arguments = string.Format(chromeArgsTemplate, resultPdfFilePath, sourceUrl),
UseShellExecute = false,
CreateNoWindow = false
};
using (Process process = Process.Start(startInfo))
{
process.WaitForExit();
}
Console.WriteLine("HTML page is converted to the PDF document.");
}
}
}
using CefSharp;
using CefSharp.OffScreen;
using System;
using System.Threading.Tasks;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
string sourceUrl = "https://www.vintasoft.com/index.html";
string resultPdfFilePath = @"D:\result.pdf";
Task task = ConvertHtmlToPdfUsingCefSharpOffScreen(sourceUrl, resultPdfFilePath);
task.Wait();
Console.WriteLine("HTML page is converted to the PDF document.");
Console.ReadKey();
}
static async Task ConvertHtmlToPdfUsingCefSharpOffScreen(string url, string pdfPath)
{
// if CEF is not initialized
if (Cef.IsInitialized == null || Cef.IsInitialized == false)
{
// create CEF settings
CefSettings settings = new CefSettings();
// initialize CEF
Cef.Initialize(settings);
}
// create Chromium web browser
using (ChromiumWebBrowser browser = new ChromiumWebBrowser(url))
{
// wait while page will be loaded
await browser.WaitForInitialLoadAsync();
// create PDF print settings
PdfPrintSettings printSettings = new PdfPrintSettings
{
MarginType = CefPdfPrintMarginType.None,
PrintBackground = true,
Landscape = false,
Scale = 1.0,
PreferCssPageSize = true,
DisplayHeaderFooter = false
};
// print web page to a PDF file
await browser.PrintToPdfAsync(pdfPath, printSettings);
}
}
}
}