有這么一個(gè)需求亡资,將指定文件夾下的圖片做成PDF格式的文件澜共,然后上傳到服務(wù)端便于相關(guān)人員的瀏覽。
直接上代碼吧锥腻。嗦董。。
//讀寫(xiě)權(quán)限均已允許
//sdCardPath根目錄 根目錄下有三張圖片aaa瘦黑、bbb京革、ccc
Bitmap bitmap1 = BitmapFactory.decodeFile(sdCardPath + "/aaa.jpg");
Bitmap bitmap2 = BitmapFactory.decodeFile(sdCardPath + "/bbb.jpg");
Bitmap bitmap3 = BitmapFactory.decodeFile(sdCardPath + "/ccc.jpg");
List<Bitmap> bitmaps = new ArrayList<>();
bitmaps.add(bitmap1);
bitmaps.add(bitmap2);
bitmaps.add(bitmap3);
//bitmaps存放的即將要寫(xiě)入PDF文件里面的圖片
saveBitmapForPdf(bitmaps);
接下來(lái)是重要的代碼片段了销睁,這段代碼可以直接復(fù)制粘貼到項(xiàng)目里使用。
private void saveBitmapForPdf(List<Bitmap> bitmaps) {
//將bitmap轉(zhuǎn)為pdf
PdfDocument doc = new PdfDocument();
//PrintAttributes.MediaSize.ISO_A4 這是A4紙的尺寸 獲取到A4紙頁(yè)面的寬度 pageWidth
int pageWidth = PrintAttributes.MediaSize.ISO_A4.getWidthMils() * 72 / 1000;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
for (Bitmap bitmap : bitmaps){
float scale = (float) pageWidth / (float) bitmap.getWidth();
int pageHeight = (int) (bitmap.getHeight() * scale);
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
//每一頁(yè)畫(huà)一張圖
PdfDocument.PageInfo newPage = new PdfDocument.PageInfo.Builder
(pageWidth, pageHeight, bitmaps.indexOf(bitmap)).create();
PdfDocument.Page page = doc.startPage(newPage);
Canvas canvas = page.getCanvas();
canvas.drawBitmap(bitmap, matrix, paint);
canvas.save();
canvas.restore();
doc.finishPage(page);
}
//將pdf文件存到根目錄
File file = new File(sdCardPath, "pdfDemo.pdf");
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
doc.writeTo(outputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
doc.close();
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
到這里就結(jié)束了存崖,我這邊的需求是每一頁(yè)展示一張圖即可冻记,如果涉及到頁(yè)面排版的需求就需要根據(jù)具體的排版需求來(lái)計(jì)算Bitmap的縮放以及頁(yè)面的排版了。