c# - 如何打印用户选择的文档?

标签 c# .net winforms c#-4.0

我想使用文件对话框选择一个文件,然后使用 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/

相关文章:

.net - 性能是拥有单例或静态类的充分理由吗?

c# - 如何在窗体中制作圆形标签?

c# - Web API 过滤器未捕获方法组引发的异常

c# - 如何在不违反 MVVM 的情况下将项目附加到 ListBox

c# - WPF RibbonWindow + Ribbon = 屏幕外的标题?

c# - 代码中的表格布局被认为是错误的原因是什么?

c# - 等于 NHibernate 实体的实现,unproxy 问题

c# - 通过代码创建和显示标签

c# - 将按钮添加到 DataGridView

c# - KeyNotFoundException : The given key was not present in the dictionary C#