Created
June 1, 2023 09:59
-
-
Save DarkIrata/5cc4b4091233c7b6dffb7e4874e813dc to your computer and use it in GitHub Desktop.
Maui Android PDF Renderer example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace TestApp.Platforms.Android.Services | |
{ | |
internal class PDFRenderService : IPDFRenderService | |
{ | |
private AppCompatActivity activity; | |
public PDFRenderService(AppCompatActivity activity) | |
{ | |
this.activity = activity; | |
} | |
public byte[] RenderPdf(string filePath, int pageNum, int left, int top, int right, int bottom, int width) | |
{ | |
//var fileStreamPath = this.activity.GetFileStreamPath(filePath); | |
var fileStreamPath = new Java.IO.File(filePath); | |
var renderer = new PdfRenderer(ParcelFileDescriptor.Open(fileStreamPath, ParcelFileMode.ReadOnly)); | |
//var screenWidth = Resources.System.DisplayMetrics.WidthPixels; | |
var page = renderer.OpenPage(pageNum); | |
// create bitmap at appropriate size | |
var ratio = (float)page.Height / page.Width; | |
var newHeight = width * ratio; | |
var bitmap = Bitmap.CreateBitmap(width, (int)newHeight, Bitmap.Config.Argb8888); | |
// render PDF page to bitmap | |
var rect = new androidGraphics.Rect(left, top, right, bottom); | |
page.Render(bitmap, rect, null, PdfRenderMode.ForPrint); | |
page.Close(); | |
renderer.Close(); | |
using (var ms = new MemoryStream()) | |
{ | |
if (bitmap.Compress(Bitmap.CompressFormat.Png, 100, ms)) | |
{ | |
return ms.ToArray(); | |
} | |
} | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment