2017-09-13 143 views
1

我正在開發基於Xamarin.Forms的項目,嘗試打印帶分頁的webview內容。Xamarin.Forms UWP - 打印Webview和分頁支持

我已經提到下面的鏈接已經: How do I print WebView content in a Windows Store App?

但不幸的是這種方式是不工作與Xamarin.Forms因爲在上面的鏈接證明的方式使用webviewbrush(是通過填充矩形(窗口形狀)矩形和webviewbrush都是與UWP平臺相關的控件)。問題是我們無法使用webviewbrush繪製矩形(Xamarin Forms形狀)。

作爲一種變通方法,我做了以下內容:

  • 創造xamarin形成BoxView中的PCL項目
  • 創造了這個BoxView中的UWP項目渲染器(這會給我們的窗口矩形),然後我確實將這個矩形形狀放入PCL項目的App.cs類中的一個公共靜態屬性中,以使其可用於Webviewrenderer.cs類,以便使用webviewbrush填充此矩形。
  • 我可以從UWP項目的webviewrenderer.cs類訪問它,但問題是打印機對話框顯示空白頁面。
  • 如上面的堆棧溢出鏈接所示,分頁工作正常,但所有頁面都是空的。

顯然問題是矩形。因爲如果我創建本機UWP項目並且打印機對話框也顯示網頁,則相同的邏輯工作正常。

任何幫助將不勝感激。

在此先感謝!

回答

0

如上面的堆棧溢出鏈接所示,分頁工作正常,但所有頁面都是空的。

我已經根據您的過程實現了基本打印功能。我在webviewrenderer中放置了GetWebViewBrush方法。不幸的是,我身邊也出現了同樣的問題。

async Task<WebViewBrush> GetWebViewBrush(Windows.UI.Xaml.Controls.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 
    { 
     Stretch = Stretch.Uniform, 
     SourceName = webView.Name 
    }; 
    // _Brush.SetSource(webView); 

    _Brush.Redraw(); 

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

當我調試運行,我發現webView.Name從未設定值,所以我提出一個新的Name屬性爲customWebView。

public static readonly BindableProperty NameProperty = BindableProperty.Create(
propertyName: "Name", 
returnType: typeof(string), 
declaringType: typeof(MyWebView), 
defaultValue: default(string)); 

    public string Name 
    { 
     get { return (string)GetValue(NameProperty); } 
     set { SetValue(NameProperty, value); } 
    } 

} 

並設置天然對照()與OnElementChanged方法如下代碼的Name屬性。

if (e.NewElement != null) 
{ 
    Control.Name = (Element as MyWebView).Name; 
    Control.NavigationCompleted += Control_NavigationCompleted; 
} 

令人驚訝的是,頁面不再是空的。 enter image description here

+0

太棒了!這就像一個魅力!非常感謝你:) –

+0

@清道夫:謝謝,我已經完成了! –