Trying to create a PDF from a listview

listview to pdf
create pdf file in android programmatically example
create pdf from images android programmatically
how to generate pdf in android application
how to generate pdf report in android studio
how to convert recyclerview to pdf in android
create pdf in background android
generate pdf from json data in android

Hello Everyone I'm trying to create a pdf programatically from a set of images. I'm loading images on Listview from array list. after displaying the images on click floating action button I'm willing to create a new PDF file. I'm successfully creating file, Unfortunately I can able to see only one image on the pdf file out of 5 images. For reference purpose here I'm sharing the code which I'm trying to achieve. Please help me in creating and displaying list of images on PDF

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.drawable.Drawable;
import android.graphics.pdf.PdfDocument;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.FileHandler;

public class DisplayPreview extends AppCompatActivity {

    String TAG = DisplayPreview.class.getName();

    ListView imagesLV;

    FloatingActionButton fabPDF;

    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;
    ArrayList<String> selectedImagesList;
    String targetPdf;

    DisplayPreviewAdapter displayPreviewAdapter;

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

        Intent intent = getIntent();
        selectedImagesList = intent.getStringArrayListExtra("selectedArray");
        fn_permission();
        imagesLV = findViewById(R.id.imagesLV);

        displayPreviewAdapter = new DisplayPreviewAdapter(this, selectedImagesList);
        imagesLV.setAdapter(displayPreviewAdapter);

        fabPDF = findViewById(R.id.fabPDF);
        fabPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (boolean_save) {
                    Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
                    intent.putExtra("pdfFile", targetPdf);
                    startActivity(intent);

                } else {
                    if (boolean_permission) {
                        progressDialog = new ProgressDialog(DisplayPreview.this);
                        progressDialog.setMessage("Please wait");
                        bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
                        makePDF();

                    } else {

                    }

                    makePDF();
                }
            }
        });


    }


    private void makePDF() {

        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.img_1);

        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(getBitmapFromView(imagesLV), convertWidth, convertHighet, true);
//        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";
        targetPdf = "mnt/sdcard/testing_1.pdf";
        File filePath = new File(targetPdf);
        try {
            document.writeTo(new FileOutputStream(filePath));
            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;
    }

    public static Bitmap getBitmapFromView(View view) {
        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(returnedBitmap);
        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null)
            bgDrawable.draw(canvas);
        else
            canvas.drawColor(Color.WHITE);
        view.draw(canvas);
        return returnedBitmap;
    }


    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(DisplayPreview.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
            } else {
                ActivityCompat.requestPermissions(DisplayPreview.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_PERMISSIONS);

            }

            if ((ActivityCompat.shouldShowRequestPermissionRationale(DisplayPreview.this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
            } else {
                ActivityCompat.requestPermissions(DisplayPreview.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();

            }
        }
    }



}

After hours of Struggle I found my own answer in creating multiple pages in a single PDF using android also image annotating with text here is the following source code

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
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.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

public class DisplayPreview extends AppCompatActivity {

    String TAG = DisplayPreview.class.getName();

    ListView imagesLV;

    FloatingActionButton fabPDF;

    Bitmap anImage;

    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;
    ArrayList<String> selectedImagesList;
    String targetPdf;

    DisplayPreviewAdapter displayPreviewAdapter;
    String familyStatus, userNameStr;



    public static final Integer[] IMAGES = {
            R.drawable.img_1,
            R.drawable.img_2,
            R.drawable.img_3,
            R.drawable.img_4,
            R.drawable.img_5,
            R.drawable.img_6,
            R.drawable.img_7
//            ,R.drawable.img_8,
//            R.drawable.img_9
    };

    private ProgressDialog pDialog;

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

        Intent intent = getIntent();
        selectedImagesList = intent.getStringArrayListExtra("selectedArray");
        familyStatus = intent.getStringExtra("familyStatus");
        userNameStr = intent.getStringExtra("userNameStr");



        targetPdf = "mnt/sdcard/testing_2.pdf";

        imagesLV = findViewById(R.id.imagesLV);

        displayPreviewAdapter = new DisplayPreviewAdapter(this, selectedImagesList, IMAGES);
//        imagesLV.setAdapter(displayPreviewAdapter);

        fabPDF = findViewById(R.id.fabPDF);

        Drawable myDrawable = getResources().getDrawable(R.drawable.img_1);
        anImage = ((BitmapDrawable) myDrawable).getBitmap();

        createMultiPagePDF();

        fabPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (boolean_save) {
                    Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
                    intent.putExtra("pdfFile", targetPdf);
                    startActivity(intent);

                } else {
                    if (boolean_permission) {
                        progressDialog = new ProgressDialog(DisplayPreview.this);
                        progressDialog.setMessage("Please wait");
//                        bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
                        bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
//                        makePDF();

                        createMultiplePDF();
                    } else {

                    }

                    createMultiplePDF();
//                    makePDF();
                }
            }
        });


    }

    private void createMultiPagePDF() {

        pDialog = new ProgressDialog(DisplayPreview.this);
        pDialog.setMessage("Please wait...Creating Invitation");
        pDialog.setCancelable(false);
        pDialog.show();

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app main activity

                if (boolean_save) {
                    Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
                    intent.putExtra("pdfFile", targetPdf);
                    startActivity(intent);

                } else {
                    if (boolean_permission) {
                        progressDialog = new ProgressDialog(DisplayPreview.this);
                        progressDialog.setMessage("Please wait");
//                        bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
                        bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
//                        makePDF();

                        createMultiplePDF();
                    } else {

                    }

                    createMultiplePDF();
//                    makePDF();
                }
            }
        }, 4000);
    }


    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;
    }


    @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();

            }
        }
    }


    public void createMultiplePDF() {

//        targetPdf = "mnt/sdcard/testing_1.pdf";
        targetPdf = "mnt/sdcard/" + userNameStr + ".pdf";
        File filePath = new File(targetPdf);

//        Document document = new Document();
        Document document = new Document(PageSize.A4, 0, 0, 0, 0);
        // step 2
        PdfWriter writer = null;
        try {
            writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // step 3
        document.open();
        // step 4
        try {

            Drawable myDrawable = null;

            for (int i = 0; i < selectedImagesList.size(); i++) {
//

                String imagePath = selectedImagesList.get(i).replaceAll("^\"|\"$", "");
                Log.i(TAG, "Image Path is :: 271 :: " + imagePath);

//                if (imagePath.equals("R.drawable.img_8")) {
                if (imagePath.equals(userNameStr)) {

                    Bitmap processedBitmap = ProcessingBitmap();

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    processedBitmap.compress(Bitmap.CompressFormat.JPEG, 40, stream);
                    Image myImg = Image.getInstance(stream.toByteArray());

                    DisplayMetrics displaymetrics = new DisplayMetrics();
                    this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                    float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
                    float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));


//                    myImg.scaleToFit(hight, width);
                    myImg.scaleToFit(PageSize.ARCH_A);
                    myImg.setAlignment(Image.ALIGN_CENTER);
                    document.add(myImg);
                    writer.setPageEmpty(false);

                }
                if (imagePath.equals("R.drawable.img_2")) {
                    myDrawable = getResources().getDrawable(R.drawable.img_2);

                    Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
                    Image myImg = Image.getInstance(stream.toByteArray());

                    DisplayMetrics displaymetrics = new DisplayMetrics();
                    this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                    float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
                    float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));

//                    myImg.scaleToFit(hight, width);
                    myImg.scaleToFit(PageSize.ARCH_A);
                    myImg.setAlignment(Image.ALIGN_CENTER);
                    document.add(myImg);
                    writer.setPageEmpty(false);
                }
                if (imagePath.equals("R.drawable.img_3")) {
                    myDrawable = getResources().getDrawable(R.drawable.img_3);

                    Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
                    Image myImg = Image.getInstance(stream.toByteArray());

                    DisplayMetrics displaymetrics = new DisplayMetrics();
                    this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                    float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
                    float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));

//                    myImg.scaleToFit(hight, width);
                    myImg.scaleToFit(PageSize.ARCH_A);
                    myImg.setAlignment(Image.ALIGN_CENTER);
                    document.add(myImg);
                    writer.setPageEmpty(false);
                }
                if (imagePath.equals("R.drawable.img_4")) {
                    myDrawable = getResources().getDrawable(R.drawable.img_4);

                    Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
                    Image myImg = Image.getInstance(stream.toByteArray());

                    DisplayMetrics displaymetrics = new DisplayMetrics();
                    this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                    float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
                    float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));

//                    myImg.scaleToFit(hight, width);
                    myImg.scaleToFit(PageSize.ARCH_A);
                    myImg.setAlignment(Image.ALIGN_CENTER);
                    document.add(myImg);
                    writer.setPageEmpty(false);
                }
                if (imagePath.equals("R.drawable.img_5")) {
                    myDrawable = getResources().getDrawable(R.drawable.img_5);

                    Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
                    Image myImg = Image.getInstance(stream.toByteArray());

                    DisplayMetrics displaymetrics = new DisplayMetrics();
                    this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                    float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
                    float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));

