WORD、EXCEL、图片转PDF

/*
 * Copyright (c) 2018, QiJuBian and/or its affiliates. All rights reserved.
 * QiJuBian PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.qijubian.commons;

import com.aspose.cells.License;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

/**
 * Pdfs.java
 * <pre>
 * public static void main(String[] args) {
 *     try {
 *         Pdfs.wordToPdf(new FileInputStream("D:/xxx.docx"), "test.pdf", "/");
 *     } catch (FileNotFoundException e) {
 *         e.printStackTrace();
 *     }
 * }
 * </pre>
 *
 * @author hongquanli <hongquanli@qq.com>
 * @version 1.0 2019-08-02 23:26
 */
public class Pdfs {

    private static Logger logger = LoggerFactory.getLogger(Pdfs.class);

    // 凭证
    private static final String LICENSE_TEXT = "" +
        "<License>\n" +
        "  <Data>\n" +
        "    <Products>\n" +
        "      <Product>Aspose.Total for Java</Product>\n" +
        "      <Product>Aspose.Words for Java</Product>\n" +
        "    </Products>\n" +
        "    <EditionType>Enterprise</EditionType>\n" +
        "    <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
        "    <LicenseExpiry>20991231</LicenseExpiry>\n" +
        "    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
        "  </Data>\n" +
        "  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
        "</License>";

