itext pdf 图片转PDF

maven

        <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.2</version>
        </dependency>

PdfUtil.java

import cn.hutool.core.io.IoUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.ByteArrayOutputStream;

/**
 * 图片转PDF
 *
 * @author liaozesong
 */
public class PdfUtil {
    /**
     * 图片的二进制数组
     * 可接受多个图片
     */
    public static byte[] pdf(byte[]... bytes) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            //A4旋转90度
            Rectangle rotate = PageSize.A4.rotate();
            //边框设置为0
            Document document = new Document(rotate, 0, 0, 0, 0);
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            FontFactoryImp ffi = new FontFactoryImp();
            ffi.registerDirectories();
            document.open();
            for (int i = 0; i < bytes.length; i++) {
                if (i != 0) {
                    document.newPage();
                }
                //图片缩小到A4大小,原始图片生成时,最好为A4的2倍以上,显示时清晰度才高
                Image image = Image.getInstance(bytes[i]);
                image.scaleAbsolute(842, 595);
                document.add(Jpeg.getInstance(image));
            }
            document.close();
            writer.close();
            outputStream.flush();
            return outputStream.toByteArray();
        } finally {
            IoUtil.close(outputStream);
        }
    }
}

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页