2017-09-27 7 views
2

인쇄 않는다 슬프게도 윈도우 10 UWP 애플 리케이션을 위해 업데이트되지 않았지만 obsoletes 함수가 작동하여 다른 문제를 일으킬 수 있도록 변환했습니다.어떻게 웹보기 콘텐츠 C 번호를 UWP 승리는 내가 같은 간단한 <code>WebView</code>을 인쇄하는 방법을 검색 한 10

미리보기가 필요하기 때문에 인쇄하려면 샘플의 일부 클래스를 사용했습니다 (Windows-universal-samples/Samples/Printing/cs/). 오버 플로우가 관리하지 않는

<RichTextBlock 
    x:Name="TextContent" 
    Grid.Row="1" 
    Grid.ColumnSpan="2" 
    Width="595" 
    HorizontalAlignment="Center" 
    VerticalAlignment="Top" 
    Foreground="Black" 
    IsTextSelectionEnabled="True" 
    OverflowContentTarget="{Binding ElementName=FirstLinkedContainer}"> 
     <Paragraph> 
      <InlineUIContainer> [The question XAML] 

, 그래서 WebView는 다음과 같이 볼 수 있습니다 : enter image description here 참고 : 나는 XAML 언어와 논리에 새로 온 사람 나는대로 위에서 언급 한 문제에 주어진 예제를 넣어 이것 뒤에.

가능한 방법에 대한 업데이트가 필요합니까?

편집 :

가 여기 내 PageToPrint.xaml.cs의 뒤에있는 코드이다 : 당신의 requment를 들어

using System; 
using System.Collections.Generic; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
using Windows.UI.Xaml.Media; 
using Windows.UI.Xaml.Navigation; 

namespace TestPrint 
{ 
    /// <summary> 
    /// Page content to send to the printer 
    /// </summary> 
    public sealed partial class PageToPrint : Page 
    { 
     public RichTextBlock TextContentBlock { get; set; } 

     public PageToPrint() 
     { 
      this.InitializeComponent(); 
      TextContentBlock = TextContent; 
      MyWebView.LoadCompleted += MyWebView_LoadCompletedAsync; 
     } 

     async void MyWebView_LoadCompletedAsync(object sender, NavigationEventArgs e) 
     { 
      MyWebViewRectangle.Fill = await GetWebViewBrushAsync(MyWebView); 
      MyPrintPages.ItemsSource = await GetWebPagesAsync(MyWebView, new Windows.Foundation.Size(100d, 150d)); 
      MyWebView.Visibility = Windows.UI.Xaml.Visibility.Visible; 
     } 

     async System.Threading.Tasks.Task<WebViewBrush> GetWebViewBrushAsync(WebView webView) 
     { 
      // resize width to content 
      var _OriginalWidth = webView.Width; 
      var _WidthString = await webView.InvokeScriptAsync("eval", 
       new[] { "document.body.scrollWidth.toString()" }); 
      int _ContentWidth; 
      if (!int.TryParse(_WidthString, out _ContentWidth)) 
       throw new Exception(string.Format("failure/width:{0}", _WidthString)); 
      webView.Width = _ContentWidth; 

      // resize height to content 
      var _OriginalHeight = webView.Height; 
      var _HeightString = await webView.InvokeScriptAsync("eval", 
       new[] { "document.body.scrollHeight.toString()" }); 
      int _ContentHeight; 
      if (!int.TryParse(_HeightString, out _ContentHeight)) 
       throw new Exception(string.Format("failure/height:{0}", _HeightString)); 
      webView.Height = _ContentHeight; 

      // create brush 
      var _OriginalVisibilty = webView.Visibility; 
      webView.Visibility = Windows.UI.Xaml.Visibility.Visible; 
      var _Brush = new WebViewBrush 
      { 
       SourceName = webView.Name, 
       Stretch = Stretch.Uniform 
      }; 
      _Brush.Redraw(); 

      // reset, return 
      webView.Width = _OriginalWidth; 
      webView.Height = _OriginalHeight; 
      webView.Visibility = _OriginalVisibilty; 
      return _Brush; 
     } 