    /**
     * WORD 转 PDF
     *
     * @param is         WORD流
     * @param fileName   pdf文件名
     * @param targetPath 指定生成路径
     */
    public static void wordToPdf(
        InputStream is, String fileName, String targetPath
    ) {
        try {
            com.aspose.words.Document doc = new com.aspose.words.Document(is);

            FileClients.StoreFileRequest request = new FileClients.StoreFileRequest();
            request.setFileName(fileName);
            // request.setOriginalName(originalName);
            request.setUploadPath(targetPath);
            try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                doc.save(out, com.aspose.words.SaveFormat.PDF);
                request.setInputStream(new ByteArrayInputStream(out.toByteArray()));
            }
            FileClients.storeFile(request);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * WORD 转 PDF
     *
     * @param filepath   WORD路径
     * @param targetPath 指定生成路径
     */
    public static void wordToPdf(String filepath, String targetPath) {
        try {
            /*
            InputStream in = Excels.class.getClassLoader().getResourceAsStream("license.xml");
            License license = new License();
            license.setLicense(in);
            */

            com.aspose.words.Document doc = new com.aspose.words.Document(filepath);

            File file = new File(targetPath);
            if (!file.getParentFile().exists()) {
                // file.getParentFile().mkdirs();
                Files.createDirectories(file.getParentFile().toPath());
            }

            try (FileOutputStream out = new FileOutputStream(file)) {
                doc.save(out, com.aspose.words.SaveFormat.PDF);
                // out.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * EXCEL 转 PDF
     *
     * @param is         EXCEL流
     * @param fileName   pdf文件名
     * @param targetPath 指定生成路径
     */
    public static void excelToPdf(
        InputStream is, String fileName, String targetPath
    ) {
        try {
            /*
            InputStream in = Excels.class.getClassLoader().getResourceAsStream("license.xml");
            License license = new License();
            license.setLicense(in);
            */
            InputStream in = new ByteArrayInputStream(LICENSE_TEXT.getBytes(StandardCharsets.UTF_8));
            License license = new License();
            license.setLicense(in);

            com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(is);

            /*
            WorksheetCollection collection = wb.getWorksheets();
            List<String> names = new ArrayList<>();
            collection.forEach(w -> {
                Worksheet worksheet = (Worksheet) w;
                if (!worksheet.getName().equals(sheetName)) {
                    names.add(worksheet.getName());
                }
            });
            names.forEach(n -> wb.getWorksheets().removeAt(n));
            */

            FileClients.StoreFileRequest request = new FileClients.StoreFileRequest();
            request.setFileName(fileName);
            request.setUploadPath(targetPath);
            // request.setOriginalName(originalName);
            try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                wb.save(out, com.aspose.cells.SaveFormat.PDF);
                request.setInputStream(new ByteArrayInputStream(out.toByteArray()));
            }
            FileClients.storeFile(request);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * EXCEL 转 PDF
     *
     * @param filepath   EXCEL路径
     * @param targetPath 指定生成路径
     */
    public static void excelToPdf(String filepath, String targetPath) {
        try {
            /*
            InputStream in = Excels.class.getClassLoader().getResourceAsStream("license.xml");
            License license = new License();
            license.setLicense(in);
            */
            InputStream in = new ByteArrayInputStream(LICENSE_TEXT.getBytes(StandardCharsets.UTF_8));
            License license = new License();
            license.setLicense(in);

            com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(filepath);

            /*
            WorksheetCollection collection = wb.getWorksheets();
            List<String> names = new ArrayList<>();
            collection.forEach(w -> {
                Worksheet worksheet = (Worksheet) w;
                if (!worksheet.getName().equals(sheetName)) {
                    names.add(worksheet.getName());
                }
            });
            names.forEach(n -> wb.getWorksheets().removeAt(n));
            */

            File file = new File(targetPath);
            if (!file.getParentFile().exists()) {
                // file.getParentFile().mkdirs();
                Files.createDirectories(file.getParentFile().toPath());
            }

            try (FileOutputStream out = new FileOutputStream(file)) {
                wb.save(out, com.aspose.cells.SaveFormat.PDF);
                // out.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 图片转PDF
     *
     * @param is         图片流
     * @param fileName   pdf文件名
     * @param targetPath 目标目录
     */
    @SuppressWarnings("Duplicates")
    public static void imageToPdf(
        InputStream is, String fileName, String targetPath
    ) {
        com.itextpdf.text.Document document = new com.itextpdf.text.Document(
            PageSize.A4, 8, 8, 8, 8
        );
        try {
            FileClients.StoreFileRequest request = new FileClients.StoreFileRequest();
            request.setFileName(fileName);
            request.setUploadPath(targetPath);
            // request.setOriginalName(originalName);

            try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                PdfWriter.getInstance(document, out);
                document.open();
                // document.newPage();
                // document.add(new Paragraph("Test"));
                Image image = Image.getInstance(toBytes(is));
                float height = image.getHeight();
                float width = image.getWidth();
                float percent = getPercent(width, height);
                image.setAlignment(Image.MIDDLE);
                // 表示是原来图像的比例;
                image.scalePercent(percent);
                document.add(image);
                out.close();
                document.close();
                request.setInputStream(new ByteArrayInputStream(out.toByteArray()));
            }
            FileClients.storeFile(request);
        } catch (DocumentException | IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 图片转PDF
     *
     * @param images      the images
     * @param pdfFileName the pdfFileName
     * @return the pdf
     */
    @SuppressWarnings("Duplicates")
    public static String imageToPdf(List<String> images, String pdfFileName) {
        com.itextpdf.text.Document document = new com.itextpdf.text.Document(
            PageSize.A4, 8, 8, 8, 8
        );
        try {
            PdfWriter.getInstance(document, new FileOutputStream(pdfFileName));
            document.open();
            for (String imagePath : images) {
                document.newPage();
                // document.add(new Paragraph("Test"));
                Image image = Image.getInstance(toBytes(imagePath));
                float height = image.getHeight();
                float width = image.getWidth();
                float percent = getPercent(width, height);
                image.setAlignment(Image.MIDDLE);
                // 表示是原来图像的比例;
                image.scalePercent(percent);
                document.add(image);
            }
            document.close();
        } catch (DocumentException | IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return pdfFileName;
    }

    private static byte[] toBytes(String filePath) {
        File file = new File(filePath);
        FileInputStream fis;
        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return toBytes(fis);
    }

    private static byte[] toBytes(InputStream fis) {
        byte[] buffer;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return buffer;
    }

    /**
     * 按宽度缩放
     *
     * @param w the width
     * @param h the height
     * @return the percent
     */
    private static float getPercent(float w, float h) {
        float p = 0.0f;
        if (w > PageSize.A4.getWidth() - 16) {
            p = (PageSize.A4.getWidth() - 16) / w * 100;
        }
        return p;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值