用Java实现不同格式的文件转换成PDF文件

使用Java实现文件转PDF的工具类,支持多种常见格式的转换。

根据自己的使用场景决定保留对应的方法。

1.将图片流保存到文件

2.将图片转换为PDF格式文件

3.将word文件转换为PDF格式文件

4.将excel文件转换为PDF格式文件

5.设置打印的sheet,自动拉伸比例

6.隐藏workbook中不需要的sheet页

7.将powerpoint文件转换为PDF格式文件

8.将txt文件转换为PDF格式文件

public class PDFConvertUtil {

    /**
     * 将图片流直接保存到文件
     *
     * @param inputStream 图片文件流
     * @param savePath    保存路径
     * @return 是否成功
     */
    public static boolean saveImage(InputStream inputStream, String savePath) {
        try (FileOutputStream outputStream = new FileOutputStream(savePath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将图片转换为PDF格式文件
     *
     * @param inputStream 图片文件流
     * @param savePath    PDF文件保存路径
     * @return
     */
    public static boolean imgToPDF(InputStream inputStream, String savePath) {
        Document document = null;
        try {
            // 将文件流转换为字节流,便于格式转换
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int length = 0;
            while (-1 != (length = bufferedInputStream.read(bytes))) {
                byteArrayOutputStream.write(bytes, 0, length);
            }
            // 处理img图片
            Image image = Image.getInstance(byteArrayOutputStream.toByteArray());
            //图片的原始宽高
            float height = image.getHeight();
            float width = image.getWidth();
            Rectangle pageSize = new Rectangle(width,height);

            File file = new File(savePath);
            FileOutputStream outputStream = new FileOutputStream(file);
            // 创建文档,设置PDF页面的大小 A2-A9, 个人觉得A3最合适
            document = new Document(pageSize, 0, 0, 0, 0);
            // 新建pdf文档,具体逻辑看.getInstance方法
            PdfWriter.getInstance(document, outputStream);
            document.open();
            document.newPage();

            image.setAlignment(Image.MIDDLE);
            //image.setRotationDegrees(90);     //旋转

            // 将图片放入文档中,完成pdf转换
            document.add(image);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (document != null) {
                    document.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 将word文件转换为PDF格式文件
     *
     * @param inputStream word文件流
     * @param savePath    PDF文件保存路径
     * @return  .
     */
    public static boolean wordToPDF(InputStream inputStream, String savePath) {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense("word")) {
            return false;
        }
        File file = new File(savePath);
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            // 将源文件保存在com.aspose.words.Document中,具体的转换格式依靠里面的save方法
            com.aspose.words.Document doc = new com.aspose.words.Document(inputStream);
            // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,EPUB, XPS, SWF 相互转换
            doc.save(outputStream, SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    /**
     * 将excel文件转换为PDF格式文件
     *
     * @param inputStream excel文件流
     * @param savePath    PDF文件保存路径
     * @return
     */
    public static boolean excelToPDF(InputStream inputStream, String savePath) {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense("excel")) {
            return false;
        }
        File file = new File(savePath);
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            Workbook wb = new Workbook(inputStream);// 原始excel路径
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            //开启以下注释的配置,则会将宽表格拆断并分页
            //pdfSaveOptions.setOnePagePerSheet(false);
            //int[] autoDrawSheets = {3};
            //当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。
            //autoDraw(wb, autoDrawSheets);
            int[] showSheets = {0};
            //隐藏workbook中不需要的sheet页。
            printSheetPage(wb, showSheets);
            wb.save(outputStream, pdfSaveOptions);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    /**
     * 设置打印的sheet 自动拉伸比例
     *
     * @param wb
     * @param page 自动拉伸的页的sheet数组
     */
    private static void autoDraw(Workbook wb, int[] page) {
        if (null != page && page.length > 0) {
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
                wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
            }
        }
    }

    /**
     * 隐藏workbook中不需要的sheet页。
     *
     * @param wb
     * @param page 显示页的sheet数组
     */
    private static void printSheetPage(Workbook wb, int[] page) {
        for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
            wb.getWorksheets().get(i).setVisible(false);
        }
        if (null == page || page.length == 0) {
            wb.getWorksheets().get(0).setVisible(true);
        } else {
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }

    /**
     * 将powerpoint文件转换为PDF格式文件
     *
     * @param inputStream powerpoint文件流
     * @param savePath    PDF文件保存路径
     * @return
     */
    public static boolean powerpointToPDF(InputStream inputStream, String savePath) {
        // 验证License
        if (!getLicense("ppt")) {
            return false;
        }
        try {
            //输入ppt文件流
            Presentation pres = new Presentation(inputStream);
            pres.save(savePath, com.aspose.slides.SaveFormat.Pdf);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static boolean getLicense(String type) {
        boolean result = false;
        try {
            String s = "<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>";
            ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
            switch (type) {
                case "word":
                    com.aspose.words.License aposeLicWord = new com.aspose.words.License();
                    aposeLicWord.setLicense(is);
                    break;
                case "excel":
                    com.aspose.cells.License aposeLicExcel = new com.aspose.cells.License();
                    aposeLicExcel.setLicense(is);
                    break;
                case "ppt":
                case "pptx":
                    com.aspose.slides.License aposeLicPowerPoint = new com.aspose.slides.License();
                    aposeLicPowerPoint.setLicense(is);
                    break;
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 将txt文件转换为PDF格式文件
     *
     * @param inputStream txt文件流
     * @param savePath    PDF文件保存路径
     * @return
     */
    public static boolean txtToPDF(InputStream inputStream, String savePath) {
        File tempDir = new File(SystemCache.txtTempDir);
        if (!tempDir.exists()) {
            tempDir.mkdirs();
        }
        String tempPath = SystemCache.txtTempDir + savePath.substring(savePath.lastIndexOf(File.separator), savePath.lastIndexOf(".")) + ".txt";
        File tempFile = new File(tempPath);
        try {
            FileUtils.copyInputStreamToFile(inputStream, tempFile);
            String charset = getCharset(tempFile);
            return txt2PDF(tempPath, savePath, charset);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                FileUtils.delete(tempFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getCharset(File file) {
        String charset = "GBK";
        byte[] first3Bytes = new byte[3];
        try {
            boolean checked = false;
            InputStream is = new FileInputStream(file);
            int read = is.read(first3Bytes, 0, 3);

            if (read == -1)
                return charset;
            if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
                charset = "UTF-16LE";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xFE
                    && first3Bytes[1] == (byte) 0xFF) {
                charset = "UTF-16BE";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xEF
                    && first3Bytes[1] == (byte) 0xBB
                    && first3Bytes[2] == (byte) 0xBF) {
                charset = "UTF-8";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xA
                    && first3Bytes[1] == (byte) 0x5B
                    && first3Bytes[2] == (byte) 0x30) {
                charset = "UTF-8";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xD
                    && first3Bytes[1] == (byte) 0xA
                    && first3Bytes[2] == (byte) 0x5B) {
                charset = "GBK";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0x5B
                    && first3Bytes[1] == (byte) 0x54
                    && first3Bytes[2] == (byte) 0x49) {
                charset = "windows-1251";
                checked = true;
            }
            InputStream istmp = new FileInputStream(file);
            if (!checked) {
                int loc = 0;
                while ((read = istmp.read()) != -1) {
                    loc++;
                    if (read >= 0xF0)
                        break;
                    if (0x80 <= read && read <= 0xBF)
                        break;
                    if (0xC0 <= read && read <= 0xDF) {
                        read = istmp.read();
                        if (0x80 <= read && read <= 0xBF)
                            continue;
                        else
                            break;
                    } else if (0xE0 <= read && read <= 0xEF) {
                        read = istmp.read();
                        if (0x80 <= read && read <= 0xBF) {
                            read = istmp.read();
                            if (0x80 <= read && read <= 0xBF) {
                                charset = "UTF-8";
                                break;
                            } else
                                break;
                        } else
                            break;
                    }
                }
            }
            is.close();
            istmp.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return charset;
    }

    /**
     * 将txt文件转换为PDF格式文件
     *
     * @param sourcePath txt文件路径
     * @param savePath   PDF文件保存路径
     * @param charset    txt文件编码格式
     * @return
     */
    public static boolean txt2PDF(String sourcePath, String savePath, String charset) {
        Document document = null;
        PdfWriter writer = null;
        try {
            FontFactoryImp fontFactoryImp = new FontFactoryImp();
            fontFactoryImp.registerDirectories();
            com.itextpdf.text.Font font = fontFactoryImp.getFont("宋体", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 16, Font.UNDEFINED, null);
            File file = new File(savePath);
            FileOutputStream outputStream = new FileOutputStream(file);
            com.itextpdf.text.Rectangle rectangle = new com.itextpdf.text.Rectangle(PageSize.A4.rotate());
            document = new Document(rectangle);
            writer = PdfWriter.getInstance(document, outputStream);
            document.open();
            Paragraph paragraph = new Paragraph();
            paragraph.setFont(font);
            String fileToString = FileUtils.readFileToString(new File(sourcePath), charset);
            paragraph.add(fileToString);
            document.add(paragraph);
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (document != null) {
                document.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
        return true;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值