如何使用pdfjs xamarin表单从url显示pdf

时间:2018-05-03 20:48:40

标签: xamarin xamarin.forms

我曾与pdfjs合作,并且可以正常使用本地存储pdf,但我有另一个问题:我需要显示来自WEB API的pdf,因为我已经存储了我需要的pdf二进制数据显示??这是我的代码

public pdfjsPage(string url)
{
    InitializeComponent();

    var localPath = string.Empty;

    if (Device.RuntimePlatform == Device.Android)
    {
        var dependency = DependencyService.Get<ILocalFileProvider>();

        if (dependency == null)
        {
            DisplayAlert("Error loading PDF", "Computer says no", "OK");
            return;
        }

        var fileName = Guid.NewGuid().ToString();

        // Download PDF locally for viewing
        using (var httpClient = new HttpClient())
        {
            var pdfStream = Task.Run(() => httpClient.GetStreamAsync(url)).Result;

            localPath =
                Task.Run(() => dependency.SaveFileToDisk(pdfStream, $"{fileName}.pdf")).Result;
        }

        if (string.IsNullOrWhiteSpace(localPath))
        {
            DisplayAlert("Error loading PDF", "Computer says no", "OK");
            return;
        }
    }

    if (Device.RuntimePlatform == Device.Android)
        PdfView.Source = $"file:///android_asset/pdfjs/web/viewer.html?file={WebUtility.UrlEncode(localPath)}";
    else
        PdfView.Source = url;
}

这适用于本地pdf,但我有WEB API网址,我需要在线获取pdf。

这是我检索它的链接:http://veezo2007pkk.somee.com/api/DiagnosticDetail/RetrieveFile/1

1 个答案:

答案 0 :(得分:0)

将PDF保存到设备后,将路径传递给意图。

//Example
var fileName = "/storage/emulated/0/yourPDF.pdf"
Uri pdfPath = Uri.FromFile(new File(fileName));
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(pdfPath, "application/pdf");
intent.SetFlags(ActivityFlags.NewTask);                    
Android.App.Application.Context.StartActivity(intent);