项目介绍
用于在Android、iOS、MacOS和Windows平台显示PDF文件的库。
| .NET MAUI | .NET 9 | .NET 10 |
|---|
| Platform | Android | iOS | MacOS | Windows |
|---|---|---|---|---|
| 支持 | ✅ | ✅ | ✅ | ✅ |
项目地址
https://github.com/vitalii-vov/Maui.PDFView
使用方法
1、安装
通过Nuget进行安装:
Install-Package Vitvov.Maui.PDFView
2、使用
在MauiProgram中添加.UseMauiPdfView()。
csharp
using Maui.PDFView;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseMauiPdfView(); // <- Write this
return builder.Build();
}
}
在XMAL中添加PdfView
<ContentPage
x:Class="Example.Business.UI.Pages.MainPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:pdf="clr-namespace:Maui.PDFView;assembly=Maui.PDFView">
<!--
IsHorizontal --- display PDF horizontally
Uri --- path to the file on the device
MaxZoom --- max zoom level
PageIndex --- set the current page by index
PageChangedCommand --- event of changing the current page
-->
<pdf:PdfView
IsHorizontal="{Binding IsHorizontal}"
Uri="{Binding PdfSource}"
MaxZoom="4"
PageIndex="{Binding PageInex}"
PageChangedCommand="{Binding PageChangedCommand}">
</pdf:PdfView>
</ContentPage>
在ViewModel中添加PsfSource
csharp
internal partial class MainPageViewModel : ObservableObject
{
[ObservableProperty] private string? _pdfSource;
[RelayCommand] private void ChangeUri()
{
try
{
// See the example project to understand how to work with paths.
PdfSource = "/path/to/file.pdf";
// You can set the Uri property to null to clear the component.
//PdfSource = null;
}
catch(Exception ex)
{
// handle exceptions
}
}
}
3、个性化
PdfView 组件仅支持文件路径。这是因为在原生平台组件主要通过文件路径进行操作,若在组件内注解处理不同PDF数据源将极大增加代码复杂度。
因此,无论你的PDF数据以何种形式呈现------无论是字节数组、流、资源、还是URL------你都必须始终提供文件路径。
为简化与这些数据源的交互,该组件提供了实现PdfSource接口的辅助类:
- AssetPdfSource
- ByteArrayPdfSource
- FilePdfSource
- HttpPdfSource
使用PdfSource的例子:
[RelayCommand] private async Task UploadUri()
{
var source = new HttpPdfSource("https://www.adobe.com/support/products/enterprise/knowledgecenter/media/c4611_sample_explain.pdf");
PdfSource = await source.GetFilePathAsync();
}
[RelayCommand] private async Task UploadAsset()
{
var source = new AssetPdfSource("Example.Resources.PDF.pdf2.pdf");
PdfSource = await source.GetFilePathAsync();
}
你还可以创建自己的IPdfSource接口实现来满足你的特定需求。