Search code examples
androidpdfmobility

How can i create landscape PDF using android native PdfDocument API?


I am using PdfDocument API to write a PDF from View using Android

Problem

If am writing PDF of A4 size. How can i make in landscape mode?

Thanks in Advance.


Solution

  • A typical use of the Android PDF APIs looks like this:

    // create a new document
    PdfDocument document = new PdfDocument();
    
    // crate a page description
    PageInfo pageInfo = new PageInfo.Builder(300, 300, 1).create();
    
    // start a page
    Page page = document.startPage(pageInfo);
    
    // draw something on the page
    View content = getContentView();
    content.draw(page.getCanvas());
    
    // finish the page
    document.finishPage(page);
    . . .
    // add more pages
    . . .
    // write the document content
    document.writeTo(getOutputStream());
    
    // close the document
    document.close();
    

    According to the developer.android.com reference:

    public PdfDocument.PageInfo.Builder (int pageWidth, int pageHeight, int pageNumber)
    

    Added in API level 19

    Creates a new builder with the mandatory page info attributes.

    Parameters

    pageWidth The page width in PostScript (1/72th of an inch).

    pageHeight The page height in PostScript (1/72th of an inch).

    pageNumber The page number.

    To create a PDF with portrait A4 pages, therefore, you can define the page descriptions like this:

    PageInfo pageInfo = new PageInfo.Builder(595, 842, 1).create();
    

    and for a PDF with landscape A4 pages, you can define them like this:

    PageInfo pageInfo = new PageInfo.Builder(842, 595, 1).create();