前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >Word转PDF 并转成base64(亲测可用)

Word转PDF 并转成base64(亲测可用)

作者头像
默 语
发布于 2024-11-20 03:04:14
发布于 2024-11-20 03:04:14
20300
代码可运行
举报
文章被收录于专栏:JAVAJAVA
运行总次数:0
代码可运行
Word转PDF 并转成base64(亲测可用)
博主 默语带您 Go to New World.

个人主页—— 默语 的博客👦🏻

《java 面试题大全》

🍩惟余辈才疏学浅,临摹之作或有不妥之处,还请读者海涵指正。☕🍭

《MYSQL从入门到精通》数据库是开发者必会基础之一~

🪁 吾期望此文有资助于尔,即使粗浅难及深广,亦备添少许微薄之助。苟未尽善尽美,敬请批评指正,以资改进。!💻⌨

摘要:

  1. Word转PDF: 使用库(如Apache POI或iText)读取Word文档内容,并使用PDF相关的库(如Apache PDFBox)将其转换为PDF格式。这一步是将文档格式转换为可打印格式,方便后续处理。
  2. PDF转Base64: 使用Java的文件读取和Base64编码库,将生成的PDF文件读取为字节流,并将其编码为Base64格式的字符串。Base64编码是一种将二进制数据编码为可传输文本的方法。
  3. 代码实现: 编写Java代码,使用适当的库实现Word到PDF的转换和PDF到Base64的编码。在此代码中,您需要调用适当的库函数以及文件读取和编码功能。
  4. 错误处理: 考虑异常处理,例如捕获文件读取和转换过程中可能出现的错误。确保在代码中进行适当的异常处理以防止程序崩溃或不正常终止。
  5. 性能和效率: 在处理大文件时,确保代码的性能和效率。避免不必要的内存消耗和重复计算。
  6. 文件清理: 在完成Base64编码后,可以考虑删除生成的临时PDF文件,以保持文件系统整洁。
  7. 测试和调试: 使用不同的Word文档进行测试,确保转换和编码过程正常工作。在问题出现时,进行调试和排除。
  8. 使用场景: 将Word文档转换为PDF并编码为Base64适用于将文档转换为可嵌入网页或作为API响应传递给前端等场景。

控制台

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Override
	public String printFile(Long id) throws IOException {

		try {
			FileDypeVo fileDypeVos = fileMapper.selectFileId(id);

			String path = fileDypeVos.getFilePath();
			String name = fileDypeVos.getFileName();

			File file = new File(path + name);
			// 获取后缀
			String str = name.substring(name.lastIndexOf(".") + 1);
			// 获取前面的名字
			String str1 = name.substring(0, name.lastIndexOf(".") - 1);
			// 拼装为pdf
			String str2 = str1 + ".pdf";
			LOGGER.info("str==》" + str);
			LOGGER.info("str1===>" + str1);
			LOGGER.info("str2===>" + str2);
			LOGGER.info("file===>" + file);

			BASE64Encoder encoder = new BASE64Encoder();

			if (str.equals("pdf")) {

				FileInputStream inputFile = new FileInputStream(file);
				byte[] buffer = new byte[(int) file.length()];

				inputFile.read(buffer);
				inputFile.close();

				System.out.println("pdf预览成功");

				return encoder.encode(buffer);
			}
			if (str.equals("docx") || str.equals("doc")) {

				String sourcePath = path + name;

				String targetPath = path + str2;

				String files01 = str2;

				LOGGER.info("sourcePath==>" + sourcePath + "==>targetPath==>" + targetPath + "==files" + files01);
				File fileYan = new File(targetPath);

				// 查看是否生成过pdf了查看文件是否是存在 不存在则进入 存在不执行
				if (!fileYan.exists()) {
					ExcelPdToWord.documents4jWordToPdf(sourcePath, targetPath);
				}

				FileInputStream inputFile = new FileInputStream(fileYan);

				byte[] buffer = new byte[(int) fileYan.length()];

				inputFile.read(buffer);
				inputFile.close();

				System.out.println("pdf预览成功");

				return encoder.encode(buffer);
			} else {
				throw new ServiceException("该文档格式无法预览");
			}

		} catch (Exception e) {
			throw new ServiceException("预览失败" + e.getMessage());
			// TODO: handle exception
		}

	}

