2015-10-22 54 views
0

我正在使用WinForms。我有一個這種形式的按鈕。當點擊按鈕時,我希望程序每次點擊它時都打印一個特定的文件。在您的計算機C中打印特定文件#

我的問題是:我的代碼不打印我的電腦中的特定文件。它打印出一個空白的文件。

例如:按鈕點擊一直打印文檔「C:\ image.jpg」。

private void btn_Print_Click (object sender, EventArgs e) 
    { 
     printDialog1.AllowSomePages = true; 
     printDialog1.AllowSelection = true; 
     printDocument1.PrinterSettings.PrintToFile = true; 

     if (printDialog1.ShowDialog() == DialogResult.OK) 
     { 
      printDialog1.PrinterSettings.PrintFileName = @"C:\\image"; 
      printDocument1.Print(); 
     } 
    } 

      private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) 
    { 

    } 
+0

感謝那些@xPeke –

+0

我不知道如何打印特定文件從我的電腦@xPeke –

+1

是否可能與權限相關?您是否能夠使用Windows資源管理器在程序之外打印C:\ image?我沒有看到您提供的代碼有任何問題 – Krondorian

回答

0

以下代碼有效。您可能需要根據需要進行調整,但這將是您的出發點。

參考:https://social.msdn.microsoft.com/Forums/windows/en-US/f83aff78-44c1-465c-86b4-9e4e5a2d97e2/how-to-print-files-stored-at-your-local-hard-drive-in-c?forum=winforms

請確保您有:

using System.Drawing; 
using System.Drawing.Printing; 

那就是:我加入

private void button1_Click(object sender, EventArgs e) 
    { 
     using (PrintDocument pd = new PrintDocument()) 
     { 
     if (printDialog1.ShowDialog() == DialogResult.OK) 
     { 
      string filePath = @"C:\image.JPG"; 
      pd.OriginAtMargins = true; 
      pd.PrintPage += pd_PrintPage; 
      pd.DocumentName = filePath; 
      pd.Print(); 
      pd.PrintPage -= pd_PrintPage; 
     } 
     } 
    } 

    public void pd_PrintPage(object sender, PrintPageEventArgs e) 
    { 
     string labelPath = ((PrintDocument)sender).DocumentName; 
     e.Graphics.DrawImage(new Bitmap(labelPath), 0, 0); 
    } 
+0

當然,如果這對你有用,請接受答案:) – Krondorian

+0

我發佈的代碼打印出圖像本身。根據他在他的問題中的評論,它正在打印出一個空白頁。此代碼打印出圖像。 – Krondorian

+0

我會,什麼是:pd.PrintPage + = pd_PrintPage? –

相關問題