Golang中从Google添加字体时遇到的错误
Golang中从Google添加字体时遇到的错误 我正在制作一份PDF报告,尝试使用谷歌的Roboto字体。 下载了包含所有ttf文件的Roboto字体。以下是我获取字体的操作:
//******设置字体******
gofpdf.MakeFont("font/Roboto/Roboto-Regular.ttf", "font/cp1252.map", "font", nil, true)
pdf.SetFontLocation("font")
pdf.AddFont("Roboto", "B", "Roboto-Regular.json")
//*************为页面创建页眉*************
pdf.SetHeaderFunc(func() {
//******添加Logo******
pdf.Image("IFM-Site-Logo.png", 154, 40, 30, 0, false, "", 0, "")
//***添加地址字段***
pdf.SetY(25)
pdf.SetX(5)
pdf.SetFont("Times", "", 16)
lines := pdf.SplitLines([]byte(Address()), 85)
for _, line := range lines {
pdf.CellFormat(180.0, 5, string(line), "", 2, "L", false, 0, "")
}
目前我的代码可以运行,但一旦我执行 pdf.SetFont("Roboto","", 10),它就会崩溃,并在下一行抛出索引越界错误。
我不确定为什么会发生这种情况,有什么建议吗?
更多关于Golang中从Google添加字体时遇到的错误的实战教程也可以访问 https://www.itying.com/category-94-b0.html
问题在于 addFont 应该与 TTF 文件的名称匹配,这就是让它为我工作的原因。
errs := gofpdf.MakeFont("font/Roboto/Roboto-Regular.ttf", "font/cp1252.map", "font", nil, true) if errs != nil { fmt.Println("Something is wrong with font maker") } errs2 := gofpdf.MakeFont("font/Roboto/Roboto-Bold.ttf", "font/cp1252.map", "font", nil, true) if errs2 != nil { fmt.Println("Something is wrong with font maker") } pdf.SetFontLocation("font") pdf.AddFont("Roboto-Regular", "", "Roboto-Regular.json") pdf.AddFont("Roboto-Bold", "", "Roboto-Bold.json")
更多关于Golang中从Google添加字体时遇到的错误的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
根据你提供的代码和错误描述,问题很可能出现在字体文件的生成或加载过程中。gofpdf 要求字体文件必须正确生成并放置在指定位置。以下是一个完整的示例,展示如何正确生成和使用 Roboto 字体:
package main
import (
"github.com/jung-kurt/gofpdf"
)
func main() {
// 1. 生成字体文件(仅需运行一次)
// 确保字体文件路径正确
err := gofpdf.MakeFont(
"font/Roboto/Roboto-Regular.ttf",
"font/cp1252.map",
"font",
nil,
true,
)
if err != nil {
panic(err)
}
// 2. 创建PDF文档
pdf := gofpdf.New("P", "mm", "A4", "font") // 注意第三个参数指定字体目录
pdf.AddPage()
// 3. 添加生成的字体
pdf.AddFont("Roboto", "", "Roboto-Regular.json")
// 4. 使用字体
pdf.SetFont("Roboto", "", 16)
pdf.Cell(40, 10, "Hello World with Roboto!")
// 保存PDF
err = pdf.OutputFileAndClose("output.pdf")
if err != nil {
panic(err)
}
}
关键点说明:
-
字体生成:
MakeFont函数会生成两个文件:Roboto-Regular.json(字体度量文件)和Roboto-Regular.z(压缩的字体数据)。这两个文件必须位于font目录中。 -
字体目录设置:在
gofpdf.New()的第四个参数中指定字体目录为"font"。 -
字体注册:使用
AddFont注册字体时,第二个参数是样式("" 表示常规,“B” 表示粗体等),第三个参数是 JSON 文件名。 -
常见问题排查:
- 确保
font目录包含所有必要的文件:font/ ├── Roboto-Regular.json ├── Roboto-Regular.z └── cp1252.map - 检查
MakeFont是否成功执行,没有错误返回 - 验证字体文件路径是否正确
- 确保
如果问题仍然存在,可以检查生成的 JSON 文件内容是否完整,或者尝试使用绝对路径来排除路径问题。