     async System.Threading.Tasks.Task<IEnumerable<FrameworkElement>> GetWebPagesAsync(WebView webView, Windows.Foundation.Size page) 
     { 
      // ask the content its width 
      var _WidthString = await webView.InvokeScriptAsync("eval", 
       new[] { "document.body.scrollWidth.toString()" }); 
      int _ContentWidth; 
      if (!int.TryParse(_WidthString, out _ContentWidth)) 
       throw new Exception(string.Format("failure/width:{0}", _WidthString)); 
      webView.Width = _ContentWidth; 

      // ask the content its height 
      var _HeightString = await webView.InvokeScriptAsync("eval", 
       new[] { "document.body.scrollHeight.toString()" }); 
      int _ContentHeight; 
      if (!int.TryParse(_HeightString, out _ContentHeight)) 
       throw new Exception(string.Format("failure/height:{0}", _HeightString)); 
      webView.Height = _ContentHeight; 

      // how many pages will there be? 
      var _Scale = page.Width/_ContentWidth; 
      var _ScaledHeight = (_ContentHeight * _Scale); 
      var _PageCount = (double)_ScaledHeight/page.Height; 
      _PageCount = _PageCount + ((_PageCount > (int)_PageCount) ? 1 : 0); 

      // create the pages 
      var _Pages = new List<Windows.UI.Xaml.Shapes.Rectangle>(); 
      for (int i = 0; i < (int)_PageCount; i++) 
      { 
       var _TranslateY = -page.Height * i; 
       var _Page = new Windows.UI.Xaml.Shapes.Rectangle 
       { 
        Height = page.Height, 
        Width = page.Width, 
        Margin = new Thickness(5), 
        Tag = new TranslateTransform { Y = _TranslateY }, 
       }; 
       _Page.Loaded += async (s, e) => 
       { 
        var _Rectangle = s as Windows.UI.Xaml.Shapes.Rectangle; 
        var _Brush = await GetWebViewBrushAsync(webView); 
        _Brush.Stretch = Stretch.UniformToFill; 
        _Brush.AlignmentY = AlignmentY.Top; 
        _Brush.Transform = _Rectangle.Tag as TranslateTransform; 
        _Rectangle.Fill = _Brush; 
       }; 
       _Pages.Add(_Page); 
      } 
      return _Pages; 
     } 
    } 
} 
+0

수행 한 코드 샘플을 공유해도 되겠습니까? –

답변

1

, 나는 official samplePrintHelper을 단순화하고 사용 WebViewBrush를 통해 웹보기를 인쇄하는 간단한 샘플을 만들었습니다.

<Page.BottomAppBar> 
    <CommandBar> 
     <AppBarButton 
      x:Name="appbar_Printer" 
      Click="appbar_Printer_Click" 
      Label="printer" /> 
    </CommandBar> 
</Page.BottomAppBar> 

<Grid x:Name="PrintArea" Background="White"> 

    <Grid.ColumnDefinitions> 
     <ColumnDefinition Width="995" /> 
     <ColumnDefinition Width="300" /> 
     <ColumnDefinition Width="50"/> 

    </Grid.ColumnDefinitions> 

    <WebView Grid.Column="0" x:Name="MyWebView" Source="http://www.stackoverflow.com" HorizontalAlignment="Right" /> 
    <Rectangle Grid.Column="1" x:Name="MyWebViewRectangle" Fill="Red" /> 
    <Button Grid.Column="2" Content="Print" HorizontalAlignment="Center"/> 

</Grid> 

웹보기로드가 완료되면, 당신은 printDocWebViewBrush로 채우기 MyWebViewRectangle을 추가 할 수 있습니다.

private async void appbar_Printer_Click(object sender, RoutedEventArgs e) 
{ 
    if (printDoc != null) 
    { 
     printDoc.GetPreviewPage -= OnGetPreviewPage; 
     printDoc.Paginate -= PrintDic_Paginate; 
     printDoc.AddPages -= PrintDic_AddPages; 
    } 
    this.printDoc = new PrintDocument(); 
    printDoc.GetPreviewPage += OnGetPreviewPage; 
    printDoc.Paginate += PrintDic_Paginate; 
    printDoc.AddPages += PrintDic_AddPages; 
    bool showPrint = await PrintManager.ShowPrintUIAsync(); 
} 
private void PrintDic_AddPages(object sender, AddPagesEventArgs e) 
{ 
    Rectangle page = (Rectangle)this.FindName("MyWebViewRectangle"); 
    printDoc.AddPage(page); 
    printDoc.AddPagesComplete(); 
} 
private void PrintDic_Paginate(object sender, PaginateEventArgs e) 
{ 
    PrintTaskOptions opt = task.Options; 
    PrintTaskOptionDetails printDetailedOptions = PrintTaskOptionDetails.GetFromPrintTaskOptions(e.PrintTaskOptions); 

    printDoc.SetPreviewPageCount(1, PreviewPageCountType.Final); 
} 

enter image description here

난 당신을 참조 수 GitHub를 위해 code sample을 업로드했습니다.

+0

답변 해 주셔서 감사합니다.하지만 'WebView'의 오버플로를 관리합니까? 예를 들어 페이지가 너무 길어서 스크롤해야하므로 인쇄 미리보기에서이를 적용하여 여러 페이지를 만들어 모든 페이지에 맞 춥니 다. –

+0

여러 페이지의 경우이 [방법] (https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/Printing/cs/Scenario5Photos.xaml.cs#L456)을 참조 할 수 있습니다. –

+0

당신의 솔루션을 테스트 해 보았습니다. 첫째, 11 월 업데이트 (10240)를 최소 버전으로 사용하고 있으며, 제 제작자는 업데이트 (15063)입니다. 둘째, github에 대한 해결책이 작동하지 않습니다. 인쇄 작업이 PrintAliment라는 프로젝트에 대해 알지 못하는 몇 가지 이유 때문에 빈 페이지가 렌더링됩니다. 그래도 고마워. –