图片转pdf

/**
* 依赖包:<dependency>
* <groupId>org.eclipse.birt.runtime.3_7_1</groupId>
* <artifactId>com.lowagie.text</artifactId>
* <version>2.1.7</version>
* </dependency>
* <dependency>
* <groupId>com.itextpdf</groupId>
* <artifactId>itextpdf</artifactId>
* <version>5.5.7</version>
* </dependency>
*/
public class Test {

private static final Logger LOGGER = LoggerFactory.getLogger(Test.class);

/**
* 多张图转为pdf
* param imageFolderPath
* param pdfPath
*/
public static void toPdf(String imageFolderPath, String pdfPath) {
try {
long start = System.currentTimeMillis();
ArrayList<String> list = new ArrayList<>();
// 图片地址
String imagePath = null;
new File(pdfPath);
FileOutputStream fos = new FileOutputStream(pdfPath);
// 创建文档
Document doc = new Document(null, 30, 30, 30, 30);
// 写入PDF文档
PdfWriter.getInstance(doc, fos);
// 读取图片流
BufferedImage img;
// 实例化图片
Image image;
// 获取图片文件夹对象
File file = new File(imageFolderPath);
file.setReadable(true, false);
File[] files = file.listFiles();
// 循环获取图片文件夹内的图片
for (File file1 : files) {
if (file1.getName().endsWith(".png") || file1.getName().endsWith(".jpg") || file1.getName().endsWith(".gif")
|| file1.getName().endsWith(".jpeg") || file1.getName().endsWith(".tif")) {
imagePath = imageFolderPath + File.separator + file1.getName();
list.add(file1.getName());
File tf = new File(imagePath);
// 读取图片流
img = ImageIO.read(tf);
// 根据图片大小设置文档大小
doc.setPageSize(new Rectangle(img.getHeight(), img.getWidth()));
// 实例化图片
image = Image.getInstance(imagePath);
// 添加图片到文档
doc.open();
doc.add(image);
}
}
LOGGER.info("fileName is list={}", list);
// 关闭文档
doc.close();
long endTime = System.currentTimeMillis();
int time = (int) ((endTime - start) / 1000);
LOGGER.info("用时:{}:秒!", time);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}


public static void main(String[] args) {
toPdf("C:" + File.separator + "Users" + File.separator + "hp" + File.separator + "Desktop" + File.separator + "bg", "C:" + File.separator + "Users" + File.separator + "hp" + File.separator + "Desktop" + File.separator + "mypdf.pdf");
}
}
posted @   清明雨下  阅读(65)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2021-06-28 hudi spparksql 注意点
点击右上角即可分享
微信分享提示