PDF工具

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.PdfWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.constraints.NotNull;
import java.io.*;
import java.net.URISyntaxException;

public class PdfUtil {
    private static final Logger logger = LoggerFactory.getLogger(PdfUtil.class);

    public static void main(String[] args) throws URISyntaxException {
//        String base64 = Base64Utils.fileToBase64("D:\\20220715_acc.ofd");
//        Base64Utils.base64ToFile("E:\\20220715_acc.ofd", base64, "20220715_acc.ofd");
//        ofd2pdf(new File("E:\\\\20220715_acc.ofd").getPath(), "E:\\20220718.pdf");
    }


    /**
     * 图片转PDF
     *
     * @param imagePath 图片地址,支持网络/本地
     * @param pdfPath   PDF待存储地址目录
     * @param margin    上下左右边距,图片缩放时会减小.但是最终生成PDF时可能会被修正成0.
     * @return
     */
    public static boolean image2pdf(@NotNull String imagePath, @NotNull String pdfPath, float margin) {
        log("image2pdf begin,imagePath:" + imagePath);

        //画布尺寸默认竖向A4
        com.itextpdf.text.Rectangle pageSize = PageSize.A4;

        long startTime = System.currentTimeMillis();
        System.out.println("image2pdf startTime = " + startTime);
        try {

            //优先处理图片,防止图片路径或者地址错误加载异常
            com.itextpdf.text.Image itextImage = com.itextpdf.text.Image.getInstance(imagePath);

            //计算缩放比例和旋转图片,以适应指定尺寸显示
            float heigth = itextImage.getHeight();
            float width = itextImage.getWidth();
            if (width > heigth) {
                pageSize = new RectangleReadOnly(pageSize.getHeight(), pageSize.getWidth());
            }
            int percent = getPercent(heigth, width, pageSize.getHeight() - margin * 2, pageSize.getWidth() - margin * 2);

            //图片显示位置,默认居中
            itextImage.setAlignment(com.itextpdf.text.Image.MIDDLE);
            //表示是原来图像的比例;
            itextImage.scalePercent(percent);

            long itextImageTime = System.currentTimeMillis();
            System.out.println("image2pdf itextImageTime = " + itextImageTime + ", 耗时 = " + (itextImageTime - startTime));


            //重置边距margin,居中显示
            float marginLeft = (pageSize.getWidth() - width * percent / 100) / 2;
            marginLeft = marginLeft > 0 ? marginLeft : 0;
            float marginTop = (pageSize.getHeight() - heigth * percent / 100) / 2;
            marginTop = marginTop > 0 ? marginTop : 0;


            //初始化PDF画板
            Document document = new Document(pageSize, marginLeft, marginLeft, marginTop, marginTop);
            PdfWriter.getInstance(document, new FileOutputStream(pdfPath));

            //按照: 打开-新增页面-添加元素 流程处理PDF,多页时执行newPage,add 添加页面即可
            document.open();
            document.newPage();
            document.add(itextImage);

            //处理完页面后关闭就可生成pdf
            document.close();

            long endTime = System.currentTimeMillis();
            System.out.println("image2pdf endTime = " + endTime + ", 耗时 = " + (endTime - itextImageTime) + ",总耗时 = " + (endTime - startTime));

            log("image2pdf success,pdfPath:" + pdfPath);

            return true;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return false;
    }


    public static boolean ofd2pdf(@NotNull String ofdPath, @NotNull String pdfPath) {
        log("ofd2pdf begin,ofdPath:" + ofdPath);
        System.out.println("ofd2pdf startTime = " + System.currentTimeMillis());

        try {
            if (ofdPath.endsWith(".ofd")) {
                //OFD转PDF
                ConvertHelper.toPdf(Paths.get(ofdPath), Paths.get(pdfPath));
                return true;
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return false;
    }

    public static String writeToFile(InputStream inputStream, String upload_path, String fileName) {
        FileOutputStream fos = null;
        try {
            String path  = upload_path.endsWith("/") ? upload_path : (upload_path + "/");
            if (!new File(path).exists()) {
                if (!new File(path).mkdirs()) {
                    throw new Exception("path is not dir");
                }
            }

            String uploadedFileLocation = path + fileName;
            logger.info("uploadedFileLocation"+uploadedFileLocation);
            File tempFile = new File(uploadedFileLocation);
            if (tempFile.exists() || tempFile.createNewFile()) {
                fos = new FileOutputStream(tempFile);
                byte[] buffer = readInputStream(inputStream);
                fos.write(buffer);
                return uploadedFileLocation;
            } else {
                throw new IOException("file not exists");
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    logger.error("FileOutputStream close error",ex);
                }
            }
        }
    }

    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static int getPercent(float h, float w, float eh, float ew) {
        float p2 = h > w ? eh / h * 100 : ew / w * 100;
        return Math.round(p2);
    }

    public static void log(String message) {
        logger.info(message);
    }

}

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值