【发布时间】:2016-04-13 06:41:12
【问题描述】:
我生成了一长串按要求格式化的发票。我现在需要在打印机上打印出来,每页显示一张发票。
我查看了这些教程/帮助以及一些我曾经使用过的代码:
https://msdn.microsoft.com/en-us/library/cwbe712d%28v=vs.110%29.aspx
我主要关注第二个。
我最终得到的是(使用单个表单和单个按钮工作的 VS C# 项目):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestPrint
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string stringToPrint = "Hello\r\nWorld\r\n\r\n<<< Page >>>World\r\nHello";
private void button1_Click(object sender, EventArgs e)
{
// Convert string to strings
string[] seperatingChars = { "<<< Page >>>" };
string[] printString = stringToPrint.Split(seperatingChars, System.StringSplitOptions.RemoveEmptyEntries);
// Connect to the printer
PrintDocument printDocument1 = new PrintDocument(); // Stream to the printer
// Send to printer (reference: https://social.msdn.microsoft.com/Forums/en-US/93e54c4f-fd07-4b60-9922-102439292f52/c-printing-a-string-to-printer?forum=csharplanguage)
foreach (string s in printString)
{
printDocument1.PrintPage += delegate (object sender1, PrintPageEventArgs e1)
{
e1.Graphics.DrawString(s, new Font("Times New Roman", 12), new SolidBrush(Color.Black),
new RectangleF(0, 0, printDocument1.DefaultPageSettings.PrintableArea.Width,
printDocument1.DefaultPageSettings.PrintableArea.Height));
};
try
{
printDocument1.Print();
printDocument1.Dispose();
}
catch (Exception ex)
{
throw new Exception("Exception Occured While Printing", ex);
}
}
}
}
}
我将长字符串分成我想要打印到每个单独页面的部分,然后将其发送到打印机。这适用于第一张发票/页面,但之后它只是将每一页添加到第一张的图像上(我添加了 printDocument1.Dispose(); 以尝试对其进行排序,但没有奏效)。
我想知道的是如何将字符串打印为单个字符串,同时每页保留一张发票。
编辑:如何将字符串生成为打印机的多页图像?
【问题讨论】:
-
你试过把 PrintDocument printDocument1 = new PrintDocument();在 foreach 循环内?
-
那行得通。我仍然将它作为多个文件的输出(打印到 PDF 而不是打印机),我希望它转到一个文件。当然,在打印到打印机时不会有任何区别,但在打印到文件时会有所不同——如果可以用我所拥有的来完成的话。
-
所以您只想将字符串打印到一个文件中?然后您需要在将文档发送到打印机之前生成文档。目前,您正在打印时生成文档。听起来你需要把你的
printDocument1.Print();带出 for 循环并在里面做其他事情,然后最后打电话给你的printDocument1.Print(); -
是的,我认为这将是一个更好的方法,但我如何首先生成它?
标签: c#