word转pdf的几种方法

word转pdf的几种方法

需求是实现将word转换成pdf在线预览, 试了几种方法发现样式效果最好的是aspose-words,但是需要破解, 附带了激活方式

  • openOffice 与 libreOffice

    两款都是运行在服务器上面的office处理软件, 通过命令行的方式去执行转换命令

    下载安装好之后需要在代码中引入jodconverter相关jar包依赖(jodconverter.zip解压后lib下的都需要引入)

    相关软件及jar下载链接:https://pan.baidu.com/s/1u0U5jYYAjWRYO7mL5ilD8Q 提取码:8888

    // openOffice 和 libreOffice 差不多除了命令不一样
    // 1.执行系统命令启动openoffice线程
    // 2.连接openoffice服务连接
    // 3.执行转换
    
    // window 使用  调用openoffice服务线程  
    String command = "C:/Program Files (x86)/OpenOffice 4/program/soffice-headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
    // Linux使用
    // String command = "/opt/openoffice4/program/soffice -headless -accept=\"socket,host=127.0.0.1,port=8100;urp; -nofirststartwizard\"";
    Process p = Runtime.getRuntime().exec(command);
    
    // 连接openoffice服务
    OpenOfficeConnection connection = new SocketOpenOfficeConnection(
        "127.0.0.1", 8100);
    connection.connect();
    
    // 转换word到pdf
    DocumentConverter converter = new OpenOfficeDocumentConverter(
        connection);
    converter.convert(new File("/temp/1.doc"), new File("/temp/1.pdf"));
    
    connection.disconnect();
    p.destroy();
    
    • 如果出现中文乱码问题, 确定一下服务器上缺不缺中文字体

    ps: 试了大部分的word都能转换pdf, 有一些样式复杂的会渲染不出来, 直接把word源码生成pdf

  • spire.doc.free

    免费版的有页数限制, 我的场景不会有多页的就直接用的免费版本

    效果可以参照https://smallpdf.com/cn/word-to-pdf, https://www.freepdfconvert.com/zh-cn/word-to-pdf这些在线转换网站,我试了生成的效果和这些网站的一样.

    <!-- spire.doc.free 相关依赖 -->
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc.free</artifactId>
        <version>3.9.0</version>
    </dependency>
    
    <repositories>
        <repository>
            <id>com.e-iceblue</id>
            <url>http://repo.e-iceblue.cn/repository/maven-public/</url>
        </repository>
    </repositories>
    

    代码相当简单…

    import com.spire.doc.*;
    
    public class WordtoPDF {
        public static void main(String[] args) {
            // 加载word示例文档
            Document document = new Document();
            document.loadFromFile("D:\\2.doc");
            // 保存结果文件
            document.saveToFile("D:\\3.pdf");
        }
    }
    

    ps: 我生成的最后换行不一致, 所以没选用这个

  • aspose-words(推荐)

    效果可以参照迅捷pdf在线转换器https://app.xunjiepdf.com/pdf2word/

    需要引入aspose-words-15.8.0-jdk16.jar到项目中

    链接:https://pan.baidu.com/s/1q06E0wK13dC2ejDbDtdpZQ
    提取码:8888

    <!-- 下载后放项目lib下通过system引用 -->
    <dependency>
        <groupId>com.aspose</groupId>
        <artifactId>aspose-words</artifactId>
        <version>15.8.0</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
    </dependency>
    

    核心代码

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    
    import com.aspose.words.Document;
    import com.aspose.words.License;
    import com.aspose.words.SaveFormat;
    
    public class WordPdfUtil {
        
        private static boolean license = false;
        
        static {
            try {
                // license.xml放在src/main/resources文件夹下
                InputStream is = WordPdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
                License aposeLic = new License();
                aposeLic.setLicense(is);
                license = true;
            } catch (Exception e) {
                license = false;
                e.printStackTrace();
            }
        }
        
        public static void doc2pdf(String wordPath, String pdfPath) {
            // 验证License 若不验证则转化出的pdf文档会有水印产生
            if (!license) {
                System.out.println("License验证不通过...");
                return;
            }
            
            try {
                File file = new File(pdfPath);
                FileOutputStream os = new FileOutputStream(file);
                Document doc = new Document(wordPath);
                // 支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
                doc.save(os, SaveFormat.PDF);
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        public static void main(String[] args) {
            doc2pdf("D:\\3.doc","D:\\5.pdf");
        }
    }
    

    在src/main/resources文件夹下创建license.xml填充下面内容激活

    <?xml version="1.0" encoding="UTF-8" ?>
    <License>
        <Data>
            <Products>
                <Product>Aspose.Total for Java</Product>
                <Product>Aspose.Words for Java</Product>
            </Products>
            <EditionType>Enterprise</EditionType>
            <SubscriptionExpiry>20991231</SubscriptionExpiry>
            <LicenseExpiry>20991231</LicenseExpiry>
            <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
        </Data> <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
    </License>
    
  • file-online-preview

    github上面找到的一个开源项目, 活跃度比较高也记录一下. 目前试了效果没有aspose-words好用, 底层是集成的LibreOffice.

    项目地址: https://github.com/kekingcn/kkFileView

    支持的类型比较多,后续如果有需求,方便二次开发

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值