文档展示:使用iText转换各种图片为PDF

如题:

下面这段代码可以处理各种格式的图片,代码的出处忘记了。

上代码:

/**
* 图片转PDF
* @param sourceFile
* @param destFile
* @return
*/
public static File picToPdf(String sourceFile, String destFile) {
File inputFile = new File(sourceFile);
if (!inputFile.exists()) {
return null;// 找不到源文件, 则返回null
}
// 如果目标路径不存在, 则新建该路径
File outputFile = new File(destFile);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
ArrayList<String> imageUrllist = new ArrayList<String>();
imageUrllist.add(sourceFile);
return imgToPdf(imageUrllist, destFile);
}

/**
* iText转各种图片为pdf
* @param imageUrllist
* @param mOutputPdfFileName
* @return
*/
private static File imgToPdf(ArrayList<String> imageUrllist,String mOutputPdfFileName) {
if(null == imageUrllist){
return null;
}
long beginTime = System.nanoTime();
Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
try {
PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName));
doc.open();
for (int i = 0; i < imageUrllist.size(); i++) {
doc.newPage();
// doc.add(new Paragraph("简单使用iText"));
Image png1 = Image.getInstance(imageUrllist.get(i));
float heigth = png1.getHeight();
float width = png1.getWidth();
int percent = getPercent2(heigth, width);
png1.setAlignment(Image.MIDDLE);
png1.scalePercent(percent+3);// 表示是原来图像的比例;
doc.add(png1);
}
doc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

File mOutputPdfFile = new File(mOutputPdfFileName);
if (!mOutputPdfFile.exists()) {
mOutputPdfFile.deleteOnExit();
return null;
}

try {
mOutputPdfFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
long endTime = System.nanoTime();
System.out.println("图片转pdf耗时: " + (endTime - beginTime) / 1000000000 + " 秒 " + imageUrllist.toString());
return mOutputPdfFile;
}
/**
* 第一种解决方案 在不改变图片形状的同时,判断,如果h>w,则按h压缩,否则在w>h或w=h的情况下,按宽度压缩
*
* @param h
* @param w
* @return
*/

public static int getPercent(float h, float w) {
int p = 0;
float p2 = 0.0f;
if (h > w) {
p2 = 297 / h * 100;
} else {
p2 = 210 / w * 100;
}
p = Math.round(p2);
return p;
}

/**
* 第二种解决方案,统一按照宽度压缩 这样来的效果是,所有图片的宽度是相等的,自我认为给客户的效果是最好的
*
* @param args
*/
public static int getPercent2(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值