当前位置: 首页 > 编程语言 > C#

如何使用wkhtmltopdf将html作为字符串传递?Share

时间:2023-04-10 20:00:22 C#

如何使用wkhtmltopdf将html作为字符串传递?如何使用asp.net、c#在wltmltopdf中将wtml作为字符串而不是url传递?STDIn和STDOut在此示例中已被重定向,因此您根本不需要该文件。publicstaticclassPrinter{publicconststringHtmlToPdfExePath="wkhtmltopdf.exe";publicstaticboolGeneratePdf(stringcommandLocation,StreamReaderhtml,Streampdf,SizepageSize){Processp;StreamWriter标准输入;ProcessStartInfopsi=newProcessStartInfo();psi.FileName=Path.Combine(commandLocation,HtmlToPdfExePath);psi.WorkingDirectory=Path.GetDirectoryName(psi.FileName);//运行转换工具psi.UseShellExecute=false;psi.CreateNoWindow=true;psi.RedirectStandardInput=true;psi.RedirectStandardOutput=true;psi.RedirectStandardError=true;//注意:我们告诉wkhtmltopdf安静并且不运行脚本psi.Arguments="-q-n--disable-smart-shrinking"+(pageSize.IsEmpty?"":"--page-width"+pageSize.Width+"mm--page-height"+pageSize.Height+"mm")+"--";p=Process.Start(psi);尝试{stdin=p.StandardInput;stdin.AutoFlush=true;stdin.Write(html.ReadToEnd());标准输入.Dispose();CopyStream(p.StandardOutput.BaseStream,pdf);p.StandardOutput.Close();pdf.位置=0;p.WaitForExit(10000);返回真;}赶上{返回假;}最后{p.Dispose();}}publicstaticvoidCopyStream(Streaminput,Streamoutput){byte[]buffer=newbyte[32768];诠释阅读;while((read=input.Read(buffer,0,buffer.Length))>0){output.Write(buffer,0,read);}}}重定向STDIN可能是完成你想要做的事情的最简单方法使用wkhtmltopdf(在ASP.Net中)重定向STDIN的一种方法如下:privatevoidWritePDF(stringHTML){stringinFileName,outFileName,tempPath;进程p;System.IO.StreamWriter标准输入;ProcessStartInfopsi=newProcessStartInfo();tempPath=Request.PhysicalApplicationPath+"temp\";inFileName=Session.SessionID+".htm";outFileName=Session.SessionID+".pdf";//运行转换工具psi.UseShellExecute=false;psi.FileName="c:\ProgramFiles(x86)\wkhtmltopdf\wkhtmltopdf.exe";psi.CreateNoWindow=true;psi.RedirectStandardInput=true;psi.RedirectStandardOutput=true;psi.RedirectStandardError=true;//注意我们告诉wkhtmltopdf安静并且不运行脚本//注意:我想不出一种方法来重定向stdin和stdout所以我们必须写入一个文件然后清理psi.Arguments="-q-n-"+tempPath+outFileName;p=Process.Start(psi);尝试{stdin=p.StandardInput;stdin.AutoFlush=true;标准输入。写入(HTML);秒tdin.关闭();if(p.WaitForExit(15000)){//注意:当我们使用WriteFile时应用程序挂起(由于下面的删除?);这有效Response.BinaryWrite(System.IO.File.ReadAllBytes(tempPath+outFileName));//Response.WriteFile(tempPath+outFileName);}}最后{p.Close();p.Dispose();}//删除pdfSystem.IO.File.Delete(tempPath+outFileName);请注意,上面的代码假定您的应用程序目录中有一个临时目录。此外,您必须为运行IIS进程的用户帐户显式启用对此目录的写访问权限。我知道这是一篇较旧的帖子,但我希望未来的开发人员有这个选项。我有同样的需求,必须启动后台进程才能在Web应用程序中获取PDF的想法非常糟糕。这是另一个选项:https://github.com/TimothyKhouri/WkHtmlToXDotNet它是围绕wkhtmltopdf的.NET本机包装器。示例代码:varpdfData=HtmlToXConverter.ConvertToPdf("COOOL!");请注意,它现在不是线程安全的——我正在研究它。因此,只需使用监视器或其他东西或锁即可。以上就是C#学习教程:Howtousewkhtmltopdftopasshtmlasastring?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: