0
votes

I try to print a letter for making a simple letter merge application. But I'm struggled on how to set the printer options within WPF and .NET 4.

Here's my code:

    private void button_Print_Click(object sender, RoutedEventArgs e)
    {
        PrintDialog pd = new PrintDialog();
        if (pd.ShowDialog() == true)
        {
            pd.PrintTicket.PageOrientation = PageOrientation.Landscape;
            pd.PrintTicket.PageMediaSize = new PageMediaSize(865, 612);
            pd.PrintVisual(canvas_Letter, "Letter Canvas");
        }
    }

In the PrintDialog I choose the MP tray, which is feeded with letters of C5 size. Its printing my WPF, but not with the correct positions of the elements. Its like the Margin detects the paper size of a A4 paper. Even if I choose paper size of C5 in the PrintDialog, the print is still out of bounds.

Any idea how to fit the size of C5 to my visual print? It seems like my pd.PrintTicket.PageMediaSize set to 865px width and 612px height doesn't work :/

1

1 Answers

0
votes

Not sure if I'm understanding your question right. Do you want to print out your canvas_Letter adjusted to the selected paper size? In this case I think you have to use the 'PrintCapabilities' and further you have to call Measure() and Arrange() on your canvas_Letter.

Something like this:

PrintDialog pd = new PrintDialog();
if (pd.ShowDialog() == true)
{
   Rect printableArea = GetPrintableArea(printDlg);

   // I'm using here a viewbox for easily adjust the canvas_Letter to the desired size
   Viewbox viewBox = new Viewbox { Child = canvas_Letter };
   viewBox.Measure(printableArea.Size);
   viewBox.Arrange(printableArea);
   printDlg.PrintVisual(viewBox, "Letter Canvas");
}

private static Rect GetPrintableArea(PrintDialog printDialog)
{
   PrintCapabilities cap;
   try
   {
      cap = printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket);
   }
   catch (PrintQueueException)
   {
      return Rect.Empty;
   }

   if (cap.PageImageableArea == null)
   {
      return Rect.Empty;
   }

   var leftMargin = cap.OrientedPageMediaWidth.HasValue ? (cap.OrientedPageMediaWidth.Value - cap.PageImageableArea.ExtentWidth) / 2 : 0;
   var topMargin = cap.OrientedPageMediaHeight.HasValue ? (cap.OrientedPageMediaHeight.Value - cap.PageImageableArea.ExtentHeight) / 2 : 0;
   var width = cap.PageImageableArea.ExtentWidth;
   var height = cap.PageImageableArea.ExtentHeight;
   return new Rect(leftMargin, topMargin, width, height);
}