Creación de un archivo pdf en android mediante programación y escritura en él
Estoy tratando de crear un archivo pdf dentro de mi aplicación, guardarlo en el almacenamiento externo de abrirlo. Guardar un archivo no es un problema para mí, ni es la apertura de uno, mi problema es crear uno y escribir en él. Así que después de algunas investigaciones en línea encontré la siguiente manera de hacerlo:
File file = new File(directoryName, fileName); // Creating output stream to write in the newly created file FileOutputStream fOut = null; try { fOut = new FileOutputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } // Creating a new document Document document = new Document(PageSize.A4, 50, 50, 50, 50); try { PdfWriter.getInstance(document, fOut); // Open the document for writing document.open(); // Write in the document document.add(new Paragraph("Hello world")); document.close(); } catch(DocumentException de) { System.err.println(de.getMessage()); }
Al ejecutar mi aplicación y ejecutar el código anterior, obtengo el siguiente error:
- ¿Cómo obtener la ruta del archivo desde URI?
- Crear archivo PDF / Word (Doc) en la aplicación
- ¿Qué le pasó a DroidText?
- Uso de la clase PdfDocument para la versión antigua de Android
- Aumentar el brillo y el contraste de la imagen después de capturar desde la cámara en Android
java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Color;
¿Alguien sabe cuál es el problema con mi código, o de otra manera que está seguro de trabajar para crear y escribir un archivo pdf?
Gracias !
- Convertir JPG a PDF
- cómo: descargar y abrir un archivo pdf mediante programación a través de conexión http
- Android - cómo convertir html a pdf?
- Android: inflar un diseño y escribirlo en PDF produce un PDF en blanco
- ¿Cómo abrir un archivo PDF en Android desde la carpeta de activos?
- Webview to PDF ignora el nombre del trabajo
- Problema al convertir .docx al archivo pdf en android
- Biblioteca de visor de PDF de Android sin licencia GPL
Así que aparentemente el código que estaba usando no era compatible con Android, de ahí el error que estaba recibiendo. A continuación encontrará el código correcto que funciona correctamente (para crear un archivo pdf, poner algún contenido en él, guardar y abrir el archivo recién creado):
PS: Para esto tendrás que añadir el tarro de iTextG a tu proyecto:
// Method for creating a pdf file from text, saving it then opening it for display public void createandDisplayPdf(String text) { Document doc = new Document(); try { String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Dir"; File dir = new File(path); if(!dir.exists()) dir.mkdirs(); File file = new File(dir, "newFile.pdf"); FileOutputStream fOut = new FileOutputStream(file); PdfWriter.getInstance(doc, fOut); //open the document doc.open(); Paragraph p1 = new Paragraph(text); Font paraFont= new Font(Font.COURIER); p1.setAlignment(Paragraph.ALIGN_CENTER); p1.setFont(paraFont); //add paragraph to document doc.add(p1); } catch (DocumentException de) { Log.e("PDFCreator", "DocumentException:" + de); } catch (IOException e) { Log.e("PDFCreator", "ioException:" + e); } finally { doc.close(); } viewPdf("newFile.pdf", "Dir"); } // Method for opening a pdf file private void viewPdf(String file, String directory) { File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file); Uri path = Uri.fromFile(pdfFile); // Setting the intent for pdf reader Intent pdfIntent = new Intent(Intent.ACTION_VIEW); pdfIntent.setDataAndType(path, "application/pdf"); pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { startActivity(pdfIntent); } catch (ActivityNotFoundException e) { Toast.makeText(TableActivity.this, "Can't read pdf file", Toast.LENGTH_SHORT).show(); } }
La clase PdfDocument permite generar un documento PDF desde contenido nativo de Android. Usando esta clase podemos crear pdf y también abrirlo usando PdfRenderer . Ejemplo de código para crear un archivo pdf
public void stringtopdf(String data) { String extstoragedir = Environment.getExternalStorageDirectory().toString(); File fol = new File(extstoragedir, "pdf"); File folder=new File(fol,"pdf"); if(!folder.exists()) { boolean bool = folder.mkdir(); } try { final File file = new File(folder, "sample.pdf"); file.createNewFile(); FileOutputStream fOut = new FileOutputStream(file); PdfDocument document = new PdfDocument(); PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(100, 100, 1).create(); PdfDocument.Page page = document.startPage(pageInfo); Canvas canvas = page.getCanvas(); Paint paint = new Paint(); canvas.drawText(data, 10, 10, paint); document.finishPage(page); document.writeTo(fOut); document.close(); }catch (IOException e){ Log.i("error",e.getLocalizedMessage()); }
Descargar el código fuente desde aquí ( Crear un archivo PDF en android mediante programación )
Activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:orientation="vertical"> <Button android:id="@+id/btn_generate" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Generate PDF" /> <LinearLayout android:layout_width="match_parent" android:orientation="vertical" android:id="@+id/ll_pdflayout" android:background="#ffffff" android:layout_height="match_parent"> <ImageView android:id="@+id/iv_image" android:src="@drawable/image" android:layout_width="300dp" android:scaleType="fitXY" android:layout_marginTop="10dp" android:layout_gravity="center" android:layout_height="250dp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14dp" android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." android:layout_marginTop="10dp" android:gravity="center" android:paddingLeft="10dp" android:paddingRight="10dp" android:textColor="#000000"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv_link" android:textSize="10dp" android:textColor="#000000"/> </LinearLayout> </LinearLayout>
MainActivity.java
package com.deepshikha.generatepdf; import android.Manifest; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.pdf.PdfDocument; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ Button btn_generate; TextView tv_link; ImageView iv_image; LinearLayout ll_pdflayout; public static int REQUEST_PERMISSIONS = 1; boolean boolean_permission; boolean boolean_save; Bitmap bitmap; ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); fn_permission(); listener(); } private void init(){ btn_generate = (Button)findViewById(R.id.btn_generate); tv_link = (TextView)findViewById(R.id.tv_link); iv_image = (ImageView) findViewById(R.id.iv_image); ll_pdflayout = (LinearLayout) findViewById(R.id.ll_pdflayout); } private void listener(){ btn_generate.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_generate: if (boolean_save) { Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class); startActivity(intent); } else { if (boolean_permission) { progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setMessage("Please wait"); bitmap = loadBitmapFromView(ll_pdflayout, ll_pdflayout.getWidth(), ll_pdflayout.getHeight()); createPdf(); // saveBitmap(bitmap); } else { } createPdf(); break; } } } private void createPdf(){ WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); DisplayMetrics displaymetrics = new DisplayMetrics(); this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); float hight = displaymetrics.heightPixels ; float width = displaymetrics.widthPixels ; int convertHighet = (int) hight, convertWidth = (int) width; // Resources mResources = getResources(); // Bitmap bitmap = BitmapFactory.decodeResource(mResources, R.drawable.screenshot); PdfDocument document = new PdfDocument(); PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(convertWidth, convertHighet, 1).create(); PdfDocument.Page page = document.startPage(pageInfo); Canvas canvas = page.getCanvas(); Paint paint = new Paint(); canvas.drawPaint(paint); bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, true); paint.setColor(Color.BLUE); canvas.drawBitmap(bitmap, 0, 0 , null); document.finishPage(page); // write the document content String targetPdf = "/sdcard/test.pdf"; File filePath = new File(targetPdf); try { document.writeTo(new FileOutputStream(filePath)); btn_generate.setText("Check PDF"); boolean_save=true; } catch (IOException e) { e.printStackTrace(); Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show(); } // close the document document.close(); } public static Bitmap loadBitmapFromView(View v, int width, int height) { Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); v.draw(c); return b; } private void fn_permission() { if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)|| (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) { if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) { } else { ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSIONS); } if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) { } else { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSIONS); } } else { boolean_permission = true; } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PERMISSIONS) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { boolean_permission = true; } else { Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show(); } } } }
¡Gracias!
- ¿Por qué Android cambia la tarea de compilación a la tarea de implementación en la compilación de gradle?
- ¿Hay alguna biblioteca o algoritmo para convertir Shamsi (Jalali) a fecha gregoriana en Java?