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

最后

如果觉得本文对你有帮助的话,不妨给我点个赞,关注一下吧!

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

需要这份系统化的资料的朋友,可以点击这里获取

  <version>2.0.1</version>

在关闭流之前添加并修改reponse中.docx为.pdf



response.setHeader(“Content-Disposition”, “attachment; filename=” + java.net.URLEncoder.encode(“日报-”+datetime+“.pdf”, “UTF-8”));
//转为PDF
PdfOptions options = PdfOptions.create();
PdfConverter.getInstance().convert(document, outStream, options);
//下面再是转word里面最后的代码,关闭流


2:**使用aspose.words的Document方式将word转换为PDF**  
 1:下载jar包:[jar包下载]( )  
 2:将jar包放入项目中resources目录下的lib文件夹中:  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/762adec6635740e2b63ac8fafd6e8795.png)  
 3:将jar包转为library  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/b3d79e02a6994a799fb263a0a0a30c44.png)  
 转换后就会出现上面图中箭头处的样子可以打开。


4:引入jar包依赖:



com.aspose.words aspose-words 15.8.0 system ${project.basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar

在打包的依赖中添加:



		<plugin>
            <configuration>
                <includeSystemScope>true</includeSystemScope>
            </configuration>
		</plugin>

5:转换



String s = “Aspose.Total for JavaAspose.Words for JavaEnterprise20991231209912318bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=”;
//去除水印
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模板,将需要转换的数值写成了${变量名}。  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/300e995470ff451f8d6adf6bee972b27.png)  
 2:转换



//模板文件的地址
String filePath = “/usr/local/data/模板.docx”;
//Map存储需要替换的值
Map<String, Object> map = new HashMap<>();
map.put(“ d a t e " , d a t e ) ; m a p . p u t ( " {date}", date); map.put(" date",date);map.put("{datetime}”, datetime);
//写入
try {
// 替换的的关键字存放到Set集合中
Set set = map.keySet();
// 读取模板文档
XWPFDocument document = new XWPFDocument(new FileInputStream(filePath ));
/**
* 替换段落中的指定文字
*/
// 读取文档中的段落,回车符为一个段落。
// 同一个段落里面会被“:”等符号隔开为多个对象
Iterator itPara = document.getParagraphsIterator();
while (itPara.hasNext()) {
// 获取文档中当前的段落文字信息
XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
List 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 iterator = set.iterator();
while (iterator.hasNext()) {
// 当前关键字
String key = iterator.next();
// 替换内容
sectionItem = sectionItem.replace(key, String.valueOf(map.get(key)));
}
//System.out.println(sectionItem);
run.get(i).setText(sectionItem, 0);
}
}

        /\*\*

* 替换表格中的指定文字

总结

无论是哪家公司,都很重视高并发高可用的技术,重视基础,重视JVM。面试是一个双向选择的过程,不要抱着畏惧的心态去面试,不利于自己的发挥。同时看中的应该不止薪资,还要看你是不是真的喜欢这家公司,是不是能真的得到锻炼。其实我写了这么多,只是我自己的总结,并不一定适用于所有人,相信经过一些面试,大家都会有这些感触。

最后我整理了一些面试真题资料,技术知识点剖析教程,还有和广大同仁一起交流学习共同进步,还有一些职业经验的分享。

面试了阿里,滴滴,网易,蚂蚁,最终有幸去了网易【面试题分享】

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

需要这份系统化的资料的朋友,可以点击这里获取

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录**

需要这份系统化的资料的朋友,可以点击这里获取

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

余额充值