七叶笔记 » golang编程 » 使用golang生成PDF文件

使用golang生成PDF文件

 package main

import (
"log"

" github .com/jung-kurt/gofpdf"
)

func main() {
err := CreatePdf("hello.pdf")
if err != nil {
log.Fatal(err)
}
}

func CreatePdf(filename string) error {

// 指定页面方向,页面原始单位,纸张
pdf := gofpdf.New("P", "mm", "A4", "")
// 添加一页
pdf.AddPage()
// 加载字体
pdf.AddUTF8Font("SimHei", "", "./SimHei.ttf")
// 设置字体
pdf.SetFont("SimHei", "", 16)

// 用来设置边框,背景颜色,文本对齐方式
pdf.CellFormat(180, 10, "运维开发", "0", 0, "CM", false, 0, "")

// 写入文本的多种方式
// 获取下一行位置
_, h := pdf.GetFontSize()
pdf.Write(h, "Write date: 9月27日 星期日\n")
pdf.Writef(h, "date: %s\n", "9月27日星期日")
pdf.Cell(0, 20, "cell") // 也可以手动指定高度
pdf.Text(2, 50, "9月27日 星期日")

//  添加图片
  // 点击图片可以跳转到指定URL
pdf.ImageOptions(
"/home/Pictures/20180611095853_263. JPG ",
0, 80,
0, 0,
false,
gofpdf.ImageOptions{ImageType: "JPG", ReadDpi: true},
0,
"#34;,
)
//加密PDF
pdf.SetProtection(gofpdf.CnProtectPrint, "123", "")

return pdf.OutputFileAndClose(filename)
}
  

加密如下:

生成的PDF如下:

相关文章