[英]print txt file direct to printer aspx.net
我正在使用以下方法創建txt文件,但現在我不知道如何直接將此文件發送到打印機。我希望當用戶單擊button_click事件時,無需打印預覽即可打印txt文件...等是網絡部署的
public void Print()
{
string path = @"c:\Restaurant\kitchen.txt";
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
if (Label53.Text == "4")
{
String s = Label47.Text;
s = String.Format(s.Replace("S", "С").Replace("U", "У").Replace("P", "П").Replace("A", "А"));
sw.WriteLine(s);
}
}
}
}
對的,這是可能的...
首先您將Reference System.Drawing
添加到項目中,之后您需要使用:
using System.Drawing;
using System.Drawing.Printing;
我將為控制台應用程序顯示它,您可以輕松將其轉換為asp.net。
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern IntPtr GetStockObject(int fnObject);
private static string stringToPrint;
static void Main(string[] args)
{
PrintDocument doc = new PrintDocument();
ReadFile(doc);
doc.PrintPage += doc_PrintPage;
doc.Print();
}
private static void ReadFile(PrintDocument printDocument1)
{
string docName = "Test.txt";
string docPath = @"c:\";
printDocument1.DocumentName = docName;
using (FileStream stream = new FileStream(docPath + docName, FileMode.Open))
using (StreamReader reader = new StreamReader(stream))
{
stringToPrint = reader.ReadToEnd();
}
}
static void doc_PrintPage(object sender, PrintPageEventArgs e)
{
int charactersOnPage = 0;
int linesPerPage = 0;
// Sets the value of charactersOnPage to the number of characters
// of stringToPrint that will fit within the bounds of the page.
e.Graphics.MeasureString(stringToPrint, Font.FromHfont(GetStockObject(0)),
e.MarginBounds.Size, StringFormat.GenericTypographic,
out charactersOnPage, out linesPerPage);
// Draws the string within the bounds of the page
e.Graphics.DrawString(stringToPrint, Font.FromHfont(GetStockObject(0)), Brushes.Black,
e.MarginBounds, StringFormat.GenericTypographic);
// Remove the portion of the string that has been printed.
stringToPrint = stringToPrint.Substring(charactersOnPage);
// Check to see if more pages are to be printed.
e.HasMorePages = (stringToPrint.Length > 0);
}
這是代碼。 我使用GetStockObject
只是為了創建Font,可以根據需要使用另一個自定義Font。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.