Java将word转成pdf

在工作中遇到需求,需要将word文档转换为pdf以便前端预览。本文介绍了一种不依赖jar包的Java转换方法,虽然转换速度较慢,但显示效果接近。对于追求快速转换的读者,建议考虑其他方案。
摘要由CSDN通过智能技术生成

最近在工作中需要上传简历文件,需求是可以上传word文档,但在前端预览时iframe不支持word预览,所以需要把word文档转成pdf,网上有很多种转换的方法,不列举出来,我使用的不需要引入jar包,显示效果接近,但速度慢,如果需求速度快的小伙伴可以选择其他方法

直接贴上代码

import java.io.File;
import java.io.FileInputStream;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Random;
/**
     * 描述: word转PDf
     *
     * @param docUrl
     * @return
     * @auther 
     * @date 2018/9/14 11:22
     */
    private String getWordToPdf(String docUrl) {
    
        String fileUrl = docUrl;
        try {
    
            String suffix = docUrl.substring(docUrl.lastIndexOf("."), docUrl.length()).toLowerCase();
            if (StringUtils.equals(suffix, ".doc") || StringUtils.equals(suffix, ".docx")) {
    
                XDocService xDocService = new XDocService();
                File file = new File(createFilePath());
                xDocService.to(docUrl, file);

                FileInputStream inputStream = new FileInputStream(file);
                fileUrl = FileUtil.uploadFileForSurffix(inputStream, ".pdf", "resumeAttachment/");
                file.delete();
            }
        } catch (Exception e) {
    
            log.error("转换文件失败", e);
        }
        return fileUrl;
    }

    /**
     * 描述: 生成文件路径
     *
     * @param
     * @return
     * @auther 
     * @date 2018/8/9 10:42
     */
    private static String createFilePath() throws Exception {
    
        //获取当前文件的根路径
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()) path = new File("");

        //路径,盘符路径
        StringBuilder codeUrl = new StringBuilder().append(path.getAbsolutePath()).append("/static/attachment");

        String filePath = codeUrl.toString();
        File filedir = new File(filePath);
        if (!filedir.exists())
            filedir.mkdirs();
        codeUrl.append("/").append(getFileName()).append(".pdf");
        return codeUrl.toString();
    }

package com.dxyl.util.file;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.*;
import java.lang.annotation.*;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * XDoc服务
 *
 * @author xdoc
 * @version 11.4.2
 */
public class XDocService {
    
    /**
     * 默认服务器地址
     */
    public static String DEFAULT_URL = "http://www.xdocin.com";
    /**
     * 默认账号口令
     */
    public static String DEFAULT_KEY = "";
    private String url;
    private String key;

    /**
     * 服务地址
     *
     * @return
     */
    public String getUrl() {
    
        return url;
    }

    /**
     * 服务地址
     *
     * @param url
     */
    public void setUrl(String url) {
    
        this.url = url;
    }

    /**
     * 账号口令
     *
     * @return
     */
    public String getKey() {
    
        return key;
    }

    /**
     * 账号口令
     *
     * @param key
     */
    public void setKey(String key) {
    
        this.key = key;
    }

    /**
     * 构造器
     */
    public XDocService() {
    
        this(DEFAULT_URL, DEFAULT_KEY);
    }

    /**
     * 构造器
     *
     * @param url 服务地址
     */
    public XDocService(String url) {
    
        this(url, DEFAULT_KEY);
    }

    /**
     * 构造器
     *
     * @param url 服务地址
     * @param key 账号
     */
    public XDocService(String url, String key) {
    
        this.url = url;
        this.key = key;
    }

    /**
     * 转换为其它格式文件
     *
     * @param xdoc xdoc
     * @param file 其它格式文件,如:a.pdf
     * @throws IOException
     */
    public void to(File xdoc, File file) throws IOException {
    
        to(xdoc.getAbsolutePath(), file);
    }

    /**
     * 转换为其它格式文件
     *
     * @param xdoc xdoc文本<br>
     *             URL:文档URL地址,格式支持:xdoc、json、docx、epub、txt、rtf等,支持datauri协议,可传递二进制数据,支持本地文件<br>
     *             纯文本:以"text:"开头的文本<br>
     *             JSON:符合XDOC-JSON规范的JSON文本<br>
     *             XML:符合XDOC-XML规范的XML文本<br>
     *             HTML:用html标签括起来的html文本,如:&lt;html&gt;&lt;h1&gt;Hello&lt;/h1&gt;&lt;/html&gt;
     * @param file 其它格式文件,如:a.pdf
     * @throws IOException
     */
    public void to(String xdoc, File file) throws IOException {
    
        to(xdoc, new FileOutputStream(file), getFormat(file.getName()));
    }

    /**
     * 转换为其它格式,保存到指定流中
     *
     * @param xdoc   xdoc
     * @param out    输出目标,OutputStream或HttpServletResponse
     * @param format format
     * @throws IOException
     */
    public void to(String xdoc, Object out, String format) throws IOException {
    
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("_func", "to");
        param.put("_xdoc", xdoc);
        param.put("_format", format);
        invoke(checkParam(param), out);
    }

    /**
     * 转换为其它格式并发送
     *
     * @param xdoc   xdoc
     * @param to     目标,支持ftp、http、mail、datauri等
     * @param format format
     * @throws IOException
     */
    public String to(String xdoc, String to, String format) throws IOException {
    
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("_func", "to");
        param.put("_xdoc", xdoc);
        param.put("_to", to);
        param.put("_format", format);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        invoke(checkParam(param), out);
        return new String(out.toByteArray(), "UTF-8");
    }

