功能:相机、相册选取单张图片,合并转PDF文件,过大图片可全部展示
效果图:

实现组件:iText组件
代码:
implementation 'com.itextpdf:itextg:5.5.10'
private static String pdfUrl;
//画布最宽:500
private static int MAX_WIDTH = 550;
//画布最高:750
private static int MAX_HEIGHT = 750;
public static String imgOfPdf(String filepath, String imgUrl) {
try {
//图片list集合
ArrayList<String> imageUrllist = new ArrayList<String>();
String[] imgUrls = imgUrl.split(",");
for (int i=0; i<imgUrls.length; i++) {
imageUrllist.add(imgUrls[i]);
}
//输出pdf文件路径
Log.d("测试输出pdf文件路径", filepath);
pdfUrl = filepath;
//生成pdf
File file = imgToPdf(imageUrllist, pdfUrl);
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return pdfUrl;
}
public static File imgToPdf(ArrayList<String> sources, String target) {
//创建文件并设置文档页边距
Document document = new Document(PageSize.A4, 20, 20, 20, 20);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(target);
PdfWriter.getInstance(document , fos);
//打开文件
document .open();
// 添加PDF文档的某些信息,比如作者,主题等等
//document.addTitle("鲁班移动");
//document.addAuthor("作者:zhengtai.li@kuwo.cn");
//document.addSubject("主题:企业信息");
// 写入一段文字
// document.add(new Paragraph("Test! Test! Test! Test! Test! Test!"));
for (int i = 0; i < sources.size(); i++) {
//获取原图片的宽高
Image image = Image.getInstance(sources.get(i));
float imageHeight = image.getScaledHeight();
float imageWidth = image.getScaledWidth();
// 获取缩放比例
int percent = 100;
//如果原图宽度大于原图高度,则使用宽度来计算缩放比例,否则按高度来计算缩放比较。
//例:原图高1500,宽1000,则使用画布高度和原图高度来计算缩放比例(750/1500*100=50%)
if (imageWidth >= imageHeight) {
//小于画布宽度的图片不用缩放
if (imageWidth > MAX_WIDTH) {
percent = Math.round(MAX_WIDTH / imageWidth * 100) - 3;
}
} else {
//小于画布高度的图片不用缩放
if (imageHeight > MAX_HEIGHT) {
percent = Math.round(MAX_HEIGHT / imageHeight * 100) - 3;
}
}
// 设置图片比例,表示是原来图像的比例(原图越大,percent的值越小);
image.scalePercent(percent);
//图片居中
image.setAlignment(Image.MIDDLE);
//新建一页添加图片
document.newPage();
document.add(image);
}
} catch (Exception e) {
Log.d("{}图片合成失败:{}", target+ e.getMessage()+ e);
return null;
}finally {
//关闭文档
document.close();
try {
fos.flush();
fos.close();
} catch (IOException e) {
Log.d("关闭文档失败。。。","");
}
}
File outputPdfFile = new File(target);
if (!outputPdfFile.exists()) {
outputPdfFile.deleteOnExit();
return null;
}
return outputPdfFile;
}