WebView设置开启页面缩放:
settings = webView.getSettings();
settings.setSupportZoom(true);
settings.setJavaScriptEnabled(true);
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
实际上并不是WebView设置开启页面缩放后,所有页面都能使用缩放,只有WebView设置的url的页面允许使用缩放才有用。
像我们使用的pdf文件链接是不会生效的,我们需要自定义HTML,并开启页面缩放,让将pdf文件加载到自定义的HTML页面里。
自定义HTML:
编写html中的meta属性,设置minimum-scale,maximum-scale属性,将user-scalable设置为yes
index.html完整代码:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport"content="width=device-width,initial-scale=1.0,maximum-scale=4.0,user-scalable=yes"/><title>Document</title><style type="text/css">canvas {width: 100%;height: 100%;border: 1px solid black;}</style><link rel="resource" type="application/l10n" href="locale/locale.properties"><script src="https://unpkg.com/pdfjs-dist@1.9.426/build/pdf.min.js"></script><script src="https://unpkg.com/pdfjs-dist@1.9.426/build/pdf.worker.min.js"></script><script type="text/javascript" src="index.js"></script>
</head>
<body>
</body>
</html>
index.js完整代码:
var url = location.search.substring(1);PDFJS.cMapUrl = 'https://unpkg.com/pdfjs-dist@1.9.426/cmaps/';
PDFJS.cMapPacked = true;var pdfDoc = null;function createPage() {var div = document.createElement("canvas");document.body.appendChild(div);return div;
}function renderPage(num) {pdfDoc.getPage(num).then(function (page) {var viewport = page.getViewport(2.0);var canvas = createPage();var ctx = canvas.getContext('2d');canvas.height = viewport.height;canvas.width = viewport.width;page.render({canvasContext: ctx,viewport: viewport});});
}PDFJS.getDocument(url).then(function (pdf) {pdfDoc = pdf;for (var i = 1; i <= pdfDoc.numPages; i++) {renderPage(i)}
});
将index.html和index.js文件放到项目src下面的assets文件夹:
webview使用:
webView?.loadUrl(“file:///android_asset/index.html?https://www.xxx.cn/pdf/123.pdf”);
测试pdf文件能够正常缩放。