最近我在開發一個檔案轉換工具時,需要將多張圖片轉換為一個PDF檔案。由於我使用的是Golang語言,因此我選擇了使用Go語言編寫圖片轉PDF的程式。
在這篇文章中,我將分享我在開發過程中獲得的經驗和一些關鍵細節。以下是該程式的主要功能和流程:
- 讀取多個圖片檔案
- 建立PDF檔案
- 將所有的圖片轉換為PDF頁面
- 將所有頁面保存到PDF檔案
首先,我們需要處理的是檔案讀取。 Go中有一個標準函式庫 “io/ioutil” 用來讀取文件,並且非常方便易用。我們可以透過使用該庫中的ReadDir()方法來取得指定目錄下的所有檔案。
func getImagesFromDir(dir string) ([]string, error) { files, err := ioutil.ReadDir(dir) images := []string{} if err != nil { return images, err } for _, file := range files { if !file.IsDir() && strings.Contains(file.Name(), ".jpg") { images = append(images, filepath.Join(dir, file.Name())) } } return images, nil }
接下來,我們需要建立一個PDF檔案。 Go中有多個第三方函式庫可以建立PDF文件,我們可以選擇使用GoFPDF庫。該庫提供多種自訂選項和功能,如調整頁面大小,設定字體和顏色等。
pdf := gofpdf.New("P", "mm", "A4", "") pdf.AddPage() pdf.SetFont("Arial", "B", 16) pdf.Cell(40, 10, "Hello, world!") pdf.OutputFileAndClose("hello.pdf")
我們現在已經成功地創建了一個PDF文件,但是我們還沒有將圖片添加到其中。下一步是將所有的圖片轉換為PDF頁面,這可以透過將圖片新增為頁面背景來實現。我們可以使用Go中的image和image/draw標準庫來開啟和處理圖片。
func imageToPdf(imagePath string, pdf *gofpdf.Fpdf) { image.RegisterFormat("jpeg", "jpeg", jpeg.Decode, jpeg.DecodeConfig) f, err := os.Open(imagePath) defer f.Close() if err != nil { log.Fatal("Failed to open file:", err) } // decode the image img, _, err := image.Decode(f) if err != nil { log.Fatal("Failed to decode image:", err) } // get image dimensions w := float64(img.Bounds().Max.X) h := float64(img.Bounds().Max.Y) // add page to pdf pdf.AddPageFormat("P", gofpdf.SizeType{Wd: w, Ht: h}) pdf.Image(imagePath, 0, 0, w, h, false, "", 0, "") }
最後一步是將所有的頁面儲存到PDF檔案中。我們可以使用golang中的WriteFile()方法來將所有頁面寫入到以pdf為後綴的檔案中。
func savePdf(pdf *gofpdf.Fpdf, outputPath string) error { return pdf.OutputFileAndClose(outputPath) }
現在我們可以將上述所有程式碼整合在一起來實作一個完整的圖片轉PDF的程式。
package main import ( "fmt" "github.com/jung-kurt/gofpdf" "image" "image/jpeg" "io/ioutil" "log" "os" "path/filepath" "strings" ) func getImagesFromDir(dir string) ([]string, error) { files, err := ioutil.ReadDir(dir) images := []string{} if err != nil { return images, err } for _, file := range files { if !file.IsDir() && strings.Contains(file.Name(), ".jpg") { images = append(images, filepath.Join(dir, file.Name())) } } return images, nil } func imageToPdf(imagePath string, pdf *gofpdf.Fpdf) { image.RegisterFormat("jpeg", "jpeg", jpeg.Decode, jpeg.DecodeConfig) f, err := os.Open(imagePath) defer f.Close() if err != nil { log.Fatal("Failed to open file:", err) } // decode the image img, _, err := image.Decode(f) if err != nil { log.Fatal("Failed to decode image:", err) } // get image dimensions w := float64(img.Bounds().Max.X) h := float64(img.Bounds().Max.Y) // add page to pdf pdf.AddPageFormat("P", gofpdf.SizeType{Wd: w, Ht: h}) pdf.Image(imagePath, 0, 0, w, h, false, "", 0, "") } func savePdf(pdf *gofpdf.Fpdf, outputPath string) error { return pdf.OutputFileAndClose(outputPath) } func main() { inputDir := "input" outputPdf := "output.pdf" fmt.Printf("Reading images from '%v' ", inputDir) images, err := getImagesFromDir(inputDir) if err != nil { log.Fatal("Failed to read images:", err) } if len(images) == 0 { log.Fatal("No images found in directory") } fmt.Printf("Found %v images ", len(images)) pdf := gofpdf.New("P", "mm", "A4", "") for _, imagePath := range images { fmt.Printf("Converting '%v' ", imagePath) imageToPdf(imagePath, pdf) } if err = savePdf(pdf, outputPdf); err != nil { log.Fatal("Failed to save PDF:", err) } fmt.Printf("Saved PDF to '%v' ", outputPdf) }
幾點建議:
- 改進擴充功能。如果您的應用程式需要使用更多的檔案副檔名,請記得在getImagesFromDir函數中進行對應的變更。
- 縮放圖片。您可以使用image/draw庫中的方法可以縮放圖片以避免溢位PDF頁面。
- 新增頁碼或文字。除了應用程式中顯示的圖片之外,您還可以添加文字、標題、頁碼等內容。
結論:
圖片轉PDF是一項常見的任務,但這並不意味著它應該太困難或複雜。主要關注文件讀取、PDF文件創建、將圖片轉換為PDF頁面以及將所有頁面保存到單一文件的過程,就可以建立自己的轉換程序。如果您的專案依賴將圖片轉換為PDF文件,我們建議您使用Golang語言。
以上是圖片轉pdf golang的詳細內容。更多資訊請關注PHP中文網其他相關文章!

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines

goisbeneformervicesduetoitssimplicity,效率,androbustConcurrencySupport.1)go'sdesignemphasemphasizessimplicity and效率,Idealformicroservices.2))其ConcconcurnCurnInesSandChannelsOdinesSallessallessallessAlloSalosalOsalOsalOsalOndlingConconcConccompi.3)

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang在並發性上優於C ,而C 在原始速度上優於Golang。 1)Golang通過goroutine和channel實現高效並發,適合處理大量並發任務。 2)C 通過編譯器優化和標準庫,提供接近硬件的高性能,適合需要極致優化的應用。

選擇Golang的原因包括:1)高並發性能,2)靜態類型系統,3)垃圾回收機制,4)豐富的標準庫和生態系統,這些特性使其成為開發高效、可靠軟件的理想選擇。

Golang適合快速開發和並發場景,C 適用於需要極致性能和低級控制的場景。 1)Golang通過垃圾回收和並發機制提升性能,適合高並發Web服務開發。 2)C 通過手動內存管理和編譯器優化達到極致性能,適用於嵌入式系統開發。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

Atom編輯器mac版下載
最受歡迎的的開源編輯器

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

禪工作室 13.0.1
強大的PHP整合開發環境

WebStorm Mac版
好用的JavaScript開發工具