Paolo Ardissone
Paolo Ardissone

Reputation: 847

Print multiple canvas WPF?

Today I'm working with WPF! My app is almost finished, except for the last feature. I have created a graphic element which represents a label like the ones you can see under the goods in a supermarket shelf. Print one of them is easy, using PrintDialog.PrintVisual(myVisualItem,"description");. Now, I have to print a series of these labels, using PintVisual() in a loop, prints every element in a separate document! There's no overload of PrintVisual() which accepts an IEnumerable of visual item. I've seen online that i should paginate these elements, but I cannot find a way to do it What can I do? Thanks!

Upvotes: 0

Views: 951

Answers (2)

bwing
bwing

Reputation: 781

If you believe they will all fit on one page, you could put them in a StackPanel with Orientation = Vertical. Then print the stack panel.

var panel = new StackPanel() { Orientation = Orientation.Vertical };
panel.Children.Add(canvas1);
panel.Children.Add(canvas2);
panel.UpdateLayout();
var dlg = new PrintDialog();
dlg.PrintVisual(panel, "description");

Upvotes: 0

Iqon
Iqon

Reputation: 1992

You could combine all canvas you got into one big canvas and then print this one.

Here is some sample code how to concat multiple canvas into one big one:

public Canvas CombineCanvases(params Canvas[] canvases)
{
   // Force each canvas to update its desired size
   foreach (var canvas in canvases) { canvas.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); }

   var result = new Canvas
   {
      Height = canvases.Sum(x => x.DesiredSize.Height), // add all heights to get needed height
      Width = canvases.Max(x => x.DesiredSize.Width)  // find required width 
   };

   var pos = 0d;
   foreach (var canvas in canvases)
   {
      Canvas.SetLeft(canvas, 0);
      Canvas.SetTop(canvas, pos); // position element at this pixel count
      pos += canvas.DesiredSize.Height; // and increment it

      result.Children.Add(canvas);
   }

   return result;
}

You need to pass all canvas's you want to print and print the result.

var c1 = new Canvas
{
   Width = 100,
   Height = 100,
   Children = { new TextBlock { Text = "Canvas 1" } }
};
var c2 = new Canvas
{
   Width = 100,
   Height = 100,
   Children = { new TextBlock { Text = "Canvas 2" } }
};

var canvas = CombineCanvases(c1, c2);
// print canvas here

Pagination would be if you check how many labels fit on one page and then not concat all canvas into one huge on, but just take as many as are needed to fill one page.

Then print the page and repeat this until all Labels were printed. This is called pagination.

Upvotes: 2

Related Questions