2017-04-03 75 views
1

如何在XAML/XAML.cs中打印整個tabitem或其中的一部分?打印一個標籤項目

我使用下面的代碼,並能夠打印tabitem,但我想控制大小和預覽。如果我使用橫向頁面格式,它仍然不打印整個頁面,但會截斷其中的一部分。

TabItem Header = 「Stars

XAML

<Button Margin=" 5,5,5,5" Grid.Row="3" x:Name="PrintOilTab" 
     Click="PrintOilTab_Click" Content="Print" FontSize="10"/> 

XAML.CS

private void PrintOilTab_Click(object sender, RoutedEventArgs e) 
{ 
    System.Windows.Controls.PrintDialog Printdlg = 
     new System.Windows.Controls.PrintDialog(); 

    if ((bool)Printdlg.ShowDialog().GetValueOrDefault()) 
    { 
     CompleteOilLimitDiagram.Measure(
      new Size(Printdlg.PrintableAreaWidth,    
        Printdlg.PrintableAreaHeight)); 
     Printdlg.PrintVisual(CompleteOilLimitDiagram, "Stars"); 
    } 
} 

回答

1

我從來沒有好運氣PrintVisual()。我一直必須生成FixedDocument,然後使用PrintDocument()

該代碼被設計來打印ImageSource,但我認爲它可以很容易地適於通過將控制到FixedDocument打印任何控制:

using System.Windows.Documents; 

    public async void SendToPrinter() 
    { 
     if (ImageSource == null || Image == null) 
      return; 

     var printDialog = new PrintDialog(); 

     bool? result = printDialog.ShowDialog(); 
     if (!result.Value) 
      return; 

     FixedDocument doc = GenerateFixedDocument(ImageSource, printDialog); 
     printDialog.PrintDocument(doc.DocumentPaginator, ""); 

    } 

    private FixedDocument GenerateFixedDocument(ImageSource imageSource, PrintDialog dialog) 
    { 
     var fixedPage = new FixedPage(); 
     var pageContent = new PageContent(); 
     var document = new FixedDocument(); 

     bool landscape = imageSource.Width > imageSource.Height; 

     if (landscape) 
     { 
      fixedPage.Height = dialog.PrintableAreaWidth; 
      fixedPage.Width = dialog.PrintableAreaHeight; 
      dialog.PrintTicket.PageOrientation = PageOrientation.Landscape; 
     } 
     else 
     { 
      fixedPage.Height = dialog.PrintableAreaHeight; 
      fixedPage.Width = dialog.PrintableAreaWidth; 
      dialog.PrintTicket.PageOrientation = PageOrientation.Portrait; 
     } 

     var imageControl = new System.Windows.Controls.Image {Source = ImageSource,}; 
     imageControl.Width = fixedPage.Width; 
     imageControl.Height = fixedPage.Height; 

     pageContent.Width = fixedPage.Width; 
     pageContent.Height = fixedPage.Height; 

     document.Pages.Add(pageContent); 
     pageContent.Child = fixedPage; 

     // You'd have to do something different here: possibly just add your 
     // tab to the fixedPage.Children collection instead. 
     fixedPage.Children.Add(imageControl); 

     return document; 
    }