using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using InABox.Core; using InABox.Mobile; using Syncfusion.SfPdfViewer.XForms; using Xamarin.Forms; using Xamarin.Forms.Xaml; using XF.Material.Forms.UI.Dialogs; namespace PRS.Mobile { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class DocumentViewer { public static async Task Load(Guid id) { DocumentModel docmodel = new DocumentModel(App.Data, () => new Filter(x => x.ID).IsEqualTo(id), () => CoreRepository.CacheFileName($"{id}") ); using (await MaterialDialog.Instance.LoadingDialogAsync("Loading Document")) docmodel.Refresh(true); if (docmodel.Any()) { var editor = new DocumentViewer(); editor.Load(docmodel.First().FileName, docmodel.First().Data); return editor; } else await MaterialDialog.Instance.AlertAsync("Cannot Load Document!"); return null; } public void Load(String filename, byte[] data) { _filename.Text = filename; _filename.IsVisible = ShowFileName && !String.IsNullOrWhiteSpace(filename); if (data?.Any() == true) { if (filename.ToUpper().EndsWith(".PDF")) LoadPDF(data); else LoadImage(data); _noimage.IsVisible = false; } else { _noimage.IsVisible = true; _pdf.IsVisible = false; _image.IsVisible = false; } } private bool _showfilename = false; public bool ShowFileName { get => _showfilename; set { _showfilename = value; _filename.IsVisible = value && !String.IsNullOrWhiteSpace(_filename.Text); } } public DocumentViewer() { InitializeComponent(); BindingContext = this; if (Device.RuntimePlatform.Equals(Device.Android)) { var service = DependencyService.Get(); var renderer = service?.AlternatePdfRenderer; _pdf.CustomPdfRenderer = renderer; } } private byte[]? _data; public event EventHandler DocumentLoaded; private void LoadPDF(byte[] data) { _data = data; _image.IsVisible = false; MemoryStream memoryStream = new MemoryStream(data); _pdf.LoadDocument(memoryStream); _pdf.IsVisible = true; DocumentLoaded?.Invoke(this, EventArgs.Empty); } private void LoadImage(byte[] data) { _data = data; _pdf.IsVisible = false; _image.Source = ImageSource.FromStream(() => new MemoryStream(data)); _image.IsVisible = true; DocumentLoaded?.Invoke(this, EventArgs.Empty); } public byte[] GetThumbnail() { if (_data?.Any() != true) return new byte[] { }; if (_image.IsVisible) { return MobileUtils.ImageTools.CreateThumbnail(_data, 256, 256); } else if (_pdf.IsVisible) { var stream = _pdf.ExportAsImage(0) as MemoryStream; if (stream?.Length > 0) { var imgdata = stream.ToArray(); return MobileUtils.ImageTools.CreateThumbnail(imgdata, 256, 256); } } return new byte[] { }; } } }