PDFrenderer 设置屏幕比例

PDFrenderer setting scale to screen

我正在使用下面的代码来呈现 pdf。这是在 try/catch 中并且效果很好,显示了 pdf。

问题是 pdf 文件对于屏幕来说太大了。有谁知道如何缩小它以适应吗?

谢谢。

        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();

您需要创建一个与页面的纵横比相匹配的位图。最好也匹配 ImageView 的尺寸:

                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);

编辑:

为了避免 ImageView 的宽度和高度为 0,一种解决方案是 post 包含以下代码的 Runnable:

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