如何在C# UWP Win 10中打印WebView内容

5

我搜索了如何将一个简单的WebView打印为:

 <WebView x:Name="MyWebView" Source="http://www.stackoverflow.com" />

我尝试了很多方法,例如:

如何在Windows Store应用中打印WebView内容?

这个解决方案可惜没有更新到Windows 10 UWP应用程序,但是,我转换了它,以便过时的函数可以工作,这导致了另一个问题。

为了打印,我使用了一些来自示例(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后台代码:

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;
        }
    }
}

你能否分享一下你已经完成的代码示例? - Nico Zhu
1个回答

4
针对您的需求,我简化了PrintHelper官方示例,并创建了一个简单的示例,通过使用WebViewBrush来打印WebView。
<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>

当WebView加载完成后,您可以将使用WebViewBrush填充的MyWebViewRectangle添加到printDoc中。
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,您可以参考。

1
谢谢您的回答,但它是否处理WebView的溢出问题呢?例如,页面非常长,我们必须滚动,因此打印预览将调整并创建多个页面以适合全部内容。 - Emy Blacksmith
对于多个页面,您可以参考此方法 - Nico Zhu
我测试了你的解决方案:首先,你使用的是11月更新版(10240)作为最低版本,而我的是创作者更新版(15063)。其次,你在github上的解决方案无法正常工作,因为它会呈现一个空白页面,我无法找出原因(对于名为PrintAliment的项目)。不过还是谢谢你的回答。 - Emy Blacksmith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接