I do not know about best practices, but I use phantomJS without problems with the following code.
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; }
Here is the flow of action:
The user clicks a link to the DownloadStatement Action . Inside, a new Thread is created to call the ExecuteCommand method.
The ExecuteCommand method ExecuteCommand responsible for calling phantomJS. The string passed as an argument does the following.
Go to the place where the phantomJS application is located, and then call rasterize.js with the URL created by the file name and print format. ( Read more about rasterization here ).
In my case, what I really want to print is the content provided by the action filetoupload file. This is a simple action that returns a simple look. PhantomJS will call the URL passed as a parameter and do all the magic.
While phantomJS is still creating the file (I think), I cannot return the request made by the client. This is why I used the DoWhile method. It will keep the request until the file is created by phantomJS and loaded by the application into the request.
Felipe miosso
source share