/*
* 圖片轉換成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;
}