问题描述:

I have a form on which I have a number of textboxes. I wish to print the text from these textboxes in the locations they are on the form. It is printing at the moment using the code below. However, the text prints differently on different printers (on some it prints just right, on some too high, etc). It is being printed on a pre-printed form with spaces for the text so it needs to be fairly exact. What am I missing to make it print the same on every printer?

public void printDocument_PrintPage(object sender, PrintPageEventArgs e)

{

Panel curPanel = this.FormPanel;

Graphics g = (Graphics)e.Graphics;

Pen aPen = new Pen(Brushes.Black, 1);

// Cycle through each control. Determine if it's a checkbox or a textbox and draw the information inside

// in the correct position on the form

int xLocation, yLocation;

for (int j = 0; j < curPanel.Controls.Count; j++)

{

// Check if its a TextBox type by comparing to the type of one of the textboxes

if (curPanel.Controls[j] is TextBox)

{

// Unbox the Textbox

TextBox theText = (TextBox)curPanel.Controls[j];

// Draw the textbox string at the position of the textbox on the form, scaled to the print page

xLocation = theText.Bounds.Left;

yLocation = theText.Bounds.Top;

g.DrawString(theText.Text, theText.Font, Brushes.Black, xLocation, yLocation);

}

}

}

网友答案:

The problem is that you ignoring how the text is aligned inside the control. Default alignment is roughly equal to StringFormat.Alignment = StringAlignment.Center, it can be changed for buttons and check boxes with their TextAlign property. You'll need to use the DrawString() overload that takes a Rectangle and a StringFormat. Note that TextBox is tricky, you might still be off by a few pixels.

Take a look at Control.DrawToBitmap() for a completely different approach.

网友答案:

I'm wondering if maybe the problem is discrepencies in how different printers pull in the paper. The text is off by a maximum of half an inch between printers. I was hoping this wasn't the case because if so I will just have to tailor my application to the client's particular printer (not ideal). Has anyone else run into this situation?

网友答案:

This is most likely a combination of two things:

  1. You need to explicitly set up the page margins/boundaries. Various printers will have default margin and page size settings. Use a PageSetupDialog to help you out. If you want consistent printing, you can make the margins constant, but page size should be the responsibility of the user (and then check to make sure your margins actually fit on the page!).
  2. The text needs to be placed on the page in relation to the page boundaries. I know your comment says that it will be, but it doesn't look like that it is actually implemented in your code. Setting the OriginAtMargins (on your PrintDocument control) to true helps immensely with this.
相关阅读:
Top