用 c 锐利打印文件 [英] Printing a file in c sharp
问题描述
我已经写了一个写文件的cSharp控制台应用程序,现在我想打印它.我在搜索时看到了很多示例,但其中许多示例都以表单和按钮开头,我不希望用户按任何按钮,因为我已经知道文件、字体和大小,我只想打印文档.另外我发现的每个应用程序都是 Windows Form 应用程序,你能告诉我如何从控制台应用程序调用它吗?
I have written a c sharp console application that writes a file, now I want to print it. I saw many examples while searching, but many of them start with a form and buttons, I don't want the user to press any button since I already know the file, the font and the size, I just want to print the document. Also every application I found is a Windows Form application, can you tell me how to call it from a console application?
对不起,如果问题有点基础,我才刚刚开始学习.
Sorry if the question is a little basic, I'm just beginning to learn.
推荐答案
您可以使用 PrintDocument 对象
这是来自 MSDN 的示例代码:
here is a sample code from MSDN:
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
public class PrintingExample
{
private Font printFont;
private StreamReader streamToPrint;
static string filePath;
public PrintingExample()
{
Printing();
}
// The PrintPage event is raised for each page to be printed.
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
String line=null;
// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height /
printFont.GetHeight(ev.Graphics) ;
// Iterate over the file, printing each line.
while (count < linesPerPage &&
((line=streamToPrint.ReadLine()) != null))
{
yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString (line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
count++;
}
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}
// Print the file.
public void Printing()
{
try
{
streamToPrint = new StreamReader (filePath);
try
{
printFont = new Font("Arial", 10);
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
// Print the document.
pd.Print();
}
finally
{
streamToPrint.Close() ;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// This is the main entry point for the application.
public static void Main(string[] args)
{
string sampleName = Environment.GetCommandLineArgs()[0];
if(args.Length != 1)
{
Console.WriteLine("Usage: " + sampleName +" <file path>");
return;
}
filePath = args[0];
new PrintingExample();
}
}
这篇关于用 c 锐利打印文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!