Home  >  Article  >  Backend Development  >  html to pdf golang

html to pdf golang

王林
王林Original
2023-05-15 15:22:081304browse

In actual development projects, there may be a need to convert HTML to PDF. For example, we want to save some pages as PDF files for printing or distribution. It is also very simple to use Golang language to realize this requirement. Let's explain step by step how to use Golang to realize the function of converting HTML to PDF.

First we need to clarify a few concepts:

HTML (Hyper Text Markup Language), hypertext markup language, is used to create structured documents and web pages, which can be accessed through a browser.

PDF (Portable Document Format), a portable document format, is suitable for multiple operating systems and can display the same appearance on different devices.

Next, we need to use some important libraries:

  1. gofpdf library, used to generate PDF files in Golang. You can install it with the following command:

    go get -u github.com/jung-kurt/gofpdf

  2. wkhtmltopdf, one for converting HTML/ The command line tool for converting CSS to PDF can be downloaded at this URL: https://wkhtmltopdf.org/downloads.html

After installing these two libraries, we can start to implement HTML conversion PDF function, here are the specific steps:

  1. Read HTML file content

We need to first read the content of the HTML file to be converted locally, you can use Use the Open method in the os package to open the file, and then use the ReadFile method in the ioutil package to read the file content. The specific code is as follows:

content, err := ioutil.ReadFile("path/to/html")
if err != nil {
    log.Fatalf("Could not read html file: %v", err)
}
  1. Convert HTML content to PDF

We can use the exec package to call the wkhtmltopdf command line tool to convert HTML content into PDF files. The specific code is as follows:

cmd := exec.Command("wkhtmltopdf", "-", "path/to/pdf")
stdin, err := cmd.StdinPipe()
if err != nil {
    log.Fatalf("Could not get stdin pipe: %v", err)
}
go func() {
    defer stdin.Close()
    _, _ = io.WriteString(stdin, string(content))
}()
out, err := cmd.CombinedOutput()
if err != nil {
    log.Fatalf("Could not convert html to pdf: %v: %s", err, out)
}

Among them, cmd.StdinPipe() returns a pipe that can be written to the standard input of the command. We can use HTML content as the standard input of the command. cmd.CombinedOutput() waits for the command to complete and returns the command output. If there is an error, it returns an error message.

  1. Prompt the user that the conversion is successful

Finally, we need to prompt the user that the HTML file has been successfully converted to a PDF file. The code is as follows:

fmt.Println("Convert completed.")

The complete code is as follows:

package main

import (
    "fmt"
    "io"
    "io/ioutil"
    "log"
    "os/exec"
)

func main() {
    content, err := ioutil.ReadFile("path/to/html")
    if err != nil {
        log.Fatalf("Could not read html file: %v", err)
    }

    cmd := exec.Command("wkhtmltopdf", "-", "path/to/pdf")
    stdin, err := cmd.StdinPipe()
    if err != nil {
        log.Fatalf("Could not get stdin pipe: %v", err)
    }
    go func() {
        defer stdin.Close()
        _, _ = io.WriteString(stdin, string(content))
    }()
    out, err := cmd.CombinedOutput()
    if err != nil {
        log.Fatalf("Could not convert html to pdf: %v: %s", err, out)
    }

    fmt.Println("Convert completed.")
}

In the above code, we use the gofpdf library to generate PDF files through Golang code. We can use the relevant methods in the gofpdf library to add text, pictures, tables, etc., and then generate a PDF file. The code is as follows:

package main

import (
    "fmt"
    "github.com/jung-kurt/gofpdf"
    "log"
)

func main() {
    pdf := gofpdf.New("P", "mm", "A4", "")

    pdf.AddPage()

    pdf.SetFont("Arial", "B", 16)
    pdf.Cell(40, 10, "Hello, World!")

    pdf.Image("path/to/image", 10, 20, 30, 0, false, "", 0, "")

    pdf.OutputFileAndClose("path/to/pdf")

    fmt.Println("PDF created.")
}

In the above code, we create a PDF file and add it to it. Hello, World! and a picture. Finally, we save the PDF file locally and prompt the user that the PDF file has been successfully created.

Summary: HTML to PDF conversion is a very common requirement, which can also be achieved through command line tools and related libraries in the Golang language. I hope that through this article, readers will have a comprehensive and in-depth understanding of this process and be able to use it flexibly in actual development.

The above is the detailed content of html to pdf golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn