2012-08-08 74 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