在日常工作中,我們經常需要將一些文件轉換成PDF格式,以方便分享和列印。雖然市面上有許多現成的PDF轉換工具,但對於大部分技術人員而言,自己實作一個文件轉PDF的工具才是更有趣、更有意義的事情。在本文中,我們將介紹如何使用Golang實作一個簡單的文檔轉PDF工具。
首先,我們需要安裝兩個函式庫來完成檔案轉換和PDF產生的任務。這兩個庫分別是:
我們可以使用go mod指令來安裝這兩個函式庫:
go get -u github.com/SebastiaanKlippert/go-wkhtmltopdf go get -u github.com/unidoc/unioffice
package main import ( "log" "github.com/unidoc/unioffice/document" ) func DocxToHtml(inputFilePath string) (string, error) { doc, err := document.Open(inputFilePath) if err != nil { return "", err } defer func() { err := doc.Close() if err != nil { log.Fatalf("unable to close document: %s", err) } }() html, err := doc.Html() if err != nil { return "", err } return html, nil }
package main import ( "io/ioutil" "strings" "github.com/SebastiaanKlippert/go-wkhtmltopdf" ) func HtmlToPdf(html string, outputFilePath string) error { err := ioutil.WriteFile("input.html", []byte(html), 0644) if err != nil { return err } pdfg, err := wkhtmltopdf.NewPDFGenerator() if err != nil { return err } pdfg.AddPage(wkhtmltopdf.NewPageReader(strings.NewReader(html))) pdfg.Dpi.Set(300) pdfg.Orientation.Set(wkhtmltopdf.OrientationPortrait) pdfg.PageSize.Set(wkhtmltopdf.PageSizeA4) err = pdfg.Create() if err != nil { return err } err = pdfg.WriteFile(outputFilePath) if err != nil { return err } return nil }
package main import ( "io/ioutil" "log" "os" "strings" "github.com/SebastiaanKlippert/go-wkhtmltopdf" "github.com/unidoc/unioffice/document" ) func main() { inputFilePath := "input.docx" outputFilePath := "output.pdf" html, err := DocxToHtml(inputFilePath) if err != nil { log.Fatalf("unable to convert docx to html: %s", err) } err = HtmlToPdf(html, outputFilePath) if err != nil { log.Fatalf("unable to convert html to pdf: %s", err) } err = os.Remove("input.html") if err != nil { log.Fatalf("unable to delete input.html: %s", err) } } func DocxToHtml(inputFilePath string) (string, error) { doc, err := document.Open(inputFilePath) if err != nil { return "", err } defer func() { err := doc.Close() if err != nil { log.Fatalf("unable to close document: %s", err) } }() html, err := doc.Html() if err != nil { return "", err } return html, nil } func HtmlToPdf(html string, outputFilePath string) error { err := ioutil.WriteFile("input.html", []byte(html), 0644) if err != nil { return err } pdfg, err := wkhtmltopdf.NewPDFGenerator() if err != nil { return err } pdfg.AddPage(wkhtmltopdf.NewPageReader(strings.NewReader(html))) pdfg.Dpi.Set(300) pdfg.Orientation.Set(wkhtmltopdf.OrientationPortrait) pdfg.PageSize.Set(wkhtmltopdf.PageSizeA4) err = pdfg.Create() if err != nil { return err } err = pdfg.WriteFile(outputFilePath) if err != nil { return err } return nil }
以上是golang文檔轉pdf的詳細內容。更多資訊請關注PHP中文網其他相關文章!