如何从 pdf 文件生成器将文件下载到 Go 和 React 中的本地客户端

我创建了一个服务来生成pdf文件go-wkhtmltopdf


这是功能


func Pdf() func(c *gin.Context) {

    return func(c *gin.Context) {

        // download wkhtmltopdf and set that wkhtmltopdf on below

        wkhtmltopdf.SetPath("/usr/local/bin/wkhtmltopdf")

        type ReqHtml struct {

            Html string `json:"html"`

        }

        var html ReqHtml

        _ = c.BindJSON(&html)


        pdfg, err := wkhtmltopdf.NewPDFGenerator()

        if err != nil {

            log.Fatal(err)

        }


        page := wkhtmltopdf.NewPageReader(strings.NewReader(html.Html))

        pdfg.Orientation.Set(wkhtmltopdf.OrientationPortrait)

        page.FooterRight.Set("[page]")

        page.FooterFontSize.Set(10)


        pdfg.AddPage(page)


        err = pdfg.Create()

        if err != nil {

            log.Println(err)

        }

        err = pdfg.WriteFile("./myPdf.pdf")

        if err != nil {

            log.Fatal(err)

        }


    }

}

那个Writefile将文件写入我的根文件夹服务器,如何让客户端下载它?


假设我有<button> download file </button>


我应该用该结果的缓冲区向客户端做出响应吗?要不然是啥?


大话西游666
浏览 126回答 1
1回答

不负相思意

只需将缓冲区发送到客户端并使用此函数下载文件(React 示例代码):prepareDocForDownload = result => {&nbsp; &nbsp; const length = Object.entries(result.data).length;&nbsp; &nbsp; let bytes = new Uint8Array(length);&nbsp; &nbsp; for (let i=0; i<length; i++) {&nbsp; &nbsp; &nbsp; bytes[i] = result.data[i];&nbsp; &nbsp; }&nbsp; &nbsp; const file = new Blob(&nbsp; &nbsp; &nbsp; [bytes.buffer],&nbsp; &nbsp; &nbsp; {type: 'application/pdf'});&nbsp; &nbsp; const fileURL = URL.createObjectURL(file);&nbsp; &nbsp; const link = document.createElement('a');&nbsp; &nbsp; link.href = fileURL;&nbsp; &nbsp; link.setAttribute('download', 'file.pdf');&nbsp; &nbsp; document.body.appendChild(link);&nbsp; &nbsp; link.click();&nbsp; };
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go