Edit Pdf

Edit

We can edit a PDF, we have to create a new copy from original.

Generate pdf

private static String sInPutfile = "Android/data/Example.pdf";
    private static String sOutPutFile = "Android/data/ExampleCopy.pdf";

Then we have to PdfReader and PdfStamper, you can check the library iText.

private void editPDF(String string) {

        try {

            FileInputStream is = new FileInputStream(mPdfFile);
            PdfReader pdfReader = new PdfReader(is);
            PdfStamper pdfStamper = new PdfStamper(pdfReader,
                    new FileOutputStream(mPdfFileOutPut));

            for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {

                //create content from pdfStamper
                PdfContentByte content = pdfStamper.getUnderContent(i);

                // Text over the existing page
                BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                        BaseFont.WINANSI, BaseFont.EMBEDDED);

                content.beginText();
                //set the font
                content.setFontAndSize(bf, 18);
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, string, 430, 15, 0);
                content.endText();

            }

            pdfStamper.close();

        } catch (IOException e) {
            e.printStackTrace();

        } catch (DocumentException e) {
            e.printStackTrace();

        }

    }

And we can edit the PDF generated other PDF in android.

Example in Github

Generate PDF

Generate

In this example we use iText library, we can download in this link.

Generate pdf

Then we add the library in libs file and we include this conde in your activity.

private void generateAndwritePDF() {

        // create a new document
        Document document = new Document();

        try {
            PdfWriter.getInstance(document, new FileOutputStream(mPdfFile));
            document.open();
            document.add(new Paragraph("Title"));
            document.close();

            mProgressDialog.cancel();

        } catch (Exception e) {
            e.printStackTrace();

        }

    }

And we can generate pdf in android.

Example in Github

Open PDF

How to open PDF in Android?

Open pdf

We have to put the ourexample.pdf in our divice, in this case in Android/data

File file =new File(Environment.getExternalStorageDirectory(),"Android/data/ExampleForm.pdf");

if (file.exists()) {
     Uri path = Uri.fromFile(file);
     Intent intent = new Intent(Intent.ACTION_VIEW);
     intent.setDataAndType(path, "application/pdf");
     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

     try {
        startActivity(intent);
     }
        catch (ActivityNotFoundException e) {
            Toast.makeText(MainActivity.this,
            "No Application Available to View PDF",
            Toast.LENGTH_SHORT).show();

        }
     }
}

Example in Github