「Android」将网页转换为PDF的初步实现
获取目标网页URL
// 需要转换为网页URL
private static final String URL = "https://www.baidu.com";
获取WebView对象
// 获取WebView对象
mWebView = findViewById(R.id.demo_webView);
初始化WebView对象
// 初始化WebView对象
private void initWebView() {
WebSettings settings = mWebView.getSettings();
settings.setAllowContentAccess(true);
settings.setBuiltInZoomControls(false);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
settings.setJavaScriptEnabled(true);
// 开启Application Cache功能
settings.setAppCacheEnabled(true);
// 设置适配
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setDomStorageEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.d(TAG, "onPageStarted");
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d(TAG, "onPageFinished");
// 网页加载完成后
// 将浏览器网页转换为PDF
captureBrowser(mWebView, WebViewActivity.this);
}
});
mWebView.loadUrl(URL);
}
将浏览器网页转换为PDF
/**
* 将浏览器网页转换为PDF
*
* @param webView webView
* @param context context
*/
public static void captureBrowser(WebView webView, Context context) {
Log.d(TAG, "captureBrowser: ");
try {
// 创建存储文件
File pdfFile = new File(context.getExternalFilesDir(null).getAbsolutePath() + "/PDF.pdf");
if (pdfFile.exists()) {
pdfFile.delete();
}
pdfFile.createNewFile();
sDescriptor = ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_WRITE);
// 设置参数
PrintAttributes.MediaSize isoA4 = PrintAttributes.MediaSize.ISO_A4;
PrintAttributes attributes = new PrintAttributes.Builder().setMediaSize(isoA4)
.setResolution(new PrintAttributes.Resolution("id", Context.PRINT_SERVICE, 500, 500))
.setColorMode(PrintAttributes.COLOR_MODE_COLOR)
.setMinMargins(PrintAttributes.Margins.NO_MARGINS)
.build();
// 计算需要的页数
int numberOfPages = (webView.getContentHeight() * 500 / (isoA4.getHeightMils()));
sRanges = new PageRange[] {new PageRange(0, numberOfPages)};
// 获取webView适配器
sPrintAdapter = webView.createPrintDocumentAdapter("PDF");
// 开始打印
sPrintAdapter.onStart();
sPrintAdapter.onLayout(attributes, attributes, new CancellationSignal(),
new PrintDocumentAdapter.LayoutResultCallback() {
@Override
public void onLayoutFinished(PrintDocumentInfo info, boolean changed) {
sPrintAdapter.onWrite(sRanges, sDescriptor, new CancellationSignal(),
new PrintDocumentAdapter.WriteResultCallback() {
@Override
public void onWriteFinished(PageRange[] pages) {
Log.d(TAG, "onWriteFinished: PdfWrite is Finished");
super.onWriteFinished(pages);
}
});
super.onLayoutFinished(info, changed);
}
}, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。