Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create, write and display PDF file in android app

Tags:

android

pdf

itext

I have an android app which is basically a form to accept user input. This input is stored in a database. But I want to create a pdf file with the information a user enters and and display it so that the user can print the file or save the file to their android note tab. What is the best way to go about it. I have seen iText around but this does not render the file. I found this code online and I tested it to understand the concept of pdf creation. This uses Lowagie 2.1.7

    package com.example.sweetiean.androidpdfdemo;

        import android.content.Intent;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.graphics.Color;
        import android.net.Uri;
        import android.os.Environment;
        import android.support.v7.app.ActionBarActivity;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.widget.Button;
        import android.widget.Toast;

        import com.lowagie.text.Document;
        import com.lowagie.text.DocumentException;
        import com.lowagie.text.Font;
        import com.lowagie.text.HeaderFooter;
        import com.lowagie.text.Paragraph;
        import com.lowagie.text.Phrase;
        import com.lowagie.text.pdf.PdfWriter;
        import com.lowagie.text.Image;


        import java.io.ByteArrayOutputStream;
        import java.io.File;
        import java.io.FileOutputStream;
        import java.io.IOException;




    public class MainActivity extends ActionBarActivity {

    private Button createPDF , openPDF;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        createPDF = (Button)findViewById(R.id.button1);
        createPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                createPDF();
            }
        });

        openPDF = (Button)findViewById(R.id.button2);
        openPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                openPdf();
            }
        });
    }

    public void createPDF()
    {
        Document doc = new Document();

        try {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

            File dir = new File(path);
            if(!dir.exists())
                dir.mkdirs();

            Log.d("PDFCreator", "PDF Path: " + path);

            File file = new File(dir, "demo.pdf");
            FileOutputStream fOut = new FileOutputStream(file);

            PdfWriter.getInstance(doc, fOut);

            //open the document
            doc.open();

          /* Create Paragraph and S`enter code here`et Font */
            Paragraph p1 = new Paragraph("Hi! I am Generating my first PDF using DroidText");

   /* Create Set Font and its Size */
            Font paraFont= new Font(Font.HELVETICA);
            paraFont.setSize(16);
            p1.setAlignment(Paragraph.ALIGN_CENTER);
            p1.setFont(paraFont);

            //add paragraph to document
            doc.add(p1);


            Paragraph p2 = new Paragraph("This is an example of a simple paragraph");

  /* You can also SET FONT and SIZE like this */
            Font paraFont2= new Font(Font.COURIER,14.0f, Color.GREEN);
            p2.setAlignment(Paragraph.ALIGN_CENTER);
            p2.setFont(paraFont2);

            doc.add(p2);

   /* Inserting Image in PDF */
            /*ByteArrayOutputStream stream = new ByteArrayOutputStream();
            Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.android);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
            Image myImg = Image.getInstance(stream.toByteArray());
            myImg.setAlignment(Image.MIDDLE);

            //add image to document
            doc.add(myImg);*/

            //set footer
            Phrase footerText = new Phrase("This is an example of a footer");
            HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
            doc.setFooter(pdfFooter);

            Toast.makeText(getApplicationContext(), "Created...", Toast.LENGTH_LONG).show();

        } catch (DocumentException de) {
            Log.e("PDFCreator", "DocumentException:" + de);
        } catch (IOException e) {
            Log.e("PDFCreator", "ioException:" + e);
        }
        finally
        {
            doc.close();
        }
    }

    void openPdf()
    {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

        File file = new File(path, "demo.pdf");

        intent.setDataAndType( Uri.fromFile(file), "application/pdf" );
        startActivity(intent);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

And this is the main activity.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<Button
    android:id="@+id/button2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="100dp"
    android:text="Open PDF" />

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="44dp"
    android:text="Generate PDF" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="50dp"
    android:text="@string/hello_world" />

like image 739
Sweetie Anang Avatar asked Apr 29 '15 11:04

Sweetie Anang


People also ask

In which app we can write and make PDF?

With Acrobat online, you can do much more to PDFs than just type on them. Easily add sticky notes and annotation, mark up text, and convert PDFs to other file formats — all on your Android device.


3 Answers

Do it this way:

import com.cete.dynamicpdf.*;
import com.cete.dynamicpdf.pageelements.Label;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

public class DynamicPDFHelloWorld extends Activity {
    private static String FILE = Environment.getExternalStorageDirectory()
            + "/HelloWorld.pdf";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Create a document and set it's properties
        Document objDocument = new Document();
        objDocument.setCreator("DynamicPDFHelloWorld.java");
        objDocument.setAuthor("Your Name");
        objDocument.setTitle("Hello World");

        // Create a page to add to the document
        Page objPage = new Page(PageSize.LETTER, PageOrientation.PORTRAIT,
                54.0f);

        // Create a Label to add to the page
        String strText = "Hello World...\nFrom DynamicPDF Generator "
                + "for Java\nDynamicPDF.com";
        Label objLabel = new Label(strText, 0, 0, 504, 100,
                Font.getHelvetica(), 18, TextAlign.CENTER);

        // Add label to page
        objPage.getElements().add(objLabel);

        // Add page to document
        objDocument.getPages().add(objPage);

        try {
            // Outputs the document to file
            objDocument.draw(FILE);
            Toast.makeText(this, "File has been written to :" + FILE,
                    Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(this,
                    "Error, unable to write to file\n" + e.getMessage(),
                    Toast.LENGTH_LONG).show();
        }
    }
}

Also check these links. They will help you to fulfill your requirement.

  1. http://www.dynamicpdf.com/Blog/post/2012/06/15/Generating-PDFs-Dynamically-on-Android.aspx

  2. https://github.com/JoanZapata/android-pdfview

  3. How to create PDFs in an Android app?

  4. Render a PDF file using Java on Android

like image 62
Jignesh Jain Avatar answered Nov 23 '22 23:11

Jignesh Jain


you'll find the correct code that actually works right.for creating a pdf file, putting some content in it, saving in and the opening the newly created file.

For this you'll need to add the jar of iTextG to your project:

  • OR

if you WANT TO convert your layout or view into pdf then you have to create image from your layout and then add into pdf.Perfect tutorial of that Go Through this Link . Hope this will help you guys.Thank you.

For Simple Create and Open pdf:

// 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() + "/PDF";

        File dir = new File(path);
        if(!dir.exists())
            dir.mkdirs();

        File file = new File(dir, "mypdffile.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.FontFamily.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("mypdffile.pdf", "PDF");
}

// 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(this, "Can't read pdf file", Toast.LENGTH_SHORT).show();
    }
}
like image 41
Kaushik Khambhadiya Avatar answered Nov 24 '22 00:11

