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
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
Install-Package PCLStorage
Add iTEXT PDF to your PCL project
Install-Package iTextSharp
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 PCLReadFile(string path)
{
IFile file = await FileSystem.Current.GetFileFromPathAsync(path);
return file.Path;
}
}
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);
}
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.