使用C#打印PDF文件和Doc文件

时间:2012-08-08 02:25:12

标签: c# pdf printing doc

在我的应用程序中,我正在尝试创建一个打印现有PDF或Doc的功能。如何在C#中执行此操作并提供一种机制,以便用户可以选择其他打印机或其他属性。

我查看了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()
         {
         }
     }
 }

1 个答案:

答案 0 :(得分: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();

要打印到默认打印机,请将printto替换为print,然后不要使用Arguments行。