PdfDocument類
Android API19中提供了PdfDocument類,實(shí)現(xiàn)了根據(jù)Android頁(yè)面生成PDF文檔炕泳。
API21中提供了PdfRenderer類纵诞,實(shí)現(xiàn)了渲染PDF文檔。
實(shí)現(xiàn)頁(yè)面生成PDF
首先新建PdfDocument對(duì)象培遵。
PdfDocument document = new PdfDocument();
新建一個(gè)PageInfo對(duì)象浙芙,參數(shù)分別是,寬籽腕、高和頁(yè)數(shù)嗡呼。
這里view的getWidth()方法是獲取控件的高度,使用getMeasuredHeight()方法是獲取可視范圍內(nèi)的高度皇耗。
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(scrollView.getWidth(), scrollView.getHeight(), 1).create();
同根document對(duì)象南窗,新建第一頁(yè)對(duì)象。
PdfDocument.Page page = document.startPage(pageInfo);
用View的draw()方法,page對(duì)象提供畫筆繪制View万伤。
scrollView.draw(page.getCanvas());
調(diào)用finishPage()方法表示繪制結(jié)束窒悔。
document.finishPage(page);
最后,將document對(duì)象輸出為File即可敌买。
document.writeTo(new FileOutputStream(file));
最后要將document關(guān)閉以免內(nèi)存泄漏简珠。
document.close();
這里有一個(gè)重點(diǎn),在Android7.0及以下版本(版本節(jié)點(diǎn)可能上下有所浮動(dòng)虹钮,測(cè)試不完全)北救,會(huì)出現(xiàn)繪制速度慢導(dǎo)致線程阻塞,生成文件過(guò)大(中字導(dǎo)致)芜抒,所以最好將執(zhí)行方法放到子線程進(jìn)行
Android PdfViewer進(jìn)行本地預(yù)覽
集成
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
在XML中填充控件
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdf_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
直接傳入文件對(duì)象,可以直接加載本地文件
File file = new File(Environment.getExternalStorageDirectory() + "/計(jì)價(jià)器檢定證書.pdf");
pdfView.fromFile(file).load();