PDFRenderer.iOS.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using InABox.Core;
  2. namespace InABox.Avalonia.Platform.iOS;
  3. public class iOS_PdfRenderer : IPdfRenderer
  4. {
  5. public Logger? Logger { get; set; }
  6. public byte[]? PdfToImage(byte[]? pdf, int pageIndex, int dpi)
  7. {
  8. float scale = 2F;
  9. // Step 1: Load the PDF document from byte array
  10. using var data = NSData.FromArray(pdf);
  11. using var provider = new CGDataProvider(data);
  12. using var pdfDoc = new CGPDFDocument(provider);
  13. // Validate page index
  14. int pageCount = (int)pdfDoc.Pages;
  15. if (pageIndex < 0 || pageIndex >= pageCount)
  16. throw new ArgumentOutOfRangeException(nameof(pageIndex), "Invalid PDF page index.");
  17. using var page = pdfDoc.GetPage(pageIndex + 1); // Pages are 1-indexed
  18. var pageRect = page.GetBoxRect(CGPDFBox.Media);
  19. var scaledSize = new CGSize(pageRect.Width * scale, pageRect.Height * scale);
  20. // Step 2: Render the page to an image
  21. UIGraphics.BeginImageContextWithOptions(scaledSize, false, 1.0f);
  22. using (var context = UIGraphics.GetCurrentContext())
  23. {
  24. context.SaveState();
  25. context.TranslateCTM(0, scaledSize.Height);
  26. context.ScaleCTM(scale, -scale); // Flip and scale
  27. context.DrawPDFPage(page);
  28. context.RestoreState();
  29. }
  30. using var image = UIGraphics.GetImageFromCurrentImageContext();
  31. UIGraphics.EndImageContext();
  32. // Step 3: Convert UIImage to PNG byte array
  33. using var pngData = image.AsPNG();
  34. return pngData.ToArray();
  35. }
  36. public Task<byte[]?> PdfToImageAsync(byte[]? pdf, int page, int dpi)
  37. {
  38. var tcs = new TaskCompletionSource<byte[]>();
  39. UIApplication.SharedApplication.BeginInvokeOnMainThread(() =>
  40. {
  41. try
  42. {
  43. var result = PdfToImage(pdf, page, dpi);
  44. tcs.SetResult(result);
  45. }
  46. catch (Exception ex)
  47. {
  48. tcs.SetException(ex);
  49. }
  50. });
  51. return tcs.Task;
  52. }
  53. public byte[]? ImageToPdf(byte[]? image)
  54. {
  55. return null;
  56. }
  57. public Task<byte[]?> ImageToPdfAsync(byte[]? image)
  58. {
  59. var tcs = new TaskCompletionSource<byte[]>();
  60. UIApplication.SharedApplication.BeginInvokeOnMainThread(() =>
  61. {
  62. try
  63. {
  64. var result = ImageToPdf(image);
  65. tcs.SetResult(result);
  66. }
  67. catch (Exception ex)
  68. {
  69. tcs.SetException(ex);
  70. }
  71. });
  72. return tcs.Task;
  73. }
  74. }