//                    myImg.scaleToFit(hight, width);
                    myImg.scaleToFit(PageSize.ARCH_A);
                    myImg.setAlignment(Image.ALIGN_CENTER);
                    document.add(myImg);
                    writer.setPageEmpty(false);
                }
                if (imagePath.equals("R.drawable.img_6")) {
                    myDrawable = getResources().getDrawable(R.drawable.img_6);

                    Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
                    Image myImg = Image.getInstance(stream.toByteArray());

                    DisplayMetrics displaymetrics = new DisplayMetrics();
                    this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                    float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
                    float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));

//                    myImg.scaleToFit(hight, width);
                    myImg.scaleToFit(PageSize.ARCH_A);
                    myImg.setAlignment(Image.ALIGN_CENTER);
                    document.add(myImg);
                    writer.setPageEmpty(false);
                }
                if (imagePath.equals("R.drawable.img_7")) {
                    myDrawable = getResources().getDrawable(R.drawable.img_7);

                    Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
                    Image myImg = Image.getInstance(stream.toByteArray());

                    DisplayMetrics displaymetrics = new DisplayMetrics();
                    this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                    float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
                    float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));

//                    myImg.scaleToFit(hight, width);
                    myImg.scaleToFit(PageSize.ARCH_A);
                    myImg.setAlignment(Image.ALIGN_CENTER);
                    document.add(myImg);
                    writer.setPageEmpty(false);
                }
              /*  if (imagePath.equals("R.drawable.img_8")) {
                    myDrawable = getResources().getDrawable(R.drawable.img_8);

                    Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
                    Image myImg = Image.getInstance(stream.toByteArray());

                    DisplayMetrics displaymetrics = new DisplayMetrics();
                    this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                    float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
                    float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));

//                    myImg.scaleToFit(hight, width);
                    myImg.scaleToFit(PageSize.ARCH_A);
                    myImg.setAlignment(Image.ALIGN_CENTER);
                    document.add(myImg);
                    writer.setPageEmpty(false);
                } if (imagePath.equals("R.drawable.img_9")) {
                    myDrawable = getResources().getDrawable(R.drawable.img_9);

                    Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
                    Image myImg = Image.getInstance(stream.toByteArray());

                    DisplayMetrics displaymetrics = new DisplayMetrics();
                    this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                    float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
                    float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));

//                    myImg.scaleToFit(hight, width);
                    myImg.scaleToFit(PageSize.ARCH_A);
                    myImg.setAlignment(Image.ALIGN_CENTER);
                    document.add(myImg);
                    writer.setPageEmpty(false);
                }*/


            }
            document.close();

            pDialog.dismiss();

            Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
            intent.putExtra("pdfFile", targetPdf);
            startActivity(intent);
            finish();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @SuppressLint("ResourceAsColor")
    private Bitmap ProcessingBitmap() {

        Resources resources = DisplayPreview.this.getResources();
        float scale = resources.getDisplayMetrics().density;

        Bitmap bm1 = BitmapFactory.decodeResource(getResources(), R.drawable.img_1);


        Bitmap.Config config = bm1.getConfig();
        if (config == null) {
            config = Bitmap.Config.ARGB_8888;
        }

//        newBitmap = Bitmap.createBitmap(bm1.getWidth(), bm1.getHeight(), config);
        anImage = Bitmap.createBitmap(bm1.getWidth(), bm1.getHeight(), config);
//            Canvas newCanvas = new Canvas(newBitmap);
        Canvas newCanvas = new Canvas(anImage);

        newCanvas.drawBitmap(bm1, 0, 0, null);

        String captionString = userNameStr.trim();
        if (captionString != null) {

            TextPaint paintText = new TextPaint(Paint.ANTI_ALIAS_FLAG);
            paintText.setColor(R.color.wedding_guest_name);
            paintText.setTextSize(100);
            paintText.setStyle(Paint.Style.FILL_AND_STROKE);
            paintText.setTextAlign(Paint.Align.CENTER);

            int textWidth = newCanvas.getWidth() - (int) (250 * scale);

            StaticLayout textLayout = new StaticLayout(
                    captionString, paintText, textWidth, Layout.Alignment.ALIGN_LEFT, 1.0f, 1.4f, false);


            Rect rectText = new Rect();
            paintText.getTextBounds(captionString, 0, captionString.length(), rectText);

            float xPos = (newCanvas.getWidth() / 2.16f);
            float yPos = (int) ((newCanvas.getHeight() / 2.4) - ((paintText.descent() + paintText.ascent()) / 3.0));

            float x = newCanvas.getWidth()/2;
//            float y = newCanvas.getHeight()/2;

            // draw text to the Canvas center
            newCanvas.save();
//            newCanvas.translate(xPos, yPos);
            newCanvas.translate(x, yPos);



            textLayout.draw(newCanvas);
            newCanvas.restore();


//            drawMultiLineText(captionString,xPos, yPos, paintText, newCanvas);


//            newCanvas.drawText(captionString,xPos, yPos, paintText);


        } else {
            Toast.makeText(getApplicationContext(),
                    "caption empty!",
                    Toast.LENGTH_LONG).show();
        }

        //        return newBitmap;
        return anImage;
    }

}

Create pdf from android list view, I tried the way u mention in the post but i didn't get the .getRootView and is that for the layout because i have used this type of xml <relative> Easily Make any PDF! Create, Edit, Convert PDFs. (Ideal tool for PDFs)

I suggest you to use iTextPdf to create pdf in easy way

compile 'com.itextpdf:itextg:5.5.10'

Android Generate PDF from view, Use https://github.com/tejpratap46 , public final void generatePDF(final List<View> contentViews, final String filePath, try {. // Create PDF Document. PdfDocument pdfDocument = new  Fully Edit PDF Text/Image In Every Way When Using Other File Formats. Try Now!

Add itextpdf library into your project app build.gradle file

implementation 'com.itextpdf:itext-pdfa:5.5.5'

Below is the code to create pdf file and add image into each cell in table

Document document = new Document(PageSize.A4, 10, 10, 10, 10);
try {

    File f = new File(Environment.getExternalStorageDirectory() + "/*foldername*");
    f = new File(f.getAbsolutePath() + "/" + * filename *);
    if (!f.exists()) {
        f.mkdir();
    }

    PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(f.getAbsolutePath() + "/" + * filename * +".pdf"));

    document.open();

    for (int l = 0; l < list.size; l++) {
        PdfPTable thirdPart = new PdfPTable(col);
        thirdPart.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        thirdPart.setWidthPercentage(100.0f);
        thirdPart.setHorizontalAlignment(Element.ALIGN_LEFT);

        Image str = list.get(l);
        PdfPCell imageCell = new PdfPCell(str);
        thirdPart.addCell(imageCell);
    }
    document.add(thirdPart);

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

document.close();

print a view with a recyclerview · Issue #34 · HendrixString/Android , @jwhijazi can you give me a sample? i tried to use a ListView with a ArrayAdapter but don't work Code in main activity to generate PDF Upload, Edit, Sign & Export PDF Forms Online. No Installation Needed. Try Now! Easily eSign Documents, Forms and Agreements Online. eSign From Any Device.

C# ListView to PDF : Spire.DataExport, NET" and trying to create a PDF from a ListView in C#. I was able to work my way through the example exporting to Microsoft Excel, however,  Create your PDF documents - Free! Easily Convert any file in a PDF.

how can i export listview into a PDF file? : Spire.PDF, I've already tried the given example in titled Export Data from Listview to PDF with C#/VB.NET. I have no idea where did the cellexport1 came  Hello Everyone I'm trying to create a pdf programatically from a set of images. I'm loading images on Listview from array list. after displaying the images on click floating action button I'm willing to create a new PDF file. I'm successfully creating file, Unfortunately I can able to see only one image on the pdf file out of 5 images.

ListView, To take advantage of this feature, check if the convertView provided to getView(​) is null before creating or inflating a new view object. See Making ListView  I just paid 89.00 for a subscription to create pdf's and for some for reason I have forgotten how to do because I don't do it very often can you please walk me through the steps to do this Solved! Go to Solution.

Comments
  • Just integrate itextpdf and create table and cell dynamically and add image in each cell.
  • Can you say it via programatically
  • Please check my below answer to display multiple images in pdf
  • possibly answer to your question. stackoverflow.com/a/4565602/2900893
  • Possible duplicate of Creating a pdf file in android programmatically and writing in it
  • Yes I integrated above thing in gradle
  • if you want to create pdf for whole view than put that view into NestedView, you can create screenshot of whole view using private Bitmap getBitmapFromView(View view, int height, int width) { Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); Drawable bgDrawable = view.getBackground(); if (bgDrawable != null) bgDrawable.draw(canvas); else canvas.drawColor(Color.WHITE); view.draw(canvas); return bitmap; } and put this image into your pdf