go项目实战之word、pdf、txt操作

最近在项目开发中,频繁的遇到需要对Docx、PDF、TXT等类型的文本进行操作,

而目前这方面有 unidoc/unioffice,但这个是非开源的,所以使用起来有诸多不方便。而且也搜了很多资料,但是都太笼统了,不方便使用,所以特写此文章希望能帮助大家解决问题!

以下代码都可直接复制粘贴使用


DOCX

word文档字数统计

word文档字数统计,并返回不包含空格、包含空格的总字数

该方法主要是使用的 第三方库 go-docx,更多的可以点击链接查看查看源码

func WordCount(ctx context.Context, filepath string) (nonSpaceCountTotal, hasSpaceCountTotal int64) {
	nonSpaceCountTotal = 0
	hasSpaceCountTotal = 0
	readFile, err := os.Open(filepath)
	if err != nil {
		return
	}

	fileInfo, err := readFile.Stat()
	if err != nil {
		return
	}

	size := fileInfo.Size()
	// docx是使用的 github.com/fumiama/go-docx
	doc, err := docx.Parse(readFile, size)
	if err != nil {
		return
	}

	// 定义正则表达式,匹配Text标签内的内容
	re := regexp.MustCompile(`"Text":"([^"]+)"`)

	for _, it := range doc.Document.Body.Items {
		// helper.TypeConvert().InterfaceToString() 是自己封装的interface转字符串方法
		v := helper.TypeConvert().InterfaceToString(it)
		matches := re.FindAllStringSubmatch(v, -1)

		// 输出匹配结果
		for _, match := range matches {
			runes := []rune(match[1])
			var nonSpaceCount int64
			for _, r := range runes {
				if r != ' ' {
					nonSpaceCount++
				}
			}
			nonSpaceCountTotal = nonSpaceCountTotal + nonSpaceCount
			hasSpaceCountTotal = hasSpaceCountTotal + int64(len(runes))
		}
	}

	return
}

TXT

txt文件的字符数统计

txt文件的字符数统计,并返回不包含空格、包含空格的总字符数

func CharacterCount(ctx context.Context, filepath string) (nonSpaceCountTotal, hasSpaceCountTotal int64) {
	nonSpaceCountTotal = 0
	hasSpaceCountTotal = 0
	file, err := os.Open(filepath)
	if err != nil {
		return
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		if line == "" {
			continue
		}

		runes := []rune(line)
		var nonSpaceCount int64
		for _, r := range runes {
			if r != ' ' {
				nonSpaceCount++
			}
		}
		nonSpaceCountTotal = nonSpaceCountTotal + nonSpaceCount
		hasSpaceCountTotal = hasSpaceCountTotal + int64(len(runes))
	}

	if err = scanner.Err(); err != nil {
		return
	}

	return
}

PDF

html网页转pdf

html网页转pdf,需要一个可访问的URL,哪怕是局域网URL也可以

该方法主要是使用的 第三方库 chromedp,更多的可以点击链接查看源码

func HtmlToPdf(ctx context.Context, htmlUrl, pdfUrl string, printBackground bool) (err error) {
	// chromedp使用的是 github.com/chromedp/chromedp
	ctx2, cancel := chromedp.NewContext(ctx)
	defer cancel()
	var buf []byte
	if err = chromedp.Run(ctx2, printToPdf(htmlUrl, printBackground, &buf)); err != nil {
		return
	}

	if err = os.WriteFile(pdfUrl, buf, 0o644); err != nil {
		return
	}

	return nil
}

func printToPdf(url string, printBackground bool, res *[]byte) chromedp.Tasks {
	// 更多参数可点击链接查看源码
	return chromedp.Tasks{
		chromedp.Navigate(url),
		chromedp.ActionFunc(func(ctx context.Context) error {
			buf, _, err := page.PrintToPDF().WithPrintBackground(printBackground).Do(ctx)
			if err != nil {
				return err
			}
			*res = buf

			return nil
		}),
	}
}

以上代码都是亲测过的,可直接复制粘贴使用。

但,注意注意📢:

所有的代码都没有经过性能测试,线上对性能要求较高时请先做一次性能测试!!!


当然,它们的操作绝对不止这几种,目前我也只是归纳了这几种,如果后续有机会再补充完善。

如果代码有问题或者有可优化的空间,也欢迎大家指正。

后续如果还有其他需要的操作,欢迎留言。


  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值