1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > html转换为pdf c# wkhtmltopdf - 直接在C#中将html代码转换为pdf

html转换为pdf c# wkhtmltopdf - 直接在C#中将html代码转换为pdf

时间:2020-04-12 03:39:08

相关推荐

html转换为pdf c# wkhtmltopdf  - 直接在C#中将html代码转换为pdf

我找到了一个方法。

您可以设置另一个输出正常的html。

并使用该url作为wkhtml2pdf进程的输入值。

- - - - - 编辑

public byte[] WKHtmlToPdf(string url_input)

{

try

{

var fileName = " - ";

var wkhtmlDir = ConfigurationSettings.AppSettings["wkhtmlDir"];

var wkhtml = ConfigurationSettings.AppSettings["wkhtml"];

var p = new Process();

string url = Request.Url.GetLeftPart(UriPartial.Authority) + @"/application/" + url_input;

p.StartInfo.CreateNoWindow = true;

p.StartInfo.RedirectStandardOutput = true;

p.StartInfo.RedirectStandardError = true;

p.StartInfo.RedirectStandardInput = true;

p.StartInfo.UseShellExecute = false;

p.StartInfo.FileName = wkhtml;

p.StartInfo.WorkingDirectory = wkhtmlDir;

string switches = "";

switches += "--print-media-type ";

switches += "--margin-top 10mm --margin-bottom 10mm --margin-right 10mm --margin-left 10mm ";

switches += "--page-size Letter ";

p.StartInfo.Arguments = switches + " " + url + " " + fileName;

p.Start();

//read output

byte[] buffer = new byte[32768];

byte[] file;

using (var ms = new MemoryStream())

{

while (true)

{

int read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);

if (read <= 0)

{

break;

}

ms.Write(buffer, 0, read);

}

file = ms.ToArray();

}

// wait or exit

p.WaitForExit(60000);

// read the exit code, close process

int returnCode = p.ExitCode;

p.Close();

return returnCode == 0 ? file : null;

}

catch (Exception ex)

{

// set your exceptions here

return null;

}

}

---------- web.config关键示例

基本思想是将url作为参数传递给exe。

HTH!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。