    /**
     * 运行xdoc
     *
     * @param xdoc  xdoc
     * @param param 参数
     * @param file  目标文件
     * @throws IOException
     */
    public void run(File xdoc, Map<String, Object> param, File file) throws IOException {
    
        if (!param.containsKey("_xformat")) {
    
            param.put("_xformat", getFormat(file.getName()));
        }
        run(xdoc.getAbsolutePath(), param, file);
    }

    /**
     * 运行xdoc
     *
     * @param xdoc  xdoc
     * @param param 参数
     * @param file  目标文件
     * @throws IOException
     */
    public void run(String xdoc, Map<String, Object> param, File file) throws IOException {
    
        run(xdoc, param, new FileOutputStream(file), getFormat(file.getName()));
    }

    /**
     * 运行xdoc
     *
     * @param xdoc   xdoc
     * @param param  参数
     * @param out    输出目标,OutputStream或HttpServletResponse
     * @param format 目标格式
     * @throws IOException
     */
    public void run(String xdoc, Map<String, Object> param, Object out, String format) throws IOException {
    
        param.put("_func", "run");
        param.put("_xdoc", xdoc);
        param.put("_format", format);
        invoke(checkParam(param), out);
    }

    /**
     * 运行xdoc并发送
     *
     * @param xdoc   xdoc
     * @param param  参数
     * @param to     目标,支持ftp、http、mail、datauri等
     * @param format 目标格式
     * @throws IOException
     */
    public String run(String xdoc, Map<String, Object> param, String to, String format) throws IOException {
    
        param.put("_func", "run");
        param.put("_xdoc", xdoc);
        param.put("_to", to);
        param.put("_format", format);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        invoke(checkParam(param), out);
        return new String(out.toByteArray(), "UTF-8");
    }

    /**
     * 运行注解XDoc
     *
     * @param obj
     * @param file
     * @throws IOException
     */
    public void run(Object obj, File file) throws IOException {
    
        run(obj, new FileOutputStream(file), getFormat(file.getName()));
    }

    /**
     * 运行注解XDoc
     *
     * @param obj
     * @param out    目标流
     * @param format 目标格式
     * @throws IOException
     */
    public void run(Object obj, Object out, String format) throws IOException {
    
        run(obj, out, null, format);
    }

    /**
     * 运行注解XDoc
     *
     * @param obj
     * @param to     目标,支持ftp、http、mail、datauri等
     * @param format 目标格式
     * @throws IOException
     */
    public void run(Object obj, String to, String format) throws IOException {
    
        run(obj, null, to, format);
    }

    private void run(Object obj, Object out, String to, String format) throws IOException {
    
        String xurl = "";
        XDoc xdoc = obj.getClass().getAnnotation(XDoc.class);
        if (xdoc != null) {
    
            xurl = xdoc.value();
        }
        if (xurl.length() == 0) {
    
            xurl = "./" + obj.getClass().getSimpleName() + ".xdoc";
        }
        Field[] fields = obj.getClass().getDeclaredFields();
        boolean hasXParam = false;
        XParam xParam;
        Map<String, Object> param = new HashMap<String, Object>();
        String name;
        Object value;
        for (Field field : fields) {
    
            xParam = field.getAnnotation(XParam.class);
            if (xParam != null) {
    
                hasXParam = true;
                name = xParam.value();
                if (name.length() == 0) {
    
                    name = field.getName();
                }
                try {
    
                    field.setAccessible(true);
                    value = field.get(obj);
                    if (name.equals("_xdoc")) {
    
                        xurl = String.valueOf(value);
                    } else {
    
                        param.put(name, value);
                    }
                } catch (Exception e) {
    
                    throw new IOException(e);
                }
            }
        }
        if (!hasXParam) {
     //没有指定xparam,传入所有属性
            for (Field field : fields) {
    
                try {
    
                    field.setAccessible(true);
                    param.put(field.getName(), field.get(obj));
                } catch (Exception e) {
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将Word文档转换为PDF文件,可以使用Apache POI和iText库。以下是一个示例代码: ``` import java.io.*; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.converter.WordToPdfConverter; import org.apache.poi.hwpf.usermodel.Range; import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfWriter; public class WordToPDFConverter { public static void main(String[] args) { String inputFile = "input.doc"; String outputFile = "output.pdf"; try (FileInputStream fis = new FileInputStream(inputFile); HWPFDocument doc = new HWPFDocument(fis); OutputStream fileOutputStream = new FileOutputStream(outputFile); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { Range range = doc.getRange(); WordToPdfConverter converter = new WordToPdfConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()); converter.processDocument(doc, range, byteArrayOutputStream); Document pdfDoc = new Document(); PdfWriter.getInstance(pdfDoc, fileOutputStream); pdfDoc.open(); pdfDoc.addCreator("Word to PDF Converter"); pdfDoc.addTitle("Converted from Word document"); pdfDoc.addSubject("PDF document generated from Word document"); ByteArrayInputStream in = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); int bytesRead; byte[] buffer = new byte[4096]; while ((bytesRead = in.read(buffer)) != -1) { pdfDoc.add(new com.itextpdf.text.Paragraph(new String(buffer, 0, bytesRead))); } pdfDoc.close(); System.out.println("Conversion complete."); } catch (Exception e) { e.printStackTrace(); } } } ``` 在这个示例中,我们使用两个库:Apache POI和iText。我们首先打开Word文档,并使用`WordToPdfConverter`将其转换为PDF。然后,我们创建一个新的PDF文档,并将转换后的内容写入其中。最后,我们关闭PDF文档并完成转换。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值