Home Backend Development Golang How to use template functions in Go language to dynamically generate Word documents and export PDF?

How to use template functions in Go language to dynamically generate Word documents and export PDF?

Jul 31, 2023 pm 05:36 PM
template functions dynamic generation export pdf (export pdf)

How to use template functions in Go language to dynamically generate Word documents and export PDF?

Introduction:
During the development process, we often need to generate Word documents based on templates and export them to PDF. This article will introduce how to dynamically generate and export PDF documents through template function examples in the Go language.

1. Install the required libraries and tools
Before we start, we need to install and configure the following libraries and tools:

  1. Go language: Make sure that Go has been installed and configured correctly Locales.
  2. GoDoc: Used to automatically generate documentation and view detailed information about the Go language library.
  3. Go-PDF: A library for manipulating PDF files in the Go language. You can install Go-PDF using the following command:
    go get -u github.com/signintech/gopdf

2. Create a Word template file
Before we start, we need to create a Word template file (.docx format) and define the content that needs to be dynamically generated. Markers can be included in the template so that we can replace them using template functions in subsequent steps.

The following is the content of a simple example Word template file:

欢迎您,{{.Name}}!

以下是您的订单详情:
订单号:{{.OrderNumber}}
订单总价:{{.TotalPrice}}
Copy after login

Please note that {{.Name}}, {{.OrderNumber}} and {{.TotalPrice}} are tags , we will use template functions to replace them with dynamic data.

3. Use template functions to generate Word documents
First, we need to import the required packages and libraries:

package main

import (
    "fmt"
    "os"
    "text/template"
)
Copy after login

Then, we define a structure to save dynamic data:

type Order struct {
    Name        string
    OrderNumber string
    TotalPrice  float64
}
Copy after login

Next, we use the template function to generate a Word document:

func main() {
    // 定义模板文件路径
    tmpl := "./template.docx"

    // 定义动态数据
    order := Order{
        Name:        "张三",
        OrderNumber: "2021123456789",
        TotalPrice:  100.00,
    }

    // 解析模板文件
    t := template.Must(template.ParseFiles(tmpl))

    // 生成Word文档
    docxFile, err := os.Create("./output.docx")
    if err != nil {
        fmt.Println("创建Word文档失败:", err)
        return
    }
    defer docxFile.Close()

    // 渲染模板并写入Word文档
    err = t.Execute(docxFile, order)
    if err != nil {
        fmt.Println("生成Word文档失败:", err)
        return
    }

    fmt.Println("Word文档生成成功!")
}
Copy after login

4. Export the Word document to PDF
To export the generated Word document to PDF, we need to use the Go-PDF library .

First, we need to import the required packages and libraries:

package main

import (
    "fmt"
    "github.com/signintech/gopdf"
)
Copy after login

Then, we use the following code to convert the Word document to PDF:

func main() {
    // 打开生成的Word文档
    docxFile, err := os.Open("./output.docx")
    if err != nil {
        fmt.Println("打开Word文档失败:", err)
        return
    }
    defer docxFile.Close()

    // 创建PDF文档
    pdf := gopdf.GoPdf{}
    pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
    pdf.AddPage()

    // 将Word文档内容添加到PDF中
    err = pdf.AddTTFFont("font", "./arialuni.ttf")
    if err != nil {
        fmt.Println("添加字体失败:", err)
        return
    }

    pdf.SetFont("font", "", 14)
    pdf.SetX(40)
    pdf.SetY(40)

    // 读取Word文档内容并写入PDF
    bs, _ := ioutil.ReadAll(docxFile)
    pdf.Cell(nil, string(bs))

    // 保存为PDF文件
    pdf.WritePdf("./output.pdf")

    fmt.Println("PDF文件导出成功!")
}
Copy after login

Please note that the above code arialuni.ttf used in is a Unicode font file used to support the display of Chinese characters. You need to download the font file and save it in the root directory of your project.

5. Test run
After completing the above steps, we use the go run command to run the code. After successful operation, two files, output.docx and output.pdf, will be generated in the project root directory.

Please note that the generated output.docx is a dynamically generated Word document, and output.pdf is the result of exporting the Word document to PDF.

Conclusion:
This article introduces how to use the template function in the Go language to dynamically generate Word documents and export them to PDF. This approach is very flexible and can meet a variety of dynamic generation and export needs. I hope this article will help you generate Word documents and export PDF in Go language development.

The above is the detailed content of How to use template functions in Go language to dynamically generate Word documents and export PDF?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Getting Started with Go: A Beginner's Guide Getting Started with Go: A Beginner's Guide Apr 26, 2025 am 12:21 AM

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Golang vs. C  : Performance and Speed Comparison Golang vs. C : Performance and Speed Comparison Apr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C   and Golang: When Performance is Crucial C and Golang: When Performance is Crucial Apr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

See all articles