9

Is there a way to change default portrait preview to landscape in print framework?

I have tried below -

PrintAttributes attrib = new PrintAttributes.Builder()
.setMediaSize(PrintAttributes.MediaSize.NA_LETTER.asLandscape())
.setMinMargins(PrintAttributes.Margins.NO_MARGINS)
. build();

and also tried below -

PrintAttributes attrib = new PrintAttributes.Builder()
.setMediaSize(PrintAttributes.MediaSize.UNKNOWN_LANDSCAPE)
.setMinMargins(PrintAttributes.Margins.NO_MARGINS)
. build();

I've noticed that it doesn't change the page orientation to Landscape

print settings

In above print setting dialog if I do change the orientation to landscape then and only then the print preview page changes orientation to Landscape. Can this be done programmatically? I want default preview in Landscape.

kevz
  • 2,727
  • 14
  • 39

2 Answers2

7

I used below Code:

PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);
    String jobName = this.getString(R.string.app_name) + " Document";

    PrintAttributes attrib = new PrintAttributes.Builder()
            .setMediaSize(PrintAttributes.MediaSize.UNKNOWN_LANDSCAPE)
            . build();

    printManager.print(jobName, pda, attrib);

My Result:

enter image description here

Md. Zakir Hossain
  • 1,082
  • 11
  • 24
1

Just in case anyone find it useful, it’s possible to set the orientation from MediaSize object using asPortrait() or asLandscape().

Example:

PrintAttributes attributes = new PrintAttributes.Builder().
setMediaSize(PrintAttributes.MediaSize.ISO_A4.asLandscape()).build();

If someone want to set this dynamically based on a PDF file dimension, it’s is also possible to use PdfRenderer to render a page and get the PDF dimensions:

try {
        ParcelFileDescriptor fileDescriptor = ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY);
        PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
        PdfRenderer.Page p= pdfRenderer.openPage(1);
        if(p.getHeight()>=p.getWidth())
            printAttrbutesBuilder.setMediaSize(PrintAttributes.MediaSize.ISO_A4.asPortrait());
        else
            printAttrbutesBuilder.setMediaSize(PrintAttributes.MediaSize.ISO_A4.asLandscape());
    }catch (Exception e){
        printAttrbutesBuilder.setMediaSize(PrintAttributes.MediaSize.ISO_A4);
    }