简体   繁体   中英

Print rectangle in specified position

I would print rectangle in specified position from c# application. For example 1 centimeter from the left edge of sheet and 1 centimeter from the top edge of sheet.

I tried something like this:

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    Brush brush = new SolidBrush(Color.Black);
    Pen blackPen = new Pen(Color.Black, 1);
    e.Graphics.PageUnit = GraphicsUnit.Millimeter;
    e.PageSettings.Margins = new Margins(10, 10, 10, 10);        
    Rectangle rect = new Rectangle(10, 10, 50, 90);
    e.Graphics.DrawRectangle(blackPen, rect);
}

But it does not work correctly.

This seems to be a very helpful discussion of the whole matter.

If you want your margins to work you need to change the PrintDocument.OriginsAtMargins from its default (false) to true.

As you don't seem to do that, your origin will be at the printable area , which is printer-dependent and seems to be at (3,2)mm for your printer. A simple test for this would be to print to a PDF printer, which ought to have the full page as its printable area; so it should appear at the top left of its page.

So if you add printDocument.OriginAtMargins = true; to maybe the BeginPrint event (or whereever you set up th page) and then print the rectangle to (0,0) it should appear at the margins you have set..

I change void to :

printDocument1.OriginAtMargins = true;
Graphics g = e.Graphics;
Brush brush = new SolidBrush(Color.Black);
Pen blackPen = new Pen(Color.Black, 1);
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
e.PageSettings.Margins = new Margins(0, 0, 0, 0);
Rectangle rect = new Rectangle(10, 10, 20, 20);
e.Graphics.DrawRectangle(blackPen, rect);

Now on print I have rectangle in 13 milimeter from the left edge of sheet and 12 milimeter from the top edge of sheet, but when I change code to :

printDocument1.OriginAtMargins = true;
Graphics g = e.Graphics;
Brush brush = new SolidBrush(Color.Black);
Pen blackPen = new Pen(Color.Black, 1);
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
e.PageSettings.Margins = new Margins(0, 0, 0, 0);
Rectangle rect = new Rectangle(10, 10, 20, 20);
e.Graphics.DrawRectangle(blackPen, rect);

and print to pdf printer I have rectango on 0,0 on sheet...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM