-1

I have a layout with several relative layout with scrollview like this :

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    android:id="@+id/root"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">
    <RelativeLayout
        android:id="@+id/relativeRoot"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

<RelativeLayout
    android:id="@+id/mainr"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAlignment="center">
    <RelativeLayout
        android:gravity="center"
        android:id="@+id/business_details"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/business_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_gravity="center"
            android:layout_marginLeft="88dp"
            android:layout_marginStart="88dp"
            android:padding="2dp"
            android:textStyle="bold"
            android:text=" Business Name "
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/business_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/business_name"
            android:layout_alignStart="@+id/business_name"
            android:layout_below="@+id/business_name"
            android:layout_gravity="center"
            android:padding="2dp"
            android:text=" Business Address "
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/business_contact"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/business_name"
            android:layout_alignStart="@+id/business_name"
            android:layout_below="@+id/business_add"
            android:layout_gravity="center"
            android:padding="2dp"
            android:text=" Business contactNo "
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textSize="16sp" />
        <View
            android:layout_below="@+id/business_contact"
            android:layout_width="match_parent"
            android:layout_height="3dp"
            android:background="@android:color/black"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/customer_details"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/business_details"
        android:gravity="center">

        <TextView
            android:id="@+id/gstuin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="GSTIN  :"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/gstinvalue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignEnd="@+id/datev"
            android:layout_alignParentTop="true"
            android:layout_alignRight="@+id/datev"
            android:text="xyz1234566" />

        <TextView



        <TextView
            android:id="@+id/date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/bill"
            android:text="Bill date:"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/datev"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/date"
            android:layout_alignBottom="@+id/date"
            android:layout_alignLeft="@+id/customerNamev"
            android:layout_alignStart="@+id/customerNamev"
            android:text="20-12-2017" />



        <View
            android:id="@+id/view"
            android:layout_width="match_parent"
            android:layout_height="3dp"
            android:layout_below="@+id/customerName"
            android:background="@android:color/black" />

    </RelativeLayout>
<LinearLayout
    android:layout_below="@+id/customer_details"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/linearLayout">


    <TextView
        android:id="@+id/product_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:text=" Product Name   "
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/gst"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:padding="2dp"
        android:textStyle="bold"
        android:text=" gst% "
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textSize="16sp" />


    <TextView
        android:id="@+id/total"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:padding="2dp"
        android:text="     Total "
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textSize="16sp"
        android:textStyle="bold" />

</LinearLayout>
    <View
        android:id="@+id/v2"
        android:layout_below="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="3dp"
        android:background="@android:color/black"/>
    <RelativeLayout
        android:id="@+id/r2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/v2"
        android:background="@color/colorAccent"
        android:textAlignment="center">

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="1dp"
            android:background="@color/white">

        </ListView>
        <View
            android:id="@+id/v3"
            android:layout_below="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="3dp"
            android:background="@android:color/black"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/r3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/r2">

        <TextView
            android:id="@+id/netTotal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:text="Net Total :" />



        <View
            android:id="@+id/v4"
            android:layout_below="@+id/netTotalv"
            android:layout_width="match_parent"
            android:layout_height="3dp"




    </RelativeLayout>

</RelativeLayout>

        <Button
            android:id="@+id/print"
            android:background="@null"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginLeft="12dp"
            android:layout_marginStart="12dp"
            android:text="Print" />
 </RelativeLayout>
</ScrollView>

Basically this is a fromat of invoice. Now I'm trying to convert whole layout into bitmap image and after that trying to convert this image into pdf.

But my pdf result shows only some part of list view only.

Here is my java code:

public class InvoicePreview extends AppCompatActivity {
    String str,customerName,email,phone,zipcode,comment,invoiceTotal,loginId;
    List<ItemModel> itemsList = new ArrayList<ItemModel>();
    ItemAdapter aAdpt;
    ListView listView;
    Button print,download,cancel;
    RelativeLayout main,relativeroot;
    WebView mWebView;
    ScrollView root;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.invoice_preview);
        listView=(ListView)findViewById(R.id.list);

        print = (Button)findViewById(R.id.print);
        download = (Button)findViewById(R.id.down);
        cancel = (Button)findViewById(R.id.cancel);

        main = (RelativeLayout)findViewById(R.id.relativeRoot);

        aAdpt = new ItemAdapter(itemsList, this);
        listView.setAdapter(aAdpt);

        Intent intent = getIntent();
        str = intent.getExtras().getString("json");
        Log.d("json preview",str);
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
        try {
            jsonparse();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        print.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                try {
                    Toast.makeText(InvoicePreview.this, "clicked", Toast.LENGTH_SHORT).show();
                    createPdf();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });


    }

    private void createPdf() throws IOException, DocumentException {

        File pdfFolder = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), "pdfdemo");
        if (!pdfFolder.exists()) {
            pdfFolder.mkdir();
//            Log.i(LOG_TAG, "Pdf Directory created");
        }

        //Create time stamp
        Date date = new Date() ;
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);

        File myFile = new File(pdfFolder + timeStamp + ".pdf");

        OutputStream output = new FileOutputStream(myFile);

        //Step 1
        Rectangle pagesize = new Rectangle(4000f, 14000f);
        Document document = new Document(pagesize, 36f, 7f, 10f, 18f);

        //Step 2
        PdfWriter.getInstance(document, output);

        //Step 3
        document.open();
