使用Java实现Excel文件转PDF文件

本文介绍了如何在Java项目中利用Aspose.Cells库和SpringBoot框架将Excel文件转换为PDF格式,包括环境准备、jar包管理、许可证设置和API调用示例。
摘要由CSDN通过智能技术生成

前提

上一篇我们用到了word转pdf的工具,这一篇我们会拿excel做例子进行转pdf。

环境准备

	<dependencies>
        <dependency>
            <groupId>aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>8.5.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

jar包的网盘链接和提取码

链接:https://pan.baidu.com/s/1vgAa1vlBtDgNT00rVBRi2Q?pwd=7284 
提取码:7284 
--来自百度网盘超级会员V6的分享

将jar包导入本地Maven仓库,命令如下:

mvn install:install-file -Dfile=刚下载的jar包的位置 -DgroupId=依赖里写的groupId -DartifactId=依赖里写的artifactId -Dversion=上面的version -Dpackaging=jar
示例:
mvn install:install-file -Dfile=F:\项目\文件预览\java_application_aspose_demo-master\java_application_aspose_demo-master\lib\aspose-cells-8.5.2.jar -DgroupId=aspose -DartifactId=aspose-cells -Dversion=8.5.2 -Dpackaging=jar

准备工作已完成,开始上代码。

项目代码

import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * excel转换为pdf的工具类
 *
 * @author shmily
 */
public class Excel2PdfUtil {

    /**
     * 许可证字符串
     */
    private static final String LICENSE = "<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>";

