C#中打印拼接的字符串

1、实例化打印文档
//声明打印对象
PrintDocument pd = new PrintDocument();
int ilvPreviewIndex = 0;
 
2、在打印事件中设置基本属性
private void btnPrint_Click(object sender, EventArgs e)
{
//获取和设置标签的高宽和边距
decimal dLabelHeight = nudLabelHeight.Value;
decimal dLabelWidth = nudLabelWidth.Value;
decimal dTopMargin = nudTopMargin.Value;
decimal dLeftMargin = nudLeftMargin.Value;
//设置边距
Margins margin = new Margins(0, 0, 0, 0);
pd.DefaultPageSettings.Margins = margin;
pd.DefaultPageSettings.Margins = margin;
//横向打印
//pd.DefaultPageSettings.Landscape = true;
//循环打印
for (; ilvPreviewIndex < dgvPreview.Rows.Count; ilvPreviewIndex++)
{
//页面尺寸
pd.DefaultPageSettings.PaperSize = new PaperSize("Custom", Utility.GetPixelByWidth(dLabelWidth), Utility.GetPixelByWidth(dLabelHeight));
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
pd.Print();
}
}
 
3、打印事件处理
/// <summary>
/// 打印事件处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
//排架号中的行间距
int iMiddle = int.Parse(Utility.ConfigGetItem("ShelfMiddle"));
//获取和设置标签的高宽和边距
decimal dLabelHeight = nudLabelHeight.Value;
decimal dLabelWidth = nudLabelWidth.Value;
decimal dTopMargin = nudTopMargin.Value;
decimal dLeftMargin = nudLeftMargin.Value;
//获取排架号
string sBeginCallNo = dgvPreview.Rows[ilvPreviewIndex].Cells[0].Value.ToString();
string sConnectSymbol = txtConnectSymbol.Text.Trim();
string sEndCallNo = dgvPreview.Rows[ilvPreviewIndex].Cells[1].Value.ToString();
//设置水平文字对齐方式
StringFormat stringFormat = new StringFormat();
stringFormat.LineAlignment = StringAlignment.Center;
stringFormat.Alignment = StringAlignment.Center;
 
//将排架号进行拼接打印
Graphics g = e.Graphics;
float leftMargin = Utility.GetPixelByWidth(dLeftMargin); //左边距
SolidBrush myBrush = new SolidBrush(Color.Black);//刷子
float yPosition = Utility.GetPixelByHeight(dTopMargin);//行定位
Font printFont = new Font("宋体", 12f, FontStyle.Bold);//设置字体
g.DrawString(sBeginCallNo, printFont, myBrush, leftMargin, yPosition, stringFormat);
yPosition += Utility.GetPixelByHeight(iMiddle);//另起一行
g.DrawString(sConnectSymbol, printFont, myBrush, leftMargin, yPosition, stringFormat);
yPosition += Utility.GetPixelByHeight(iMiddle);//另起一行
g.DrawString(sEndCallNo, printFont, myBrush, leftMargin, yPosition, stringFormat);
}

猜你喜欢

转载自www.cnblogs.com/masonblog/p/12740733.html