Golang HTML转PDF并直接下载的实现

如何在Golang中实现将HTML转换为PDF并直接下载的功能?目前需要将网页内容生成PDF文件并提供下载,但不太清楚具体的实现方法。请问有哪些可靠的库可以使用?最好是能支持中文显示并且性能较好的方案。另外,如何设置PDF的页面大小、边距等参数?希望能提供一个完整的示例代码,包括HTML模板渲染和PDF生成的完整流程。

2 回复

使用Golang实现HTML转PDF并直接下载,可以通过以下步骤:

  1. 选择库:推荐使用github.com/SebastiaanKlippert/go-wkhtmltopdf,它是wkhtmltopdf的Go封装。

  2. 安装依赖

    • 安装wkhtmltopdf(系统级依赖)
    • go get github.com/SebastiaanKlippert/go-wkhtmltopdf
  3. 核心代码

func convertHTMLToPDF(w http.ResponseWriter, htmlContent string) {
    pdfg, err := wkhtmltopdf.NewPDFGenerator()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    page := wkhtmltopdf.NewPage(htmlContent)
    pdfg.AddPage(page)
    
    err = pdfg.Create()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "application/pdf")
    w.Header().Set("Content-Disposition", "attachment; filename=output.pdf")
    w.Write(pdfg.Bytes())
}
  1. 注意事项
    • 确保服务器已安装wkhtmltopdf
    • 支持从URL或HTML字符串转换
    • 可配置页面大小、边距等参数
    • 处理中文字体需在HTML中指定字体文件

这种方法转换质量好,但需要外部依赖。纯Go方案可考虑pdfcpu,但HTML渲染能力有限。

更多关于Golang HTML转PDF并直接下载的实现的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Golang中实现HTML转PDF并直接下载,可以通过以下步骤完成:

推荐方案:使用 go-wkhtmltopdf

1. 安装依赖

go get github.com/SebastiaanKlippert/go-wkhtmltopdf

2. 核心实现代码

package main

import (
    "fmt"
    "net/http"
    "time"

    "github.com/SebastiaanKlippert/go-wkhtmltopdf"
)

func generatePDF(w http.ResponseWriter, r *http.Request) {
    // 创建PDF生成器
    pdfg, err := wkhtmltopdf.NewPDFGenerator()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // 设置HTML内容(可以直接使用URL或HTML字符串)
    page := wkhtmltopdf.NewPage("https://example.com") // 或者使用HTML字符串
    
    // 或者使用HTML字符串:
    // page := wkhtmltopdf.NewPageReader(strings.NewReader("<html><body><h1>Hello PDF</h1></body></html>"))
    
    // 添加到PDF生成器
    pdfg.AddPage(page)

    // 设置PDF选项
    pdfg.Dpi.Set(300)
    pdfg.Orientation.Set(wkhtmltopdf.OrientationPortrait)
    pdfg.PageSize.Set(wkhtmltopdf.PageSizeA4)

    // 生成PDF
    err = pdfg.Create()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // 设置HTTP响应头,触发下载
    w.Header().Set("Content-Type", "application/pdf")
    w.Header().Set("Content-Disposition", "attachment; filename=document.pdf")
    w.Header().Set("Content-Length", fmt.Sprint(len(pdfg.Bytes())))

    // 写入PDF内容到响应
    _, err = w.Write(pdfg.Bytes())
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
}

func main() {
    http.HandleFunc("/download-pdf", generatePDF)
    fmt.Println("服务器启动在 :8080")
    http.ListenAndServe(":8080", nil)
}

3. 系统依赖

需要安装 wkhtmltopdf

Ubuntu/Debian:

sudo apt-get install wkhtmltopdf

macOS:

brew install wkhtmltopdf

Windows: 从官网下载并安装

4. 替代方案:使用 chromedp

如果需要更现代的渲染引擎,可以使用Chrome Headless:

import (
    "context"
    "github.com/chromedp/chromedp"
)

func generatePDFWithChrome(w http.ResponseWriter, r *http.Request) {
    ctx, cancel := chromedp.NewContext(context.Background())
    defer cancel()

    var buf []byte
    err := chromedp.Run(ctx,
        chromedp.Navigate("https://example.com"),
        chromedp.ActionFunc(func(ctx context.Context) error {
            var err error
            buf, err = pdf.PrintToPDF().Do(ctx)
            return err
        }),
    )

    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "application/pdf")
    w.Header().Set("Content-Disposition", "attachment; filename=document.pdf")
    w.Write(buf)
}

主要特点:

  • wkhtmltopdf: 轻量级,安装简单,支持CSS和JavaScript
  • chromedp: 基于Chrome,渲染效果更好,但需要安装Chrome/Chromium

选择哪种方案取决于你的具体需求和部署环境。

回到顶部