2012-08-08 83 views
0

在我的應用程序中,我試圖創建一個功能來打印現有的PDF或文檔。我如何在C#中執行此操作並提供一種機制,以便用戶可以選擇不同的打印機或其他屬性。使用C#打印PDF文件和Doc文件

我已經看了PrintDialog,但不知道它試圖打印什麼文件,如果有的話,B/C輸出總是空白頁。也許我只是想念那裏的東西。

任何建議,例子或示例代碼將是偉大的!下面

是我的代碼

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 


namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
       InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
       string printPath = 
        System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop); 
       System.IO.StreamReader fileToPrint; 
       fileToPrint= new System.IO.StreamReader(printPath + @"\myFile.txt"); 
       System.Drawing.Font printFont; 
       printPDF(e); 
       printDocument1.Print(); 
       fileToPrint.Close(); 
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
       //printDoc(e); 
     } 

     public void printPDF(object sender , 
           System.Drawing.Printing.PrintPageEventArgs e)) 
     {  
       printFont = new System.Drawing.Font("Arial", 10); 
       float yPos = 0f; 
       int count = 0; 
       float leftMargin = e.MarginBounds.Left; 
       float topMargin = e.MarginBounds.Top; 
       string line = null; 
       float linesPerPage = e.MarginBounds.Height/ 
            printFont.GetHeight(e.Graphics); 
       while (count < linesPerPage) 
       { 
        line = fileToPrint.ReadLine(); 
        if (line == null) 
        { 
         break; 
        } 
       yPos = topMargin + count * printFont.GetHeight(e.Graphics); 
       e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, 
            new StringFormat()); 
       count++; 
       } 

       if (line != null) 
       { 
        e.HasMorePages = true; 
       } 

       fileToPrint.Close();   
     } 

     public void printDoc() 
     { 
     } 
    } 
} 
+0

我可以說你的應用程序已經將文件加載到內存了嗎?爲什麼不發佈你嘗試過的? – 2012-08-08 02:32:10

回答

1

這已經在過去的工作:

using System.Diagnostics.Process; 

... 

Process process = new Process(); 

process.StartInfo.FileName = pathToPdfOrDocFile; 
process.UseShellExecute = true; 
process.StartInfo.Verb = "printto"; 
process.StartInfo.Arguments = "\"" + printerName + "\""; 
process.Start(); 

process.WaitForInputIdle(); 
process.Kill(); 

要打印到默認打印機,用print取代printto,並留下關閉Arguments線。

+0

如果Process缺失,如何添加相關引用? – 2012-08-08 03:33:13

+0

我無法找到任何處理 – 2012-08-08 03:57:34

+1

'使用System.Diagnostics;' – 2013-09-25 08:33:15