Java 将word转为PDF的三种方式和处理在服务器上下载后乱码的格式_java word转pdf

5:转换

String s = "<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>";
		//去除水印
        ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
        License license = new License();
        license.setLicense(is);

		//将XWPFDocument转换为InputStream
        ByteArrayOutputStream b = new ByteArrayOutputStream();
        //这里的document=XWPFDocument document,在下面的word转换中
        document.write(b);
        InputStream inputStream = new ByteArrayInputStream(b.toByteArray());
        
        //这里的Document 的引入是
        //import com.aspose.words.Document;
		//import com.aspose.words.License;
		//import com.aspose.words.SaveFormat;
        Document doc = new Document(inputStream);
        doc.save(outStream, SaveFormat.PDF);
        b.close();
        inputStream.close();
        //下面再是转word里面最后的代码,关闭流

3:使用documents4j 的方式将word转换为PDF

1:引入依赖:

        <!-- word 转 pdf   通过documents4j实现    -->

        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-local</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-transformer-msoffice-word</artifactId>
            <version>1.0.3</version>
        </dependency>

2:转换如下:

		//将XWPFDocument转换为InputStream
		ByteArrayOutputStream b = new ByteArrayOutputStream();
		//这里的document=XWPFDocument document,在下面的word转换中
        document.write(b);
        InputStream docxInputStream = new ByteArrayInputStream(b.toByteArray());
        
        //下面的引入类为:
        //import com.documents4j.api.DocumentType;
		//import com.documents4j.api.IConverter;
		//import com.documents4j.job.LocalConverter;
        IConverter converter = LocalConverter.builder().build();
        boolean execute = converter.convert(docxInputStream)
                .as(DocumentType.DOCX)
                .to(outStream)
                .as(DocumentType.PDF).schedule().get();
        
        b.close();
        docxInputStream.close();

3:这里之前转换word方式记录如下

1:制作word模板,将需要转换的数值写成了${变量名}。
在这里插入图片描述
2:转换

