有这么一个需求,将指定文件夹下的图片做成PDF格式的文件,然后上传到服务端便于相关人员的浏览。
直接上代码吧。。。
//读写权限均已允许
//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存放的即将要写入PDF文件里面的图片
saveBitmapForPdf(bitmaps);
接下来是重要的代码片段了,这段代码可以直接复制粘贴到项目里使用。
private void saveBitmapForPdf(List<Bitmap> bitmaps) {
//将bitmap转为pdf
PdfDocument doc = new PdfDocument();
//PrintAttributes.MediaSize.ISO_A4 这是A4纸的尺寸 获取到A4纸页面的宽度 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);
//每一页画一张图
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();
}
}
}
到这里就结束了,我这边的需求是每一页展示一张图即可,如果涉及到页面排版的需求就需要根据具体的排版需求来计算Bitmap的缩放以及页面的排版了。