Android creates and prints PDF from layout view

I am trying to generate a PDF from a xml layout view. I have a list box in this layout, adding items and setting height based on child. PDF creates but does not fill the entire page. I tried,

 PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(2250, 1400, 1).create();

        // start a page
        PdfDocument.Page page = document.startPage(pageInfo);


        // draw something on the page
        LayoutInflater inflater = (LayoutInflater)
                getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View content = inflater.inflate(R.layout.pdf_layout, null);

        content.measure(2250, 1400);
        content.layout(0,0, 2250, 1400);

        tvName = (TextView)content.findViewById(R.id.tvName);
        tvDate = (TextView)content.findViewById(R.id.tvDate);
        tvAge = (TextView)content.findViewById(R.id.tvAge);
        tvGender = (TextView)content.findViewById(R.id.tvGender);
        tvPhone = (TextView)content.findViewById(R.id.tvPhone);
        lvList = (ListView)content.findViewById(R.id.lvList);
        lvList.setAdapter(adapter);
        Utils.setListViewHeight(lvList, CreatePDFDemo.this);

        tvName.setText(name);
        tvAge.setText(age + "Y");
        tvGender.setText(gender);
        tvPhone.setText(phone);

        content.draw(page.getCanvas());

        // finish the page
        document.finishPage(page);
        // add more pages
        // write the document content
        try {
            document.writeTo(output);
        } catch (IOException e) {
            e.printStackTrace();
        }

      

This output is similar to this image,

enter image description here

How can I write a layout view that spans the full width of the PDF page?

+3


source to share


3 answers


Change this,

        int measureWidth = View.MeasureSpec.makeMeasureSpec(page.getCanvas().getWidth(), View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(page.getCanvas().getHeight(), View.MeasureSpec.EXACTLY);

        content.measure(measureWidth, measuredHeight);
        content.layout(0, 0, page.getCanvas().getWidth(), page.getCanvas().getHeight());

      



This will result in the full height and width of the page.

0


source


Use [PrintContent] ( https://developer.android.com/reference/android/support/v4/print/PrintHelper.html )!



 // Get the print manager.
PrintHelper printHelper = new PrintHelper(this);

// Set the desired scale mode.
printHelper.setScaleMode(PrintHelper.SCALE_MODE_FIT);

// Get the bitmap for the ImageView drawable.
Bitmap bitmap = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();

// Print the bitmap.
printHelper.printBitmap("Print Bitmap", bitmap);

      

+1


source


Try converting your layout to an image and then set that image to PDF. read this maybe you get some idea. Convert presentation to PDF

0


source







All Articles