go实现word,excel,pptx转pdf

本文介绍了如何使用Golang通过libreoffice命令行工具实现文档转换,并特别指出并发限制。着重于Mac、Linux和Windows系统的兼容处理,以及如何解决文件转换过程中的问题和注意事项。

因工作需要实现word转pdf

实现原理:利用go命令行调用libreffice命令实现文件转化

**使用 libreffice 文件转pdf 并发数不能超2,只能一个文件转化成功后,在进行下一个

注意事项使用前本机或者服务器先安装开源软件 libreffice !!!

注意事项使用前本机或者服务器先安装开源软件 libreffice !!!

传送门:libreoffice

代码如下(粘贴后直接运行):

package Test

import (
	"fmt"
	"os"
	"os/exec"
	"path"
	"runtime"
	"strings"
	"testing"
)

//TestToPdf golang+libreffice 实现word,excel,pptx转pdf,html
func TestToPdf(t *testing.T) {

	fileSrcPath := "/Users/xing/Desktop/123/test2.docx" //自己机器上的文件地址
	outPath := "/Users/xing/Desktop/123/pdf"            //转出文件的路径
	fileType := "pdf"

	osName := runtime.GOOS //获取系统类型
	switch osName {
	case "darwin": //mac系统
		command := "/Applications/LibreOffice.app/Contents/MacOS/soffice"
		pdfFile, err := FuncDocs2Pdf(command, fileSrcPath, outPath, fileType)
		if err != nil {
			println("转化异常:", err.Error())
		}
		fmt.Println("转化后的文件:", pdfFile)
	case "linux":
		command := "libreoffice7.3"
		pdfFile, err := FuncDocs2Pdf(command, fileSrcPath, outPath, fileType)
		if err != nil {
			println("转化异常:", err.Error())
		}
		fmt.Println("转化后的文件:", pdfFile)
	case "windows":
		command := "soffice libreoffice" // 因为没有windows机器需要自己测试下这个命令行
		pdfFile, err := FuncDocs2Pdf(command, fileSrcPath, outPath, fileType)
		if err != nil {
			println("转化异常:", err.Error())
		}
		fmt.Println("转化后的文件:", pdfFile)
	default:
		fmt.Println("暂时不支持的系统转化:" + runtime.GOOS)
	}
}

/**
*@tips libreoffice 转换指令:
* libreoffice6.2 invisible --convert-to pdf csDoc.doc --outdir /home/[转出目录]
*
* @function 实现文档类型转换为pdf或html
* @param command:libreofficed的命令(具体以版本为准);win:soffice; linux:libreoffice6.2
*     fileSrcPath:转换文件的路径
*     fileOutDir:转换后文件存储目录
*     converterType:转换的类型pdf/html
* @return fileOutPath 转换成功生成的文件的路径 error 转换错误
 */
func FuncDocs2Pdf(command string, fileSrcPath string, fileOutDir string, converterType string) (fileOutPath string, error error) {
	//校验fileSrcPath
	srcFile, erByOpenSrcFile := os.Open(fileSrcPath)
	if erByOpenSrcFile != nil && os.IsNotExist(erByOpenSrcFile) {
		return "", erByOpenSrcFile
	}
	//如文件输出目录fileOutDir不存在则自动创建
	outFileDir, erByOpenFileOutDir := os.Open(fileOutDir)
	if erByOpenFileOutDir != nil && os.IsNotExist(erByOpenFileOutDir) {
		erByCreateFileOutDir := os.MkdirAll(fileOutDir, os.ModePerm)
		if erByCreateFileOutDir != nil {
			fmt.Println("File ouput dir create error.....", erByCreateFileOutDir.Error())
			return "", erByCreateFileOutDir
		}
	}
	//关闭流
	defer func() {
		_ = srcFile.Close()
		_ = outFileDir.Close()
	}()
	//convert
	cmd := exec.Command(command, "--invisible", "--language=zh-CN", "--convert-to", converterType,
		fileSrcPath, "--outdir", fileOutDir)
	byteByStat, errByCmdStart := cmd.Output()
	//命令调用转换失败
	if errByCmdStart != nil {
		return "", errByCmdStart
	}
	//success
	fileOutPath = fileOutDir + "/" + strings.Split(path.Base(fileSrcPath), ".")[0]
	if converterType == "html" {
		fileOutPath += ".html"
	} else {
		fileOutPath += ".pdf"
	}
	fmt.Println("文件转换成功...", string(byteByStat))
	return fileOutPath, nil
}

