我想使用文件对话框选择一个文件,然后使用PrintDocument.Print方法打印所选文件。

以下是一些代码,它们是我要完成的工作的部分实现:

     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)
        {


此时,我要打印选定的文件。

            pd_doc.Print();
        }
    }


我上面的代码显然不能满足我的需求。哪种替代方法可以引导我朝正确的方向发展?

最佳答案

您可以使用以下代码段解决该问题。

       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);
        }

关于c# - 如何打印用户选择的文档?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19686123/

10-11 22:40
查看更多