public void ToPdf(TaskCompletionSource <ToFileResult> taskCompletionSource, string html, string fileName, PageSize pageSize, PageMargin margin) { var externalPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath; using (var dir = new Java.IO.File(externalPath)) using (var file = new Java.IO.File(dir + "/" + fileName + ".pdf")) { if (!dir.Exists()) { dir.Mkdir(); } if (file.Exists()) { file.Delete(); } var webView = new Android.Webkit.WebView(Android.App.Application.Context); webView.Settings.JavaScriptEnabled = true; #pragma warning disable CS0618 // Type or member is obsolete webView.DrawingCacheEnabled = true; #pragma warning restore CS0618 // Type or member is obsolete webView.SetLayerType(LayerType.Software, null); //webView.Layout(0, 0, (int)((size.Width - 0.5) * 72), (int)((size.Height - 0.5) * 72)); webView.Layout(0, 0, (int)System.Math.Ceiling(pageSize.Width), (int)System.Math.Ceiling(pageSize.Height)); webView.LoadData(html, "text/html; charset=utf-8", "UTF-8"); webView.SetWebViewClient(new WebViewCallBack(taskCompletionSource, fileName, pageSize, margin, OnPageFinished)); } }
public void ToPng(TaskCompletionSource <ToFileResult> taskCompletionSource, string html, string fileName, int width) { //var size = new Size(8.5, 11); //var externalPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath; //using (var dir = new Java.IO.File(externalPath)) //using (var file = new Java.IO.File(dir + "/" + fileName + ".png")) //{ // if (!dir.Exists()) // dir.Mkdir(); // if (file.Exists()) // file.Delete(); var webView = new Android.Webkit.WebView(Android.App.Application.Context); webView.Settings.JavaScriptEnabled = true; #pragma warning disable CS0618 // Type or member is obsolete webView.DrawingCacheEnabled = true; #pragma warning restore CS0618 // Type or member is obsolete webView.SetLayerType(LayerType.Software, null); //webView.Layout(0, 0, (int)((size.Width - 0.5) * 72), (int)((size.Height - 0.5) * 72)); webView.Layout(0, 0, width, width); webView.SetWebViewClient(new WebViewCallBack(taskCompletionSource, fileName, new PageSize { Width = width }, null, OnPageFinished)); webView.LoadData(html, "text/html; charset=utf-8", "UTF-8"); //} }
public async Task <string> ConvertHtmlToPDF(string html, string fileName) { var dir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Download/"); var file = new Java.IO.File(dir + "/" + fileName + ".pdf"); if (!dir.Exists()) { dir.Mkdirs(); } int x = 0; while (file.Exists()) { x++; file = new Java.IO.File(dir + "/" + fileName + "(" + x + ")" + ".pdf"); } var webpage = new Android.Webkit.WebView(MainActivity.Instance); //var windowManager = MainActivity.Instance.GetSystemService(Android.Content.Context.WindowService); //DisplayMetrics outMetrics = new DisplayMetrics(); //windowManager.DefaultDisplay.GetMetrics(outMetrics); //int widthPixels = outMetrics.WidthPixels; //int heightPixels = outMetrics.HeightPixels; //int width = widthPixels; //int height = heightPixels; int width = 2102; int height = 2937; webpage.Layout(0, 0, width, height); var client = new WebViewCallBack(file.ToString()); var tokenSource = new CancellationTokenSource(); var task = Task.Run(() => { if (tokenSource.Token.IsCancellationRequested) { return; } while (true) { if (tokenSource.Token.IsCancellationRequested) { break; } } }, tokenSource.Token); client.OnPageLoadFinished += (s, e) => { tokenSource.Cancel(); }; webpage.SetWebViewClient(client); webpage.LoadDataWithBaseURL("", html, "text/html", "UTF-8", null); await task; return(file.ToString()); }
async Task OnPageFinished(Android.Webkit.WebView view, string fileName, PageSize pageSize, PageMargin margin, TaskCompletionSource <ToFileResult> taskCompletionSource) { /* * var widthString = await view.EvaluateJavaScriptAsync("document.documentElement.offsetWidth"); * var width = (int)System.Math.Ceiling(double.Parse(widthString.ToString())); * * var heightString = await view.EvaluateJavaScriptAsync("document.documentElement.offsetHeight"); * var height = (int)System.Math.Ceiling(double.Parse(heightString.ToString())); * var contentHeight = view.ContentHeight; */ //var imageView = new WebViewImage(view, fileName, taskCompletionSource); int specWidth = MeasureSpecFactory.MakeMeasureSpec((int)(pageSize.Width), MeasureSpecMode.Exactly); int specHeight = MeasureSpecFactory.MakeMeasureSpec(0, MeasureSpecMode.Unspecified); view.Measure(specWidth, specHeight); var height = view.ContentHeight; view.Layout(0, 0, view.MeasuredWidth, height); //imageView.Layout(0, 0, width, height); if (height < 1) { var heightString = await view.EvaluateJavaScriptAsync("document.documentElement.offsetHeight"); height = (int)System.Math.Ceiling(double.Parse(heightString.ToString())); } var width = view.MeasuredWidth; if (width < 1) { var widthString = await view.EvaluateJavaScriptAsync("document.documentElement.offsetWidth"); width = (int)System.Math.Ceiling(double.Parse(widthString.ToString())); } if (height < 1 || width < 1) { taskCompletionSource.SetResult(new ToFileResult(true, "WebView width or height is zero.")); return; } await Task.Delay(50); //using (var _dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments)) //using (var _dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads)) using (var _dir = Forms9Patch.Droid.Settings.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads)) { if (!_dir.Exists()) { _dir.Mkdir(); } //var path = _dir.Path + "/" + fileName + ".png"; //var path = System.IO.Path.Combine(_dir.AbsolutePath, Android.OS.Environment.DirectoryDownloads, fileName + ".png"); //var file = new Java.IO.File(path); var file = new Java.IO.File(_dir, fileName + ".png"); int iter = 0; while (file.Exists()) { file.Dispose(); iter++; //path = System.IO.Path.Combine(_dir.AbsolutePath, Android.OS.Environment.DirectoryDownloads, fileName + "_" + iter.ToString("D4") + ".png"); //file = new Java.IO.File(path); file = new Java.IO.File(_dir, fileName + "_" + iter.ToString("D4") + ".png"); } //file.CreateNewFile(); file = Java.IO.File.CreateTempFile(fileName + "_" + iter.ToString("D4"), "png", _dir); var path = file.AbsolutePath; using (var stream = new FileStream(file.Path, FileMode.Create, System.IO.FileAccess.Write)) { if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Honeycomb) { await Task.Delay(1000); //using (var bitmap = Bitmap.CreateBitmap(System.Math.Max(view.MeasuredWidth, view.ContentWidth()), view.MeasuredHeight, Bitmap.Config.Argb8888)) using (var bitmap = Bitmap.CreateBitmap(view.MeasuredWidth, height, Bitmap.Config.Argb8888)) { using (var canvas = new Canvas(bitmap)) { if (view.Background != null) { view.Background.Draw(canvas); } else { canvas.DrawColor(Android.Graphics.Color.White); } view.SetClipChildren(false); view.SetClipToPadding(false); view.SetClipToOutline(false); await Task.Delay(50); view.Draw(canvas); await Task.Delay(50); bitmap.Compress(Bitmap.CompressFormat.Png, 80, stream); } } } else { await Task.Delay(1000); #pragma warning disable CS0618 // Type or member is obsolete using (var bitmap = Bitmap.CreateBitmap(view.DrawingCache)) #pragma warning restore CS0618 // Type or member is obsolete { bitmap.Compress(Bitmap.CompressFormat.Png, 80, stream); } } stream.Flush(); stream.Close(); /* * if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Q) * { * // You can add more columns.. Complete list of columns can be found at * // https://developer.android.com/reference/android/provider/MediaStore.Downloads * var contentValues = new ContentValues(); * contentValues.Put(Android.Provider.MediaStore.DownloadColumns.Title, System.IO.Path.GetFileName(path)); * contentValues.Put(Android.Provider.MediaStore.DownloadColumns.DisplayName, System.IO.Path.GetFileName(path)); * contentValues.Put(Android.Provider.MediaStore.DownloadColumns.MimeType, "image/png"); * contentValues.Put(Android.Provider.MediaStore.DownloadColumns.Size, File.ReadAllBytes(path).Length); * * // If you downloaded to a specific folder inside "Downloads" folder * //contentValues.Put(Android.Provider.MediaStore.DownloadColumns.RelativePath, Android.OS.Environment.DirectoryDownloads + File.separator + "Temp"); * * // Insert into the database * ContentResolver database = Forms9Patch.Droid.Settings.Context.ContentResolver; // getContentResolver(); * database.Insert(Android.Provider.MediaStore.Downloads.ExternalContentUri, contentValues); * } * else * { * // notify download manager! * var downloadManager = Android.App.DownloadManager.FromContext(Android.App.Application.Context); #pragma warning disable CS0618 // Type or member is obsolete * downloadManager.AddCompletedDownload( * System.IO.Path.GetFileName(path), * System.IO.Path.GetFileName(path), * true, "image/png", path, * File.ReadAllBytes(path).Length, true); #pragma warning restore CS0618 // Type or member is obsolete * } */ taskCompletionSource.SetResult(new ToFileResult(false, path)); view.Dispose(); } file.Dispose(); } }
async Task OnPageFinished(Android.Webkit.WebView view, string fileName, TaskCompletionSource <ToFileResult> taskCompletionSource) { var widthString = await view.EvaluateJavaScriptAsync("document.documentElement.offsetWidth"); var width = double.Parse(widthString.ToString()); var heightString = await view.EvaluateJavaScriptAsync("document.documentElement.offsetHeight"); var height = double.Parse(heightString.ToString()); int specWidth = MeasureSpecFactory.MakeMeasureSpec((int)(width * Display.Scale), MeasureSpecMode.Exactly); int specHeight = MeasureSpecFactory.MakeMeasureSpec((int)(height * Display.Scale), MeasureSpecMode.Exactly); view.Measure(specWidth, specHeight); view.Layout(0, 0, view.MeasuredWidth, view.MeasuredHeight); await Task.Delay(50); using (var _dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments)) { if (!_dir.Exists()) { _dir.Mkdir(); } var path = _dir.Path + "/" + fileName + ".png"; using (var file = new Java.IO.File(path)) { if (!file.Exists()) { file.CreateNewFile(); } using (var stream = new FileStream(file.Path, FileMode.Create, System.IO.FileAccess.Write)) { if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Honeycomb) { await Task.Delay(1000); using (var bitmap = Bitmap.CreateBitmap(System.Math.Max(view.MeasuredWidth, view.ContentWidth()), view.MeasuredHeight, Bitmap.Config.Argb8888)) { using (var canvas = new Canvas(bitmap)) { if (view.Background != null) { view.Background.Draw(canvas); } else { canvas.DrawColor(Android.Graphics.Color.White); } view.SetClipChildren(false); view.SetClipToPadding(false); view.SetClipToOutline(false); await Task.Delay(50); view.Draw(canvas); await Task.Delay(50); bitmap.Compress(Bitmap.CompressFormat.Png, 80, stream); } } } else { await Task.Delay(1000); #pragma warning disable CS0618 // Type or member is obsolete using (var bitmap = Bitmap.CreateBitmap(view.DrawingCache)) #pragma warning restore CS0618 // Type or member is obsolete { bitmap.Compress(Bitmap.CompressFormat.Png, 80, stream); } } stream.Flush(); stream.Close(); taskCompletionSource.SetResult(new ToFileResult(false, path)); view.Dispose(); } } } }
async Task OnPageFinished(Android.Webkit.WebView view, string fileName, PageSize pageSize, PageMargin margin, TaskCompletionSource <ToFileResult> taskCompletionSource) { /* * var widthString = await view.EvaluateJavaScriptAsync("document.documentElement.offsetWidth"); * var width = (int)System.Math.Ceiling(double.Parse(widthString.ToString())); * * var heightString = await view.EvaluateJavaScriptAsync("document.documentElement.offsetHeight"); * var height = (int)System.Math.Ceiling(double.Parse(heightString.ToString())); * var contentHeight = view.ContentHeight; */ //var imageView = new WebViewImage(view, fileName, taskCompletionSource); int specWidth = MeasureSpecFactory.MakeMeasureSpec((int)(pageSize.Width), MeasureSpecMode.Exactly); int specHeight = MeasureSpecFactory.MakeMeasureSpec(0, MeasureSpecMode.Unspecified); view.Measure(specWidth, specHeight); var height = view.ContentHeight; view.Layout(0, 0, view.MeasuredWidth, height); //imageView.Layout(0, 0, width, height); if (height < 1 || view.MeasuredWidth < 1) { taskCompletionSource.SetResult(new ToFileResult(true, "WebView width or height is zero.")); return; } await Task.Delay(50); //using (var _dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments)) using (var _dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads)) { if (!_dir.Exists()) { _dir.Mkdir(); } //var path = _dir.Path + "/" + fileName + ".png"; var path = System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads, fileName + ".png"); var file = new Java.IO.File(path); int iter = 0; while (file.Exists()) { file.Dispose(); iter++; path = System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads, fileName + "_" + iter.ToString("D3") + ".png"); file = new Java.IO.File(path); } file.CreateNewFile(); using (var stream = new FileStream(file.Path, FileMode.Create, System.IO.FileAccess.Write)) { if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Honeycomb) { await Task.Delay(1000); //using (var bitmap = Bitmap.CreateBitmap(System.Math.Max(view.MeasuredWidth, view.ContentWidth()), view.MeasuredHeight, Bitmap.Config.Argb8888)) using (var bitmap = Bitmap.CreateBitmap(view.MeasuredWidth, height, Bitmap.Config.Argb8888)) { using (var canvas = new Canvas(bitmap)) { if (view.Background != null) { view.Background.Draw(canvas); } else { canvas.DrawColor(Android.Graphics.Color.White); } view.SetClipChildren(false); view.SetClipToPadding(false); view.SetClipToOutline(false); await Task.Delay(50); view.Draw(canvas); await Task.Delay(50); bitmap.Compress(Bitmap.CompressFormat.Png, 80, stream); } } } else { await Task.Delay(1000); #pragma warning disable CS0618 // Type or member is obsolete using (var bitmap = Bitmap.CreateBitmap(view.DrawingCache)) #pragma warning restore CS0618 // Type or member is obsolete { bitmap.Compress(Bitmap.CompressFormat.Png, 80, stream); } } stream.Flush(); stream.Close(); // notify download manager! var downloadManager = Android.App.DownloadManager.FromContext(Android.App.Application.Context); downloadManager.AddCompletedDownload( System.IO.Path.GetFileName(path), System.IO.Path.GetFileName(path), true, "image/png", path, File.ReadAllBytes(path).Length, true); taskCompletionSource.SetResult(new ToFileResult(false, path)); view.Dispose(); } file.Dispose(); } }