参考文章:

golang+libreffice6.2实现word,excel,pptx转pdf,html - 简书

### 实现APP中PDFWord内嵌式预览的技术方案 为了在应用程序中实现PDFWord文档的内嵌式预览,可以使用多种框架和库来处理这些文件格式。以下是一些推荐的技术方案和库: #### 1. **PDF 内嵌式预览** 对于PDF文件的预览,可以使用以下库或技术: - **MuPDF**:一个轻量级的PDF、XPS和电子书查看器库,支持多平台开发。它能够高效解析和渲染PDF文件[^4]。 - **PDF.js**:由Mozilla开发的JavaScript库,用于在浏览器中渲染PDF文件。它可以轻松集成到Web应用中,并支持移动端适配。如果您的APP基于WebView,则可以将PDF.js嵌入到WebView中以实现PDF预览功能[^2]。 ```javascript // 示例代码:使用PDF.js加载并渲染PDF文件 var url = 'https://example.com/sample.pdf'; PDFJS.getDocument(url).promise.then(function(pdf) { pdf.getPage(1).then(function(page) { var scale = 1.5; var viewport = page.getViewport({ scale: scale }); var canvas = document.getElementById('the-canvas'); var context = canvas.getContext('2d'); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: context, viewport: viewport }; page.render(renderContext); }); }); ``` #### 2. **Word (.docx) 内嵌式预览** 对于Word文档(特别是`.docx`格式),可以使用以下库进行解析和渲染: - **unioffice**:这是一个纯Go语言实现的库,用于创建和处理Microsoft Word(`.docx`)、Excel(`.xlsx`)和PowerPoint(`.pptx`)文档[^1]。它可以直接解析`.docx`文件的内容,并将其换为HTML或其他格式以便于展示。 - **mammoth.js**:一个JavaScript库,用于将Word文档(`.docx`)换为HTML或Markdown。结合WebView,您可以轻松地在移动应用中显示Word文档内容[^2]。 ```javascript // 示例代码:使用mammoth.js将.docx文件换为HTML var mammoth = require("mammoth"); var result = mammoth.convertToHtml({path: "example.docx"}); result.then(function(output){ var html = output.value; // 输出生成的HTML var messages = output.messages; // 解析过程中产生的消息 document.body.innerHTML = html; }).catch(function(error){ console.error(error.message); }); ``` #### 3. **跨平台解决方案** 如果您希望实现跨平台的应用程序(例如iOS和Android),可以考虑以下技术: - **Flutter PDF Viewer**:Flutter插件,支持PDF文件的加载和渲染。它可以在iOS和Android设备上提供一致的用户体验。 - **react-native-pdf**:React Native插件,允许开发者在移动应用中加载和显示PDF文件。该插件支持多种文件来源(如本地文件、网络URL等)。 ```dart // 示例代码:使用Flutter PDF Viewer加载PDF文件 import 'package:flutter_pdfview/flutter_pdfview.dart'; class PDFViewerPage extends StatefulWidget { final String path; const PDFViewerPage({Key key, this.path}) : super(key: key); @override _PDFViewerPageState createState() => _PDFViewerPageState(); } class _PDFViewerPageState extends State<PDFViewerPage> { int pages = 0; int currentPage = 0; bool isReady = false; String errorMessage = ''; @override Widget build(BuildContext context) { return PDFView( filePath: widget.path, autoSpacing: true, enableSwipe: true, pageSnap: true, swipeHorizontal: true, nightMode: false, onError: (error) { setState(() { errorMessage = error.toString(); }); }, onPageChanged: (int page, int total) { setState(() { currentPage = page; pages = total; }); }, onViewCreated: (PDFViewController controller) { setState(() { isReady = true; }); }, ); } } ``` ### 注意事项 - 在选择库时,请确保其支持的目标平台与您的应用程序一致。 - 如果需要高性能的渲染效果,建议优先考虑原生库(如MuPDF或Flutter PDF Viewer)。 - 对于复杂的文档格式(如嵌套表格或特殊字体),可能需要额外的配置或依赖项来确保正确的渲染效果[^3]。
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值