I'm using the following to print out some text from my C# WPF app:
private void Button_Click(object sender, RoutedEventArgs e)
{
PrintDocument printDocument = new PrintDocument();
printDocument.PrinterSettings.PrinterName = "\\\\servername\\printername";
printDocument.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
if (printDocument.PrinterSettings.IsValid)
{
printDocument.Print();
}
}
// The PrintPage event is raised for each page to be printed.
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
string stringToPrint = "SOME TEXT TO PRINT";
// Create font and brush.
Font drawFont = new Font("Arial", 16);
SolidBrush drawBrush = new SolidBrush(System.Drawing.Color.Black);
System.Drawing.Point pos = new System.Drawing.Point(100, 100);
ev.Graphics.DrawString(stringToPrint, drawFont, drawBrush, pos);
ev.HasMorePages = false;
}
The above example is using a fixed position but I need to print out several lines of text all different lengths and I want to centre them all on the page (The x position).
How can I do this?
There is an overload of Graphics.DrawString that uses a StringFormat parameter that you can use to set the horizontal and vertical alignment of the text in the rectangle. I have used something like this in the past.
string stringToPrint = "SOME TEXT TO PRINT";
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
// Create font and brush.
Font drawFont = new Font("Arial", 16);
SolidBrush drawBrush = new SolidBrush(System.Drawing.Color.Black);
//Starting point of left margin,Width of page, Height of Text
System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0, 100, 100, 50);
ev.Graphics.DrawString(stringToPrint, drawFont, drawBrush, rect, sf);
ev.HasMorePages = false;
Related
The string is "Hello World " with 10 SPACE chars in the end, but Graphics.DrawString in Right Alignment omits all of SPACE chars, it just draws "Hello World" only.
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rct = new Rectangle(20, 100, 200, 20);
e.Graphics.DrawRectangle(new Pen(Color.Lime), rct);
e.Graphics.DrawString("Hello World ", Font, new SolidBrush(SystemColors.ControlText), rct, new StringFormat() { Alignment = StringAlignment.Far});
base.OnPaint(e);
}
To include the Trailing Spaces when drawing strings with Gdi+ Graphics.DrawString method, pass a StringFormat to a proper overload and add or append (|=) the StringFormatFlags.MeasureTrailingSpaces value to the StringFormat.FormatFlags property.
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Rectangle rct = new Rectangle(20, 100, 200, 20);
string s = "Hello World ";
using (var sf = new StringFormat(StringFormat.GenericTypographic))
{
sf.Alignment = StringAlignment.Far;
sf.LineAlignment = StringAlignment.Center;
sf.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
e.Graphics.DrawString(s, Font, SystemBrushes.ControlText, rct, sf);
}
e.Graphics.DrawRectangle(Pens.Lime, rct);
}
Consider using the Gdi TextRenderer class to draw strings over controls unless you encounter problems like drawing on transparent backgrounds.
The previous code could have been written like:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Rectangle rct = new Rectangle(20, 100, 200, 20);
string s = "Hello World ";
TextRenderer.DrawText(e.Graphics, s, Font, rct, SystemColors.ControlText,
TextFormatFlags.Right |
TextFormatFlags.VerticalCenter);
e.Graphics.DrawRectangle(Pens.Lime, rct);
}
I want to print a Multiline Text.
I searched and I found that I can print it with TextRenderer, but the text is printed very small in the left top of the paper. I don´t know why.
Code:
PrintDocument pd = new PrintDocument();
pd.PrintPage += PrintPage_Header;
pd.PrintPage += PrintPage_Adresse;
// pd.Print();
printPrvDlg.Document = pd;
printPrvDlg.ShowDialog();
private void PrintPage_Adresse(object sender, PrintPageEventArgs e)
{
printFont = new Font("Arial", 10, FontStyle.Bold);
Size size = TextRenderer.MeasureText(e.Graphics, stringToPrint, this.printFont, proposedSize, TextFormatFlags.WordBreak);
xPos = new System.Drawing.Rectangle(new Point(22, 150), size);
TextRenderer.DrawText(e.Graphics, stringToPrint, this.printFont, xPos, Color.Black, Color.White, TextFormatFlags.WordBreak);
}
I can´t find the problem.
I have a problem with the font of the TabControl.
I set the Alignment to Left, and use following code to set the font:
private void tabControl1_DrawItem(Object sender, System.Windows.Forms.DrawItemEventArgs e)
{
Graphics g = e.Graphics;
Brush _textBrush;
// Get the item from the collection.
TabPage _tabPage = tabControl1.TabPages[e.Index];
// Get the real bounds for the tab rectangle.
Rectangle _tabBounds = tabControl1.GetTabRect(e.Index);
if (e.State == DrawItemState.Selected) {
// Draw a different background color, and don't paint a focus rectangle.
_textBrush = new SolidBrush(Color.Black);
g.FillRectangle(Brushes.LightSkyBlue, e.Bounds);
}
else {
_textBrush = new System.Drawing.SolidBrush(e.ForeColor);
e.DrawBackground();
}
// Use our own font.
Font _tabFont = new Font("Calibri", (float)11.0, FontStyle.Regular, GraphicsUnit.Pixel);
// Draw string. Left the text.
StringFormat _stringFlags = new StringFormat();
_stringFlags.Alignment = StringAlignment.Near;
_stringFlags.LineAlignment = StringAlignment.Center;
g.DrawString(_tabPage.Text, _tabFont, _textBrush, _tabBounds, new StringFormat(_stringFlags));
}
I set the font to "Calibri", (float)11.0, but the text in the tabcontrol are smaller. Please refer to the following:
Font Error
What should I do to set the correct font?
Really appreciate your help!
Eric
I have followed the instructions in the msdn website:
https://msdn.microsoft.com/en-us/library/vstudio/ms404305%28v=vs.100%29.aspx
to display a tab control as the following picture:
And this is the code:
private void tcMain_DrawItem(Object sender, DrawItemEventArgs e)
{
Graphics g = e.Graphics;
Brush _textBrush;
TabPage _tabPage = tcMain.TabPages[e.Index];
Rectangle _tabBounds = tcMain.GetTabRect(e.Index);
if (e.State == DrawItemState.Selected)
{
_textBrush = new SolidBrush(Color.Red);
g.FillRectangle(Brushes.Gray, e.Bounds);
}
else
{
_textBrush = new System.Drawing.SolidBrush(e.ForeColor);
e.DrawBackground();
}
Font _tabFont = new Font("Times New Roman", (float)22, FontStyle.Regular, GraphicsUnit.Pixel);
StringFormat _stringFlags = new StringFormat();
_stringFlags.Alignment = StringAlignment.Near;
_stringFlags.LineAlignment = StringAlignment.Center;
g.DrawString(_tabPage.Text, _tabFont, _textBrush, _tabBounds, new StringFormat(_stringFlags));
}
Now I want to add a picture to the left of the tab control buttons? I mean, how to show a picture to the left of the word Book for example?
After trying some answers from below I ended up with the code:
private void tcMain_DrawItem(Object sender, DrawItemEventArgs e)
{
Graphics g = e.Graphics;
Brush _textBrush;
TabPage _tabPage = tcMain.TabPages[e.Index];
Rectangle _tabBounds = tcMain.GetTabRect(e.Index);
if (e.State == DrawItemState.Selected)
{
_textBrush = new SolidBrush(Color.Red);
g.FillRectangle(Brushes.Gray, e.Bounds);
}
else
{
_textBrush = new System.Drawing.SolidBrush(e.ForeColor);
e.DrawBackground();
}
tcMain.ImageList = imgList;
tcMain.TabPages[0].ImageIndex = 1;
tcMain.TabPages[1].ImageIndex = 0;
tcMain.TabPages[2].ImageIndex = 3;
tcMain.TabPages[3].ImageIndex = 2;
Rectangle tabImage = tcMain.GetTabRect(e.Index);
tabImage.Size = new Size(40, 40);
g.DrawImage(tcMain.ImageList.Images[_tabPage.ImageIndex], tabImage);
Font _tabFont = new Font("Times New Roman", (float)22, FontStyle.Regular, GraphicsUnit.Pixel);
StringFormat _stringFlags = new StringFormat();
_stringFlags.Alignment = StringAlignment.Center;
_stringFlags.LineAlignment = StringAlignment.Center;
g.DrawString(_tabPage.Text, _tabFont, _textBrush, _tabBounds, new StringFormat(_stringFlags));
}
Then when I take a snapshot to the results it comes like this:
Refreshing all the time
You could add an ImageList control to your project and add some images to it and set the ImageIndex property of your TabPages. Then just use DrawImage() method in your DrawItem event.
Rectangle tabImage = tcMain.GetTabRect(e.Index);
tabImage.Size = new Size(16, 16);
g.DrawImage(tcMain.ImageList.Images[_tabPage.ImageIndex], tabImage);
You could also use ImageKey instead of ImageIndex.
g.DrawImage(tcMain.ImageList.Images[_tabPage.ImageKey], tabImage);
If you add the ImageList and the ImageIndex programmatically take a look:
ImageList imageList = new ImageList();
imageList.Images.Add("key1", Image.FromFile("pathtofile"));
imageList.Images.Add("key2", Image.FromFile("pathtofile"));
tcMain.ImageList = imageList;
tcMain.TabPages[0].ImageIndex = 1;
tcMain.TabPages[1].ImageIndex = 0;
I have overridden the OnPaint method of my Label control in VS2008:
void Label_OnPaint(object sender, PaintEventArgs e) {
base.OnPaint(e);
dim lbl = sender as Label;
if (lbl != null) {
string Text = lbl.Text;
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
if (myShowShadow) { // draw the shadow first!
e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(myShadowColor), myShadowOffset, StringFormat.GenericDefault);
}
e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(lbl.ForeColor), 0, 0, StringFormat.GenericDefault);
}
}
This works, but I really want to find out how to center the text both vertically and horizontally. I've heard of the MeasureString() method, but my "Text" complicates matters because it could include page breaks.
Could someone guide me with how to do this?
Alternatively you can create your own StringFormat object and pass it in using an overload of DrawString that supports a RectangleF:
StringFormat formatter = new StringFormat();
formatter.LineAlignment = StringAlignment.Center;
formatter.Alignment = StringAlignment.Center;
RectangleF rectangle = new RectangleF(0, 0, lbl.Width, lbl.Height);
e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(lbl.ForeColor), rectangle, formatter);
You can call TextRenderer.DrawText with the HorizontalCenter and VerticalCenter flags.
Here is the code i'm using at the moment,
SizeF size;
string text = "Text goes here";
size = e.Graphics.MeasureString(text, font);
x = (lineWidth / 2) - (size.Width / 2);
y = top;
e.Graphics.DrawString(text, font, Brushes.Black, x, y);
I just wanted to add (a year later) a tool I created because StringAlignment turned out to be not very dependable. It turns out to be very similar to Neo's version.
The code below does an excellent job of centering the text both vertically and horizontally. Also, I wrote it with various overloads so that different options could be supplied to make this control behave exactly like I want.
Here are my overloads:
private static void DrawCenter(Label label, Graphics graphics) {
DrawCenter(label.Text, label, label.Location, label.ForeColor, graphics);
}
private void DrawCenter(string text, Label label, Graphics graphics) {
DrawCenter(text, label, label.Location, label.ForeColor, graphics);
}
private static void DrawCenter(string text, Label label, Point location, Graphics graphics) {
DrawCenter(text, label, location, label.ForeColor, graphics);
}
private static void DrawCenter(string text, Label label, Point location, Color fontColor, Graphics graphics) {
Rectangle rect = new Rectangle(location, label.Size);
SizeF lSize = graphics.MeasureString(text, label.Font, rect.Width);
PointF lPoint = new PointF(rect.X + (rect.Width - lSize.Width) / 2, rect.Y + (rect.Height - lSize.Height) / 2);
graphics.DrawString(text, label.Font, new SolidBrush(fontColor), lPoint);
}
To use these for the Label's OnPaint event, simply modify my original code in the question to following:
private void Label_OnPaint(object sender, PaintEventArgs e) {
base.OnPaint(e);
Label lbl = sender as Label;
if (lbl != null) {
string txt = lbl.Text;
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
if (myShowShadow) { // draw the shadow first!
Point offset = new Point(lbl.Location.X - 1, lbl.Location.Y - 1)
DrawCenter(txt, lbl, offset, myShadowColor, e.Graphics);
}
DrawCenter(lbl, e.Graphics);
}
}
For a Print_Document event, I have a version that will also print a box around the label if there is already a box around it in the designer:
private static void DrawCenter(string text, Label label, Point location, Color fontColor, Graphics graphics) {
Rectangle rect = new Rectangle(location, label.Size);
SizeF lSize = graphics.MeasureString(text, label.Font, rect.Width);
PointF lPoint = new PointF((rect.Width - lSize.Width) / 2, (rect.Height - lSize.Height) / 2);
graphics.DrawString(text, label.Font, new SolidBrush(fontColor), lPoint);
if (label.BorderStyle != BorderStyle.None) {
using (Pen p = new Pen(Color.Black)) {
graphics.DrawRectangle(p, rect);
}
}
}
If you find this at all useful, give me a +1.
~Joe