【问题标题】:Xamarin.Android pdf generatorXamarin.Android pdf 生成器
【发布时间】:2016-01-10 11:54:41
【问题描述】:

我最近一直在研究Xamarin.Android。我需要使用 pdf 生成器通过电子邮件发送报告。

我遇到过以下blog。我真的不知道在FileStream fs = new FileStream (???????); 中放什么。除此之外,我还想在屏幕上打开或查看该pdf。

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

编辑 1:

用下面的代码打开生成的Pdf,但是显示pdf格式无效。

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

【问题讨论】:

  • 嘿,您是否设法在 Xamarin Android 中使用 ITextSharp 生成 PDF?我试过使用ITextSharp,但没有运气。它生成异常说无法加载程序集 System.Drawing.dll。我猜这是因为ITextSharp 在其中使用 System.Drawing 而 Xamarin.Android 不是(基于this link)

标签: c# android pdf xamarin filestream


【解决方案1】:

首先确保在Manifest 文件中您允许WriteExternalStorage

为了在外部存储上读取或写入文件,您的应用必须 获取 READ_EXTERNAL_STORAGE 或 WRITE_EXTERNAL_STORAGE 系统 权限。例如:

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

FileStream 构造函数(其中之一)接受字符串作为路径,FileMode 是一个示例解决方案。

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

这会在外部存储中创建名为“pdf”的文件夹,然后创建 pdf 文件。可以包含其他代码以在创建文件之前检查文件是否存在..

编辑:完整示例,刚刚在我的设备上测试过:

        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】:

如果您正在进行跨平台开发,那么它的赌注是在共同的地方生成 PDF。请参阅下面关于使用 iTEXT sharp 在 PCL 中创建 PDF 的代码。 iTEXT PDF

这里我使用 PCL 存储库进行 IO 访问,这对 PCL 非常有用。 你可以在这里找到更多信息PCL Storage

  1. 将 PCL 存储库添加到您的 PCL 项目以及使用 nuget 的相关平台。

安装包 PCLStorage

  1. 将 iTEXT PDF 添加到您的 PCL 项目中

    安装包 iTextSharp

  2. 在 PCL 项目中使用以下代码

    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. 在android项目中使用下面的代码

生成 PDF

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

使用意图阅读 PDF

    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. 编写ios代码生成并获取PDF。

注意:有时在编译 PCL 项目后,system.drawings 和 system.security 可能会出现错误。解决方案是使用iTEXT犀利的源码去掉所有system.drawings和system.security的依赖。

快乐编码。

【讨论】:

    猜你喜欢
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 2016-12-03
    • 1970-01-01
    • 2022-07-16
    • 2011-05-29
    • 1970-01-01
    相关资源
    最近更新 更多