JAVA将WORD、EX文档转换为PDF

网上找了很多的方案,最后还是使用Apache POI + itext7适合一些,因为项目要部署在linux环境上,话不多说,直接步入整体。

一、引入相关依赖:

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>


        <!-- 引入 itext7-core 依赖 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext7-core</artifactId>
            <version>7.1.16</version>
            <type>pom</type>
        </dependency>

二、上代码:

package com.example.filterandinterceptor.utils;


import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author xiechenyu
 * @Description:
 * @date 2024/5/22 9:27
 */
public class ConvertPdfUtil {
    private final List<String> allowedFileExtensions = Arrays.asList("xls", "xlsx", "doc", "docx");

    private void convertToPdf(MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        if (Objects.isNull(originalFilename)) {
            throw new RuntimeException("请上传正确文件");
        }
        checkFileExtensions(originalFilename);

        // 转换为PDF文件


    }

    private void checkFileExtensions(String originalFilename) {
        String fileExtension = getFileExtension(originalFilename);
        if (!allowedFileExtensions.contains(fileExtension)) {
            throw new RuntimeException("文件格式不正确,支持转换为PDF文件的格式有:xls、xlsx、doc、docx");
        }

    }

    private static String getFileExtension(String filename) {
        if (filename.lastIndexOf('.') != -1 && filename.lastIndexOf('.') != 0) {
            return filename.substring(filename.lastIndexOf('.') + 1);
        } else {
            return "";
        }
    }

    //word文件转pdf,支持doc,docx
    public static void wordToPdf(String inFilePath, String outFilePath) {
        try (PdfDocument pdf = new PdfDocument(new PdfWriter(Files.newOutputStream(Paths.get(outFilePath))));
             Document pdfDocument = new Document(pdf, PageSize.A4.rotate());) {
            //指定pdf的字体样式为STSong-Light,编码方式为UniGB-UCS2-H,不指定编码方式中文乱码
            PdfFont pdfFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H");
            // 文件输入流读取文件
            InputStream in = Files.newInputStream(Paths.get(inFilePath));
            // 读取Word文档
            XWPFDocument word = new XWPFDocument(in);
            // 逐段写入PDF
            for (XWPFParagraph paragraph : word.getParagraphs()) {
                pdfDocument.add(new Paragraph(paragraph.getText()).setFont(pdfFont));
            }
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }


    //excel文件转pdf,支持xsl,xslx
    public static void excelToPdf(String inFilePath, String outFilePath) {
        try (PdfDocument pdf = new PdfDocument(new PdfWriter(Files.newOutputStream(Paths.get(outFilePath))));
             Document document = new Document(pdf, PageSize.A4.rotate());) {

            //指定pdf的字体样式为STSong-Light,编码方式为UniGB-UCS2-H
            PdfFont pdfFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H");

            // 文件输入流读取文件
            InputStream in = Files.newInputStream(Paths.get(inFilePath));

            //excel文件类型有xls和xlsx两种,对应的构造器不一样
            String fileExtension = getFileExtension(inFilePath);
            Workbook workbook = Objects.equals(fileExtension, ".xsl") ? new HSSFWorkbook(in) : new XSSFWorkbook(in);

            int numberOfSheets = workbook.getNumberOfSheets();
            for (int k = 0; k < numberOfSheets; k++) {
                Sheet sheet = workbook.getSheetAt(k);
                //获取总列数
                int column = getMaxColumn(sheet);
                //创建一个pdf的table对象,以便在pdf中以表的形式展示,列数和excel列数一致
                Table table = new Table(column);

                for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
                    for (int j = 0; j < column; j++) {
                        String str = "";
                        //获取excel单元格
                        Row row = sheet.getRow(i);
                        if (Objects.isNull(row)) {
                            continue;
                        }
                        org.apache.poi.ss.usermodel.Cell cell = row.getCell(j);
                        if (Objects.nonNull(cell)) {
                            if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                                str = (int) cell.getNumericCellValue() + "";
                            } else {
                                str = cell.getStringCellValue();
                            }
                        }
                        //将pdf的单元格初始化并添加到pdf中
                        Cell cells = new Cell().setFont(pdfFont).add(new Paragraph(str));
                        table.addCell(cells);
                    }
                }
                //两个table之间增加一个空格
                document.add(new Paragraph(" "));
                document.add(table);
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static int getMaxColumn(Sheet sheet) {
        int maxColumn = 0;
        for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
            if (Objects.nonNull(sheet.getRow(i))) {
                maxColumn = Math.max(maxColumn, sheet.getRow(i).getLastCellNum());
            }
        }
        return maxColumn;
    }

    public static void main(String[] args) {
//        excelToPdf("D:\\convertfile\\慢查询SQL.xlsx", "D:\\convertfile\\慢查询SQL.pdf");

        wordToPdf("D:\\convertfile\\测试 - 副本.doc", "D:\\convertfile\\测试 - 副本.pdf");
    }


}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中,有几种方法可以将Word转换PDF。以下是其中几种常见的方法: 1. 使用Apache POI和iText库:Apache POI用于读取Word文档,然后使用iText库将其转换PDF。您可以使用以下代码示例: ```java import org.apache.poi.xwpf.converter.pdf.PdfConverter; import org.apache.poi.xwpf.usermodel.XWPFDocument; import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfWriter; import java.io.*; public class WordToPdfConverter { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("input.docx"); XWPFDocument document = new XWPFDocument(fis); File outputFile = new File("output.pdf"); FileOutputStream out = new FileOutputStream(outputFile); Document pdfDoc = new Document(); PdfWriter writer = PdfWriter.getInstance(pdfDoc, out); pdfDoc.open(); PdfConverter.getInstance().convert(document, pdfDoc, null); pdfDoc.close(); System.out.println("Word转换PDF成功!"); } catch (Exception ex) { System.out.println("转换失败:" + ex.getMessage()); } } } ``` 2. 使用Aspose.Words库:Aspose.Words是一个功能强大的Java库,可以轻松地将Word转换PDF。您需要在项目中引入Aspose.Words库,然后可以使用以下代码示例: ```java import com.aspose.words.Document; import com.aspose.words.SaveFormat; public class WordToPdfConverter { public static void main(String[] args) { try { Document doc = new Document("input.docx"); doc.save("output.pdf", SaveFormat.PDF); System.out.println("Word转换PDF成功!"); } catch (Exception ex) { System.out.println("转换失败:" + ex.getMessage()); } } } ``` 3. 使用Jacob和Microsoft Office:如果您的系统已安装Microsoft Office,则可以使用Jacob库通过自动化操作将Word文档保存为PDF。您可以使用以下代码示例: ```java import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import com.jacob.com.Variant; public class WordToPdfConverter { public static void main(String[] args) { ActiveXComponent app = null; Dispatch doc = null; try { app = new ActiveXComponent("Word.Application"); app.setProperty("Visible", new Variant(false)); Dispatch docs = app.getProperty("Documents").toDispatch(); doc = Dispatch.call(docs, "Open", "input.docx").toDispatch(); Dispatch.call(doc, "SaveAs", "output.pdf", 17); System.out.println("Word转换PDF成功!"); } catch (Exception ex) { System.out.println("转换失败:" + ex.getMessage()); } finally { if (doc != null) { Dispatch.call(doc, "Close", false); } if (app != null) { app.invoke("Quit"); } } } } ``` 这些是将Word转换PDF的几种方法。您可以根据您的需求选择其中一种方法进行实现

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值