简体   繁体   English

Xamarin Android 将 webview 保存为 pdf

[英]Xamarin Android save webview in pdf

I'm developing an app in xamarin for android.我正在为 android 开发一个 xamarin 应用程序。

The objective is for the user to fill a document and save it as a PDF.目标是让用户填写文档并将其保存为 PDF。

I have tried this process:我试过这个过程:

HTML TO PDF HTML转PDF

I have designed a cshtml file, that contains the same structure as the document, with the input that the user inserted.我设计了一个 cshtml 文件,它包含与文档相同的结构,以及用户插入的输入。 So far so good, it looks good in the webview.到目前为止一切顺利,它在 webview 中看起来不错。 I now wish to convert this to PDF but I can't seem to find a way to convert it.我现在希望将其转换为 PDF,但我似乎找不到将其转换的方法。

Is there a way to convert CSHTML to PDF, or somehow convert the content of the webview to PDF?有没有办法将 CSHTML 转换为 PDF,或者以某种方式将 webview 的内容转换为 PDF?

I have tried an extension called "iTextSharp" to create and manipulate PDF's (my attempt to convert html to a PDF file but the styles and images used in html aren't being applied).我尝试了一个名为“iTextSharp”的扩展来创建和操作 PDF(我尝试将 html 转换为 PDF 文件,但未应用 html 中使用的样式和图像)。

The final objective is to create a PDF file that has the same structure as an HTML Page that I own.最终目标是创建一个与我拥有的 HTML 页面具有相同结构的 PDF 文件。

Any way I can accomplish this?我有什么办法可以做到这一点? Ideas are most welcome想法是最受欢迎的

I could convert the whole WebView page content to pdf with below code.我可以使用以下代码将整个WebView页面内容转换为 pdf。 Hope it may help you.希望它可以帮助你。 However, I have just tried this in Simulator.但是,我刚刚在模拟器中尝试过。

[Activity(Label = "DroidWebview", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
    WebView myWebView;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        myWebView = FindViewById<WebView>(Resource.Id.webview);
        myWebView.Settings.JavaScriptEnabled = true;
        myWebView.SetWebViewClient(new MyWebViewClient());

        myWebView.LoadUrl("https://stackoverflow.com/questions/46978983/xamarin-android-save-webview-in-pdf");

        Button myPrintButton = FindViewById<Button>(Resource.Id.myPrintButton);
        myPrintButton.Click += (sender, e) =>
        {
            var printManager = (PrintManager)GetSystemService(PrintService);
            string fileName = "MyPrint_" + Guid.NewGuid().ToString() + ".pdf";
            var printAdapter = myWebView.CreatePrintDocumentAdapter(fileName);
            PrintJob printJob = printManager.Print("MyPrintJob", printAdapter, new PrintAttributes.Builder().Build());
        };
    }
}

public class MyWebViewClient : WebViewClient
{
    public override bool ShouldOverrideUrlLoading(WebView view, string url)
    {
        view.LoadUrl(url);
        return false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM