Java 多张图片 转PDF格式
创建多张图片转PDF工具类
package order.util;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;
import com.hbasesoft.framework.common.utils.logger.LoggerUtil;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
/**
*
* <Description>多张图片转pdf
*
* @author
* @version 1.0
* @taskId
* @CreateDate 2018年8月30日
* @since V1.0
* @see order.util
*/
public class ImgToPDFUtil {
/**
*
* Description: <br>
*
* @author <br>
* @taskId <br>
* @param fileName pdf文件路径
* @param imagesPath 图片文件路径
* @return <br>
*/
public static File imageToPDF(String fileName, String imagesPath) {
try {
// 生成14位消息流水号
Random rand = new Random();
String cardNnumer = "";
for (int a = 0; a <= 14; a++) {
cardNnumer += rand.nextInt(10);
}
fileName = fileName+"\\"+cardNnumer+".pdf";
File file = new File(fileName);
// 第一步:创建一个document对象。
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
// 第二步:
// 创建一个PdfWriter实例,
PdfWriter.getInstance(document, new FileOutputStream(fileName));
// 第三步:打开文档。
document.open();
// 第四步:在文档中增加图片。
File files = new File(imagesPath);
String[] images = files.list();
int len = images.length;
for (int i = 0; i < len; i++)
{
if (images[i].toLowerCase().endsWith(".bmp")
|| images[i].toLowerCase().endsWith(".jpg")
|| images[i].toLowerCase().endsWith(".jpeg")
|| images[i].toLowerCase().endsWith(".gif")
|| images[i].toLowerCase().endsWith(".png")) {
String temp = imagesPath + "\\" + images[i];
Image img = Image.getInstance(temp);
img.setAlignment(Image.ALIGN_CENTER);
// 根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
document.newPage();
document.add(img);
} else {
LoggerUtil.info("此文件不是图片类型");
}
}
// 第五步:关闭文档。
document.close();
return file;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
下面是使用方法,使用阿里云oss