多个图片合并生成1个图片或1个pdf

原始需求:

用户分别上传身份证正反面照片,后台合并成一张照片或一个pdf文件;

为方便业务扩展,可支持多张照片合并:

方式1:多图合成一张图片

package com.solar.common.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import javax.imageio.ImageIO;
import org.springframework.util.Assert;
 

public class Test {
    /**
     * 合并图片
     * @Title:merge
     * @date 2022年12月12日 上午9:59:33
     * @author yqwang
     * @param files 源图
     * @param distPath 合并后图片存放位置
     */
    public static void merge(List<File> files, String distPath) {
         Assert.notEmpty(files,"源图参数不能为空。");
         Assert.isTrue(files.size()>=2,"源图不得少于2张。");
         int dstHeight = 0;
         int dstWidth = 0;
         // 获取需要拼接的图片长度
         int len = files.size();
         // 判断长度是否大于0
         BufferedImage[] images = new BufferedImage[len];
         int[][] ImageArrays = new int[len][];
         for (int i = 0; i < len; i++) {
             try {
            	Assert.isTrue(files.get(i)!=null,"图片文件为空");
                images[i] = ImageIO.read(files.get(i));
 	            int width = images[i].getWidth();
 	            int height = images[i].getHeight();
 	            Assert.isTrue(width>=1,"源图高度太小。");
 	            Assert.isTrue(height>=1,"源图宽度太小。");
 	            // 从图片中读取RGB 像素
 	            ImageArrays[i] = new int[width * height];
 	            ImageArrays[i] = images[i].getRGB(0, 0, width, height, ImageArrays[i], 0, width);
 	
 	            // 计算合并的宽度和高度
 	            dstWidth = dstWidth > width ? dstWidth : width;
 	            dstHeight += height;
             } catch (Exception e) {
                 e.printStackTrace();
                 Assert.isTrue(false,"读取图片信息失败:"+e.getMessage());
             }
         }

         // 合成图片像素
         //System.out.println("宽度:" + dstWidth);
         //System.out.println("高度:" + dstHeight);
         
         // 生成新图片
         try {
             BufferedImage imageNew = new BufferedImage(dstWidth, dstHeight, BufferedImage.TYPE_INT_RGB);
             int height_i = 0;
             for (int i = 0; i < images.length; i++) {
                 int width = images[i].getWidth();
                 int height = images[i].getHeight();
                 imageNew.setRGB(0, height_i, width, height, ImageArrays[i], 0, width);
                 height_i += height;
             }
             File outFile = new File(distPath);
             // 写图片,输出到硬盘
             ImageIO.write(imageNew, "jpg", outFile);
         } catch (Exception e) {
             e.printStackTrace();
             Assert.isTrue(false,e.getMessage());
         } 
    	
    }
 
}

方式2:多图合成一个pdf文件

需要使用包itextpdf


        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>xxxxxxx</version>
        </dependency>
package com.solar.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import org.springframework.util.Assert;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.solar.util.FileHelper;
import com.solar.util.ListUtil;

public class Test {
    private final static List<String> imgFileTypes=ListUtil.split("bmp,jpg,jpeg,gif,png", ","); 

	/**
	 * 多个图片生成pdf文件
	 * @Title:buildPdfByImgs
	 * @Description: TODO 
	 * @date 2022年12月12日 下午2:27:40
	 * @author yqwang
	 * @param imgs 图片文件列表
	 * @param distPath 目标路径
	 * @throws Exception
	 */
	public static void buildPdfByImgs(List<File> imgs,String distPath) throws Exception{
		// 1:创建一个document对象。
		Document document = new Document();
		try {
			// 2创建一个PdfWriter实例,
			PdfWriter.getInstance(document, new FileOutputStream(new File(distPath)));
			// 3:打开文档。
			document.open();
			// 4:在文档中增加图片。
			document.setPageSize(PageSize.A4);
			String ext;
			Image img;
			for (File file : imgs) {
				ext = FileHelper.getFileExtName(file.getName());
				//只管图片文件
				if(!imgFileTypes.contains(ext.toLowerCase())){
					continue;
				}
				//document.newPage(); 如果每张图片要放独立的一页,这需要每次newPage()
				img = Image.getInstance(FileHelper.readFileToByteArray(file));
				//img = Image.getInstance(filePath);可以使用路径方式读取图像文件
			    img.setAlignment(Image.ALIGN_CENTER);
			    //可能需要将图像缩放到一定百分比。
				Float wPercent = PageSize.A4.getWidth()/img.getWidth();
				Float hPercent = PageSize.A4.getHeight()/img.getHeight();
			    if(wPercent<1 || hPercent<1){
			    	img.scalePercent(Math.min(wPercent, hPercent)*100);
			    }else{
			    	img.scalePercent(100);
			    }
			    //在文档中增加图片
			    document.add(img);
			}
		} catch (Exception e) {
			e.printStackTrace();
			Assert.isTrue(false,e.getMessage());
		}finally{
			try {
				document.close();
			} catch (Exception e) {
			}
		}
    	
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
你可以使用 jsPDFpdf-lib 库来实现将多个 PDF 合并为一个的功能。以下是一个简单的示例: 首先安装依赖: ``` npm install jspdf pdf-lib ``` 然后在你的 Vue 组件中导入依赖: ```javascript import jsPDF from 'jspdf'; import { PDFDocument, StandardFonts } from 'pdf-lib'; ``` 接下来编写一个方法,用于将多个 PDF 合并为一个: ```javascript mergePDFs(pdfs) { // 创建一个新的 PDFDocument 对象 const mergedPdf = await PDFDocument.create(); // 遍历每个 PDF 文件 for (let i = 0; i < pdfs.length; i++) { const pdf = pdfs[i]; // 将 PDF 文件转换为数组缓冲区 const pdfBytes = await pdf.arrayBuffer(); // 将 PDF 文件添加到合并PDF 中 const pdfDoc = await PDFDocument.load(pdfBytes); const copiedPages = await mergedPdf.copyPages( pdfDoc, pdfDoc.getPageIndices() ); copiedPages.forEach((page) => { mergedPdf.addPage(page); }); } // 生成合并PDF 文件 const mergedPdfFile = await mergedPdf.save(); // 使用 jsPDF生成PDF 文件添加到页面上 const doc = new jsPDF(); const totalPages = pdfs.length; for (let pageNum = 1; pageNum <= totalPages; pageNum++) { const pdfBytes = await mergedPdfFile.arrayBuffer(); const pdfDoc = await PDFDocument.load(pdfBytes); const pdfPage = pdfDoc.getPage(pageNum); const { width, height } = pdfPage.getSize(); const pngData = await pdfPage.renderAsPNG({ scale: 1 }); doc.addImage(pngData, 'PNG', 0, 0, width, height); if (pageNum < totalPages) { doc.addPage(); } } // 保存生成PDF 文件 doc.save('merged.pdf'); } ``` 在这个方法中,我们首先创建了一个新的 PDFDocument 对象。然后,我们遍历每个 PDF 文件,并将它们添加到合并PDF 中。最后,我们使用 jsPDF合并PDF 文件添加到页面上,并保存生成PDF 文件。 你可以在你的 Vue 组件中调用这个方法,并将需要合并PDF 文件作为参数传递给它: ```javascript const pdfs = [ '/path/to/pdf1.pdf', '/path/to/pdf2.pdf', '/path/to/pdf3.pdf', ]; this.mergePDFs(pdfs); ``` 注意,这个方法是异步的,因此你需要使用 async/await 或 Promise 来处理它的返回值。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yqwang_cn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值