GO-实现简单文本格式 文本字体颜色、大小、突出

毫无疑问GO的生态就是一坨大便。老子英文水平小学啊。

实现简单文本格式 文本字体颜色、大小、突出显示等。

创建要给docx文件容器【我估算的】

doc := document.New()
defer doc.Close()

doc.SaveToFile("simple.docx")  把容器保存为文件

设置标题

创建自然段Paragraph

run设置文本内容

para := doc.AddParagraph()
run := para.AddRun()
para.SetStyle("Title")
run.AddText("Simple Document Formatting")

效果图

设置缩进

para = doc.AddParagraph()
para.Properties().SetFirstLineIndent(0.5 * measurement.Inch)

run = para.AddRun()
run.AddText("A run is a string of characters with the same formatting. ")

设置粗体、字体、大小、颜色

run = para.AddRun()
run.Properties().SetBold(true)
run.Properties().SetFontFamily("Courier")
run.Properties().SetSize(15)
run.Properties().SetColor(color.Red)
run.AddText("Multiple runs with different formatting can exist in the same paragraph. ")

换行

run.AddBreak()

run = para.AddRun()
run.AddText("Adding breaks to a run will insert line breaks after the run. ")
run.AddBreak()
run.AddBreak()

输入文本

run = createParaRun(doc, "Runs support styling options:")

大写

run = createParaRun(doc, "small caps")
	run.Properties().SetSmallCaps(true)

画线和画两条

	run = createParaRun(doc, "strike")
	run.Properties().SetStrikeThrough(true)

	run = createParaRun(doc, "double strike")
	run.Properties().SetDoubleStrikeThrough(true)

其他

run = createParaRun(doc, "outline")
	run.Properties().SetOutline(true)

	run = createParaRun(doc, "emboss")
	run.Properties().SetEmboss(true)

	run = createParaRun(doc, "shadow")
	run.Properties().SetShadow(true)

	run = createParaRun(doc, "imprint")
	run.Properties().SetImprint(true)

	run = createParaRun(doc, "highlighting")
	run.Properties().SetHighlight(wml.ST_HighlightColorYellow)

	run = createParaRun(doc, "underline")
	run.Properties().SetUnderline(wml.ST_UnderlineWavyDouble, color.Red)

	run = createParaRun(doc, "text effects")
	run.Properties().SetEffect(wml.ST_TextEffectAntsRed)

//选择编号样式?
nd := doc.Numbering.Definitions()[0]

	for i := 1; i < 5; i++ {
		p := doc.AddParagraph()
//设置编号等级?
		p.SetNumberingLevel(i - 1)
//设置编号样式
		p.SetNumberingDefinition(nd)
		run := p.AddRun()
		run.AddText(fmt.Sprintf("Level %d", i))
	}

完整DEMO代码

// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
//导包
import ( 
	"fmt"
	"os"

	"github.com/unidoc/unioffice/color"
	"github.com/unidoc/unioffice/common/license"
	"github.com/unidoc/unioffice/document"
	"github.com/unidoc/unioffice/measurement"
	"github.com/unidoc/unioffice/schema/soo/wml"
)
//资本家的密钥
func init() {
	// Make sure to load your metered License API key prior to using the library.
	// If you need a key, you can sign up and create a free one at https://cloud.unidoc.io
	err := license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`))
	if err != nil {
		panic(err)
	}
}

func main() {

//创建doc
	doc := document.New()
//关闭doc
	defer doc.Close()

	para := doc.AddParagraph()
	run := para.AddRun()
	para.SetStyle("Title")
	run.AddText("Simple Document Formatting")

	para = doc.AddParagraph()
	para.SetStyle("Heading1")
	run = para.AddRun()
	run.AddText("Some Heading Text")

	para = doc.AddParagraph()
	para.SetStyle("Heading2")
	run = para.AddRun()
	run.AddText("Some Heading Text")

	para = doc.AddParagraph()
	para.SetStyle("Heading3")
	run = para.AddRun()
	run.AddText("Some Heading Text")

	para = doc.AddParagraph()
	para.Properties().SetFirstLineIndent(0.5 * measurement.Inch)

	run = para.AddRun()
	run.AddText("A run is a string of characters with the same formatting. ")

	run = para.AddRun()
	run.Properties().SetBold(true)
	run.Properties().SetFontFamily("Courier")
	run.Properties().SetSize(15)
	run.Properties().SetColor(color.Red)
	run.AddText("Multiple runs with different formatting can exist in the same paragraph. ")

	run = para.AddRun()
	run.AddText("Adding breaks to a run will insert line breaks after the run. ")
	run.AddBreak()
	run.AddBreak()

	run = createParaRun(doc, "Runs support styling options:")

	run = createParaRun(doc, "small caps")
	run.Properties().SetSmallCaps(true)

	run = createParaRun(doc, "strike")
	run.Properties().SetStrikeThrough(true)

	run = createParaRun(doc, "double strike")
	run.Properties().SetDoubleStrikeThrough(true)

	run = createParaRun(doc, "outline")
	run.Properties().SetOutline(true)

	run = createParaRun(doc, "emboss")
	run.Properties().SetEmboss(true)

	run = createParaRun(doc, "shadow")
	run.Properties().SetShadow(true)

	run = createParaRun(doc, "imprint")
	run.Properties().SetImprint(true)

	run = createParaRun(doc, "highlighting")
	run.Properties().SetHighlight(wml.ST_HighlightColorYellow)

	run = createParaRun(doc, "underline")
	run.Properties().SetUnderline(wml.ST_UnderlineWavyDouble, color.Red)

	run = createParaRun(doc, "text effects")
	run.Properties().SetEffect(wml.ST_TextEffectAntsRed)

	nd := doc.Numbering.Definitions()[0]

	for i := 1; i < 5; i++ {
		p := doc.AddParagraph()
		p.SetNumberingLevel(i - 1)
		p.SetNumberingDefinition(nd)
		run := p.AddRun()
		run.AddText(fmt.Sprintf("Level %d", i))
	}
	doc.SaveToFile("simple.docx")
}

func createParaRun(doc *document.Document, s string) document.Run {
	para := doc.AddParagraph()
	run := para.AddRun()
	run.AddText(s)
	return run
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,请参考以下代码实现: ```go package main import ( "bytes" "fmt" "image" "image/color" "image/draw" "image/jpeg" "io/ioutil" "log" "net/http" "path/filepath" "github.com/golang/freetype" "github.com/golang/freetype/truetype" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { text := "Hello, world!" // 要插入图片中间的文本 fontPath := "msyh.ttc" // 字体文件路径 fontSize := 48.0 // 字体大小 textColor := "#FF0000" // 文本颜色 // 读取字体文件 fontBytes, err := ioutil.ReadFile(fontPath) if err != nil { log.Fatal(err) } // 解析字体文件 font, err := freetype.ParseFont(fontBytes) if err != nil { log.Fatal(err) } // 创建画布 canvas := image.NewRGBA(image.Rect(0, 0, 640, 480)) // 绘制背景色 draw.Draw(canvas, canvas.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src) // 创建文本绘制器 context := freetype.NewContext() context.SetDPI(72) context.SetFont(font) context.SetFontSize(fontSize) context.SetClip(canvas.Bounds()) context.SetDst(canvas) context.SetSrc(image.NewUniform(parseHexColor(textColor))) // 计算文本位置 textWidth := context.PointToFixed(len(text)*int(fontSize/2)) >> 6 textHeight := context.PointToFixed(fontSize) >> 6 textX := (canvas.Bounds().Max.X - textWidth) / 2 textY := (canvas.Bounds().Max.Y - textHeight) / 2 // 绘制文本 pt := freetype.Pt(textX, textY) _, err = context.DrawString(text, pt) if err != nil { log.Fatal(err) } // 保存图片 savePath := "output.jpg" err = saveImage(canvas, savePath) if err != nil { log.Fatal(err) } // 输出图片 w.Header().Set("Content-Type", "image/jpeg") http.ServeFile(w, r, savePath) }) log.Fatal(http.ListenAndServe(":8080", nil)) } // 将十六进制颜色字符串解析为颜色对象 func parseHexColor(hex string) color.Color { var c color.RGBA c.A = 0xff fmt.Sscanf(hex, "#%02x%02x%02x", &c.R, &c.G, &c.B) return c } // 保存图片到文件 func saveImage(img image.Image, path string) error { f, err := os.Create(path) if err != nil { return err } defer f.Close() var buf bytes.Buffer err = jpeg.Encode(&buf, img, nil) if err != nil { return err } _, err = f.Write(buf.Bytes()) if err != nil { return err } return nil } ``` 以上代码使用了 Go 语言的标准库和 freetype 库来生成图片,并将生成的图片输出到 HTTP 响应中。在代码中,使用了 `image.NewRGBA()` 函数创建了一个 RGBA 类型的画布,然后使用 `freetype` 库中的 `NewContext()` 函数来创建文本绘制器,计算文本位置,并绘制文本。最后,使用 `jpeg.Encode()` 函数将画布保存为 JPEG 格式的图片,并输出到 HTTP 响应中。代码中也提供了一个 `saveImage()` 函数,可以将图片保存到文件。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值