多张图片合成PDF


import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * 图片转换PDF类
 */
@Slf4j
@Service
public class ImgPDF {


    /**
     * 将图片转换成PDF
     *
     * @param urlList 文件路径的集合 可以调用 FileUtil.getFileList() 方法
     * @param target  PDF的名字和位置
     */
    public String ImgChangePDF(List<String> urlList, String target) {
        //创建一个文档对象
        Document doc = new Document();
        try {
            FileOutputStream outputStream = new FileOutputStream(target);
            //定义输出文件的位置
            PdfWriter.getInstance(doc, outputStream);
            //开启文档
            doc.open();
            // 循环获取图片文件夹内的图片
            for (int i = 0; i < urlList.size(); i++) {
                if (urlList.get(i) == null) {      //前面的方法默认了数组长度是1024,所以这里就让它提前退出循环
                    break;
                }
                StringBuffer stringBuffer = new StringBuffer();
                OkHttpClient okClient = new OkHttpClient();
                Request request = new Request.Builder().url(urlList.get(i)).build();
                try {
                    okClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            log.error(e.getMessage());
                        }

                        @Override
                        public void onResponse(Call call, Response rsp) throws IOException {
                            stringBuffer.append(rsp.body().bytes());
                        }
                    });
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
                Image img = Image.getInstance(stringBuffer.toString());
                //图片居中
                img.setAlignment(Image.MIDDLE);
                // 根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
                doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
                doc.newPage();
                //设置高和宽的比例
                doc.add(img);
            }
            // 关闭文档
            doc.close();
        } catch (IOException | DocumentException e) {
            log.error(e.getMessage());
        }
        //反回文件url
        UploadFileReq uploadFileReq = new UploadFileReq();
        uploadFileReq.setContType("application/pdf");
        uploadFileReq.setInfo(getBytesByFile(target));
        uploadFileReq.setFileName("发票图片列表_" + DateUtil.toDateString(new Date(), "yyyyMMddHHmmssSSS") + ".pdf");
        ResponseBO<FileInfoResp> responseBO = fileCommonServiceFeign.uploadPublicByte(uploadFileReq);
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "yourEndpoint";
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String content = "Hello OSS";
        PutObjectRequest putObjectRequest = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", new ByteArrayInputStream(content.getBytes()));
        URL url = ossClient.putObject(getBytesByFile(target));
        ossClient.shutdown();
        File file = new File(target);
        if (file.exists()) {
            boolean delete = file.delete();
            log.info("文件删除成功:{}", delete);
        }
        return String.valueOf(url);
    }

    public static byte[] getBytesByFile(String filePath) {
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                file.deleteOnExit();
                return null;
            }
            //获取输入流
            FileInputStream fis = new FileInputStream(file);
            //新的 byte 数组输出流,缓冲区容量1024byte
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            //缓存
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            //改变为byte[]
            byte[] data = bos.toByteArray();
            //
            bos.close();
            return data;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 压缩
     *
     * @param
     */
    public static Integer getPercent(Float h, Float w) {
        int g;
        float g2;
        g2 = 480 / w * 100;
        g = Math.round(g2);
        return g;
    }

    /**
     * @Description: 通过图片路径及生成pdf路径,将图片转成pdf
     */
    public String imgOfPdf(List<String> imgUrl) {
        //输出pdf文件路径
        return ImgChangePDF(imgUrl, UUID.randomUUID().toString()+".pdf");
    }



}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值