/*
* 图片转换成pdf
* 注意:这里需要导入 com.lowagie.text-2.1.7jar包
* imgPath:图片路径,如 E:\\victoria\\001.jpg"
* pdfPath:转换之后的pdf路径,如 E:\\victoria\\001.pdf
*/
public boolean jpgToPdf(String imgPath,String pdfPath) throws IOException {
//判断文件是否存在
if (new File(imgPath).exists()) {
Document doc = new Document(PageSize.A4);
try {
//生成pdf
PdfWriter.getInstance(doc, new FileOutputStream(pdfPath));
doc.open();
float newHeight = 0;
//判断文件的宽度
float pageWidth = doc.getPageSize().getWidth();
float pageHeight = doc.getPageSize().getHeight();
//获取图片的大小
Image image = Image.getInstance(imgPath);
float imageWidth = image.getPlainHeight();
float imageHeight = image.getPlainWidth();
//使图片自动适应大小
if(imageWidth > pageWidth - 72) {
image.scaleAbsoluteWidth(pageWidth-72);
newHeight += imageHeight*(pageWidth - 72)/imageWidth +36;
image.scaleAbsoluteHeight(imageHeight*(pageWidth -72)/imageWidth);
}else{
newHeight += imageHeight + 36;
}
//判断是否需要分页
if (pageHeight < newHeight) {
doc.newPage();
newHeight = imageHeight*(pageWidth -72)/imageWidth +36;
}
image.setAbsolutePosition(36, pageHeight - newHeight);
doc.add(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (DocumentException e) {
e.printStackTrace();
return false;
} finally {
doc.close();
File file = new File(imgPath);
if (new File(imgPath).exists()) {
file.delete();
}
}
}else{
return false;
}
return true;
}