核心代码

ExcelPdToWord.documents4jWordToPdf(sourcePath, targetPath);

实现类

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
	 /**
     * 通过documents4j 实现word转pdf
     *
     * @param sourcePath 源文件地址 如 /root/example.doc
     * @param targetPath 目标文件地址 如 /root/example.pdf
     */
    public static void documents4jWordToPdf(String sourcePath, String targetPath) {
        File inputWord = new File(sourcePath);
        File outputFile = new File(targetPath);
        try  {
            InputStream docxInputStream = new FileInputStream(inputWord);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(outputStream)
                    .as(DocumentType.PDF).execute();
            outputStream.close();
        } catch (Exception e) {
        	LOGGER.error("[documents4J] word转pdf失败:{}"+ e.toString());
           // log.error("[documents4J] word转pdf失败:{}", e.toString());
        }
    }

POM

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
		<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>

Gradle

compile 我这边设置以他为空,各位你们可自行查看;manve库和我们这边不一样

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 compile group: 'com.documents4j', name: 'documents4j-local', version: '1.0.3'
     // https://mvnrepository.com/artifact/com.documents4j/documents4j-transformer-msoffice-word
     compile group: 'com.documents4j', name: 'documents4j-transformer-msoffice-word', version: '1.0.3'
     compile group: 'com.documents4j', name: 'documents4j-api', version: '1.0.3'
  // https://mvnrepository.com/artifact/com.documents4j/documents4j-transformer
     compile group: 'com.documents4j', name: 'documents4j-transformer', version: '1.0.3'
     compile group: 'com.documents4j', name: 'documents4j-transformer-api', version: '1.0.3'
     compile group: 'com.documents4j', name: 'documents4j-transformer-msoffice-base', version: '1.0.3'
     compile group: 'com.documents4j', name: 'documents4j-util-all', version: '1.0.3'
     compile group: 'com.documents4j', name: 'documents4j-util-conversion', version: '1.0.3'
     compile group: 'com.documents4j', name: 'documents4j-util-transformer-process', version: '1.0.3'
     compile group: 'org.zeroturnaround', name: 'zt-exec', version: '1.8'

扩展其他方式 apose

https://cloud.tencent.com/developer/article/2467496@TOC

控制台

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Override
	public String printFile(Long id) throws IOException {

		try {
			FileDypeVo fileDypeVos = fileMapper.selectFileId(id);

			String path = fileDypeVos.getFilePath();
			String name = fileDypeVos.getFileName();

			File file = new File(path + name);
			// 获取后缀
			String str = name.substring(name.lastIndexOf(".") + 1);
			// 获取前面的名字
			String str1 = name.substring(0, name.lastIndexOf(".") - 1);
			// 拼装为pdf
			String str2 = str1 + ".pdf";
			LOGGER.info("str==》" + str);
			LOGGER.info("str1===>" + str1);
			LOGGER.info("str2===>" + str2);
			LOGGER.info("file===>" + file);

			BASE64Encoder encoder = new BASE64Encoder();

			if (str.equals("pdf")) {

				FileInputStream inputFile = new FileInputStream(file);
				byte[] buffer = new byte[(int) file.length()];

				inputFile.read(buffer);
				inputFile.close();

				System.out.println("pdf预览成功");

				return encoder.encode(buffer);
			}
			if (str.equals("docx") || str.equals("doc")) {

				String sourcePath = path + name;

				String targetPath = path + str2;

				String files01 = str2;

				LOGGER.info("sourcePath==>" + sourcePath + "==>targetPath==>" + targetPath + "==files" + files01);
				File fileYan = new File(targetPath);

				// 查看是否生成过pdf了查看文件是否是存在 不存在则进入 存在不执行
				if (!fileYan.exists()) {
					ExcelPdToWord.documents4jWordToPdf(sourcePath, targetPath);
				}

				FileInputStream inputFile = new FileInputStream(fileYan);

				byte[] buffer = new byte[(int) fileYan.length()];

				inputFile.read(buffer);
				inputFile.close();

				System.out.println("pdf预览成功");

				return encoder.encode(buffer);
			} else {
				throw new ServiceException("该文档格式无法预览");
			}

		} catch (Exception e) {
			throw new ServiceException("预览失败" + e.getMessage());
			// TODO: handle exception
		}

	}

核心代码

ExcelPdToWord.documents4jWordToPdf(sourcePath, targetPath);

实现类

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
	 /**
     * 通过documents4j 实现word转pdf
     *
     * @param sourcePath 源文件地址 如 /root/example.doc
     * @param targetPath 目标文件地址 如 /root/example.pdf
     */
    public static void documents4jWordToPdf(String sourcePath, String targetPath) {
        File inputWord = new File(sourcePath);
        File outputFile = new File(targetPath);
        try  {
            InputStream docxInputStream = new FileInputStream(inputWord);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(outputStream)
                    .as(DocumentType.PDF).execute();
            outputStream.close();
        } catch (Exception e) {
        	LOGGER.error("[documents4J] word转pdf失败:{}"+ e.toString());
           // log.error("[documents4J] word转pdf失败:{}", e.toString());
        }
    }

POM

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
		<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>

Gradle

compile 我这边设置以他为空,各位你们可自行查看;manve库和我们这边不一样

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 compile group: 'com.documents4j', name: 'documents4j-local', version: '1.0.3'
     // https://mvnrepository.com/artifact/com.documents4j/documents4j-transformer-msoffice-word
     compile group: 'com.documents4j', name: 'documents4j-transformer-msoffice-word', version: '1.0.3'
     compile group: 'com.documents4j', name: 'documents4j-api', version: '1.0.3'
  // https://mvnrepository.com/artifact/com.documents4j/documents4j-transformer
     compile group: 'com.documents4j', name: 'documents4j-transformer', version: '1.0.3'
     compile group: 'com.documents4j', name: 'documents4j-transformer-api', version: '1.0.3'
     compile group: 'com.documents4j', name: 'documents4j-transformer-msoffice-base', version: '1.0.3'
     compile group: 'com.documents4j', name: 'documents4j-util-all', version: '1.0.3'
     compile group: 'com.documents4j', name: 'documents4j-util-conversion', version: '1.0.3'
     compile group: 'com.documents4j', name: 'documents4j-util-transformer-process', version: '1.0.3'
     compile group: 'org.zeroturnaround', name: 'zt-exec', version: '1.8'

扩展其他方式 apose

https://cloud.tencent.com/developer/article/2467496

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-08-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
图片转base64 并根据格式加前缀
这是一个使用Java编写的示例代码,用于将图片文件转换为Base64编码并添加特定格式的前缀。代码中的 imageToBase64WithPrefix 方法接受图片路径、图片格式和前缀作为参数,然后读取图片文件的字节数据,将其转换为Base64编码,并将前缀添加到编码后的字符串中。主方法演示了如何调用这个方法并输出得到的带有前缀的Base64编码。请替换示例代码中的路径、格式和前缀以适应您的实际需求。
默 语
2024/11/20
2550
图片转base64 并根据格式加前缀
base64 和音频文件 互相转换
public static String encodeBase64File(String path) throws Exception { File file = new File(p
用户5899361
2020/12/07
3.4K0
documents4j 文档转换
https://github.com/documents4j/documents4j
鱼找水需要时间
2023/08/27
7951
documents4j 文档转换
基于POI的Word解析成HTML(base64图片)
我们一般提交文档常采用的是富文本编辑上传的常规方法,有时候想将文档上传后,再进行富文本编辑怎么办呢?
CodeWwang
2022/08/24
1.7K0
【密码学】Base64 编码 ( Base64 简介 | Base64 编码原理 | 最后编码组字节不足时补位 ‘=‘ 符号 | Base64 编码实现参考 )
Base64 不是加密算法 , 是一种 可读性算法 , 其目的不是用于保护数据 , 其目的是为了可读性 ;
韩曙亮
2023/03/29
3.6K0
【密码学】Base64 编码 ( Base64 简介 | Base64 编码原理 | 最后编码组字节不足时补位 ‘=‘ 符号 | Base64 编码实现参考 )
Java实现word、excel、ppt、txt等办公文件在线预览功能
Java实现办公文件在线预览功能是一个大家在工作中也许会遇到的需求,网上些公司专门提供这样的服务,不过需要收费。
Java旅途
2021/11/26
2.9K0
Java Base64转换,Java Base64工具类
但这个性能一般,而且转换出来的base64字符串会有换行符,可能还需要替换换行符,避免在某些场景因为分行导致出错 2、使用Jdk8的Base64工具类(优先考虑使用)
用户9131103
2023/07/17
7350
Python中String, Bytes, Hex, Base64之间的关系与转换方法详解
In this program, you are required to learn basic concepts of Python 3.
timerring
2022/07/20
7720
Python中String, Bytes, Hex, Base64之间的关系与转换方法详解
图片美化增强AI接口调用手册
POST BODY,接口要求以Post body方式发送,因为要传base64字符串,请求参数过长有400错误的
SmileNicky
2019/06/14
9500
图片美化增强AI接口调用手册
word,ppt,excel转pdf,pdf转html工具类搭建
我看到很多需求要求word,excel,ppt,pptx转pdf等工具类。还有就是pdf转图片转html这里介绍一个这个工具类。
斯文的程序
2019/11/07
3.6K0
Illegal base64 character a
base64解码为文件方式不止一种,下面两种,如果一种报错,换另外一种试一下: byte[] bytes = Base64Utils.decodeFromString(base64Str); byte[] bytes1 = new BASE64Decoder().decodeBuffer(base64Str); 先将base64字符串转为byte数组,然后再转为文件: public static File base64StrToFile(Strin
IT云清
2019/01/22
2.9K0
Java 图片URL转Base64编码
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
全栈程序员站长
2022/10/05
3.8K0
Java 图片URL转Base64编码
【小家java】java8新特性之---Base64加密和解密原理
Base64是一种字符串编码格式,采用了A-Z,a-z,0-9,“+”和“/”这64个字符来编码原始字符(还有垫字符“=”)。一个字符本身是一个字节,也就是8位,而base64编码后的一个字符只能表示6位的信息。也就是原始字符串中的3字节的信息编码会变成4字节的信息。Base64的主要作用是满足MIME的传输需求。 在Java8中Base64编码已经成为Java类库的标准,且内置了Base64编码的编码器和解码器。
YourBatman
2019/09/03
1.4K0
PDF技术 -Java实现Html转PDF文件
综合:使用WKHtmlToPdf效果(样式)最好。但速度较慢(对于文件来说)。其余均有大大小小的失真问题。
用户1518699
2022/05/09
13K0
PDF技术 -Java实现Html转PDF文件
.net pdf转word_pdf to word
文件的详细路径: pdfToDoc(String pdfPath, String docPath) 输入流: pdfToDoc(InputStream pdfPathInputStream, String docPath)
全栈程序员站长
2022/11/17
7.3K0
.net pdf转word_pdf to word
springboot中使用SFTP文件上传
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
全栈程序员站长
2022/11/03
3.4K0
C语言实现base64编解码
base64编解码 工作中经常会用到base64编解码, 有些开源库中也有实现, 但是如果再去看他们的怎么用有时候也是有点费劲的, 还有就是需要引用那个头文件啊, 什么的, 尤其是OpenSSL里边的, 所以这里献上原理, 及其使用. 至于用途还有详细的介绍我觉得某度某科里讲的挺好的, 这里就只写上实现原理及代码了. 详细请看base64.h 和base64.c, 使用见main.c 即可, 可以使用任何编译器编译运行, 下面依次是base64.h, base64.c, main.c如果需要
战神伽罗
2019/07/24
4.3K0
Java原生图片Base64转码与Base64解码
程序员朱永胜
2023/08/21
3660
Java 8中的Base64编码和解码
Java 8会因为将lambdas,流,新的日期/时间模型和Nashorn JavaScript引擎引入Java而被记住。有些人还会记得Java 8,因为它引入了各种小但有用的功能,例如Base64 API。什么是Base64以及如何使用此API?这篇文章回答了这些问题。
银河1号
2019/04/11
5.6K1
Android Base64编码字符串与文件之间的转化
开发中有时传输图片或音频等文件。我们会采用Base64编码成字符串传输 那么获取后 就要重新生成文件。
码客说
2019/10/22
2.5K0
相关推荐
图片转base64 并根据格式加前缀
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档