I am using the below code to print an image from my C# code. Can some body tell me how to pass the filePath as an argument when i assign my event handler ?
public static bool PrintImage(string filePath)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(printPage);
pd.Print();
return true;
}
private static void printPage(object o, PrintPageEventArgs e)
{
//i want to receive the file path as a paramter here.
Image i = Image.FromFile("C:\\Zapotec.bmp");
Point p = new Point(100, 100);
e.Graphics.DrawImage(i, p);
}
The simplest way is to use a lambda expression:
PrintDocument pd = new PrintDocument();
pd.PrintPage += (sender, args) => DrawImage(filePath, args.Graphics);
pd.Print();
...
private static void DrawImage(string filePath, Graphics graphics)
{
...
}
Or if you've not got a lot to do, you could even inline the whole thing:
PrintDocument pd = new PrintDocument();
pd.PrintPage += (sender, args) =>
{
Image i = Image.FromFile(filePath);
Point p = new Point(100, 100);
args.Graphics.DrawImage(i, p);
};
pd.Print();
The easiest way to do this is use an anonymous function as the event handler. This will allow you to pass the filePath
directly
public static bool PrintImage(string filePath) {
PrintDocument pd = new PrintDocument();
pd.PrintPage += delegate (sender, e) { printPage(filePath, e); };
pd.Print();
return true;
}
private static void printPage(string filePath, PrintPageEventArgs e) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With