依赖
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
图片转pdf工具方法
/**
* 图片转pdf
* @param source
* @param target
*/
public static void ImgChangePDF(List<String> source, String target) {
//创建一个文档对象
Document doc = new Document();
try {
//定义输出文件的位置
PdfWriter.getInstance(doc, new FileOutputStream(target));
//开启文档
doc.open();
// 循环获取图片文件夹内的图片
for (String url : source) {
if(url == null) {
continue;
}
//路径
Image img = Image.getInstance(url);
//获得宽高
Float h = img.getHeight();
Float w = img.getWidth();
//统一压缩
Integer percent = getPercent(h, w);
//图片居中
img.setAlignment(Image.MIDDLE);
//百分比显示图
img.scalePercent(percent);
//设置高和宽的比例
doc.add(img);
}
// 关闭文档
if(doc != null){
doc.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (BadElementException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
/**
* 压缩
* @param h
* @param w
* @return
*/
public static Integer getPercent(Float h,Float w) {
Integer g=0;
Float g2=0.0f;
g2=480/w*100;
g=Math.round(g2);
return g;
}
public static void main(String[] args) {
List<String> source = new ArrayList<String>();
source.add("http://127.0.0.1:8080/img/189.png");
source.add("http://127.0.0.1:8080/img/1222.png");
ImgChangePDF(source, "D:/attachment/PDF/test.pdf");
}
pdf合并工具方法
/**
* pdf 合并
* @param files
* @param newfile
* @return
*/
public static boolean mergePdfFiles(List<String> files, String newfile) {
boolean retValue = false;
Document document = null;
PdfCopy copy = null;
PdfReader reader = null;
try {
document = new Document(new PdfReader(files.get(0)).getPageSize(1));
copy = new PdfCopy(document, new FileOutputStream(newfile));
document.open();
for (int i = 0; i < files.size(); i++) {
reader = new PdfReader(files.get(i));
int n = reader.getNumberOfPages();
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
}
retValue = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (copy != null) {
copy.close();
}
if (document != null) {
document.close();
}
}
return retValue;
}