You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xamarin跨平台结合Web API中显示二进制PDF文件

How to Display PDF Files from Web API in Xamarin

First, let's finish your Web API endpoint to properly return the PDF binary data. Your RetrieveFile method needs to fetch the record, validate it exists, and send the bytes with the correct headers:

[Route("api/DiagnosticDetail/RetrieveFile/{id}")]
[HttpGet]
public HttpResponseMessage RetrieveFile(int id)
{
    var fileRecord = db.DiagnosticDetailModels.FirstOrDefault(d => d.id == id);
    
    if (fileRecord == null)
    {
        return Request.CreateResponse(HttpStatusCode.NotFound, "File not found");
    }

    var response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new ByteArrayContent(fileRecord.filecontent);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    // Use "inline" to display directly, "attachment" to trigger download
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
    {
        FileName = fileRecord.reportname
    };

    return response;
}

This ensures the API returns the PDF data with the right content type so clients can interpret it correctly.


Option 1: Display PDF Using WebView (Built-in, No External Libraries)

WebView works natively on both Android and iOS for basic PDF rendering. You'll just need to handle temporary file storage for Android.

Step 1: Create a Helper Method to Fetch PDF Bytes

Add this method to your Xamarin project to pull the PDF from your API:

using System.Net.Http;
using System.IO;

public async Task<byte[]> GetPdfBytesFromApi(int fileId)
{
    using (var httpClient = new HttpClient())
    {
        var apiUrl = $"https://your-api-domain/api/DiagnosticDetail/RetrieveFile/{fileId}";
        var response = await httpClient.GetAsync(apiUrl);
        
        if (response.IsSuccessStatusCode)
        {
            return await response.Content.ReadAsByteArrayAsync();
        }
        else
        {
            throw new Exception($"API request failed: {response.StatusCode}");
        }
    }
}

Step 2: Load PDF into WebView on Android

Save the PDF bytes to the app's cache directory (avoids external storage permissions) and load it into WebView:

using Android.Webkit;
using System.IO;

private async void LoadPdfInWebView(int fileId)
{
    try
    {
        var pdfBytes = await GetPdfBytesFromApi(fileId);
        var tempFilePath = Path.Combine(CacheDir.AbsolutePath, "temp_pdf.pdf");
        
        File.WriteAllBytes(tempFilePath, pdfBytes);
        
        var webView = FindViewById<WebView>(Resource.Id.pdfWebView);
        webView.Settings.JavaScriptEnabled = true;
        webView.LoadUrl($"file://{tempFilePath}");
    }
    catch (Exception ex)
    {
        // Show error alert or log details
        Console.WriteLine($"Error loading PDF: {ex.Message}");
    }
}

Step 3: Load PDF into WebView on iOS

iOS WKWebView can load PDF bytes directly or from a temporary file. Here's the file approach:

using WebKit;
using System.IO;

private async void LoadPdfInWebView(int fileId)
{
    try
    {
        var pdfBytes = await GetPdfBytesFromApi(fileId);
        var tempFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "temp_pdf.pdf");
        
        File.WriteAllBytes(tempFilePath, pdfBytes);
        
        var webView = new WKWebView(View.Bounds, new WKWebViewConfiguration());
        View.AddSubview(webView);
        
        var fileUrl = new NSUrl(tempFilePath, false);
        webView.LoadFileUrl(fileUrl, fileUrl);
    }
    catch (Exception ex)
    {
        // Handle error
        Console.WriteLine($"Error loading PDF: {ex.Message}");
    }
}

Option 2: Use a Dedicated PDF Viewer Plugin (Better Features)

For advanced functionality like zoom, page navigation, and annotations, use a plugin like Syncfusion.Xamarin.PdfViewer (they offer a free community license for small projects).

Step 1: Install the NuGet Package

Install Syncfusion.Xamarin.PdfViewer via NuGet Package Manager.

Step 2: Add the Viewer to Your XAML

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:syncfusion="clr-namespace:Syncfusion.SfPdfViewer.XForms;assembly=Syncfusion.SfPdfViewer.XForms"
             x:Class="YourApp.PdfViewerPage">
    <syncfusion:SfPdfViewer x:Name="pdfViewerControl" />
</ContentPage>

Step 3: Load the PDF from API

private async void LoadPdf(int fileId)
{
    try
    {
        var pdfBytes = await GetPdfBytesFromApi(fileId);
        pdfViewerControl.LoadDocument(pdfBytes);
    }
    catch (Exception ex)
    {
        await DisplayAlert("Error", $"Failed to load PDF: {ex.Message}", "OK");
    }
}

Key Notes:

  • Permissions: On Android, using the app's cache directory avoids needing external storage permissions. If you use external storage, request READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE.
  • Security: Make sure your API endpoint is secured (e.g., with JWT authentication) to protect sensitive PDF files.
  • Memory: For large PDFs, dispose of temporary files and unload the viewer when it's no longer needed to avoid memory leaks.

内容的提问来源于stack exchange,提问作者waqas waqas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:22:43