将多个pdf合成一个pdf、pdf拆分、图片互转

发布时间 2023-05-31 16:16:51作者: 睡个好觉"
<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.2</version>
</dependency>
<dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>15.8.0</version>
</dependency>

package com.alpari.wang.utils;

import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * 格式转换util,【jpgPng互换】,【图片转pdf】,【doc转pdf】,【将多个pdf合成一个pdf】,【pdf拆分】
 */
@Slf4j
public class FormatConversionUtil {

    /**
     * 图片转pdf,返回文件路径
     * @param photoPath 图片路径
     * @param fileName pdf路径
     * @return pdf路径
     */
    public static String photoToPdf(String photoPath, String fileName) {
        Document document = new Document(PageSize.A4, 1, 1, 1, 1);
        //设置文档页边距
        document.setMargins(0,0,0,0);
        try (FileOutputStream fos = new FileOutputStream(fileName)) {
            PdfWriter.getInstance(document, fos);
            //打开文档
            document.open();
            //获取图片的宽高
            Image image = Image.getInstance(photoPath);
            //设置图片自适应尺寸
            image.scaleToFit(document.getPageSize());
//            float imageHeight=image.getScaledHeight();
//            float imageWidth=image.getScaledWidth();
            //设置页面宽高与图片一致
//            Rectangle rectangle = new Rectangle(imageWidth, imageHeight);
//            document.setPageSize(rectangle);
            //图片居中
            image.setAlignment(Image.ALIGN_CENTER);
            //新建一页添加图片
            document.newPage();
            document.add(image);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            //关闭文档
            document.close();
        }
        return fileName;
    }

    /**
     * 将多个pdf合成一个pdf
     * @param files 要合成的pdf路径
     * @param newFilePath 合成后的新文件路径
     * @return 返回新文件路径
     * @throws Exception 异常
     */
    public static String pdfListToPdf(List<String> files, String newFilePath) throws Exception {
        Document document = null;
        try {
            document = new Document(new PdfReader(files.get(0)).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(newFilePath));
            document.open();
            for (String file : files) {
                PdfReader reader = new PdfReader(file);
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            assert document != null;
            document.close();
        }
        return newFilePath;
    }

    /**
     * 去除水印
     */
    private static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = FormatConversionUtil.class.getClassLoader().getResourceAsStream("\\license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * doc转pdf,返回pdf路径
     * @param wordPath doc路径
     * @param fileName 返回的pdf文件路劲
     * @return 回的pdf文件路劲
     * @throws Exception 异常
     */
    public static String doc2Pdf(String wordPath, String fileName) throws Exception {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            return null;
        }
        //创建随机数
        FileOutputStream os = null;
        try {
            long old = System.currentTimeMillis();
            // 新建一个空白pdf文档
            File file = new File(fileName);
            os = new FileOutputStream(file);
            // Address是将要被转化的word文档
            com.aspose.words.Document doc = new com.aspose.words.Document(wordPath);
            // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF
            doc.save(os, SaveFormat.PDF);
            // EPUB, XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            // 转化用时
            System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return fileName;
    }

    public static String png2jpg(String pngPath, String fileName) {
        /*SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
        String suijiNumber = tempDate.format(new Date()) + String.format("%06d", getRandomRange(10000, 1000));
        String fileName = BaseUtil.getSystemBasePath() + "/uploadfiles/" + suijiNumber + ".jpg";*/
        //读取图片
        try (FileOutputStream fos = new FileOutputStream(fileName)) {
            // 读取图片
            BufferedImage bufferedImage = ImageIO.read(new File(pngPath));
            //转成jpg、
            BufferedImage bufferedImage1 = new BufferedImage(bufferedImage.getWidth(),
                    bufferedImage.getHeight(),
                    BufferedImage.TYPE_INT_RGB);
            bufferedImage1.createGraphics().drawImage(bufferedImage,0,0, Color.white,null);
            ImageIO.write(bufferedImage1,"jpg",fos);
            fos.flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return fileName;
    }

    public static String jpg2png(String jpgPath, String fileName) {
        /*SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
        String suijiNumber = tempDate.format(new Date()) + String.format("%06d", getRandomRange(10000, 1000));
        String fileName = BaseUtil.getSystemBasePath() + "/uploadfiles/" + suijiNumber + ".png";*/
        //读取图片
        try {
            BufferedImage bufferedImage = ImageIO.read(new File(jpgPath));
            //转成png、
            BufferedImage bufferedImage1 = new BufferedImage(bufferedImage.getWidth(),
                    bufferedImage.getHeight(),
                    BufferedImage.TYPE_INT_ARGB);
            bufferedImage1.createGraphics().drawImage(bufferedImage,0,0, Color.white,null);
            FileOutputStream fos = new FileOutputStream(fileName);
            ImageIO.write(bufferedImage1,"png",fos);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return fileName;
    }

    /**
     * PDF拆分
     * @param pdfFile 原文件路劲
     * @param newFile 新文件路径
     * @param from 从那一页开始
     * @param end 到那一页结束
     */
    public static void partitionPdfFile(String pdfFile, String newFile, int from, int end) {
        Document document = null;
        PdfCopy copy = null;
        try {
            PdfReader reader = new PdfReader(pdfFile);
            int n = reader.getNumberOfPages();
            if (end == 0) {
                end = n;
            }
            ArrayList<String> savepaths = new ArrayList<String>();
//            String staticpath = pdfFile.substring(0, pdfFile.lastIndexOf("\\") + 1);
//            String savepath = staticpath + newFile;
            savepaths.add(newFile);
            document = new Document(reader.getPageSize(1));
            copy = new PdfCopy(document, new FileOutputStream(savepaths.get(0)));
            document.open();
            for (int j = from; j <= end; j++) {
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, j);
                copy.addPage(page);
            }
            document.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}

resource目录下新增License.xml 文件内容如下

<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose.Words for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>
        sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
    </Signature>
</License>