2014-04-22 46 views
1

我正在尝试实现WPF打印功能。只要用户不想在一页上打印更多的内容,它就会工作。我的应用程序使用户能够在运行时创建xaml。现在我想让他打印他创建的xaml控件。wpf打印多页xaml控件

我检查了所有xaml控件的总高度,由pageheight和ceiled分开,因此我知道需要打印多少页。

接下来,我为每个页面创建一个FrameworkElements列表(请参阅下面的逻辑),并将每个List(每个List代表一个页面)存储在一个数组中。

最后,我想创建一个包含每个页面的预览,并使用户能够打印所有页面。为了做到这一点,我不得不把页面放在一起到一个文件,但我不知道如何。请看看我的代码:

Package package = Package.Open("test.xps", FileMode.Create); 

     // Create new xps document based on the package opened 

     XpsDocument doc = new XpsDocument(package); 

     // Create an instance of XpsDocumentWriter for the document 

     XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc); 

     // Write the canvas (as Visual) to the document 

     double height = element.ActualHeight; 
     double width = element.ActualWidth; 
     System.Windows.Controls.PrintDialog printDlg = new System.Windows.Controls.PrintDialog(); 
     Size pageSize = new Size(printDlg.PrintableAreaWidth, printDlg.PrintableAreaHeight); 
     int pageCount = (int)Math.Ceiling(height/pageSize.Height); 


     if (pageSize.Height < height) { 
      var grid = element as Grid; 
      var children = grid.Children; 
      List<FrameworkElement>[] pages = new List<FrameworkElement>[pageCount-1]; 
      int i = 0; 
      double currentHeight = 0; 

      foreach (FrameworkElement c in children) { 


       currentHeight += c.RenderSize.Height; 


       if (currentHeight < pageSize.Height) { 

        pages[i] = new List<FrameworkElement>(); 
        pages[i].Add(c); 
       } 
       else { 
        i++; 
        currentHeight = 0; 
        pages[i] = new List<FrameworkElement>(); 
        pages[i].Add(c); 
       } 
      } 
      for (int j = 0; j < pageCount; j++) { 
       var collator = writer.CreateVisualsCollator(); 
       collator.BeginBatchWrite(); 
       foreach (FrameworkElement c in pages[j]) { 


        collator.Write(c); 


       } 
       collator.EndBatchWrite(); 
      } 
     } 


     doc.Close(); 

     package.Close(); 

     string filename = @"C:\Users\rzimmermann\Documents\Visual Studio 2012\Projects\MvvmLightPrintFunction\MvvmLightPrintFunction\bin\Debug\test.xps"; 

     DocumentViewer viewer = new DocumentViewer(); 

     doc = new XpsDocument(filename, FileAccess.Read); 

     viewer.Document = doc.GetFixedDocumentSequence(); 

     Window ShowWindow = new Window(); 

     ShowWindow.Width = 400; 

     ShowWindow.Height = 300; 

     ShowWindow.Content = viewer; 

     ShowWindow.Show(); 

非常感谢。

+0

自从我做了它已经太久了,但正如我记得为每个页面创建一个FixedPage http://msdn.microsoft.com/en-us/library/system.windows.documents.fixedpage.aspx。 – kenny

回答