VideoStudy/VideoStudy.Native/Services/WindowsPdfSaver.cs

39 lines
1.2 KiB
C#

using VideoStudy.Shared;
using Windows.Storage;
using Windows.Storage.Pickers;
using WinRT.Interop;
namespace VideoStudy.Native.Services;
public class WindowsPdfSaver : IPdfSaver
{
public async Task<string?> SavePdfAsync(byte[] pdfData, string suggestedFileName)
{
var savePicker = new FileSavePicker
{
SuggestedStartLocation = PickerLocationId.Downloads,
SuggestedFileName = suggestedFileName
};
savePicker.FileTypeChoices.Add("PDF", [".pdf"]);
// Get the window handle for the picker
var window = Application.Current?.Windows.FirstOrDefault();
var mauiWindow = window?.Handler?.PlatformView;
if (mauiWindow is Microsoft.UI.Xaml.Window winuiWindow)
{
var hwnd = WindowNative.GetWindowHandle(winuiWindow);
InitializeWithWindow.Initialize(savePicker, hwnd);
}
var file = await savePicker.PickSaveFileAsync();
if (file == null) return null;
await FileIO.WriteBytesAsync(file, pdfData);
// Open the PDF after saving
await Windows.System.Launcher.LaunchFileAsync(file);
return file.Path;
}
}