cas*_*las 10 c# pdf android filestream xamarin
我Xamarin.Android
最近一直在努力.我需要使用pdf生成器通过电子邮件发送报告.
我遇到过以下博客.我真的不知道要放什么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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑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);
Run Code Online (Sandbox Code Playgroud)
首先确保Manifest
您允许的 文件WriteExternalStorage
要在外部存储上读取或写入文件,您的应用必须获取READ_EXTERNAL_STORAGE或WRITE_EXTERNAL_STORAGE系统权限.例如:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
这会将名为"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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6504 次 |
最近记录: |