Kaushik Khambhadiya


Check this link,it requires you to download a jar file.(more description in the link).Here is a part of code to generate pdf.

package com.cete.androidexamples.dynamicpdf.helloworld;

import com.cete.dynamicpdf.*;
import com.cete.dynamicpdf.pageelements.Label;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

public class DynamicPDFHelloWorld extends Activity {
    private static String FILE = Environment.getExternalStorageDirectory()
        + "/HelloWorld.pdf";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Create a document and set it's properties
    Document objDocument = new Document();
    objDocument.setCreator("DynamicPDFHelloWorld.java");
    objDocument.setAuthor("Your Name");
    objDocument.setTitle("Hello World");

    // Create a page to add to the document
    Page objPage = new Page(PageSize.LETTER, PageOrientation.PORTRAIT,
            54.0f);

    // Create a Label to add to the page
    String strText = "Hello World...\nFrom DynamicPDF Generator "
            + "for Java\nDynamicPDF.com";
    Label objLabel = new Label(strText, 0, 0, 504, 100,
            Font.getHelvetica(), 18, TextAlign.CENTER);

    // Add label to page
    objPage.getElements().add(objLabel);

    // Add page to document
    objDocument.getPages().add(objPage);

    try {
        // Outputs the document to file
        objDocument.draw(FILE);
        Toast.makeText(this, "File has been written to :" + FILE,
                Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Toast.makeText(this,
                "Error, unable to write to file\n" + e.getMessage(),
                Toast.LENGTH_LONG).show();
    }
}
}
like image 23
Neal Ahluvalia Avatar answered Nov 24 '22 01:11

Neal Ahluvalia