PDFrenderer setting scale to screen

社会主义新天地 提交于 2019-12-12 03:49:14

问题


Im using the code below to render a pdf. This is in a try/catch and works well, showing the pdf.

The problem is that the pdf file is too big for the screen. Does anyone know how to scale it down to fit please?

Thank you.

        imageView = (ImageView) findViewById(R.id.imagePDF);

        int REQ_WIDTH = imageView.getWidth();
        int REQ_HEIGHT = imageView.getHeight();

        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int width12 = size.x;
        int height12 = size.y;

        Bitmap bitmap = Bitmap.createBitmap(width12, height12, Bitmap.Config.ARGB_4444);

        File file = new File("/sdcard/Download/sample.pdf");


        PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

        if (currentPage < 0) {
            currentPage = 0;
        } else if (currentPage > renderer.getPageCount()) {
            currentPage = renderer.getPageCount();
        }

        int pages;

        pages = renderer.getPageCount();

        Matrix m = imageView.getImageMatrix();

        Rect rect = new Rect(0, 0, width12, height12);

        renderer.openPage(currentPage).render(bitmap, rect, m, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);

        imageView.setImageMatrix(m);
        imageView.setImageBitmap(bitmap);
        imageView.invalidate();

回答1:


You need to create a Bitmap that matches the aspect ratio of the Page. It's best to match the dimensions of the ImageView as well:

                PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
                PdfRenderer.Page page = renderer.openPage(0);
                int pageWidth = page.getWidth();
                int pageHeight = page.getHeight();
                float scale = Math.min((float) REQ_WIDTH / pageWidth, (float) REQ_HEIGHT / pageHeight);
                Bitmap bitmap = Bitmap.createBitmap((int) (pageWidth * scale), (int) (pageHeight * scale), Bitmap.Config.ARGB_8888);
                page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
                imageView.setImageBitmap(bitmap);

EDIT:

To avoid ImageView having width and height of 0, one solution is to post a Runnable containing the code:

imageView.post(new Runnable() {
    public void run() {
        // The above code goes here
    }
});


来源:https://stackoverflow.com/questions/39545009/pdfrenderer-setting-scale-to-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!