Charles
Charles

Reputation: 3774

Server side printing

I've been working on a way to submit a print job from my web server.
What I want to do is render an action to pdf then submit the pdf to the default printer on the server.

The code here almost works

    public JsonResult Print(String JobName, String TargetAction, String TargetController)
    {
        var job = LocalPrintServer.GetDefaultPrintQueue().AddJob(JobName);
        var printStream = job.JobStream;
        try
        {
            var pdfResult = new UrlAsPdf(Url.Action(TargetAction, TargetController, ControllerContext.RouteData));
            var binary = pdfResult.BuildPdf(this.ControllerContext);


            printStream.Write(binary, 0, binary.Length);
            printStream.Close();
        }
        catch (Exception e)
        {
            return Json(new { Success = false, Message = e.Message });
        }
        return Json(new { Success = true });
    }

But as soon as .Close is called the job is deleted from the printer's queue. I am using Rotativa to generating the pdf.

It seems right according to the example located here http://msdn.microsoft.com/en-us/library/ms552913.aspx But I suspect there is a problem with data being deleted before the printer spooling is done.

Anyone have a suggestion or perhaps a working solution?

Upvotes: 0

Views: 2510

Answers (1)

Simon MᶜKenzie
Simon MᶜKenzie

Reputation: 8664

Your stream appears to be a PDF, but the spec in your link indicates that you need to be writing device-specific data to job.JobStream (EMF or XPS).

To convert to XPS, have a look at this Stack Overflow post.

Alternatively, this post suggests that the easiest way to print is via the shell with the "print" verb, e.g.:

ProcessStartInfo psi = new ProcessStartInfo("pdfFile.pdf") {Verb = "Print"};
Process.Start(psi);

Note that the Acrobat Reader can also print files from the commandline.

Upvotes: 1

Related Questions