//模板文件的地址
String filePath = "/usr/local/data/模板.docx";
//Map存储需要替换的值
Map<String, Object> map = new HashMap<>();
map.put("${date}", date);
map.put("${datetime}", datetime);
//写入
try {
            // 替换的的关键字存放到Set集合中
            Set<String> set = map.keySet();
            // 读取模板文档
            XWPFDocument document = new XWPFDocument(new FileInputStream(filePath ));
            /\*\*
 \* 替换段落中的指定文字
 \*/
            // 读取文档中的段落,回车符为一个段落。
            // 同一个段落里面会被“:”等符号隔开为多个对象
            Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
            while (itPara.hasNext()) {
                // 获取文档中当前的段落文字信息
                XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
                List<XWPFRun> run = paragraph.getRuns();
                // 遍历段落文字对象
                for (int i = 0; i < run.size(); i++) {
                    // 获取段落对象
                    if (run.get(i) == null) {	//段落为空跳过
                        continue;
                    }
                    String sectionItem = run.get(i).getText(run.get(i).getTextPosition());						 //段落内容
                    //System.out.println("替换前 === "+sectionItem);
                    // 遍历自定义表单关键字,替换Word文档中的内容
                    Iterator<String> iterator = set.iterator();
                    while (iterator.hasNext()) {
                        // 当前关键字
                        String key = iterator.next();
                        // 替换内容


**自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。**

**深知大多数Linux运维工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!**

**因此收集整理了一份《2024年Linux运维全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。**
![img](https://img-blog.csdnimg.cn/img_convert/53cb0369052488193571a99a9d48ed97.png)
![img](https://img-blog.csdnimg.cn/img_convert/47c8f5376489bb70fc6cb39d6bdbfaf9.png)
![img](https://img-blog.csdnimg.cn/img_convert/8cedf9dad92ba3a6558226ab97306d46.png)
![img](https://img-blog.csdnimg.cn/img_convert/aba8f88a6c0cce329cb9bdd4eb3fe63a.png)
![img](https://img-blog.csdnimg.cn/img_convert/c6d75a4987f91c161f8ba85009cfbd8b.png)

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Linux运维知识点,真正体系化!**

**由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新**

**如果你觉得这些内容对你有帮助,可以添加VX:vip1024b (备注Linux运维获取)**
![img](https://img-blog.csdnimg.cn/img_convert/1172a9126c76075479e383070022152d.jpeg)

![](https://img-blog.csdnimg.cn/img_convert/9a8cb5f8c0ec69e6499adead0da6e95b.png)



最全的Linux教程,Linux从入门到精通

======================

1.  **linux从入门到精通(第2版)**

2.  **Linux系统移植**

3.  **Linux驱动开发入门与实战**

4.  **LINUX 系统移植 第2版**

5.  **Linux开源网络全栈详解 从DPDK到OpenFlow**



![华为18级工程师呕心沥血撰写3000页Linux学习笔记教程](https://img-blog.csdnimg.cn/img_convert/59742364bb1338737fe2d315a9e2ec54.png)



第一份《Linux从入门到精通》466页

====================

内容简介

====

本书是获得了很多读者好评的Linux经典畅销书**《Linux从入门到精通》的第2版**。本书第1版出版后曾经多次印刷,并被51CTO读书频道评为“最受读者喜爱的原创IT技术图书奖”。本书第﹖版以最新的Ubuntu 12.04为版本,循序渐进地向读者介绍了Linux 的基础应用、系统管理、网络应用、娱乐和办公、程序开发、服务器配置、系统安全等。本书附带1张光盘,内容为本书配套多媒体教学视频。另外,本书还为读者提供了大量的Linux学习资料和Ubuntu安装镜像文件,供读者免费下载。



![华为18级工程师呕心沥血撰写3000页Linux学习笔记教程](https://img-blog.csdnimg.cn/img_convert/9d4aefb6a92edea27b825e59aa1f2c54.png)



**本书适合广大Linux初中级用户、开源软件爱好者和大专院校的学生阅读,同时也非常适合准备从事Linux平台开发的各类人员。**

> 需要《Linux入门到精通》、《linux系统移植》、《Linux驱动开发入门实战》、《Linux开源网络全栈》电子书籍及教程的工程师朋友们劳烦您转发+评论




**一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
![img](https://img-blog.csdnimg.cn/img_convert/6539b237d68916dd5a3c3d7211c4956a.jpeg)

》、《Linux开源网络全栈》电子书籍及教程的工程师朋友们劳烦您转发+评论




**一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
[外链图片转存中...(img-tZWEdJKG-1712497569093)]

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用内容,可以得知在Linux下进行wordPDF时,可能会出现中文乱码的问题,原因是缺少一些字体。而Java作为一种跨平台的编程语言,同样也可能会出现这个问题。解决方法如下: 1.安装所需字体 在Linux系统中,可以通过以下命令安装中文字体: ```shell sudo apt-get install ttf-wqy-zenhei ``` 2.使用iText库进行换 iText是一个开源的Java PDF库,可以用于创建、修改和维护PDF文档。使用iText库进行wordPDF,可以避免中文乱码的问题。以下是一个简单的示例代码: ```java import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.converter.PDFConverter; import org.apache.poi.hwpf.usermodel.Range; import java.io.*; public class WordToPdf { public static void main(String[] args) { String inputFile = "input.doc"; String outputFile = "output.pdf"; try { InputStream input = new FileInputStream(new File(inputFile)); HWPFDocument wordDocument = new HWPFDocument(input); Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(outputFile)); document.open(); Range range = wordDocument.getRange(); document.add(new Paragraph(range.text())); document.close(); input.close(); System.out.println("换成功!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码使用Apache POI库读取word文档,然后使用iText库将其换为PDF文档。 3.使用JODConverter进行换 JODConverter是一个开源的Java库,可以将Office文档换为PDF、HTML、ODF等格式。以下是一个简单的示例代码: ```java import org.artofsolving.jodconverter.OfficeDocumentConverter; import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration; import org.artofsolving.jodconverter.office.OfficeManager; import java.io.File; public class WordToPdf { public static void main(String[] args) { String inputFile = "input.doc"; String outputFile = "output.pdf"; OfficeManager officeManager = null; try { officeManager = new DefaultOfficeManagerConfiguration().buildOfficeManager(); officeManager.start(); OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager); converter.convert(new File(inputFile), new File(outputFile)); System.out.println("换成功!"); } catch (Exception e) { e.printStackTrace(); } finally { if (officeManager != null) { officeManager.stop(); } } } } ``` 以上代码使用JODConverter将word文档换为PDF文档。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值