c#html转pdf
时间: 2023-11-24 09:50:06 浏览: 105
Pechkin是一个开源的C#组件,它使用wkhtmltopdf将HTML转换为PDF。你可以使用Pechkin来将HTML字符串或URL转换为PDF文件。下面是一个使用Pechkin将HTML转换为PDF的示例代码:
```csharp
SynchronizedPechkin sc = new SynchronizedPechkin(new GlobalConfig()
.SetMargins(new Margins() { Left = 50, Right = 50, Top = 50, Bottom = 50 }) //设置边距
.SetPaperOrientation(false) //设置纸张方向为横向
.SetPaperSize(ConvertToHundredthsInch(210), ConvertToHundredthsInch(297)) //设置纸张大小210mm * 297mm
);
byte[] buf = sc.Convert(new ObjectConfig(), html);
if (buf == null) {
MessageBox.Show("Error converting!");
}
try {
string fn = "D:\XXX.pdf";
FileStream fs = new FileStream(fn, FileMode.Create);
fs.Write(buf, 0, buf.Length);
fs.Close();
Process myProcess = new Process();
myProcess.StartInfo.FileName = fn;
myProcess.Start();
} catch (Exception ex) {
MessageBox.Show($"PDF {ex.Message}");
}
```
这段代码使用SynchronizedPechkin类将HTML字符串转换为PDF文件。在这个示例中,PDF文件将被保存在D:\XXX.pdf中,并且在转换完成后会自动打开。