Kūrosh
Kūrosh

Reputation: 452

printing a wpf usercontrol on custom paper size

i have a wpf usercontrol with bellow properties:

  1. Width=170mm(642px)
  2. Height=85mm(321px)

i want to print that on a paper with above size(Width=170mm and Height=85mm)

my problem is:when i print it,some items print out of the paper,i think the paper size if Letter by default,if it is correct,how can i change it to above Width and Height?

my code is bellow:

        var p = new myUserControl();
        var pDoc = new System.Windows.Controls.PrintDialog();

        if (pDoc.ShowDialog().Value)
        {
            pDoc.PrintVisual(p, "MyPrint");
        }

maybe something like this needs(this is a settings for System.Windows.Forms.PrintDialog but i use System.Windows.Controls.PrintDialog that it has no PrinterSettings property):

    var printerSettings = new PrinterSettings();
    var labelPaperSize = new PaperSize { RawKind = (int)PaperKind.A6, Height = 148, Width = 105 };
    printerSettings.DefaultPageSettings.PaperSize = labelPaperSize;
    var labelPaperSource = new PaperSource { RawKind = (int)PaperSourceKind.Manual };
    printerSettings.DefaultPageSettings.PaperSource = labelPaperSource;
    if (printerSettings.CanDuplex)
    {
        printerSettings.Duplex = Duplex.Default;
    }

Upvotes: 0

Views: 2533

Answers (1)

user4561879
user4561879

Reputation:

In WPF 1 unit = 1/96 of inch, so you can calculate your size in inches using this formula

you can set printDlg.PrintTicket.PageMediaSize to the size of the Paper and then transform your window to print in that area as below:

private void _print()
 {
      PrintDialog printDlg = new System.Windows.Controls.PrintDialog();

       PrintTicket pt = printDlg.PrintTicket;
       Double printableWidth = pt.PageMediaSize.Width.Value;
       Double printableHeight = pt.PageMediaSize.Height.Value;

       Double xScale = (printableWidth - xMargin * 2) / printableWidth;
       Double yScale = (printableHeight - yMargin * 2) / printableHeight;


        this.Transform = new MatrixTransform(xScale, 0, 0, yScale, xMargin, yMargin);


    //now print the visual to printer to fit on the one page.
     printDlg.PrintVisual(this, "Print Page");
}

Upvotes: 1

Related Questions