Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a PDF with custom size in android with PdfDocument

Tags:

java

android

pdf

PdfDocument is a class that makes it possible to generate a PDF from an Android View. You simply add a View to PdfDocument and then save the PDF to memory.

However, I wouldn't like to add a View that is already rendered in the screen, because such View is only good for smartphone screens, and I want to generate a PDF document for printers.

Therefore, I want to pass a View without rendering. While it's certainly possible for me to do that, how would the dimensions and proportions be decided? How can I control this in my PDF?

UPDATE:

Following the answer below from clotodex, I did:

    LayoutInflater inflater = getLayoutInflater();
    View linearview;
    linearview = inflater.inflate(R.layout.printed_order,
                                  findViewById(android.R.id.content),
                                  false);

    PdfDocument document = new PdfDocument();
    PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(2480, 3508, 0).create();
    PdfDocument.Page page = document.startPage(pageInfo);

    linearview.draw(page.getCanvas());
    document.finishPage(page);

    OutputStream outStream;
    File file = new File(getExternalFilesDir(null), "pedido.PDF");

    try {
        outStream = new FileOutputStream(file);
        document.writeTo(outStream);
        document.close();
        outStream.flush();
        outStream.close();

but I get an empty PDF. If I do

View view = findViewById(android.R.id.content);
view.draw(page.getCanvas());

in place of

linearview.draw(page.getCanvas()); 

I get the activity I'm in, which confirms everything is rigth, except for the view that I'm trying to print.

like image 961
PPP Avatar asked Oct 15 '22 07:10

PPP


1 Answers

Have a look at this question render view off-screen in android.

In Android the measurements for a view are given by the parent layout. This means you can create a new layout with your desired measurements and inflate your view with attachToRoot=false and root=your_new_layout.

When you have rendered the view you can now proceed as you would with drawing a rendered view to pdf (following the instruction in your link or converting it to a bitmap before drawing to the page canvas).

like image 88
clotodex Avatar answered Oct 19 '22 02:10

clotodex