Skip to content

庄朋龙的博客

有志者自有千方万计,无志者只感千难万难。

Menu
  • 首页
  • 生活
  • 创业
  • 编程
  • 运维
  • 视频课程
    • 跨境独立站
    • Shopee跨境电商
    • TEMU跨境电商
  • 资源分享
    • 网站推荐
    • 开源推荐
    • 可商用字体
    • 书籍分享
Menu

用go语言写一个把epub文件转换成pdf的代码

Posted on 2023年5月9日2023年5月9日 by 庄朋龙

以下是使用Go语言实现将EPUB文件转换为PDF的示例代码:

package main

import (
    "fmt"
    "log"
    "os"
    "path/filepath"
    "github.com/signintech/gopdf"
    "github.com/bmaupin/go-epub"
)

func main() {
    // 获取要转换的文件路径
    epubPath := "/path/to/epub/file.epub"

    // 解析EPUB文件
    epubFile, err := epub.Open(epubPath)
    if err != nil {
        log.Fatalf("Failed to open EPUB file: %s", err)
    }

    // 获取封面图片并加载
    coverImage, err := epubFile.GetCoverImage()
    if err != nil {
        log.Fatalf("Failed to get cover image from EPUB: %s", err)
    }

    // 创建一个新的PDF文件
    pdf := gopdf.GoPdf{}
    pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
    pdf.AddPage()

    // 添加封面
    if coverImage != nil {
        imageWidth, imageHeight, err := coverImage.Bounds().Size()
        if err != nil {
            log.Fatalf("Failed to get size of cover image: %s", err)
        }
        pdf.Image(coverImage, 0, 0, float64(imageWidth), float64(imageHeight))
    }

    // 添加EPUB中的所有HTML页面
    for _, chapter := range epubFile.Content {
        html, err := epubFile.GetChapter(chapter)
        if err != nil {
            log.Fatalf("Failed to get chapter from EPUB: %s", err)
        }
        pdf.AddPage()
        pdf.SetY(10)
        pdf.SetX(10)
        _, lineHt := pdf.GetFontSize()
        htmlLines := pdf.SplitLines([]byte(html), 500)
        for _, line := range htmlLines {
            pdf.Cell(nil, string(line))
            pdf.Br(lineHt + 1.0)
        }
    }

    // 保存PDF文件
    outputPath := filepath.Join(filepath.Dir(epubPath), fmt.Sprintf("%s.pdf", filepath.Base(epubPath)))
    if err := pdf.WritePdf(outputPath); err != nil {
        log.Fatalf("Failed to write PDF file: %s", err)
    }

    fmt.Printf("PDF file saved to %s\n", outputPath)
}

这个代码使用了Go语言的第三方库github.com/signintech/gopdf和github.com/bmaupin/go-epub,需要先使用go get命令安装:

go get github.com/signintech/gopdf
go get github.com/bmaupin/go-epub

代码的核心逻辑是使用go-epub库来解析EPUB文件,然后使用gopdf库将HTML页面转换为PDF页面,并将它们保存为PDF文件。在转换过程中,还添加了封面图片。你可以将epubPath变量修改为你自己的EPUB文件路径,并运行程序来测试它。

Category: 编程

全栈开发者×创业偏执狂

相信代码能改变命运,也相信凌晨四点的服务器警报里有真实的人生。

我的创业项目:
SHOPAGG / SmallShop / DigitShops / 文硕阁

© 2025 庄朋龙的博客