Skip to content

Instantly share code, notes, and snippets.

@kapraran
Created June 27, 2019 01:10
Show Gist options
  • Save kapraran/86750aa5d698c536d1728d97a388eb19 to your computer and use it in GitHub Desktop.
Save kapraran/86750aa5d698c536d1728d97a388eb19 to your computer and use it in GitHub Desktop.
a printer util for windows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Printing;
using System.Drawing;
namespace ConsoleApp1
{
class Program
{
private static int printerIndex;
private static bool isLandscape;
private static System.Drawing.Image img;
static void Main(string[] args)
{
// Check for arguments
if (args.Count() < 1)
{
System.Environment.Exit(1);
}
string mode = args[0];
var printers = System.Drawing.Printing.PrinterSettings.InstalledPrinters;
// List available printers
if (mode.Equals("list"))
{
ListPrinters();
}
// Print selected image using selected printer
else if (mode.Equals("print"))
{
printerIndex = GetIndexOpt(args, printers.Count - 1);
isLandscape = HasOption("-l", args) > -1;
string imgPath;
try
{
imgPath = args[1];
img = System.Drawing.Image.FromFile(imgPath);
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("File not found");
Environment.Exit(0);
}
catch (Exception)
{
Console.WriteLine("Unknown error");
Environment.Exit(0);
}
PrintDocument pd = new PrintDocument();
pd.PrinterSettings.PrinterName = printers[printerIndex];
pd.PrintPage += PrintPage;
pd.DefaultPageSettings.Landscape = isLandscape;
pd.Print();
Console.WriteLine("OK");
}
}
private static void PrintPage(object sender, PrintPageEventArgs e)
{
Rectangle m = e.MarginBounds;
if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
}
e.Graphics.DrawImage(img, m);
img.Dispose();
}
private static void ListPrinters()
{
foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
Console.WriteLine(printer);
}
}
private static int GetIndexOpt(string[] args, int maxIndex, int defIndex = 0)
{
int optIndex = HasOption("-i", args);
if (optIndex < 0)
{
return defIndex;
}
else if (optIndex + 1 < args.Count())
{
try
{
return Math.Max(0, Math.Min(Int32.Parse(args[optIndex + 1]), maxIndex));
}
catch
{
return defIndex;
}
}
return defIndex;
}
static int HasOption(string opt, string[] args)
{
for (int i = 0; i < args.Count(); i++)
{
if (args[i].Trim().Equals(opt))
{
return i;
}
}
return -1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment