【发布时间】:2014-08-07 09:31:19
【问题描述】:
我开发了一个 Intranet 网站。 我想使用 wkhtmltopdf 从我的网站页面生成 pdf。经过一番研究,我发现了 wkhtmltopdf。该应用程序运行良好。但我是 C# 的新手,即使我读过 Calling wkhtmltopdf to generate PDF from HTML 我也无法使用这段代码。
编辑
这是代码,我在 p.Start() 处似乎有一个错误(目录名称无效); :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Web;
using System.Web.Hosting;
using System.Diagnostics;
using System.IO;
public partial class _zipdownload : System.Web.UI.Page {
protected void DoDownload(object sender, EventArgs e)
{
var url = "http://dlp-wdi/TR/view_I.asp?ID=11080";
var file = WKHtmlToPdf(url);
if (file != null)
{
Response.ContentType = "Application/pdf";
Response.BinaryWrite(file);
Response.End();
}
}
public byte[] WKHtmlToPdf(string url)
{
var fileName = " - ";
var wkhtmlDir = "bin\\wkhtmltopdf\\";
var wkhtml = "bin\\wkhtmltopdf\\wkhtmltopdf.exe";
var p = new Process();
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;
}
}
感谢您的帮助。
【问题讨论】:
-
告诉我们,出了什么问题。有任何错误信息吗?
-
我正在我的 IIS 中测试这段代码,我在有 private void DoDownload() 的那一行有一个“CS1518:预期的类、委托、枚举、接口或结构”
-
这些只是方法。你必须把它们放到一个类中。所以在它周围添加类似“class MyClass { // yourcode here }”之类的东西
-
我真傻!谢谢奥莱阿尔伯斯!我可以问你一个新问题吗?经过一些更正后,我的按钮终于可见,但我有另一个错误:System.ComponentModel.Win32Exception:此行的目录名称无效:p.Start();
-
您输入一个相对路径。你确定它存在于程序执行的地方吗? (通常,当 C# 程序运行时,您位于“bin\Debug”目录中。尝试使用绝对路径。如果这没有帮助:Ask a new question here in SO
标签: c# pdf wkhtmltopdf