Search code examples
.netvb.netprintingsystem.printing

Printing with custom margins in .NET


I am printing labels through a Dymo printer using vb.Net and the standard .NET printing routines, my app has to support any type of label printer though. Because the dymo driver does not have accessible margins in control panel, and control panel is restricted for most of my users anyway, I am setting the page margins using the application.

I replace the margins in the PrintDocument using the ones set from the application, which is fine, but I also have some code for calculating the text size and format based on the width of the printable area. I can never get the printable area to change size? All the margin setting does is shunt the entire Graphic down and right based on the top and left margin, the printable area and VisibleClipBounds in the graphics object never change? When this happens, the text just flows off the right and bottom of the page, so it never obeys the right and bottom margins at all.

Is this normal behaviour? Do I have to do a bunch more processing in the application to calculate the printable area myself based on my margins and the initial page size?

'Code to setup PrintDocument
    MyDocument.DefaultPageSettings.Margins = New Margins(Printers.LabelPrinter.MarginLeft / 0.254, Printers.LabelPrinter.MarginRight / 0.254, Printers.LabelPrinter.MarginTop / 0.254, Printers.LabelPrinter.MarginBottom / 0.254)
    MyDocument.OriginAtMargins = True


'Code that runs during the MyDocument.Print event
    width = e.Graphics.VisibleClipBounds.Width
    height = e.Graphics.VisibleClipBounds.Height
    'Calculate best fit text size here and update graphics object

Solved it. My routine was just using the Graphics Object, not the full eventargs for the Print event.

The print event contains the MarginBounds property which returns a rectangle of the size after the margins have been applied, and so works perfectly.


Solution

  • Solved it. My routine was just using the Graphics Object, not the full eventargs for the Print event.

    The print event contains the MarginBounds property which returns a rectangle of the size after the margins have been applied, and so works perfectly.

    (Added this as answer as did not have enough cred to do this at the time, and hope this will help people who see this question as unanswered).