Sei sulla pagina 1di 3

using System; using Android.App; using Android.Content; using Android.

Runtime; u
sing Android.Views; using Android.Widget; using Android.OS; using System.IO; usi
ng XamiTextSharpLGPL; using iTextSharp.text; using iTextSharp.text.pdf; using iT
extSharp;

2 Solutions collect form web for “Generador


Xamarin.Android pdf”
Primero asegúrese de que en el archivo Manifest que permite WriteExternalStorage

Para leer o escribir archivos en el almacenamiento externo, su aplicación


debe adquirir los permisos del sistema READ_EXTERNAL_STORAGE o
WRITE_EXTERNAL_STORAGE. Por ejemplo:

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


L_STORAGE" /> </manifest>

FileStream constructor (uno de los muchos) acepta cadena para una ruta de acceso
y FileMode por lo que sería una solución de ejemplo.

var directory = new Java.IO.File(Android.OS.Environment.ExternalStorageDirecto


ry, "pdf").ToString(); if (!Directory.Exists(directory)) { Directory.CreateDirec
tory(directory); } var path = Path.Combine(directory, "myTestFile.pdf"); var fs
= new FileStream(path, FileMode.Create);

Esto crea la carpeta llamada "pdf" en el almacenamiento externo y luego crea el archivo pdf.
Se podría incluir un código adicional para comprobar si existe un archivo antes de crearlo.
Editar: ejemplo completo, probado en mi dispositivo:

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


t 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.CreateDirecto
ry(directory); } var path = Path.Combine(directory, "myTestFile.pdf"); if (File.
Exists(path)) { File.Delete(path); } var fs = new FileStream(path, FileMode.Crea
te); Document document = new Document(PageSize.A4, 25, 25, 30, 30); PdfWriter wr
iter = PdfWriter.GetInstance(document, fs); document.Open(); document.Add(new Pa
ragraph("Hello World")); document.Close(); writer.Close(); fs.Close(); Java.IO.F
ile file = new Java.IO.File(path); Intent intent = new Intent(Intent.ActionView)
; intent.SetDataAndType(Android.Net.Uri.FromFile(file), "application/pdf"); Star
tActivity(intent); }

Si usted está haciendo el desarrollo de la plataforma cruzada su apostante para genarate PDF
en lugar del commen. Consulte el código a continuación en la creación de PDF en PCL
utilizando iTEXT agudo. ITEXT PDF
Aquí tengo uso biblioteca de almacenamiento PCL para el acceso IO que es muy útil para
PCL. Puede encontrar más información aquí PCL Storage

1. Agregue la biblioteca de almacenamiento PCL a su proyecto PCL y, además de las


plataformas pertinentes, utilizando nuget.

Paquete de instalación PCLStorage


2. Agregar iTEXT PDF a su proyecto PCL
Install-Package iTextSharp
3. Use debajo del código en el proyecto PCL

public class PdfHelper { public async Task PCLGenaratePdf(string path) {


IFolder rootFolder = await FileSystem.Current.GetFolderFromPathAsync(path
); IFolder folder = await rootFolder.CreateFolderAsync("folder", Creation
CollisionOption.OpenIfExists); IFile file = await folder.CreateFileAsync(
"file.pdf", CreationCollisionOption.ReplaceExisting); using (var fs = awa
it file.OpenAsync(FileAccess.ReadAndWrite)) { var document = new Document
(PageSize.A4, 25, 25, 30, 30); PdfWriter writer = PdfWriter.GetInstance(d
ocument, fs); document.Open(); document.Add(new Paragraph("heloo everyone
")); document.Close(); writer.Close(); } } public async Task<string> PCLR
eadFile(string path) { IFile file = await FileSystem.Current.GetFileFromP
athAsync(path); return file.Path; } }

4. Use el siguiente código en el proyecto android

Generar PDF

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

Leer el PDF con la intención

private async void ReadPDF(object sender, EventArgs e) { String sdCardPath = E


nvironment.ExternalStorageDirectory.AbsolutePath; String fullpath = Path.Combine
(sdCardPath, "folder/" + "file.pdf"); var creator = new PdfHelper(); string file
Path = 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); Applicatio
n.Context.StartActivity(intent); }

5. Escribir ios código para generar y obtener PDF.


Nota : a veces puede haber error en system.drawings y system.security una vez que compile
el proyecto PCL.Solución está usando el código fuente iTEXT nítida quitar todos los
system.drawings y system.security dependencias.
Codificación feliz.

Potrebbero piacerti anche