c# - 在 C#.net 中,如何在打印时获取行中的文本?
问题描述
我在 C# windows 窗体应用程序中创建了一个项目。我正在使用 Visual Studio 2010 和 .net 框架 4.0 版。我的项目有打印按钮。我为打印按钮编写了代码:
private void btn_Print_Click(object sender, EventArgs e)
{
PrintDialog pd = new PrintDialog();
PrintDocument pdoc = new PrintDocument();
PrinterSettings ps = new PrinterSettings();
PaperSize psize = new PaperSize("Custom", 100, 200);
pd.Document = pdoc;
pd.Document.DefaultPageSettings.PaperSize = psize;
pdoc.DefaultPageSettings.PaperSize.Height = 820;
pdoc.DefaultPageSettings.PaperSize.Width = 520;
pdoc.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
DialogResult result = pd.ShowDialog();
if (result == DialogResult.OK)
{
PrintPreviewDialog pp = new PrintPreviewDialog();
pp.Document = pdoc;
result = pp.ShowDialog();
if (result == DialogResult.OK)
{
pdoc.Print();
}
}
}
和 printDocument1 控件的事件处理程序代码
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
string s1 = "1st line text";
string s2 = "2nd line text";
string s3 = "3rd line text";
Font f1 = new Font("Arial", 10, FontStyle.Bold, GraphicsUnit.Pixel);
Font f2 = new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel);
Font f3 = new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel);
e.Graphics.DrawString(s1, f1, Brushes.Black, new Point(260, 10));
e.Graphics.DrawString(s2, f2, Brushes.Black, new Point(260, 20));
e.Graphics.DrawString(s3, f3, Brushes.Black, new Point(260, 30));
}
我需要在行中间的字符串 s1,s2,s3。从上面的代码中,我得到了从行的中点开始的字符串的第一个字符。但我需要在中间的整个字符串。我尝试了网上给出的所有解决方案。但还没有得到结果。请帮我找出,我错过了什么。谢谢你的时间。
解决方案
e.Graphics.DrawString(s1, f1, Brushes.Black, new RectangleF(0, 10, e.PageBounds.Width, 30), new StringFormat() { Alignment = StringAlignment.Center });
而不是点,设置您需要打印的区域的实际矩形并设置对齐方式
在您的声明中,代码必须是
string s1 = "1st line text";
string s2 = "2nd line text";
string s3 = "3rd line text";
Font f1 = new Font("Arial", 10, FontStyle.Bold, GraphicsUnit.Pixel);
Font f2 = new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel);
Font f3 = new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel);
e.Graphics.DrawString(s1, f1, Brushes.Black, new RectangleF(0, 10, e.PageBounds.Width, 10), new StringFormat() { Alignment = StringAlignment.Center });
e.Graphics.DrawString(s2, f2, Brushes.Black, new RectangleF(0, 20, e.PageBounds.Width, 10), new StringFormat() { Alignment = StringAlignment.Center });
e.Graphics.DrawString(s3, f3, Brushes.Black, new RectangleF(0, 30, e.PageBounds.Width, 10), new StringFormat() { Alignment = StringAlignment.Center });
推荐阅读
- java - Eclipse Debugger 如何跳过 ClassLoader.class?
- python - 如何根据python 3.X中的模式在char中添加双引号?
- javascript - 在水平条形图上的条形之后附加文本
- html - 如何更改悬停按钮颜色?
- javascript - 使用 Laravel mix 将模板文件/存根编译成 JS 变量
- reactjs - React Hooks Mobx:无效的钩子调用。Hooks 只能在函数组件的主体内部调用
- angular7 - 如何从 Angular 7 中传递 id 的 json 对象获取特定数据
- postgresql - 触发器根据另一个表记录更新计数
- angular - 将 ionic4/socket.io 连接到 expressjs net::ERR_CONNECTION_REFUSED
- checkbox - 在Google表格中选中复选框时如何更改指定单元格的颜色?