Skip to content

Instantly share code, notes, and snippets.

@Radzhab
Created September 30, 2016 13:08
Show Gist options
  • Save Radzhab/46abc95cdfe4b018ad3c9a8dae7003ca to your computer and use it in GitHub Desktop.
Save Radzhab/46abc95cdfe4b018ad3c9a8dae7003ca to your computer and use it in GitHub Desktop.
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