使用 go-wkhtmltopdf 将html转pdf

  1. GoLand IDE创建go项目
    这里项目名称为 toPDF

  2. 添加main.go文件,添加main函数,
    例子来自: https://github.com/adrg/go-wkhtmltopdf

package main

import (
	"fmt"
	"github.com/adrg/go-wkhtmltopdf"
	"log"
)

func main(){
	pdf.Init()
	defer pdf.Destroy()

	// Create object from url
	object1, err := pdf.NewObject("https://www.baidu.com/")
	if err != nil {
		log.Fatal(err)
	}
	object1.SetOption("footer.right", "[page]")
	
	// Create converter
	converter := pdf.NewConverter()
	defer converter.Destroy()

	// Add created objects to the converter
	converter.AddObject(object1)

	// Add converter options
	converter.SetOption("documentTitle", "Sample document")
	converter.SetOption("margin.left", "10mm")
	converter.SetOption("margin.right", "10mm")
	converter.SetOption("margin.top", "10mm")
	converter.SetOption("margin.bottom", "10mm")

	// Convert the objects and get the output PDF document
	output, err := converter.Convert()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(output))
}

  1. GoLand terminal 执行 go run main.go
    GoLand会自动提示下载github.com/adrg/go-wkhtmltopdf
    也可以手动在terminal中输入: go get github.com/adrg/go-wkhtmltopdf来下载

下载下来之后,运行go run main.go
报:找不到gcc编译器

  1. 下载安装MinGW
    下载安装mingw-w64-install.exe
    添加到path环境变量:C:\javaware\mingw\mingw64\bin

  2. 下载wkhtmltopdf
    go-wkhtmltopdf项目又依赖于wkhtmltopdf,
    terminal中输入: go get github.com/wkhtmltopdf/wkhtmltopdf进行下载

再次执行:go run main.go
结果报错:fatal error: wkhtmltox/pdf.h: No such file or directory
报错原因,看了一下,应该是如下的include引起的:

package pdf

/*
#cgo LDFLAGS: -lwkhtmltox
#include 
#include 
#include 
*/
import "C"

import (
	"errors"
	"unsafe"
)

type Converter struct {
	converter *C.wkhtmltopdf_converter
	settings  *C.wkhtmltopdf_global_settings

	objects []*Object
}
...
  1. wkhtmltox
    又牵扯到了wkhtmltox,继续下载github.com/tcort/wkhtmltox
    尝试go get github.com/tcort/wkhtmltox
    结果报:go: warning: “github.com/tcort/wkhtmltox/…” matched no packages
    手动下载binary:https://wkhtmltopdf.org/downloads.html
    这里我下载了wkhtmltox-0.12.5-1.mxe-cross-win64.7z,里面包含:
    ./bin
    libwkhtmltox.a
    wkhtmltox.dll
    wkhtmltoimage.exe
    wkhtmltopdf.exe
    ./include/wkhtmltox
    dllbegin.inc
    dllend.inc
    image.h
    pdf.h
    然后
    把include里面的wkhtmltox目录复制到MinGW64的安装目录:
    C:\javaware\mingw\mingw64\x86_64-w64-mingw32\include
    把bin里面的 libwkhtmltox.a, wkhtmltox.dll拷贝到:
    C:\javaware\mingw\mingw64\x86_64-w64-mingw32\lib
    把bin里面的wkhtmltoimage.exe,wkhtmltopdf.exe拷贝到:
    C:\javaware\mingw\mingw64\x86_64-w64-mingw32\bin

再次执行:go run main.go
这次终于运行成功了:

/CreationDate (D:20181025170310+08'00')
>>
endobj
3 0 obj
<<
/Type /ExtGState
/SA true
/SM 0.02
/ca 1.0
/CA 1.0
...

你可能感兴趣的:(golang)