最近我在开发一个文件转换工具时,需要将多张图片转换为一个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标准库来打开和处理图片。
立即学习“go语言免费学习笔记(深入)”;
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 mainimport ( "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的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2546360.html