1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- using InABox.Core;
- namespace InABox.Avalonia.Platform.iOS;
- public class iOS_PdfRenderer : IPdfRenderer
- {
- public Logger? Logger { get; set; }
- public byte[]? PdfToImage(byte[]? pdf, int pageIndex, int dpi)
- {
- float scale = 2F;
- // Step 1: Load the PDF document from byte array
- using var data = NSData.FromArray(pdf);
- using var provider = new CGDataProvider(data);
- using var pdfDoc = new CGPDFDocument(provider);
- // Validate page index
- int pageCount = (int)pdfDoc.Pages;
- if (pageIndex < 0 || pageIndex >= pageCount)
- throw new ArgumentOutOfRangeException(nameof(pageIndex), "Invalid PDF page index.");
- using var page = pdfDoc.GetPage(pageIndex + 1); // Pages are 1-indexed
- var pageRect = page.GetBoxRect(CGPDFBox.Media);
- var scaledSize = new CGSize(pageRect.Width * scale, pageRect.Height * scale);
- // Step 2: Render the page to an image
- UIGraphics.BeginImageContextWithOptions(scaledSize, false, 1.0f);
- using (var context = UIGraphics.GetCurrentContext())
- {
- context.SaveState();
- context.TranslateCTM(0, scaledSize.Height);
- context.ScaleCTM(scale, -scale); // Flip and scale
- context.DrawPDFPage(page);
- context.RestoreState();
- }
- using var image = UIGraphics.GetImageFromCurrentImageContext();
- UIGraphics.EndImageContext();
- // Step 3: Convert UIImage to PNG byte array
- using var pngData = image.AsPNG();
- return pngData.ToArray();
- }
- public Task<byte[]?> PdfToImageAsync(byte[]? pdf, int page, int dpi)
- {
- var tcs = new TaskCompletionSource<byte[]>();
- UIApplication.SharedApplication.BeginInvokeOnMainThread(() =>
- {
- try
- {
- var result = PdfToImage(pdf, page, dpi);
- tcs.SetResult(result);
- }
- catch (Exception ex)
- {
- tcs.SetException(ex);
- }
- });
- return tcs.Task;
- }
- public byte[]? ImageToPdf(byte[]? image)
- {
- return null;
- }
- public Task<byte[]?> ImageToPdfAsync(byte[]? image)
- {
- var tcs = new TaskCompletionSource<byte[]>();
- UIApplication.SharedApplication.BeginInvokeOnMainThread(() =>
- {
- try
- {
- var result = ImageToPdf(image);
- tcs.SetResult(result);
- }
- catch (Exception ex)
- {
- tcs.SetException(ex);
- }
- });
- return tcs.Task;
- }
- }
|