// for bitmap
        main.setDrawingCacheEnabled(true);
        main.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        main.layout(0, 0, main.getMeasuredWidth(), main.getMeasuredHeight());
        main.buildDrawingCache(true);

        Bitmap b = Bitmap.createBitmap(main.getDrawingCache());
        main.setDrawingCacheEnabled(false);
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        Image myImg = Image.getInstance(bytes.toByteArray());
//        document.setPageSize(myImg);
//        document.newPage();
//        myImg.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
        document.add(myImg);
        //Step 4 Add content
//        document.add(new Paragraph("test doc"));
//        document.add(new Paragraph(mBodyEditText.getText().toString()));

        //Step 5: Close the document
        document.close();

//        Image img = Image.getInstance(IMAGES[0]);
//        Document document = new Document(img);
//        PdfWriter.getInstance(document, new FileOutputStream(dest));
//        document.open();
//      
//        document.close();

//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.setDataAndType(Uri.fromFile(myFile), "application/pdf");
//        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
//        startActivity(intent);

    }
 }

I'm trying various methods available on net but still facing same issue that whole layout is not showing in pdf. How to resolve this issue?(If any necessary info is missing plz ask).

Neo
  • 119
  • 8
  • If you save the bitmap, does that contain the whole layout? – Amedee Van Gasse Jan 03 '18 at 07:57
  • 1
    Please don't use images as pages in a PDF. It ruins every possible kind of further interaction with your document. Suppose that somebody receiving your invoice needs/wants to automatically extract data from it, then what? – Joris Schellekens Jan 03 '18 at 07:57
  • Not sure about that@AmedeeVanGasse. – Neo Jan 03 '18 at 08:01
  • Currently no need of data extraction. data already saved as its elementary level@JorisSchellekens. – Neo Jan 03 '18 at 08:02
  • your ListView has a fixed height of 200dp, I guess that's what you're going to see in the image, just 200dp, have you tried setting the height to wrap_content? – lelloman Jan 03 '18 at 08:10
  • Still same issue@lelloman – Neo Jan 03 '18 at 08:15
  • "No need of data extraction" isn't sufficient as an argument to make the wrong architectural decisions. If I were your customer, I wouldn't be pleased with a PDF that consist of nothing but raster images. I consider this abuse of the PDF format. – Bruno Lowagie Jan 03 '18 at 15:37
  • Thanx For your suggestion @BrunoLowagie.Can you gave a proper sample sample regarding this. – Neo Jan 08 '18 at 10:52

2 Answers2

0

Try to get the complete height of the view so that you can have the complete scroll view into the pdf conversion. For doing so, add below code

Image myImg = Image.getInstance(bytes.toByteArray());
float scaler = ((document.getPageSize().getHeight() - document.topMargin() - document.bottomMargin() - 0) / myImg.getHeight()) * 100; // getting height of your scroll view 
myImg.scalePercent(scaler);
myImg.setAlignment(Image.ALIGN_TOP | Image.ALIGN_CENTER | Image.ALIGN_BOTTOM);
document.add(myImg);

this will get your complete height of view into A4 size pdf.

0

You can use this library to make it easy to do within a few lines of code -

  PdfGenerator.getBuilder()
                        .setContext(context)
                        .fromViewIDSource()
                        .fromViewID(activity,R.id.fulldoc) //The specifi view id you want to print
                        .setDefaultPageSize(PdfGenerator.PageSize.A4)
                        .setFileName("Allotment_PaperPDF")
                        .setFolderName("TCBMobileApp")
                        .build(new PdfGeneratorListener() {
                        @Override
                        public void onFailure(FailureResponse failureResponse) {
                            super.onFailure(failureResponse);
                        }
            
                        @Override
                        public void onStartPDFGeneration() {
                            /*When PDF generation begins to start*/
                        }

                        @Override
                        public void onFinishPDFGeneration() {
                            /*When PDF generation is finished*/
                        }

                        @Override
                        public void showLog(String log) {
                            super.showLog(log);
                        }

                        @Override
                        public void onSuccess(SuccessResponse response) {
                            super.onSuccess(response);
                        }
                    });

For more insight, please see my doc which is related to your problem. To get an example please see here.

Gk Mohammad Emon
  • 6,084
  • 3
  • 42
  • 42