簡體   English   中英

Xamarin.Forms UWP-具有分頁支持的打印Webview

[英]Xamarin.Forms UWP - Print Webview with pagination support

我正在研究基於Xamarin.Forms的項目,試圖通過分頁打印Webview內容。

我已經引用了以下鏈接: 如何在Windows Store應用程序中打印WebView內容?

但是不幸的是,這種方法不適用於Xamarin.Forms,因為上面鏈接中演示的方法是使用webviewbrush填充矩形(windows形狀)(矩形和webviewbrush都是UWP的依賴於平台的控件)。 問題是我們不能使用webviewbrush繪制矩形(Xamarin Forms形狀)。

作為解決方法,我執行了以下操作:

  • 在xamarin表單PCL項目中創建了boxview
  • 在UWP項目中為此BoxView創建了一個渲染器(這將為我們提供Windows矩形形狀),然后我將該矩形形狀放入PCL項目的App.cs類的公共靜態屬性之一中,以使其可用於Webviewrenderer.cs類用webviewbrush填充此矩形。
  • 我可以從UWP項目的webviewrenderer.cs類訪問它,但問題是打印機對話框顯示空白頁。
  • 分頁工作正常,如上面的堆棧溢出鏈接所示,但是所有頁面都為空。

顯然問題出在矩形上。 因為如果創建本地UWP項目,並且打印機對話框也顯示網頁,則相同的邏輯就可以正常工作。

任何幫助將非常感激。

提前致謝!

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

我已經根據您的過程實現了基本的打印功能。 我把GetWebViewBrush在方法webviewrenderer 不幸的是,同樣的問題發生在我這邊。

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從未設置過值,因此我為customWebView創建了一個新的Name屬性。

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方法中的以下代碼設置本機控件( Windows.UI.Xaml.Controls.WebView )的Name屬性。

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

令人驚訝的是,該頁面不再為空。 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM