前言
图片文件转pdf
如何将图片转pdf
- 引入依赖
xml
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
- 转换工具
java
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageToPdfUtil {
private static Logger log = LoggerFactory.getLogger(ImageToPdfUtil.class);
/**
* 支持png jpg
*
* @param source
* @param target
* @return
*/
public static boolean image2Pdf(String source, String target) {
Document document = new Document();
// 设置文档页边距
document.setMargins(0, 0, 0, 0);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(target);
PdfWriter.getInstance(document, fos);
// 打开文档
document.open();
// 获取图片的宽高
Image image = Image.getInstance(source);
float imageHeight = image.getScaledHeight();
float imageWidth = image.getScaledWidth();
// 设置页面宽高与图片一致
Rectangle rectangle = new Rectangle(imageWidth, imageHeight);
document.setPageSize(rectangle);
// 图片居中
image.setAlignment(Image.ALIGN_CENTER);
// 新建一页添加图片
document.newPage();
document.add(image);
} catch (Exception ioe) {
log.error("image to pdf fail," + source + "-->" + target, ioe);
return false;
} finally {
// 关闭文档
try {
document.close();
fos.flush();
fos.close();
} catch (IOException e) {
log.error("document close fail", e);
}
}
return true;
}
}
- 测试用例
java
ImageToPdfUtil.image2Pdf("C:\\test\\test.jpg", "C:\\test\\test.pdf");
读取test.jpg生成一个pdf 文件