1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > Java 多张图片 转PDF格式

Java 多张图片 转PDF格式

时间:2023-02-10 22:38:46

相关推荐

Java 多张图片 转PDF格式

创建多张图片转PDF工具类

package order.util;

import java.io.File;

import java.io.FileOutputStream;

import java.util.Random;

import com.mon.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 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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。