    /**
     * 设置 license 去除水印
     */
    private static void setLicense() {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(LICENSE.getBytes());
        License license = new License();
        license.setLicense(byteArrayInputStream);
    }


    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param pdfFilePath   pdf文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void excelConvertPdf(String excelFilePath, String pdfFilePath, int[] convertSheets) {
        FileOutputStream fileOutputStream = null;
        try {
            pdfFilePath = pdfFilePath == null ? getPdfFilePath(excelFilePath) : pdfFilePath;
            // 设置License
            setLicense();
            // 读取excel文件
            Workbook wb = new Workbook(excelFilePath);
            fileOutputStream = new FileOutputStream(pdfFilePath);
            // 设置pdf格式
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            if (null != convertSheets) {
                printSheetPage(wb, convertSheets);
            }
            wb.save(fileOutputStream, pdfSaveOptions);
            fileOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert fileOutputStream != null;
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * excel 转 pdf 二进制流
     *
     * @param excelFilePath excel文件路径
     * @param pdfFilePath   pdf文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void excelConvertPdfByte(String excelFilePath, String pdfFilePath, int[] convertSheets) {
        FileOutputStream fileOutputStream = null;
        try {
            pdfFilePath = pdfFilePath == null ? getPdfFilePath(excelFilePath) : pdfFilePath;
            // 设置License
            setLicense();
            // 读取excel文件
            Workbook wb = new Workbook(excelFilePath);
            fileOutputStream = new FileOutputStream(pdfFilePath);
            // 设置pdf格式
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            if (null != convertSheets) {
                printSheetPage(wb, convertSheets);
            }
            wb.save(fileOutputStream, pdfSaveOptions);
            fileOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert fileOutputStream != null;
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取 生成的 pdf 文件路径,默认与源文件同一目录
     *
     * @param excelPath excel文件
     * @return 生成的 pdf 文件
     */
    private static String getPdfFilePath(String excelPath) {
        int lastIndexOfPoint = excelPath.lastIndexOf(".");
        String pdfFilePath = "";
        if (lastIndexOfPoint > -1) {
            pdfFilePath = excelPath.substring(0, lastIndexOfPoint);
        }
        return pdfFilePath + ".pdf";
    }



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

import alp.starcode.utils.Excel2PdfUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FileController {
    

    @GetMapping("excel2Pdf")
    public void excel2Pdf(String excelPdf) {
        Excel2PdfUtil.excelConvertPdf("D:\\code\\pdf\\用户信息.xls", "D:\\code\\pdf\\用户信息.pdf", null);
    }

}

最终实现效果
在这里插入图片描述

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是一个简单的Java程序示例,使用Apache POI和Apache PDFBox库将Office文件(Word、Excel和PowerPoint)换为PDF文件: ```java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.font.PDType1Font; import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; public class OfficeToPDFConverter { public static void main(String[] args) throws IOException, InvalidFormatException { String inputFile = "input.docx"; String outputFile = "output.pdf"; convertToPdf(inputFile, outputFile); } public static void convertToPdf(String inputFile, String outputFile) throws IOException, InvalidFormatException { File inputFileObj = new File(inputFile); File outputFileObj = new File(outputFile); String fileExtension = getFileExtension(inputFileObj); if (fileExtension.equalsIgnoreCase("docx")) { XWPFDocument document = new XWPFDocument(WorkbookFactory.create(inputFileObj)); PDDocument pdfDoc = new PDDocument(); PDPage page = new PDPage(); try (PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page)) { pdfDoc.addPage(page); contentStream.beginText(); contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12); contentStream.newLineAtOffset(20, 750); for (XWPFParagraph para : document.getParagraphs()) { contentStream.showText(para.getText()); contentStream.newLine(); } contentStream.endText(); } pdfDoc.save(outputFileObj); pdfDoc.close(); document.close(); } else if (fileExtension.equalsIgnoreCase("xlsx")) { XSSFWorkbook workbook = new XSSFWorkbook(inputFileObj); PDDocument pdfDoc = new PDDocument(); PDPage page = new PDPage(); try (PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page)) { pdfDoc.addPage(page); contentStream.beginText(); contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12); contentStream.newLineAtOffset(20, 750); for (int i = 0; i < workbook.getNumberOfSheets(); i++) { contentStream.showText(workbook.getSheetAt(i).getSheetName()); contentStream.newLine(); } contentStream.endText(); } pdfDoc.save(outputFileObj); pdfDoc.close(); workbook.close(); } else if (fileExtension.equalsIgnoreCase("pptx")) { XMLSlideShow ppt = new XMLSlideShow(WorkbookFactory.create(inputFileObj)); PDDocument pdfDoc = new PDDocument(); PDPage page = new PDPage(); try (PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page)) { pdfDoc.addPage(page); contentStream.beginText(); contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12); contentStream.newLineAtOffset(20, 750); for (XSLFSlide slide : ppt.getSlides()) { contentStream.showText(slide.getTitle()); contentStream.newLine(); } contentStream.endText(); } pdfDoc.save(outputFileObj); pdfDoc.close(); ppt.close(); } else if (fileExtension.equalsIgnoreCase("xls")) { HSSFWorkbook workbook = new HSSFWorkbook(inputFileObj); PDDocument pdfDoc = new PDDocument(); PDPage page = new PDPage(); try (PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page)) { pdfDoc.addPage(page); contentStream.beginText(); contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12); contentStream.newLineAtOffset(20, 750); for (int i = 0; i < workbook.getNumberOfSheets(); i++) { contentStream.showText(workbook.getSheetAt(i).getSheetName()); contentStream.newLine(); } contentStream.endText(); } pdfDoc.save(outputFileObj); pdfDoc.close(); workbook.close(); } } private static String getFileExtension(File file) { String fileName = file.getName(); if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) { return fileName.substring(fileName.lastIndexOf(".") + 1); } else { return ""; } } } ``` 在此示例中,我们创建了一个名为`OfficeToPDFConverter`的Java类,该类使用Apache POI和Apache PDFBox库将Office文件(Word、Excel和PowerPoint)换为PDF文件。在`main`方法中,我们调用`convertToPdf`方法,该方法接受输入文件路径和输出文件路径作为参数。在`convertToPdf`方法中,我们首先获取输入文件的扩展名,然后根据文件类型使用不同的POI库加载文件。然后,我们使用PDFBox库来创建一个PDF文档,并将Office文件的内容写入PDF页面。最后,我们将PDF文档保存到输出文件中。 请注意,在使用该程序之前,您需要下载并导入Apache POI和Apache PDFBox库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值