java实现图片转pdf文件

2021年新年快乐!在此祝大家代码无bug~~~

由于我是驻场开发,前段时间问我要个证件扫描件的PDF文件,我一想,现在转换pdf文件是要花钱的啊,这是我能忍受的了的吗!!!

答案当然是不能啊,我的贫贱怎么能让我花这钱呢~~~突然脑壳一亮,截个图直接把图片转为pdf文件不就完事了吗,说干就干:

今天记录个小知识点,主要是将图片转为pdf文档。
首先引入依赖:

    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.5.13</version>
    </dependency>

依赖版本大家可以自己看着用,没有做过太多了解。
代码如下:

public static void main(String[] arg){
      imgOfPdf();
}
public static void imgOfPdf() {
	  try {
	  		//创建个存放图片地址的集合
	       List<String> imageUrlList = new ArrayList();
	       //添加图片地址到集合
	       imageUrlList.add("C:\\Users\\Lenovo\\Pictures\\Saved Pictures\\123.jpg");
	       //存放pdf文件的路径
	       String pdfUrl = "D:\\123.pdf";
	       File file = PdfUtilImg.pdf(imageUrlList, pdfUrl);//生成pdf
	       file.createNewFile();
	   } catch (IOException e) {
	       e.printStackTrace();
	   }
}

上面代码中可以将集合和存放pdf地址当做参数传进来,这里我是直接写死的,也就不用做图片是否存在的校验了。校验步骤可以在使用此方法前完成。

OK,接下来是我们的主菜:

public static File pdf(List<String> imageUrllist, String pdfUrl) {
	//new一个pdf文档
    Document doc = new Document(PageSize.A4, 20, 20, 20, 20); 
    try {
        //pdf写入
        PdfWriter.getInstance(doc, new FileOutputStream(pdfUrl));
        //打开文档
        doc.open();
        //遍历集合,将图片放在pdf文件
        for (int i = 0; i < imageUrllist.size(); i++) {
        	//在pdf创建一页   主:此处为每一张图片是pdf文件的一页
            doc.newPage();  
            //通过文件路径获取image
            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(pdfUrl); 
    if (!mOutputPdfFile.exists()) {
        mOutputPdfFile.deleteOnExit();
        return null;
    }
    //反回文件输出流
    return mOutputPdfFile;
}

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;
}

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;
}

代码到此结束,给大家展示下转换后效果:
在这里插入图片描述

此文借鉴于:https://www.cnblogs.com/sky-zky/p/9639256.html

猜你喜欢

转载自blog.csdn.net/xaiobaicai/article/details/112182147