Created
September 30, 2016 13:08
-
-
Save Radzhab/46abc95cdfe4b018ad3c9a8dae7003ca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Codaxy.WkHtmlToPdf; | |
using Nancy; | |
using Nancy.Responses; | |
using System.Diagnostics; | |
using System.Drawing.Printing; | |
namespace HtmlToPrinter | |
{ | |
public class HelloModule : NancyModule | |
{ | |
public HelloModule() | |
{ | |
Get["/{url}/{printer}", runAsync: true] = async (parameters, ct) => | |
{ | |
try | |
{ | |
var fileName = Path.GetRandomFileName() + ".pdf"; | |
PdfDocument doc = new PdfDocument | |
{ | |
Url = parameters.url, | |
HeaderLeft = "[title]", | |
HeaderRight = "[date] [time]", | |
FooterCenter = "Page [page] of [topage]" | |
}; | |
PdfOutput pdf = new PdfOutput | |
{ | |
// OutputFilePath = "wkhtmltopdf-page.pdf" | |
OutputFilePath = fileName | |
}; | |
PdfConvert.ConvertHtmlToPdf(doc, pdf); | |
SendToPrinter(fileName, parameters.printer); | |
// File.Delete(fileName); | |
return "OK"; | |
} | |
catch | |
{ | |
return "Error"; | |
} | |
}; | |
} | |
private void SendToPrinter(string fileName, string printer) | |
{ | |
Process proc = new Process(); | |
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; | |
proc.StartInfo.Verb = "print"; | |
proc.StartInfo.FileName = @"SumatraPDF.exe"; | |
proc.StartInfo.Arguments = string.Format(@"-print-to {0} -silent {1}", "\"" + printer + "\"", "\"" + fileName + "\""); | |
proc.StartInfo.UseShellExecute = false; | |
proc.StartInfo.CreateNoWindow = true; | |
proc.Start(); | |
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; | |
if (proc.HasExited == false) | |
{ | |
proc.WaitForExit(10000); | |
} | |
proc.EnableRaisingEvents = true; | |
proc.CloseMainWindow(); | |
proc.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment