golang html to pdf

  1. 在使用 Go 开发的时候,有时候需要往 HTML 中填充内容,下面一个简单的例子,说明如何使用 html/template 进行 HTML 内容的填充。
package main

import html/template"

type Data struct {
  Name string
  Gender string
}

func parseHTML() {
  tempHtmlFile := "template.html" // 源文件
	tempHtmlPath := "tmpl.html"   // 填充后的文件
	
  // 待填充内容,HTML 中通过 {{.Name}} 占位,字段和结构体中要一致
  htmlData := &Data{
    Name : "张三", 
    Gender: "男"
  }
	
  // 解析源文件
  tmpl, err := template.ParseFiles(templateHtmlPath)
	if err != nil {
		return err
	}
  
  // 创建目标文件 
	tempHtmlFile, err := os.Create(tempHtmlPath)
	if err != nil {
		return err
	}
  
  // 进行占位符填充 
	err = tmpl.Execute(tempHtmlFile, htmlData)
	if err != nil {
		return err
	}
	tempHtmlFile.Close()
}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>录用通知</title>
	<style>
		body {
		    font-family: Arial, sans-serif;
		    line-height: 1.6;
		    margin: 0;
		    padding: 20px;
		}
		
		.content {
		    margin: 20px;
		}
		
		.greeting {
		    margin-bottom: 20px;
		}
	</style>
</head>
<body>
	<div class="content">
		<p class="greeting">{{.Name}} {{.Gender}}:</p>
</p>
	</div>
</body>
</html>
  1. 更进一步,填充完的 HTML 输出为 PDF。

    	// 读取生成的 HTML 文件内容
    func htmlToPdf(tempHtmlPath string) error {
    	htmlBytes, err := os.ReadFile(tempHtmlPath)
    		return err
    	}
    
    	// 使用 wkhtmltopdf 将 HTML 转换为 PDF , 需要在服务器上安装 wkhtmltopdf
    	// 如果输出后内容没有正确展示,多半是字体缺失
    	err = runCommand("wkhtmltopdf", tempHtmlPath, pdfFile)
    	if err != nil {
      	return err
    	}
    }
    
    func runCommand(command string, args ...string) error {
    	cmd := exec.Command(command, args...)
    	err := cmd.Run()
    	return err
    }