java实现docx、doc、xlsx、xls、ppt文件转换pdf文件

1、需要引入以下jar包

    <!--word转pdf-->
    <dependency>
        <groupId>com.aspose</groupId>
        <artifactId>aspose-words</artifactId>
        <version>15.8.0</version>
    </dependency>
    
    <!--xlsx或xls转pdf-->
    <dependency>
        <groupId>com.aspose</groupId>
        <artifactId>aspose-cells</artifactId>
        <version>8.5.2</version>
    </dependency>
 
    <!--ppt转pdf-->
    <dependency>
        <groupId>com.aspose</groupId>
        <artifactId>aspose-slides</artifactId>
        <version>19.6</version>
    </dependency>

2、去除水印文件

在这里插入图片描述

3、所以的准备好以后就开始实际操作

(1)、首先是xlsx和xls转换pdf操作

i、导包

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

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

ii、读取去除水印文件方法

public static boolean getLicense() {
    boolean result = false;
    try {
        // 读取license.xml
        InputStream is = ExcelConvertPdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
        License aposeLic = new License();
        aposeLic.setLicense(is);
        result = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

iii、转换操作

public static void excel2pdf(String sourceFilePath, String desFilePathd){
    // 验证License 若不验证则转化出的pdf文档会有水印产生
    if (!getLicense()) {
        return;
    }
    log.info("开始转换excel==start");
    FileOutputStream fileOS = null;
    long old = System.currentTimeMillis();
    try {
        // 原始excel路径
        Workbook wb = new Workbook(sourceFilePath);
        fileOS = new FileOutputStream(desFilePathd);
        PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
        pdfSaveOptions.setOnePagePerSheet(true);
        int[] autoDrawSheets={3};
        //当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。
        autoDraw(wb,autoDrawSheets);
        int[] showSheets={0};
        //隐藏workbook中不需要的sheet页。
        printSheetPage(wb,showSheets);
        wb.save(fileOS, pdfSaveOptions);
        fileOS.flush();
        long now = System.currentTimeMillis();
        log.info("共耗时:{}",((now - old) / 1000.0) );
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        if(fileOS!=null){
            try {
                fileOS.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * 隐藏workbook中不需要的sheet页。
 * @param wb
 * @param page 显示页的sheet数组
 */
public 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);
        }
    }
}

/**
 * 设置打印的sheet 自动拉伸比例
 * @param wb
 * @param page 自动拉伸的页的sheet数组
 */
public 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();
        }
    }
}

iiii、运行文件

public static void main(String[] args) {
    String inputExcelPath = "/Users/Desktop/xxx.xls";
    String outputPdfPath = "/Users/Desktop/xxx.pdf";
    excel2pdf(inputExcelPath,outputPdfPath);

}   

(2)、ppt转换pdf工具类

i、导包

import com.aspose.slides.License;
import com.aspose.slides.Presentation;
import com.aspose.slides.SaveFormat;
import lombok.extern.log4j.Log4j2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

ii、读取去除水印文件方法

    public static boolean getLicense() {
    boolean result = false;
    try {
        //  license.xml
        InputStream is = ExcelConvertPdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
        License aposeLic = new License();
        aposeLic.setLicense(is);
        result = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

iii、转换方法

  public static void ppt2Pdf(String inPath,String outPath){
    // 验证License 去除水印
    if (!getLicense()) {
        return ;
    }
    long start = System.currentTimeMillis();
    try {
        FileInputStream fileInput = new FileInputStream(inPath);
        Presentation pres = new Presentation(fileInput);
        FileOutputStream out = new FileOutputStream(new File(outPath));
        pres.save(out, SaveFormat.Pdf);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    long end =System.currentTimeMillis();
    // 转化用时
    log.info("pdf转换成功,共耗时:{}" , ((end - start) / 1000.0) + "秒");
}

iiii、运行文件

public static void main(String[] args) {
String inputExcelPath = “/Users/Desktop/xxx.ppt”;
String outputPdfPath = “/Users/Desktop/pdf.pdf”;
ppt2Pdf(inputExcelPath,outputPdfPath);

}

(3)、work转pdf文件

i、导包

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.extern.log4j.Log4j2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

ii、读取去除水印文件

    public static boolean getLicense() {
    boolean result = false;
    try {
        // license.xml应放在
        InputStream is = WordConvertPdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
        License aposeLic = new License();
        aposeLic.setLicense(is);
        result = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

iii、转换方法

/**
 * @param inPath 源文件路径
 * @param outPath 新pdf文件路径
 */
public static void doc2pdf(String inPath, String outPath) {
    // 验证License 若不验证则转化出的pdf文档会有水印产生
    if (!getLicense()) {
        return;
    }
    log.info("开始转换doc==start");
    FileOutputStream os = null;
    try {
        long old = System.currentTimeMillis();
        // 新建一个空白pdf文档
        File file = new File(outPath);
        os = new FileOutputStream(file);
        // Address是将要被转化的word文档
        Document doc = new Document(inPath);
        // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
        doc.save(os, SaveFormat.PDF);
        // EPUB, XPS, SWF 相互转换
        long now = System.currentTimeMillis();
        // 转化用时
        log.info("共耗时:{}",((now - old) / 1000.0) );
    } catch (Exception e) {
        log.info("转换pdf报错==[{}]",e);
    }
    finally {
        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

iiii、运行

public static void main(String[] args) {
    String inPath = "/Users/Desktop/xxx.doc";
    String outPath ="/Users/Desktop/xxx.pdf";
    doc2pdf(inPath,outPath);
}
好的,以下是一个简单的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库。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值