搜尋
首頁後端開發Golang圖片轉pdf golang

最近我在開發一個檔案轉換工具時,需要將多張圖片轉換為一個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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在GO中使用init進行包裝初始化在GO中使用init進行包裝初始化Apr 24, 2025 pm 06:25 PM

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

GO的選擇語句:多路復用並發操作GO的選擇語句:多路復用並發操作Apr 24, 2025 pm 05:21 PM

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

GO中的高級並發技術:上下文和候補組GO中的高級並發技術:上下文和候補組Apr 24, 2025 pm 05:09 PM

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

使用微服務體系結構的好處使用微服務體系結構的好處Apr 24, 2025 pm 04:29 PM

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

Golang vs. Python:利弊Golang vs. Python:利弊Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang和C:並發與原始速度Golang和C:並發與原始速度Apr 21, 2025 am 12:16 AM

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

為什麼要使用Golang?解釋的好處和優勢為什麼要使用Golang?解釋的好處和優勢Apr 21, 2025 am 12:15 AM

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

Golang vs.C:性能和速度比較Golang vs.C:性能和速度比較Apr 21, 2025 am 12:13 AM

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

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

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

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具