Xamarin.Android pdf generator

后端 未结 2 1949
青春惊慌失措
青春惊慌失措 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:35

    If you are doing cross platform development its bettor to genarate PDF in commen place. please see the below code on PDF creation in PCL using iTEXT sharp. iTEXT PDF

    here i have use PCL storage library for IO access which is very useful for PCL. you can find more info here PCL Storage

    1. Add PCL storage library to your PCL project and as well as the relevant platforms using nuget.

    Install-Package PCLStorage

    1. Add iTEXT PDF to your PCL project

      Install-Package iTextSharp

    2. use below code in PCL project

      public class PdfHelper
      {
        public async Task PCLGenaratePdf(string path)
        {
          IFolder rootFolder = await FileSystem.Current.GetFolderFromPathAsync(path);
          IFolder folder = await rootFolder.CreateFolderAsync("folder", CreationCollisionOption.OpenIfExists);
          IFile file = await folder.CreateFileAsync("file.pdf", CreationCollisionOption.ReplaceExisting);
      
          using (var fs = await file.OpenAsync(FileAccess.ReadAndWrite))
          {
              var document = new Document(PageSize.A4, 25, 25, 30, 30);
              PdfWriter writer = PdfWriter.GetInstance(document, fs);
              document.Open();
              document.Add(new Paragraph("heloo everyone"));
              document.Close();
              writer.Close();
          }
       }
      
       public async Task<string> PCLReadFile(string path)
       {
          IFile file = await FileSystem.Current.GetFileFromPathAsync(path);
          return file.Path;
       }
      }
      
    3. use the below code in android project

    TO Generate PDF

        private async void Genarate(string path)
        {
            var creator = new PdfHelper();
            await creator.PCLGenaratePdf(path);
        }
    

    Read PDF using intent

        private async void ReadPDF(object sender, EventArgs e)
         {
            String sdCardPath = Environment.ExternalStorageDirectory.AbsolutePath;
            String fullpath = Path.Combine(sdCardPath, "folder/" + "file.pdf");
    
            var creator = new PdfHelper();
            string filePath = await creator.PCLReadFile(fullpath);
    
            Uri pdfPath = Uri.FromFile(new File(filePath));
            Intent intent = new Intent(Intent.ActionView);
            intent.SetDataAndType(pdfPath, "application/pdf");
            intent.SetFlags(ActivityFlags.NewTask);
            Application.Context.StartActivity(intent);
        }
    
    1. write ios code to generate and get PDF.

    Note: sometimes there can be error on system.drawings and system.security once you compile the PCL project. solution is using the iTEXT sharp source code remove all the system.drawings and system.security dependencies.

    Happy Coding.

    0 讨论(0)
  • 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:

     <manifest ...>
         <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     </manifest>
    

    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);
            }
    
    0 讨论(0)
提交回复
热议问题