登录
首页 >  Golang >  Go问答

如何在本地主机的 Golang 网页上浏览生成的 pdf 文件?

来源:stackoverflow

时间:2024-02-09 16:51:26 139浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《如何在本地主机的 Golang 网页上浏览生成的 pdf 文件?》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我正在尝试在 http://localhost:3333/pdf 上查看生成的 pdf。

我正在尝试学习使用 golang 生成 pdf。绑定在 pdf 中进行更改并在本地主机服务器 ( http://localhost:3333/pdf ) 上实时查看。 但我不知道如何在本地主机上显示 pdf。

我的代码::

package main

import (
    "errors"
    "fmt"
    "io"
    "net/http"
    "os"

    "github.com/krazybee/gofpdf"
)

type bufWriter struct {
    buf []byte
}

func getRoot(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("got / request\n")
    io.WriteString(w, "This is my website!\n")
}

func getHello(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("got /hello request\n")
    io.WriteString(w, "Hello, HTTP!\n")
}

func generatePDF(w http.ResponseWriter, r *http.Request) {
    pw := new(bufWriter)
    pdf := gofpdf.New("P", "mm", "A4", "")
    fontsize := 12.0

    font := "Arial"

    pdf.SetFont("Arial", "", 6)

    pdf.AddPage()
    pdf.SetMargins(5, 5, 5)
    pdf.SetAutoPageBreak(true, 34)

    pdf.SetFont(font, "B", fontsize)

    pdf.MultiCell(0, 8, "TERMS OF LIVING", "", "C", false)
    pdf.MultiCell(0, 8, "Terms", "", "C", false)

    // Show the pdf on localhost web page.
    err = pdf.OutputAndClose(pw)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println("PDF served successfully")
}

func main() {
    http.HandleFunc("/", getRoot)
    http.HandleFunc("/hello", getHello)
    http.HandleFunc("/pdf", generatePDF)

    err := http.ListenAndServe(":3333", nil)
    if errors.Is(err, http.ErrServerClosed) {
        fmt.Printf("server closed\n")
    } else if err != nil {
        fmt.Printf("error starting server: %s\n", err)
        os.Exit(1)
    }
}

这是我尝试过的。 但从评论 // show the pdf on the localhost web page. 我不知道之后如何进一步进行。

有人可以帮我吗?我该怎么做?如何在本地主机网页上查看生成的 pdf?


正确答案


默认情况下,http 包使用 content-type: text/html 标头提供页面。在编写页面内容之前,您必须自己指定所需的标题:

w.header().set("content-type", "application/pdf")

但是,您提供的示例代码不起作用,因为 io 流混乱。以下是您需要更改的内容:

func generatepdf(w http.responsewriter, r *http.request) {
    var b bytes.buffer
    pw := io.writer(&b)
    pr := io.reader(&b)
    ...
    err := pdf.output(pw)
    ...
    w.header().set("content-type", "application/pdf")
    respdf, _ := ioutil.readall(pr)
    w.write(respdf)
    fmt.println("pdf served successfully")
}

我建议你对 io 库进行一些练习。

这是适合我的完整代码:

package main

import (
    "bytes"
    "errors"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "os"

    "github.com/krazybee/gofpdf"
)

func getRoot(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("got / request\n")
    io.WriteString(w, "This is my website!\n")
}

func getHello(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("got /hello request\n")
    io.WriteString(w, "Hello, HTTP!\n")
}

func generatePDF(w http.ResponseWriter, r *http.Request) {
    var b bytes.Buffer
    pw := io.Writer(&b)
    pr := io.Reader(&b)

    pdf := gofpdf.New("P", "mm", "A4", "")
    fontsize := 12.0

    font := "Arial"

    pdf.SetFont("Arial", "", 6)

    pdf.AddPage()
    pdf.SetMargins(5, 5, 5)
    pdf.SetAutoPageBreak(true, 34)

    pdf.SetFont(font, "B", fontsize)

    pdf.MultiCell(0, 8, "TERMS OF LIVING", "", "C", false)
    pdf.MultiCell(0, 8, "Terms", "", "C", false)

    // Show the pdf on localhost web page.
    err := pdf.Output(pw)
    if err != nil {
        fmt.Println(err)
        return
    }
    w.Header().Set("Content-Type", "application/pdf")
    resPDF, _ := ioutil.ReadAll(pr)
    w.Write(resPDF)
    fmt.Println("PDF served successfully")
}

func main() {
    http.HandleFunc("/", getRoot)
    http.HandleFunc("/hello", getHello)
    http.HandleFunc("/pdf", generatePDF)

    err := http.ListenAndServe(":3333", nil)
    if errors.Is(err, http.ErrServerClosed) {
        fmt.Printf("server closed\n")
    } else if err != nil {
        fmt.Printf("error starting server: %s\n", err)
        os.Exit(1)
    }
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何在本地主机的 Golang 网页上浏览生成的 pdf 文件?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>