Java中将Word、Excel文件转成PDF文件示例

1、环境设置

先导入Jar包

方法一:创建maven项目,然后添加以下代码来配置pom.xml 文件,再点击Import Changes将 JAR文件导入到应用程序中。

<repositories>
    <repository>
        <id>public</id>
        <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.office.free</artifactId>
        <version>5.3.1</version>
    </dependency>
</dependencies>

方法二:手动导入Jar包,可以从Index of /e-iceblue/spire.office.free下载Free Spire.Office for Java,下载并进行解压;然后在IDEA中创建一个新项目,依次点击“文件”(File),“项目结构”(Project Structure),“组件”(Modules),“依赖项”(Dependencies),再点击右方绿色“+”下的第一个选项“JAR文件或路径”(JARs or Directories),找到解压后的文件,点击确认,将其导入到项目中。

注:如果打Jar包发布,需将Jar包添加到项目根目录下新建lib文件夹,将Jar包复制到文件夹中,再将Jar包在pom.xml中引入。

示例:

        <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.office.free</artifactId>
            <scope>system</scope>
            <version>5.3.1</version>
            <systemPath>${project.basedir}/lib/spire.office.free-5.3.1.jar</systemPath>
        </dependency>

2、代码示例:(仅供参考,完成的代码没贴出来,仅摘取涉及生成的部分)

import com.spire.doc.Document;
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;


    public static void main(String[] args) {
       //输出word文件路径和名称 (临时文件名,本次为测试,最好使用雪花算法生成,或者用uuid)
        String fileName = UUID.randomUUID().toString() + ".docx";
        //输出excel文件名称 (临时文件名,本次为测试,最好使用雪花算法生成,或者用uuid)
        String fileName1 = UUID.randomUUID().toString().replaceAll("-", "") + ".xlsx";
        //输出pdf文件路径和名称  (临时文件  尽可能保证文件名称的唯一性)
        String pdfName = UUID.randomUUID().toString() + ".pdf";
        //生成docx临时文件
        File tempFile = null;
        //生成转换后pdf临时文件
        File pdfFile = null;
        //生成docx临时文件
        tempFile = new File(fileName);
        //生成excel临时文件
        tempFile1 = new File(fileName1);

        /* word及excel文件内容的逻辑没写,这个根据自己的需求实现 */

        //实现word文件转成pdf文件方法
	    pdfFile = testDocxToPdf(tempFile,pdfName);
        //实现excel文件转成pdf文件方法
        pdfFile = testExcelToPdf(tempFile1,pdfName); 

    }
    


   /**
     * 通过spire.office.free下的spire.doc.free 实现word转pdf
     * @param tempPath 生成的docx临时文件
     * @return
     */
    public File testDocxToPdf(File tempPath,String pdfName) {
        //生成pdf临时文件
        File pdfFile = new File(pdfName);
        try{
            InputStream docxInputStream = null;
            OutputStream outputStream = null;
            // 原word地址
            docxInputStream = new FileInputStream(tempPath);
            // 转换后pdf生成地址
            outputStream = new FileOutputStream(pdfFile);

            //实例化Document类的对象
            Document doc = new Document();
            //加载Word
            doc.loadFromStream(docxInputStream,FileFormat.Docx);
            //保存为PDF格式
            doc.saveToFile(outputStream, FileFormat.PDF);
			//	自测的时候存饭的地址
			//doc.saveToFile("D:\\data\\word模板转pdf.pdf", FileFormat.PDF);
            // 关闭
            outputStream.close();
            // 关闭
            docxInputStream.close();

        }catch (Exception e){
            throw new ServiceException("预览失败" + e.getMessage());
        }
        return pdfFile;
    }



   /**
     * 通过spire.office.free下的spire.xls.free 实现excel转pdf
     * @param tempPath 生成的excel临时文件
     * @return
     * 通过调用Workbook类的构造函数创建一个Workbook对象,并使用loadFromFile()方法从指定的路径 
     * 加载Excel文件。接着,通过调用setSheetFitToPage()方法设置工作表适应页面,以便更好地进行 
     * PDF文件转换。最后,使用saveToFile()方法将生成的PDF文件保存到指定的位置。
     */
    public File testExcelToPdf(File tempPath,String pdfName) {
        try{
            //创建Workbook 实例并加载示例文档
            Workbook workbook = new Workbook();

            //获取excel临时文件位置(这测试用的是项目的根目录下,可以根据自己的需求调整)
            workbook.loadFromFile("/temporary/"+tempPath.getName());

            //转换时设置工作表适应页面
            workbook.getConverterSetting().setSheetFitToPage(true);

            //保存为PDF文档格式
            workbook.saveToFile(pdfName, FileFormat.PDF);

        }catch (Exception e){
            throw new ServiceException("excel转pdf失败" + e.getMessage());
        }
        //生成pdf临时文件
        File pdfFile = new File(pdfName);
        return pdfFile;
    }

  • 19
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java中将Word文档换为图片可以使用Apache POI和Apache Batik两个库来实现。具体的步骤如下: 1. 使用Apache POI读取Word文档,获取文档中的内容和样式信息。 2. 将Word文档的内容和样式信息换成HTML格式。 3. 使用Apache Batik将HTML格式的内容换成SVG格式。 4. 使用Java的图形库将SVG格式的图片换成其他格式的图片,如PNG、JPEG等。 下面是一个基本的示例代码: ```java import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.image.PNGTranscoder; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFPictureData; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.hwpf.usermodel.Picture; public class WordToImage { public static void main(String[] args) throws Exception { String filePath = "test.docx"; String imagePath = "test.png"; // 读取Word文档 XWPFDocument document = new XWPFDocument(new FileInputStream(filePath)); // 将Word文档内容换成HTML格式 String html = "<html><body>"; for (XWPFParagraph paragraph : document.getParagraphs()) { for (XWPFRun run : paragraph.getRuns()) { String text = run.getText(0); if (text != null) { html += "<span style='" + run.getColor() + ";" + run.getFontFamily() + ";" + run.getFontSize() + "'>" + text + "</span>"; } } } html += "</body></html>"; // 将HTML换成SVG格式 TranscoderInput input = new TranscoderInput(new StringReader(html)); OutputStream outputStream = new FileOutputStream(imagePath); TranscoderOutput output = new TranscoderOutput(outputStream); PNGTranscoder transcoder = new PNGTranscoder(); transcoder.transcode(input, output); outputStream.flush(); outputStream.close(); } } ``` 需要注意的是,这个例子只是一个基本的示例代码,如果要应用到实际项目中,还需要考虑很多因素,如Word文档的格式、图片的大小、图片的质量等等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值