编程语言
首页 > 编程语言> > aspose office转pdf

aspose office转pdf

作者:互联网

office文件转pdf
今天有点上火,直接上货采用方式aspose(破解版),非商业版
springboot
依赖包下载(所需依赖不能通过pom下载需要手动下载以后添加到项目)
在这里插入图片描述
添加maven依赖


```java
<dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.16</version>
        </dependency>
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>com.aspose</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/aspose.slides-15.9.0.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>com.aspose1</groupId>
            <artifactId>com.aspose</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/aspose-cells-8.5.2.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>com.jacob</groupId>
            <artifactId>com.aspose</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/aspose-words-18.6-jdk16.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>com.aspose3</groupId>
            <artifactId>com.aspose</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/itext-asian-5.2.0.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>com.aspose4</groupId>
            <artifactId>com.aspose</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/itextpdf-5.5.6.jar</systemPath>
        </dependency>
        ##打包时需要使用
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <includeSystemScope>true</includeSystemScope>
            </configuration>
        </plugin>


import com.aspose.cells.Workbook;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import com.mexue.czzp.consumer.commons.AliyunOSSFileStoreProcessor;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.ArrayList;


/**
 * office 转PDF 工具类
 */
public class Office2PdfUtil {


    public static File Pdf(ArrayList<String> imageUrllist,
                           String mOutputPdfFileName) {
        //Document doc = new Document(PageSize.A4, 20, 20, 20, 20); // new一个pdf文档
        com.itextpdf.text.Document doc = new com.itextpdf.text.Document();
        try {

            PdfWriter
                    .getInstance(doc, new FileOutputStream(mOutputPdfFileName)); // pdf写入
            doc.open();// 打开文档
            for (int i = 0; i < imageUrllist.size(); i++) { // 循环图片List,将图片加入到pdf中
                doc.newPage(); // 在pdf创建一页
                Image png1 = Image.getInstance(imageUrllist.get(i)); // 通过文件路径获取image
                float heigth = png1.getHeight();
                float width = png1.getWidth();
                int percent = getPercent2(heigth, width);
                png1.setAlignment(Image.MIDDLE);
                png1.scalePercent(percent + 3);// 表示是原来图像的比例;
                doc.add(png1);
            }
            doc.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        File mOutputPdfFile = new File(mOutputPdfFileName); // 输出流
        if (!mOutputPdfFile.exists()) {
            mOutputPdfFile.deleteOnExit();
            return null;
        }
        return mOutputPdfFile; // 反回文件输出流
    }

    public static int getPercent(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        if (h > w) {
            p2 = 297 / h * 100;
        } else {
            p2 = 210 / w * 100;
        }
        p = Math.round(p2);
        return p;
    }

    public static int getPercent2(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        p2 = 530 / w * 100;
        p = Math.round(p2);
        return p;
    }


    /**
     * 图片文件转PDF
     *
     * @param filepath
     * @param request
     * @return
     */
    public static String imgOfPdf(String filepath, HttpServletRequest request) {
        boolean result = false;
        String pdfUrl = "";
        String fileUrl = "";
        try {
            ArrayList<String> imageUrllist = new ArrayList<String>(); // 图片list集合
            imageUrllist.add(request.getSession().getServletContext()
                    .getRealPath(File.separator + filepath)); // 添加图片文件路径
            String fles = filepath.substring(0, filepath.lastIndexOf("."));
            pdfUrl = request.getSession().getServletContext()
                    .getRealPath(File.separator + fles + ".pdf"); // 输出pdf文件路径
            fileUrl = fles + ".pdf";
            result = true;
            if (result == true) {
                File file = Office2PdfUtil.Pdf(imageUrllist, pdfUrl);// 生成pdf
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileUrl;
    }


    public static boolean getLicense() {
        boolean result = false;

        try {
            InputStream is = Office2PdfUtil.class.getClassLoader()
                    .getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static String docOfPdf(String filePath) {

        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return "PDF格式转化失败";
        }
        try {
            long old = System.currentTimeMillis();
            String filePath1 = filePath;
//			String filePath1 =  request.getSession().getServletContext().getRealPath(File.separator  + filePath);
            String filePath2 = filePath.substring(0, filePath.lastIndexOf("."));
            String pdfPathString = filePath2 + ".pdf";
//			filePath2 = request.getSession().getServletContext()
//					.getRealPath(File.separator  + filePath2 + ".pdf"); // 输出pdf文件路径
            filePath2 = filePath2 + ".pdf"; // 输出pdf文件路径
            File file = new File(filePath2); // 新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(filePath1); // Address是将要被转化的word文档

            doc.save(
                    os,
                    SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML,
            // OpenDocument, PDF, EPUB, XPS, SWF
            // 相互转换
            long now = System.currentTimeMillis();
            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
            os.close();

            return file.getPath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "PDF格式转化失败";
    }


    public static boolean getLicense1() {
        boolean result = false;
        try {

            InputStream is = Office2PdfUtil.class.getClassLoader()
                    .getResourceAsStream("classpath:/license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(is);
            result = true;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     *
     */
    public static String excelOfPdf(String filePath) {
        if (!getLicense1()) {
            // 验证License 若不验证则转化出的pdf文档会有水印产生
            return "PDF格式转化失败";
        }
        try {
            //long old = System.currentTimeMillis();
            //获取路径参数
            String filePath1 = filePath;
//			String filePath1 =  request.getSession().getServletContext().getRealPath(File.separator + filePath);
            String filePath2 = filePath.substring(0, filePath.lastIndexOf("."));
            String pdfSPath = filePath2 + ".pdf";
            filePath2 = filePath2 + ".pdf"; // 输出pdf文件路径

            //文件操作
            File file = new File(filePath2); // 新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Workbook wb = new Workbook(filePath1);// 原始excel路径
            FileOutputStream fileOS = new FileOutputStream(file);
            wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
            fileOS.close();
            // long now = System.currentTimeMillis();
            //System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
            return file.getPath();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "PDF格式转化失败";
    }


    public static boolean getLicense2() {
        boolean result = false;
        try {
            InputStream is = Office2PdfUtil.class.getClassLoader()
                    .getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            com.aspose.slides.License aposeLic = new com.aspose.slides.License();
            aposeLic.setLicense(is);
            result = true;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * ppt 转pdf
     *
     * @param filePath
     * @param to       pdf文件路径
     * @return
     */
    public static String pptOfPdf2(String filePath) {
        // 验证License
        if (!getLicense2()) {
            return "PDF格式转化失败";
        }
        try {
            String filePath2 = filePath.substring(0, filePath.lastIndexOf("."));
            long old = System.currentTimeMillis();
            filePath2 = filePath2 + ".pdf";
            // 输出pdf文件路径
            //文件操作
            File file = new File(filePath2); // 新建一个空白pdf文档
            com.aspose.slides.Presentation pres = new com.aspose.slides.Presentation(filePath);//输入pdf路径
            FileOutputStream fileOS = new FileOutputStream(file);

            pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
            fileOS.close();
            long now = System.currentTimeMillis();
            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒\n\n" + "文件保存在:" + file.getPath()); //转化过程耗时
            return file.getPath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "PDF格式转化失败";
    }

    public static void main(String[] args) throws Exception {
        //pptOfpdf2("d://2_1.ppt","d://2.pdf");
        docOfPdf("d://1.docx");
        generateCoverImage(new File("d://1.pdf"), new File("d://1.png"));
    }

    /**
     * pdf 生成封面图
     *
     * @param inputFile
     * @param outputFile
     */
    public static void generateCoverImage(File inputFile, File outputFile) {
        try {
            PDDocument document = PDDocument.load(inputFile);
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            // 提取的页码
            int pageNumber = 0;
            // 以300 dpi 读取存入 BufferedImage 对象
            int dpi = 300;
            RenderedImage buffImage = pdfRenderer.renderImageWithDPI(pageNumber, dpi, ImageType.RGB);
            // 将 BufferedImage 写入到 png
            ImageIO.write(buffImage, "png", outputFile);

            // 关闭文档
            document.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String office2Pdf(String fileName){
        if(StringUtils.hasLength(fileName)){
            String sub = fileName.substring(fileName.lastIndexOf(".")).replace(".","");
            if(sub.equalsIgnoreCase("DOC") || sub.equalsIgnoreCase("DOCX")){
                return docOfPdf(fileName);
            }

            if(sub.equalsIgnoreCase("PPT") || sub.equalsIgnoreCase("PPTX")){
                return pptOfPdf2(fileName);
            }

            if(sub.equalsIgnoreCase("xls") || sub.equalsIgnoreCase("xlsx")){
                return excelOfPdf(fileName);
            }
        }

        return "";
    }

    /**
     * 验证是否是office文件
     * @param fileName 文件名
     * @return
     */
    public static boolean isOffice(String fileName){
        String sub = fileName.substring(fileName.lastIndexOf(".")).replace(".","");
        if(sub.equalsIgnoreCase("DOC") || sub.equalsIgnoreCase("DOCX")){
            return true;
        }
        if(sub.equalsIgnoreCase("PPT") || sub.equalsIgnoreCase("PPTX")){
            return true;
        }

        if(sub.equalsIgnoreCase("xls") || sub.equalsIgnoreCase("xlsx")){
            return true;
        }
        return false;
    }

}

resource.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>

``
一切准备好以后在linux时生成需要有windows字体否则可能会出现pdf乱码问题
将字体导入到linux后执行
sudo fc-cache -fv ##更新字体
fc-list :lang=zh ##查看中文字体

烧脑的一天结束了!!!!!!!!!!!!!!希望能够帮助各位看官!!!
好了,暂时未处理统计数据可能出现负值的情况,如有需要请联系578616864进行交流

标签:return,String,office,new,pdf,aspose,com
来源: https://blog.csdn.net/qq_32695621/article/details/116855064