Reputation: 455
I want to select a file using a file dialog and then print the selected file using the PrintDocument.Print
method.
Below is some code which is a partial implementation of what I am trying to accomplish:
using System;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
namespace InstalledAndDefaultPrinters
{
class Program
{
static void Main(string[] args)
{
string filename="";
foreach (string printer in PrinterSettings.InstalledPrinters)
Console.WriteLine(printer);
var printerSettings = new PrinterSettings();
Console.WriteLine(string.Format("The default printer is: {0}", printerSettings.PrinterName));
Console.WriteLine(printerSettings.PrintFileName);
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Open File Dialog";
fdlg.InitialDirectory = @"C:\ ";
fdlg.RestoreDirectory = true;
fdlg.ShowDialog();
Console.WriteLine(fdlg.Title);
if (fdlg.ShowDialog() == DialogResult.OK)
{
filename = String.Copy(fdlg.FileName);
}
Console.WriteLine(filename);
PrintDialog printdg = new PrintDialog();
PrintDocument pd_doc = new PrintDocument();
printdg.ShowDialog();
if (printdg.ShowDialog() == DialogResult.OK)
{
It is at this point that I would like to print the selected file.
pd_doc.Print();
}
}
The code I have above clearly does not do what I need. What alternative approach might steer me in the right direction?
Upvotes: 2
Views: 1389
Reputation: 5812
You can solve that using following code snippet.It works as you want.
private void button1_Click(object sender, EventArgs e)
{
PrintDialog printdg = new PrintDialog();
if (printdg.ShowDialog() == DialogResult.OK)
{
PrintDocument pd = new PrintDocument();
pd.PrinterSettings = printdg.PrinterSettings;
pd.PrintPage += PrintPage;
pd.Print();
pd.Dispose();
}
}
private void PrintPage(object o, PrintPageEventArgs e)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\Users\therath\Desktop\372\a.jpg");
// You can replace your logic @ here to load the image or whatever you want
Point loc = new Point(100, 100);
e.Graphics.DrawImage(img, loc);
}
Upvotes: 4