0

I was going through the following link:

https://www.syncfusion.com/kb/10697/how-to-convert-xaml-to-pdf-in-xamarin-using-c

This code works fine as long as what I need from the xaml fits in the screen without scrolling. But i want my all element in a ScrollView to be save in my pdf. I tried out the code in the Xamarin forums link but was not able to get it to work https://forums.xamarin.com/discussion/146465/how-to-convert-the-all-content-in-scroll-view-to-bitmap-in-xamarin-forum

this is my code

private async void button_Clicked(object sender, EventArgs e)
    {
        
        MemoryStream stream = new MemoryStream();
        //Create a new PDF document
        using (PdfDocument document = new PdfDocument())
        {
            //Add page to the PDF document.
            PdfPage page = document.Pages.Add();

            //Create graphics instance.
            PdfGraphics graphics = page.Graphics;

            Stream imageStream = null;

            if (Device.RuntimePlatform == Device.Android )
            {
                byte[] data;
                data = await Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().CaptureAsync();

                imageStream = new MemoryStream(data);

            }
            else
            {
                imageStream = new MemoryStream(DependencyService.Get<ISave>().CaptureAsync().Result);
            }

            //Load the image
            PdfBitmap image = new PdfBitmap(imageStream);

            //Draw the image
            graphics.DrawImage(image, 0, 0, page.GetClientSize().Width, page.GetClientSize().Height);

            //Save the document into memory stream
            document.Save(stream);

        }
        stream.Position = 0;
        if (Device.RuntimePlatform == Device.Android )
        {  
            Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("XAMLtoPDF.pdf", "application/pdf", stream);
        }
        else
        {
            Xamarin.Forms.DependencyService.Get<ISave>().Save("XAMLtoPDF.pdf", "application/pdf", stream);
        }
    
    }

and to save

public void Save(string fileName, String contentType, MemoryStream s)
    {
        string root = null;
        if (Android.OS.Environment.IsExternalStorageEmulated)
        {
            root = Android.OS.Environment.ExternalStorageDirectory.ToString();
        }
        else
            root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        //root = "/interner Speicher/Download/";

        Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion");
        myDir.Mkdir();

        Java.IO.File file = new Java.IO.File(myDir, fileName);

        if (file.Exists()) file.Delete();

        try
        {
            FileOutputStream outs = new FileOutputStream(file);
            outs.Write(s.ToArray());

            outs.Flush();
            outs.Close();

        }
        catch (Exception e)
        {

        }
        if (file.Exists())
        {
            Android.Net.Uri path = Android.Net.Uri.FromFile(file);
            string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
            string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
            Intent intent = new Intent(Intent.ActionView);
            intent.SetDataAndType(path, mimeType);
            Android.App.Application.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
        }
    }

and to converted the current view to bitmap in Xamarin Forms

public System.Threading.Tasks.Task<byte[]> CaptureAsync()
    {
        //            scrollversion
        var activity = Forms.Context as Activity;
        ViewGroup content = activity.FindViewById<ViewGroup>(Android.Resource.Id.Content);
        ViewGroup frameLayout = (ViewGroup)content.GetChildAt(0);
        ViewGroup relativeLayout = (ViewGroup)frameLayout.GetChildAt(0);
        ViewGroup platFormRenderer = (ViewGroup)relativeLayout.GetChildAt(0);
        ViewGroup myNavigationPageRenderer = (ViewGroup)platFormRenderer.GetChildAt(0);
        ViewGroup pageRenderer = (ViewGroup)myNavigationPageRenderer.GetChildAt(0);
        ViewGroup scrollViewRenderer = (ViewGroup)pageRenderer.GetChildAt(0);// --> scrollViewRenderer

        //Adjust this to find your own scrollViewRenderer
        Android.Widget.ScrollView z = scrollViewRenderer as Android.Widget.ScrollView;
        z.SetBackgroundColor(Android.Graphics.Color.White);
        int totalHeight = z.GetChildAt(0).Height;
        int totalWidth = z.GetChildAt(0).Width;
        Bitmap bitmap = getBitmapFromView(z, (int)totalHeight, (int)totalWidth);
        byte[] bitmapData;
        using (var stream = new MemoryStream())
        {
            bitmap.Compress(Bitmap.CompressFormat.Jpeg, 0, stream);
            bitmapData = stream.ToArray();
        }


        return Task.FromResult(bitmapData);
    }

    public Bitmap getBitmapFromView(Android.Views.View view, int totalHeight, int totalWidth)
    {
        Bitmap returnedBitmap = Bitmap.CreateBitmap(totalWidth, totalHeight, Bitmap.Config.Argb8888);
        Canvas canvas = new Canvas(returnedBitmap);
        Drawable bgDrawable = view.Background;
        if (bgDrawable != null)
            bgDrawable.Draw(canvas);
        else
            canvas.DrawColor(Android.Graphics.Color.White);
        canvas.Save();
        view.Draw(canvas);
        canvas.Restore();
        return returnedBitmap;
    }

In the code above in Part z.SetBackgroundColor(Android.Graphics.Color.White); i am getteing System.NullReferenceException: 'Object reference not set to an instance of an object.' my z value is null Am I missing something? Thank you in advance!

  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Cfun Jun 24 '21 at 11:19
  • you are trying to cast a ViewGroup to a ScrollView – Jason Jun 24 '21 at 11:47
  • Well ScrollView is a ViewGroup, but perhaps it is not the correct ViewGroup you are casting. – Cheesebaron Jun 24 '21 at 13:03
  • i am beginner in xamarin Form. Can you tell me, how I can convert ViewGroup to ScrollView? or is there any alternative solution for my problem? – SepidehDev Jun 24 '21 at 19:08
  • @SepidehDev Add break point at `ViewGroup scrollViewRenderer = (ViewGroup)pageRenderer.GetChildAt(0);` to check whether it is null or what type is it? – Cherry Bu - MSFT Jun 25 '21 at 06:13
  • No, scrollViewRenderer is not null. the base value of scrollViewRenderer is : {Xamarin.Forms.Platform.Android.VisualElementRenderer} – SepidehDev Jun 25 '21 at 12:24
  • @SepidehDev As jason said that you can not cast `scrollViewRenderer` to scrollview, you can try to cast `scrollViewRenderer` to `Xamarin.Forms.View`. – Cherry Bu - MSFT Jun 28 '21 at 06:37
  • @CherryBu-MSFT You are right. But to convert all the Scrollview content to Bitmap, i need to have the Scrollview. I also tried the suggested code in the link below. But it still did not work https://stackoverflow.com/questions/8738448/how-to-convert-all-content-in-a-scrollview-to-a-bitmap have you any idea to how can i get my Scrollview. Thank you in advance! – SepidehDev Jun 30 '21 at 10:52
  • @CherryBu-MSFT in Android native – SepidehDev Jul 01 '21 at 10:26
  • @SepidehDev Maybe your can provide one simple sample at gtihub, I will test it. – Cherry Bu - MSFT Jul 02 '21 at 09:12
  • @CherryBu-MSFT i pull my code in githup. this is the link https://github.com/sepideDev/Formulare – SepidehDev Jul 05 '21 at 15:20
  • @SepidehDev From your code, I see that you don't send your current contentpage to `CaptureAsync` by parameter, so you can not get your xaml view in android project. About convert Xamarin.Forms UI into PDF, you can take a look PdfSharp.Xamarin.Forms, some sample that you can search. – Cherry Bu - MSFT Jul 06 '21 at 06:28

0 Answers0