36

如何从 Google Go 中的 HTML 输入创建 PDF 文件?如果还不可能,是否有任何旨在解决此问题的倡议?

我正在寻找像 php 中的 TCPDF 这样的解决方案。

4

8 回答 8

18

gopdfhttps://github.com/signintech/gopdf)呢?

看来您正在寻找。

于 2014-06-20T09:40:31.930 回答
13

安装

go get -u github.com/SebastiaanKlippert/go-wkhtmltopdf

go version go1.9.2 linux/amd64

代码

   import (
        "fmt"
        "strings"
        wkhtml "github.com/SebastiaanKlippert/go-wkhtmltopdf"
    )  

      func main(){
                 pdfg, err :=  wkhtml.NewPDFGenerator()
               if err != nil{
                  return
              }
              htmlStr := `<html><body><h1 style="color:red;">This is an html
 from pdf to test color<h1><img src="http://api.qrserver.com/v1/create-qr-
code/?data=HelloWorld" alt="img" height="42" width="42"></img></body></html>`

              pdfg.AddPage(wkhtml.NewPageReader(strings.NewReader(htmlStr)))


              // Create PDF document in internal buffer
              err = pdfg.Create()
              if err != nil {
                  log.Fatal(err)
              }

               //Your Pdf Name
               err = pdfg.WriteFile("./Your_pdfname.pdf")
              if err != nil {
                  log.Fatal(err)
              }

              fmt.Println("Done")
        }

上面的代码适用于在 golang 中使用适当的背景图像和嵌入式 Css 样式标签将 html 转换为 pdf

检查回购

请参阅拉取请求文档改进

于 2018-02-01T17:22:04.163 回答
7

还有这个包wkhtmltopdf-go,它使用 libwkhtmltox 库。我不确定它有多稳定。

于 2015-02-24T06:21:14.160 回答
4

我不认为我理解你的要求。由于 HTML 是一种标记语言,它需要上下文来呈现(CSS 和屏幕大小)。我见过的现有实现通常在无头浏览器中打开页面并以这种方式创建 PDF。

就个人而言,我只会使用现有的包并从 Go 中取出。这个看起来不错;甚至在这个答案中推荐它。

如果你真的决定在 Go 中实现这一切,请查看这个 WebKit 包装器。我不确定你会用什么来生成 PDF,但至少这是一个开始。

于 2013-02-20T07:23:58.900 回答
2

我正在创建一个替代库来以更简单的方式创建 PDF(https://github.com/johnfercher/maroto)。它使用gofpdf并有一个网格系统和一些组件,如Bootstrap

于 2019-06-11T22:24:01.633 回答
2

该功能page.PrintToPDF()效果很好。

这是一个将它与 chromedp ( go get -u github.com/chromedp/chromedp) 一起使用的示例:

import (
    "context"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
    "time"

    "github.com/chromedp/cdproto/emulation"
    "github.com/chromedp/cdproto/page"
    "github.com/chromedp/chromedp"
)

func main() {
        taskCtx, cancel := chromedp.NewContext(
            context.Background(),
            chromedp.WithLogf(log.Printf),
        )
        defer cancel()
        var pdfBuffer []byte
        if err := chromedp.Run(taskCtx, pdfGrabber("https://www.wikipedia.org", "body", &pdfBuffer)); err != nil {
            log.Fatal(err)
        }
        if err := ioutil.WriteFile("coolsite.pdf", pdfBuffer, 0644); err != nil {
            log.Fatal(err)
        }
}

func pdfGrabber(url string, sel string, res *[]byte) chromedp.Tasks {

    start := time.Now()
    return chromedp.Tasks{
        emulation.SetUserAgentOverride("WebScraper 1.0"),
        chromedp.Navigate(url),
        // wait for footer element is visible (ie, page is loaded)
        // chromedp.ScrollIntoView(`footer`),
        chromedp.WaitVisible(`body`, chromedp.ByQuery),
        // chromedp.Text(`h1`, &res, chromedp.NodeVisible, chromedp.ByQuery),
        chromedp.ActionFunc(func(ctx context.Context) error {
            buf, _, err := page.PrintToPDF().WithPrintBackground(true).Do(ctx)
            if err != nil {
                return err
            }
            *res = buf
            //fmt.Printf("h1 contains: '%s'\n", res)
            fmt.Printf("\nTook: %f secs\n", time.Since(start).Seconds())
            return nil
        }),
    }
}

上面将加载 wikipedia.org 在 chrome 中无头并等待 body 出现,然后将其保存为 pdf。

结果终端:

$ go run main.go
https://www.wikipedia.org
Scraping url now...

Took: 2.772797 secs
于 2021-08-16T00:05:23.583 回答
1

另一种选择是雅典娜。它有一个用 Go 编写的微服务,也可以用作 CLI。

于 2017-11-24T17:44:22.553 回答
-2

另一个选项是UniHTML(基于容器的 API),它与UniPDF互操作,这对于创建基于 HTML 模板的 PDF 报告等很有用。

它在容器中使用了无头chrome引擎,因此呈现完美,并具有所有HTML功能。与 UniPDF 的结合带来了额外的优势,例如自动生成目录、大纲等。以及添加密码保护、添加 PDF 表单、数字签名等的能力。

要为磁盘上的 HTML 模板创建 PDF,可以通过以下方式完成:

package main

import (
    "fmt"
    "os"

    "github.com/unidoc/unihtml"
    "github.com/unidoc/unipdf/v3/common/license"
    "github.com/unidoc/unipdf/v3/creator"
)

func main() {
    // Set the UniDoc license.
    if err := license.SetMeteredKey("my api key goes here"); err != nil {
        fmt.Printf("Err: setting metered key failed: %v\n", err)
        os.Exit(1)
    }

    // Establish connection with the UniHTML Server.
    if err := unihtml.Connect(":8080"); err != nil {
        fmt.Printf("Err:  Connect failed: %v\n", err)
        os.Exit(1)
    }

    // Get new PDF Creator.
    c := creator.New()

    // AddTOC enables Table of Contents generation.
    c.AddTOC = true

    chapter := c.NewChapter("Points")

    // Read the content of the sample.html file and load it to the conversion.
    htmlDocument, err := unihtml.NewDocument("sample.html")
    if err != nil {
        fmt.Printf("Err: NewDocument failed: %v\n", err)
        os.Exit(1)
    }

    // Draw the html document file in the context of the creator.
    if err = chapter.Add(htmlDocument); err != nil {
        fmt.Printf("Err: Draw failed: %v\n", err)
        os.Exit(1)
    }

    if err = c.Draw(chapter); err != nil {
        fmt.Printf("Err: Draw failed: %v\n", err)
        os.Exit(1)
    }


    // Write the result file to PDF.
    if err = c.WriteToFile("sample.pdf"); err != nil {
        fmt.Printf("Err: %v\n", err)
        os.Exit(1)
    }
}

我已经写了一篇 UniHTML [这里] 的介绍文章,如果需要更多信息 ( https://www.unidoc.io/post/html-for-pdf-reports-in-go ),它可能会很有用。

披露:我是 UniPDF 的原始开发者。

于 2021-04-17T15:02:18.410 回答