Xamarin.Android pdf generator

北慕城南 提交于 2021-02-06 20:43:25

问题


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 do not really know what to put in the FileStream fs = new FileStream (???????); In addition to that, I would like to open or see that pdf on the screen.

using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.IO;
using XamiTextSharpLGPL;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp;



namespace PDFAapp
{
    [Activity (Label = "PDFAapp", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        int count = 1;

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            FileStream fs = new FileStream (???????);
            Document document = new Document (PageSize.A4, 25, 25, 30, 30);
            PdfWriter writer = PdfWriter.GetInstance (document, fs);
            document.Add(new Paragraph("Hello World"));
            document.Close();
            writer.Close();
            fs.Close();
        }
    }
}

EDIT 1:

Having the following code to open the generated Pdf, but it shows pdf format is not valid.

Java.IO.File file = new Java.IO.File(filePath);
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(Android.Net.Uri.FromFile(file), "application/pdf");
StartActivity(intent);

回答1:


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);
        }



回答2:


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.



来源:https://stackoverflow.com/questions/33090681/xamarin-android-pdf-generator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!