3

I am trying to print some strings using Graphicss.DrawString(). I have set margins to the printdocument but does not start from the origin of the page. I have set margins to (0,0,0,0) but somehow it prints half centimeter below the top edge of the page. Another thing is that it can print from left edge.

Below is my code.

private void button1_Click(object sender, EventArgs e)
    {
        ////PaperSize pkCustomSize1 = new PaperSize("First custom size", 1020, 3517);
        ////printDocument1.DefaultPageSettings.PaperSize = pkCustomSize1;
        printPreviewDialog1.Document = printDocument1;
        printDocument1.PrinterSettings.PrinterName = this.comboBox1.Text;
        Margins margins = new Margins(0, 0, 0, 0);
        printDocument1.PrinterSettings.DefaultPageSettings.Margins = margins;
        printPreviewDialog1.Show();
        printDocument1.Print();
    }

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
        int resX = GetPrinterResolutionX(comboBox1);
        int resY = PrnOpra.GetPrinterResolutionY(comboBox1);
        Graphics g = e.Graphics;

        float scale = resX / ScrnRes;
        Bitmap bm = new Bitmap(367, 1205);
        g.DrawRectangle(new Pen(Color.Black, 0.5F), panel9.Location.X / 2, panel9.Location.Y / 2, panel9.Width, panel9.Height);
        g.DrawImage(bm, 0, 0);
}

What's wrong with code?

DhavalR
  • 1,409
  • 3
  • 29
  • 57

1 Answers1

5

You have to set the PrintDocument.OriginAtMargins property to true to consider your margins.

From MSDN,

When OriginAtMargins is true, the Graphics object location takes into account the PageSettings.Margins property value and the printable area of the page

But printing from the exact edge depends on the printable area which is defined by the physical limitations of the printing device. Check the HardMarginX and HardMarginY to get the physical origin of the printer. For more information refer the answer of this question.

Community
  • 1
  • 1
Junaith
  • 3,298
  • 24
  • 34
  • Suppose I want to print from the left-top corner of the page, what should be the code.? I am asking this because, I set `PrintDocument.OriginMargins` to `true` after assigning `margins`, but prints even lower than before. – DhavalR Jan 30 '14 at 06:37
  • @DhavalR , see my edited answer. Printing from left-top corner should be supported by your printer. To have more clarity see the answer of the question I have linked. – Junaith Jan 30 '14 at 06:55
  • That means there is no way to print outside the max rectangle. Then what should I do to print stickers (to be used on Invitation cards). The stickers on the sheet are very near to the top edge. And I am using laser printer. – DhavalR Jan 30 '14 at 11:46
  • @DhavalR , unless your printing device supports you can't print at the top edge. You could try setting negative margins with `OriginAtMargins` true. But most probably the print will be clipped. – Junaith Jan 30 '14 at 12:29