在.NET应用程序上使用Phantom JS生成PDF

Bal*_*ash 8 asp.net asp.net-mvc phantomjs

我一直在研究phantomJS,看起来它可能是一个使用生成PDF的好工具.我想知道是否有人成功地将它用于他们的.NET应用程序.

我的具体问题是:如何在服务器上使用rasterize.js等模块,接收请求并将生成的pdf作为响应发回.

我的一般问题是:在.NET应用程序中使用phantomJS是否有任何最佳实践.实现它的最佳方法是什么?

我在.NET World中相当新,我希望得到更详细的答案.感谢大家.:)

Fel*_*sso 13

我不知道最佳实践,但是,我正在使用phantomJS,以下代码没有问题.

public ActionResult DownloadStatement(int id)
{
    string serverPath = HttpContext.Server.MapPath("~/Phantomjs/");
    string filename = DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".pdf";

    new Thread(new ParameterizedThreadStart(x =>
    {
        ExecuteCommand("cd " + serverPath + @" & phantomjs rasterize.js http://localhost:8080/filetopdf/" + id.ToString() + " " + filename + @" ""A4""");
    })).Start();

    var filePath = Path.Combine(HttpContext.Server.MapPath("~/Phantomjs/"), filename);

    var stream = new MemoryStream();
    byte[] bytes = DoWhile(filePath);

    return File(bytes, "application/pdf", filename);
}

private void ExecuteCommand(string Command)
{
    try
    {
        ProcessStartInfo ProcessInfo;
        Process Process;

        ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
        ProcessInfo.CreateNoWindow = true;
        ProcessInfo.UseShellExecute = false;

        Process = Process.Start(ProcessInfo);
    }
    catch { }
}

public ViewResult FileToPDF(int id)
{
    var viewModel = file.Get(id);
    return View(viewModel);
}

private byte[] DoWhile(string filePath)
{
    byte[] bytes = new byte[0];
    bool fail = true;

    while (fail)
    {
        try
        {
            using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                bytes = new byte[file.Length];
                file.Read(bytes, 0, (int)file.Length);
            }

            fail = false;
        }
        catch
        {
            Thread.Sleep(1000);
        }
    }

    System.IO.File.Delete(filePath);
    return bytes;
}
Run Code Online (Sandbox Code Playgroud)

这是行动流程:

用户点击指向的链接DownloadStatement Action.在那里,Thread创建一个new 来调用该ExecuteCommand方法.

ExecuteCommand方法负责调用phantomJS.作为参数传递的字符串执行以下操作.

转到phantomJS应用程序所在的位置,然后rasterize.js使用URL,要创建的文件名和打印格式进行调用.(更多关于栅格化的信息).

就我而言,我真正想要打印的是actionfiletoupload 提供的内容.这是一个简单的动作,返回一个简单的视图.PhantomJS将调用作为参数传递的URL并完成所有魔法.

虽然phantomJS仍在创建文件,但(我猜)我无法返回客户端发出的请求.这就是我使用这种DoWhile方法的原因.它将保留请求,直到文件由phantomJS创建并由应用程序加载到请求.

  • 您可以使用Process.WaitForExit而不是do while循环.http://msdn.microsoft.com/en-us/library/fb4aw7b8(v=vs.110).aspx (4认同)