Xamarin.Android pdf generator

后端 未结 2 1956
青春惊慌失措
青春惊慌失措 2021-02-14 06:51

I have been working on Xamarin.Android recently. I need to use pdf generator to send a report via email.

I have been came across to the following blog. I d

2条回答
  •  被撕碎了的回忆
    2021-02-14 07:39

    First make sure in the Manifest file you allow WriteExternalStorage

    In order to read or write files on the external storage, your app must acquire the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE system permissions. For example:

     
         
     
    

    FileStream constructor (one of the many) accepts string for a path and FileMode so an example solution would be.

      var directory = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory, "pdf").ToString();
      if (!Directory.Exists(directory))
      {
          Directory.CreateDirectory(directory);
      }
    
      var path = Path.Combine(directory, "myTestFile.pdf");
      var fs = new FileStream(path, FileMode.Create);
    

    This creates folder called "pdf" in to external storage and then creates the pdf file. Additional code could be included to check if file exists before creating it..

    Edit: complete example, just tested on my device:

            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);
    
                // Set our view from the "main" layout resource
                SetContentView(Resource.Layout.Main);
    
                var directory = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory, "pdf").ToString();
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
    
                var path = Path.Combine(directory, "myTestFile.pdf");
    
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
    
                var fs = new FileStream(path, FileMode.Create);
                Document document = new Document(PageSize.A4, 25, 25, 30, 30);
                PdfWriter writer = PdfWriter.GetInstance(document, fs);
                document.Open();
                document.Add(new Paragraph("Hello World"));
                document.Close();
                writer.Close();
                fs.Close();
    
                Java.IO.File file = new Java.IO.File(path);
                Intent intent = new Intent(Intent.ActionView);
                intent.SetDataAndType(Android.Net.Uri.FromFile(file), "application/pdf");
                StartActivity(intent);
            }
    

提交回复
热议问题