Java文档转换案例

wen java案例 2

本文目录导读:

Java文档转换案例

  1. 项目依赖配置 (pom.xml)
  2. 文档转换工具类
  3. Excel文档处理示例
  4. 主程序示例
  5. 使用说明

我来为您提供一个完整的Java文档转换案例,涵盖常见的文档格式转换场景。

项目依赖配置 (pom.xml)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>document-converter</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <!-- Apache POI - Word/Excel/PowerPoint -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>
        <!-- iText - PDF处理 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext7-core</artifactId>
            <version>7.2.5</version>
            <type>pom</type>
        </dependency>
        <!-- OpenPDF - 轻量PDF库 -->
        <dependency>
            <groupId>com.github.librepdf</groupId>
            <artifactId>openpdf</artifactId>
            <version>1.3.30</version>
        </dependency>
        <!-- Apache Commons IO -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
        <!-- Log4j2 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.20.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.20.0</version>
        </dependency>
        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.28</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

文档转换工具类

package com.example.converter;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
 * 文档转换工具类
 * 支持Word、PDF、TXT等格式转换
 */
public class DocumentConverter {
    private static final org.apache.logging.log4j.Logger logger = 
            org.apache.logging.log4j.LogManager.getLogger(DocumentConverter.class);
    /**
     * Word转PDF(使用POI和iText)
     */
    public static void wordToPdf(String wordPath, String pdfPath) {
        try (FileInputStream fis = new FileInputStream(wordPath);
             FileOutputStream fos = new FileOutputStream(pdfPath)) {
            // 加载Word文档
            XWPFDocument document = new XWPFDocument(fis);
            // 创建PDF文档
            PdfWriter writer = new PdfWriter(fos);
            PdfDocument pdf = new PdfDocument(writer);
            Document pdfDocument = new Document(pdf);
            // 遍历Word段落并转换
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            for (XWPFParagraph paragraph : paragraphs) {
                StringBuilder lineText = new StringBuilder();
                for (XWPFRun run : paragraph.getRuns()) {
                    lineText.append(run.text());
                }
                if (lineText.length() > 0) {
                    pdfDocument.add(new Paragraph(lineText.toString()));
                }
            }
            pdfDocument.close();
            document.close();
            logger.info("Word转PDF成功: {}", pdfPath);
        } catch (Exception e) {
            logger.error("Word转PDF失败", e);
            throw new RuntimeException("Word转PDF失败", e);
        }
    }
    /**
     * Word转PDF(使用POI XWPF converter)
     */
    public static void wordToPdfWithConverter(String wordPath, String pdfPath) {
        try (FileInputStream fis = new FileInputStream(wordPath);
             FileOutputStream fos = new FileOutputStream(pdfPath)) {
            XWPFDocument document = new XWPFDocument(fis);
            PdfOptions options = PdfOptions.create();
            PdfConverter.getInstance().convert(document, fos, options);
            document.close();
            logger.info("Word转PDF成功(Converter): {}", pdfPath);
        } catch (Exception e) {
            logger.error("Word转PDF失败(Converter)", e);
            throw new RuntimeException("Word转PDF失败", e);
        }
    }
    /**
     * PDF转TXT
     */
    public static void pdfToTxt(String pdfPath, String txtPath) {
        try {
            com.itextpdf.kernel.pdf.PdfDocument pdfDoc = 
                new com.itextpdf.kernel.pdf.PdfDocument(
                    new com.itextpdf.kernel.pdf.PdfReader(pdfPath));
            StringBuilder text = new StringBuilder();
            int pages = pdfDoc.getNumberOfPages();
            for (int i = 1; i <= pages; i++) {
                com.itextpdf.kernel.pdf.PdfPage page = pdfDoc.getPage(i);
                com.itextpdf.kernel.pdf.canvas.parser.PdfTextExtractor
                    .getTextFromPage(page, 
                        new com.itextpdf.kernel.pdf.canvas.parser.listener.SimpleTextExtractionStrategy());
                // 使用PDFBox或iText的extractor
                String pageText = com.itextpdf.kernel.pdf.canvas.parser.PdfTextExtractor
                    .getTextFromPage(page, new com.itextpdf.kernel.pdf.canvas.parser.listener.SimpleTextExtractionStrategy());
                text.append(pageText);
                text.append("\n");
            }
            // 写入TXT文件
            try (FileWriter writer = new FileWriter(txtPath, StandardCharsets.UTF_8)) {
                writer.write(text.toString());
            }
            pdfDoc.close();
            logger.info("PDF转TXT成功: {}", txtPath);
        } catch (Exception e) {
            logger.error("PDF转TXT失败", e);
            throw new RuntimeException("PDF转TXT失败", e);
        }
    }
    /**
     * TXT转Word
     */
    public static void txtToWord(String txtPath, String wordPath) {
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(txtPath), StandardCharsets.UTF_8));
             FileOutputStream fos = new FileOutputStream(wordPath)) {
            // 创建Word文档
            XWPFDocument document = new XWPFDocument();
            String line;
            while ((line = reader.readLine()) != null) {
                // 创建段落
                XWPFParagraph paragraph = document.createParagraph();
                XWPFRun run = paragraph.createRun();
                run.setText(line);
            }
            // 保存文档
            document.write(fos);
            document.close();
            logger.info("TXT转Word成功: {}", wordPath);
        } catch (Exception e) {
            logger.error("TXT转Word失败", e);
            throw new RuntimeException("TXT转Word失败", e);
        }
    }
    /**
     * HTML转PDF
     */
    public static void htmlToPdf(String htmlPath, String pdfPath) {
        try {
            // 读取HTML内容
            String htmlContent = new String(
                java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(htmlPath)), 
                StandardCharsets.UTF_8);
            // 创建PDF文档
            PdfWriter writer = new PdfWriter(pdfPath);
            PdfDocument pdfDoc = new PdfDocument(writer);
            Document document = new Document(pdfDoc);
            // 简单解析HTML(这里使用简单文本提取,实际应使用更复杂的HTML解析器)
            String plainText = htmlContent
                .replaceAll("<[^>]*>", "")  // 移除HTML标签
                .replaceAll("&nbsp;", " ")  // 替换空格
                .replaceAll("&amp;", "&")   // 替换&符号
                .trim();
            // 分割成段落
            String[] paragraphs = plainText.split("\\n+");
            for (String paragraph : paragraphs) {
                if (!paragraph.trim().isEmpty()) {
                    document.add(new Paragraph(paragraph.trim()));
                }
            }
            document.close();
            logger.info("HTML转PDF成功: {}", pdfPath);
        } catch (Exception e) {
            logger.error("HTML转PDF失败", e);
            throw new RuntimeException("HTML转PDF失败", e);
        }
    }
    /**
     * 批量转换目录下的所有文档
     */
    public static void batchConvert(String sourceDir, String targetDir, String fromFormat, String toFormat) {
        File sourceDirectory = new File(sourceDir);
        File[] files = sourceDirectory.listFiles((dir, name) -> name.endsWith("." + fromFormat));
        if (files == null || files.length == 0) {
            logger.warn("没有找到{}格式的文件", fromFormat);
            return;
        }
        File targetDirectory = new File(targetDir);
        if (!targetDirectory.exists()) {
            targetDirectory.mkdirs();
        }
        for (File file : files) {
            String fileName = file.getName().replaceFirst("[.][^.]+$", "");
            String sourcePath = file.getAbsolutePath();
            String targetPath = targetDir + File.separator + fileName + "." + toFormat;
            try {
                switch (fromFormat.toLowerCase() + "2" + toFormat.toLowerCase()) {
                    case "docx2pdf":
                    case "word2pdf":
                        wordToPdfWithConverter(sourcePath, targetPath);
                        break;
                    case "pdf2txt":
                        pdfToTxt(sourcePath, targetPath);
                        break;
                    case "txt2docx":
                        txtToWord(sourcePath, targetPath);
                        break;
                    case "html2pdf":
                        htmlToPdf(sourcePath, targetPath);
                        break;
                    default:
                        logger.warn("不支持的转换格式: {} -> {}", fromFormat, toFormat);
                }
            } catch (Exception e) {
                logger.error("转换文件失败: {}", file.getName(), e);
            }
        }
    }
}

Excel文档处理示例

package com.example.converter;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
 * Excel文档处理类
 */
public class ExcelConverter {
    private static final org.apache.logging.log4j.Logger logger = 
            org.apache.logging.log4j.LogManager.getLogger(ExcelConverter.class);
    /**
     * Excel转Word
     */
    public static void excelToWord(String excelPath, String wordPath) {
        try (FileInputStream fis = new FileInputStream(excelPath);
             FileOutputStream fos = new FileOutputStream(wordPath)) {
            // 读取Excel
            Workbook workbook = new XSSFWorkbook(fis);
            // 创建Word
            XWPFDocument document = new XWPFDocument();
            // 遍历所有工作表
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i);
                // 添加工作表名称作为标题
                XWPFParagraph titlePara = document.createParagraph();
                XWPFRun titleRun = titlePara.createRun();
                titleRun.setText("工作表: " + sheet.getSheetName());
                titleRun.setBold(true);
                titleRun.setFontSize(14);
                // 创建表格
                int rows = sheet.getPhysicalNumberOfRows();
                int cols = getMaxColumns(sheet);
                if (rows > 0 && cols > 0) {
                    XWPFTable table = document.createTable(rows, cols);
                    // 遍历行和列
                    for (int r = 0; r < rows; r++) {
                        Row excelRow = sheet.getRow(r);
                        XWPFTableRow wordRow = table.getRow(r);
                        for (int c = 0; c < cols; c++) {
                            Cell excelCell = excelRow != null ? excelRow.getCell(c) : null;
                            String cellText = "";
                            if (excelCell != null) {
                                switch (excelCell.getCellType()) {
                                    case STRING:
                                        cellText = excelCell.getStringCellValue();
                                        break;
                                    case NUMERIC:
                                        cellText = String.valueOf(excelCell.getNumericCellValue());
                                        break;
                                    case BOOLEAN:
                                        cellText = String.valueOf(excelCell.getBooleanCellValue());
                                        break;
                                    default:
                                        cellText = "";
                                }
                            }
                            // 设置Word表格单元格内容
                            org.apache.poi.xwpf.usermodel.XWPFTableCell tableCell = 
                                wordRow.getCell(c);
                            tableCell.setText(cellText);
                        }
                    }
                }
                // 添加空行分隔工作表
                if (i < workbook.getNumberOfSheets() - 1) {
                    document.createParagraph();
                }
            }
            // 保存文档
            document.write(fos);
            workbook.close();
            document.close();
            logger.info("Excel转Word成功: {}", wordPath);
        } catch (Exception e) {
            logger.error("Excel转Word失败", e);
            throw new RuntimeException("Excel转Word失败", e);
        }
    }
    private static int getMaxColumns(Sheet sheet) {
        int maxCols = 0;
        for (Row row : sheet) {
            if (row.getLastCellNum() > maxCols) {
                maxCols = row.getLastCellNum();
            }
        }
        return maxCols;
    }
    /**
     * Excel转PDF
     */
    public static void excelToPdf(String excelPath, String pdfPath) {
        List<List<String>> data = readExcelData(excelPath);
        String[][] arrayData = new String[data.size()][];
        for (int i = 0; i < data.size(); i++) {
            List<String> row = data.get(i);
            arrayData[i] = row.toArray(new String[0]);
        }
        try {
            com.itextpdf.kernel.pdf.PdfWriter writer = 
                new com.itextpdf.kernel.pdf.PdfWriter(pdfPath);
            com.itextpdf.kernel.pdf.PdfDocument pdfDoc = 
                new com.itextpdf.kernel.pdf.PdfDocument(writer);
            com.itextpdf.layout.Document document = 
                new com.itextpdf.layout.Document(pdfDoc);
            // 创建表格
            if (arrayData.length > 0 && arrayData[0].length > 0) {
                float[] columnWidths = new float[arrayData[0].length];
                for (int i = 0; i < columnWidths.length; i++) {
                    columnWidths[i] = 100f;
                }
                com.itextpdf.layout.element.Table table = 
                    new com.itextpdf.layout.element.Table(columnWidths);
                // 添加数据
                for (String[] rowData : arrayData) {
                    for (String cellData : rowData) {
                        table.addCell(new com.itextpdf.layout.element.Cell()
                            .add(new com.itextpdf.layout.element.Paragraph(cellData != null ? cellData : "")));
                    }
                }
                document.add(table);
            }
            document.close();
            logger.info("Excel转PDF成功: {}", pdfPath);
        } catch (Exception e) {
            logger.error("Excel转PDF失败", e);
            throw new RuntimeException("Excel转PDF失败", e);
        }
    }
    private static List<List<String>> readExcelData(String excelPath) {
        List<List<String>> data = new ArrayList<>();
        try (FileInputStream fis = new FileInputStream(excelPath)) {
            Workbook workbook = new XSSFWorkbook(fis);
            Sheet sheet = workbook.getSheetAt(0);  // 读取第一个工作表
            for (Row row : sheet) {
                List<String> rowData = new ArrayList<>();
                for (Cell cell : row) {
                    switch (cell.getCellType()) {
                        case STRING:
                            rowData.add(cell.getStringCellValue());
                            break;
                        case NUMERIC:
                            rowData.add(String.valueOf(cell.getNumericCellValue()));
                            break;
                        case BOOLEAN:
                            rowData.add(String.valueOf(cell.getBooleanCellValue()));
                            break;
                        default:
                            rowData.add("");
                    }
                }
                data.add(rowData);
            }
            workbook.close();
        } catch (Exception e) {
            logger.error("读取Excel失败", e);
            throw new RuntimeException("读取Excel失败", e);
        }
        return data;
    }
}

主程序示例

package com.example;
import com.example.converter.DocumentConverter;
import com.example.converter.ExcelConverter;
/**
 * 文档转换演示主程序
 */
public class Main {
    private static final org.apache.logging.log4j.Logger logger = 
            org.apache.logging.log4j.LogManager.getLogger(Main.class);
    public static void main(String[] args) {
        try {
            // 示例1: Word转PDF
            System.out.println("=== 测试 Word 转 PDF ===");
            DocumentConverter.wordToPdf(
                "input/sample.docx",
                "output/sample.pdf"
            );
            // 示例2: PDF转TXT
            System.out.println("=== 测试 PDF 转 TXT ===");
            DocumentConverter.pdfToTxt(
                "input/sample.pdf",
                "output/sample.txt"
            );
            // 示例3: TXT转Word
            System.out.println("=== 测试 TXT 转 Word ===");
            DocumentConverter.txtToWord(
                "input/sample.txt",
                "output/sample.docx"
            );
            // 示例4: Excel转Word
            System.out.println("=== 测试 Excel 转 Word ===");
            ExcelConverter.excelToWord(
                "input/sample.xlsx",
                "output/sample.docx"
            );
            // 示例5: HTML转PDF
            System.out.println("=== 测试 HTML 转 PDF ===");
            DocumentConverter.htmlToPdf(
                "input/sample.html",
                "output/sample.pdf"
            );
            // 示例6: 批量转换
            System.out.println("=== 测试批量转换 ===");
            DocumentConverter.batchConvert(
                "input/",
                "output/",
                "docx",
                "pdf"
            );
            System.out.println("所有文档转换完成!");
        } catch (Exception e) {
            logger.error("文档转换失败", e);
            System.err.println("错误: " + e.getMessage());
        }
    }
}

使用说明

// 创建必要的目录结构
// src/main/java/com/example/
// │── converter/
// │   ├── DocumentConverter.java
// │   └── ExcelConverter.java
// ├── Main.java
// └── resources/
//     └── log4j2.xml
// input/ 和 output/ 目录放在项目根目录
// log4j2配置 (log4j2.xml)
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <File name="File" fileName="logs/application.log">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="File"/>
        </Root>
    </Loggers>
</Configuration>

这个完整的案例涵盖了:

  1. Word转PDF:两种方式实现
  2. PDF转TXT:提取PDF文本内容
  3. TXT转Word:文本写入Word文档
  4. Excel转Word:Excel数据转换到Word表格
  5. Excel转PDF:Excel数据呈现在PDF表格中
  6. HTML转PDF:HTML内容转为PDF
  7. 批量转换:支持批量处理

使用前请确保:

  • 输入文件格式正确
  • 输出目录已创建
  • 文件编码为UTF-8(中文内容)

抱歉,评论功能暂时关闭!