简体   繁体   English

通过在C#中使用PrintDialog打印文件(PDf)

[英]Print a file(PDf) by using PrintDialog in C#

Hello everybody this is my code that I try get a file with Open File Dialog And print the file But its printing an Empty page :( :( 大家好,这是我的代码,我尝试使用“打开文件”对话框获取文件并打印文件,但打印出一个空页面:( :(

please help me :) 请帮我 :)

   private void tsmprint_Click(object sender, EventArgs e)
    {
        try
        {
            if (openFileDialog1.ShowDialog()==DialogResult.OK)
            {
                PrintDocument Pd = new PrintDocument();

                Pd.DocumentName = openFileDialog1.FileName;

                 printDialog1.Document = Pd;
                if (printDialog1.ShowDialog()==DialogResult.OK)
                {
                    Pd.Print();
                }

            }
        }
        catch (Exception)
        {

        }
    }

The easiest way is to use external library, with the following msdn example you can print the PDF files with the default printer or any other network connected printer as well as select the pages you want to print: 最简单的方法是使用外部库,在下面的msdn 示例中,您可以使用默认打印机或任何其他网络连接的打印机打印PDF文件,还可以选择要打印的页面:

        PdfDocument doc = new PdfDocument(); 
        doc.LoadFromFile(FilePathandFileName); 

        //Use the default printer to print all the pages 
        //doc.PrintDocument.Print(); 

        //Set the printer and select the pages you want to print 

        PrintDialog dialogPrint = new PrintDialog(); 
        dialogPrint.AllowPrintToFile = true; 
        dialogPrint.AllowSomePages = true; 
        dialogPrint.PrinterSettings.MinimumPage = 1; 
        dialogPrint.PrinterSettings.MaximumPage = doc.Pages.Count; 
        dialogPrint.PrinterSettings.FromPage = 1; 
        dialogPrint.PrinterSettings.ToPage = doc.Pages.Count; 

        if (dialogPrint.ShowDialog() == DialogResult.OK) 
        { 
            //Set the pagenumber which you choose as the start page to print 
            doc.PrintFromPage = dialogPrint.PrinterSettings.FromPage; 
            //Set the pagenumber which you choose as the final page to print 
            doc.PrintToPage = dialogPrint.PrinterSettings.ToPage; 
            //Set the name of the printer which is to print the PDF 
            doc.PrinterName = dialogPrint.PrinterSettings.PrinterName; 

            PrintDocument printDoc = doc.PrintDocument; 
            dialogPrint.Document = printDoc; 
            printDoc.Print(); 
        } 

PrintDocument won't print a PDF by itself. PrintDocument不会单独打印PDF。 Try this other SO post which explains how to use whatever application is associated with PDF files and the 'print' verb. 尝试另一篇SO帖子该帖子解释了如何使用与PDF文件和“打印”动词相关联的任何应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM