Help us shape the future of Go! Take the 2026 Go Developer Survey

pdf

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 23, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

README

PDF Processing Library

A cross-platform Go library for PDF processing operations: info extraction, splitting, and conversion to images.

Installation

go get github.com/yaoapp/gou/pdf

System Dependencies

macOS
# Install via Homebrew
brew install poppler      # for pdftoppm
brew install mupdf-tools   # for mutool
brew install imagemagick   # for convert
Linux (Ubuntu/Debian)
# Install via apt
sudo apt install poppler-utils  # for pdftoppm
sudo apt install mupdf-tools    # for mutool
sudo apt install imagemagick    # for convert
Linux (CentOS/RHEL)
# Install via yum/dnf
sudo yum install poppler-utils   # for pdftoppm
sudo yum install mupdf           # for mutool
sudo yum install ImageMagick     # for convert
Windows

Windows support is not yet implemented. Contributions welcome.

Usage

Basic Usage
package main

import (
    "context"
    "fmt"
    "github.com/yaoapp/gou/pdf"
)

func main() {
    // Create PDF processor
    p := pdf.New(pdf.Options{
        ConvertTool: pdf.ToolMutool,
        ToolPath:    "/usr/local/bin/mutool", // optional custom path
    })

    ctx := context.Background()

    // Get PDF info
    info, err := p.GetInfo(ctx, "document.pdf")
    if err != nil {
        panic(err)
    }
    fmt.Printf("Pages: %d\n", info.PageCount)

    // Split PDF
    files, err := p.Split(ctx, "document.pdf", pdf.SplitConfig{
        OutputDir:    "./output",
        OutputPrefix: "page",
        PageRanges:   []string{"1-5", "6-10"}, // or use PagesPerFile: 5
    })
    if err != nil {
        panic(err)
    }

    // Convert to images
    images, err := p.Convert(ctx, "document.pdf", pdf.ConvertConfig{
        OutputDir:    "./images",
        OutputPrefix: "page",
        Format:       "png",
        DPI:          150,
        PageRange:    "1-10",
    })
    if err != nil {
        panic(err)
    }

    fmt.Printf("Generated %d images\n", len(images))
}
Available Tools
  • pdf.ToolPdftoppm - Uses poppler-utils (recommended for Linux)
  • pdf.ToolMutool - Uses MuPDF tools (recommended for macOS)
  • pdf.ToolImageMagick - Uses ImageMagick convert
Configuration Options
// Create with custom tool and path
p := pdf.New(pdf.Options{
    ConvertTool: pdf.ToolPdftoppm,
    ToolPath:    "/custom/path/to/pdftoppm",
})

// Split configuration
splitConfig := pdf.SplitConfig{
    OutputDir:    "./output",
    OutputPrefix: "chapter",
    PageRanges:   []string{"1-10", "11-20"},  // specific ranges
    // OR
    PagesPerFile: 5,                          // pages per file
}

// Convert configuration
convertConfig := pdf.ConvertConfig{
    OutputDir:    "./images",
    OutputPrefix: "slide",
    Format:       "jpg",        // png, jpg, jpeg
    DPI:          300,          // resolution
    Quality:      95,           // JPEG quality (1-100)
    PageRange:    "all",        // "all", "1-5", "3"
}

API Reference

New(opts Options) *PDF

Creates a new PDF processor with specified options.

GetInfo(ctx context.Context, filePath string) (*Info, error)

Extracts PDF metadata and page count.

Split(ctx context.Context, filePath string, config SplitConfig) ([]string, error)

Splits PDF into multiple files based on page ranges.

Convert(ctx context.Context, filePath string, config ConvertConfig) ([]string, error)

Converts PDF pages to images.

Error Handling

The library returns descriptive errors for common issues:

  • Tool not found or not available
  • Invalid configuration
  • File access problems
  • Conversion failures

Handle tool availability errors:

import "strings"

// Handle tool availability errors
images, err := p.Convert(ctx, "document.pdf", convertConfig)
if err != nil {
    if strings.Contains(err.Error(), "not available") {
        fmt.Println("Required conversion tool not available")
    }
    return err
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNotImplemented = errors.New("feature not implemented for this platform")

ErrNotImplemented is returned when a feature is not implemented for the current platform

Functions

func Inspect

func Inspect() map[string]*PDFToolStatus

Inspect checks the availability and version of PDF conversion tools. It performs a silent, non-fatal check suitable for system status reporting.

func ProcessConvert

func ProcessConvert(process *process.Process) interface{}

ProcessConvert pdf.Convert Convert PDF pages to images (PNG/JPEG).

Args:

  • filePath string - Path to the PDF file
  • config map[string]interface{} - Convert configuration (optional)

Config fields:

  • format string - Output format "png" or "jpeg" (default: "png")
  • dpi int - Resolution (default: 150)
  • pages string - Page range, e.g. "1-3" (default: all pages)
  • output_dir string - Output directory (optional, default: auto temp dir)
  • output_prefix string - Prefix for output files (optional)
  • quality int - JPEG quality 1-100 (default: 95)

Returns: []string - Paths to output image files

Note: If output_dir is not specified, files are created in OS temp directory. TS scripts without "system" fs access MUST provide output_dir explicitly. The caller is responsible for cleaning up the output directory when done.

Usage:

var images = Process("pdf.Convert", "/path/to/file.pdf", {"format": "png", "dpi": 150, "pages": "1-3"})
// Returns: ["/tmp/out/page_1.png", "/tmp/out/page_2.png", "/tmp/out/page_3.png"]

func ProcessInfo

func ProcessInfo(process *process.Process) interface{}

ProcessInfo pdf.Info Get PDF file information including page count, metadata, and file size.

Args:

  • filePath string - Path to the PDF file

Returns: *Info - PDF file information

Usage:

var info = Process("pdf.Info", "/path/to/file.pdf")
// Returns: {"page_count": 10, "file_size": 12345, "title": "...", ...}

func ProcessSplit

func ProcessSplit(process *process.Process) interface{}

ProcessSplit pdf.Split Split a PDF file into multiple files by page ranges.

Args:

  • filePath string - Path to the PDF file
  • config map[string]interface{} - Split configuration

Config fields:

  • pages string - Page ranges, e.g. "1-3,5,7-10"
  • pages_per_file int - Alternative: pages per output file
  • output_dir string - Output directory (optional, default: auto temp dir)
  • output_prefix string - Prefix for output files (optional)

Returns: []string - Paths to output PDF files

Note: If output_dir is not specified, files are created in OS temp directory. TS scripts without "system" fs access MUST provide output_dir explicitly. The caller is responsible for cleaning up the output directory when done.

Usage:

var files = Process("pdf.Split", "/path/to/file.pdf", {"pages": "1-3,5,7-10", "output_dir": "/tmp/out"})
// Returns: ["/tmp/out/file_1-3.pdf", "/tmp/out/file_5.pdf", "/tmp/out/file_7-10.pdf"]

Types

type Command

type Command interface {
	// IsAvailable checks if a specific tool is available
	IsAvailable(tool ConvertTool) bool

	// GetToolPath returns the executable path for a specific tool
	GetToolPath(tool ConvertTool) string

	// ConvertWithPdftoppm converts PDF to images using pdftoppm
	ConvertWithPdftoppm(ctx context.Context, filePath string, config ConvertConfig, pageCount int) ([]string, error)

	// ConvertWithMutool converts PDF to images using mutool
	ConvertWithMutool(ctx context.Context, filePath string, config ConvertConfig, pageCount int) ([]string, error)

	// ConvertWithImageMagick converts PDF to images using ImageMagick
	ConvertWithImageMagick(ctx context.Context, filePath string, config ConvertConfig, pageCount int) ([]string, error)
}

Command defines interface for PDF conversion operations

func NewCommand

func NewCommand(toolPaths ...ToolPaths) Command

NewCommand creates a platform-specific command driver with optional custom tool paths

type CommandExecutor

type CommandExecutor interface {
	// Execute runs a command with given arguments
	Execute(ctx context.Context, command string, args []string) error

	// IsCommandAvailable checks if a command is available
	IsCommandAvailable(command string) bool

	// GetDefaultToolPaths returns default paths for conversion tools
	GetDefaultToolPaths() map[ConvertTool]string
}

CommandExecutor defines interface for executing system commands

type ConvertConfig

type ConvertConfig struct {
	OutputDir    string `json:"output_dir"`
	OutputPrefix string `json:"output_prefix"`
	Format       string `json:"format"`     // "png", "jpg", "jpeg"
	DPI          int    `json:"dpi"`        // Resolution, default 150
	Quality      int    `json:"quality"`    // JPEG quality 1-100, default 95
	PageRange    string `json:"page_range"` // e.g., "1-5" or "all"
}

ConvertConfig defines how to convert PDF to images

type ConvertTool

type ConvertTool string

ConvertTool defines supported PDF to image conversion tools

const (
	// ToolPdftoppm is the poppler-utils tool
	ToolPdftoppm ConvertTool = "pdftoppm" // poppler-utils
	// ToolMutool is the mupdf-tools tool
	ToolMutool ConvertTool = "mutool" // mupdf-tools
	// ToolImageMagick is the ImageMagick convert tool
	ToolImageMagick ConvertTool = "imagemagick" // ImageMagick convert
)

type Info

type Info struct {
	FilePath     string            `json:"file_path"`
	FileSize     int64             `json:"file_size"`
	PageCount    int               `json:"page_count"`
	Title        string            `json:"title,omitempty"`
	Author       string            `json:"author,omitempty"`
	Subject      string            `json:"subject,omitempty"`
	Creator      string            `json:"creator,omitempty"`
	Producer     string            `json:"producer,omitempty"`
	CreationDate time.Time         `json:"creation_date,omitempty"`
	ModDate      time.Time         `json:"mod_date,omitempty"`
	Metadata     map[string]string `json:"metadata,omitempty"`
}

Info contains information about a PDF file

type LinuxDriver

type LinuxDriver struct {
	// contains filtered or unexported fields
}

LinuxDriver implements Command for Linux systems

func NewLinuxDriver

func NewLinuxDriver(customPaths ToolPaths) *LinuxDriver

NewLinuxDriver creates a new Linux driver with optional custom tool paths

func (*LinuxDriver) ConvertWithImageMagick

func (d *LinuxDriver) ConvertWithImageMagick(ctx context.Context, filePath string, config ConvertConfig, pageCount int) ([]string, error)

ConvertWithImageMagick converts PDF to images using ImageMagick on Linux

func (*LinuxDriver) ConvertWithMutool

func (d *LinuxDriver) ConvertWithMutool(ctx context.Context, filePath string, config ConvertConfig, pageCount int) ([]string, error)

ConvertWithMutool converts PDF to images using mutool on Linux

func (*LinuxDriver) ConvertWithPdftoppm

func (d *LinuxDriver) ConvertWithPdftoppm(ctx context.Context, filePath string, config ConvertConfig, pageCount int) ([]string, error)

ConvertWithPdftoppm converts PDF to images using pdftoppm on Linux

func (*LinuxDriver) GetToolPath

func (d *LinuxDriver) GetToolPath(tool ConvertTool) string

GetToolPath returns the executable path for a specific tool on Linux

func (*LinuxDriver) IsAvailable

func (d *LinuxDriver) IsAvailable(tool ConvertTool) bool

IsAvailable checks if a specific tool is available on Linux

type MacOSDriver

type MacOSDriver struct {
	// contains filtered or unexported fields
}

MacOSDriver implements Command for macOS systems

func NewMacOSDriver

func NewMacOSDriver(customPaths ToolPaths) *MacOSDriver

NewMacOSDriver creates a new macOS driver with optional custom tool paths

func (*MacOSDriver) ConvertWithImageMagick

func (d *MacOSDriver) ConvertWithImageMagick(ctx context.Context, filePath string, config ConvertConfig, pageCount int) ([]string, error)

ConvertWithImageMagick converts PDF to images using ImageMagick on macOS

func (*MacOSDriver) ConvertWithMutool

func (d *MacOSDriver) ConvertWithMutool(ctx context.Context, filePath string, config ConvertConfig, pageCount int) ([]string, error)

ConvertWithMutool converts PDF to images using mutool on macOS

func (*MacOSDriver) ConvertWithPdftoppm

func (d *MacOSDriver) ConvertWithPdftoppm(ctx context.Context, filePath string, config ConvertConfig, pageCount int) ([]string, error)

ConvertWithPdftoppm converts PDF to images using pdftoppm on macOS

func (*MacOSDriver) GetToolPath

func (d *MacOSDriver) GetToolPath(tool ConvertTool) string

GetToolPath returns the executable path for a specific tool on macOS

func (*MacOSDriver) IsAvailable

func (d *MacOSDriver) IsAvailable(tool ConvertTool) bool

IsAvailable checks if a specific tool is available on macOS

type Options

type Options struct {
	ConvertTool ConvertTool `json:"convert_tool,omitempty"` // Preferred conversion tool
	ToolPath    string      `json:"tool_path,omitempty"`    // Custom path to the tool executable
}

Options defines configuration for PDF processor

type PDF

type PDF struct {
	// contains filtered or unexported fields
}

PDF handles PDF operations

func New

func New(opts Options) *PDF

New creates a new PDF processor

func (*PDF) Convert

func (p *PDF) Convert(ctx context.Context, filePath string, config ConvertConfig) ([]string, error)

Convert converts PDF to images

func (*PDF) GetInfo

func (p *PDF) GetInfo(ctx context.Context, filePath string) (*Info, error)

GetInfo reads PDF file information

func (*PDF) Split

func (p *PDF) Split(ctx context.Context, filePath string, config SplitConfig) ([]string, error)

Split splits a PDF file according to the configuration

type PDFToolStatus

type PDFToolStatus struct {
	Name      string `json:"name"`              // Tool name
	Available bool   `json:"available"`         // Whether the tool is available
	Path      string `json:"path,omitempty"`    // Resolved executable path
	Version   string `json:"version,omitempty"` // Version string
	EnvVar    string `json:"env_var,omitempty"` // Environment variable name for custom path
	Error     string `json:"error,omitempty"`   // Error message if not available
}

PDFToolStatus represents the availability status of a PDF tool.

type Parser

type Parser interface {
	// GetInfo reads PDF file information
	GetInfo(ctx context.Context, filePath string) (*Info, error)

	// Split splits a PDF file according to the configuration
	Split(ctx context.Context, filePath string, config SplitConfig) ([]string, error)

	// Convert converts PDF to images
	Convert(ctx context.Context, filePath string, config ConvertConfig) ([]string, error)
}

Parser defines the contract for PDF processing operations

type SplitConfig

type SplitConfig struct {
	OutputDir    string   `json:"output_dir"`
	OutputPrefix string   `json:"output_prefix"`
	PageRanges   []string `json:"page_ranges,omitempty"`    // e.g., ["1-5", "6-10", "11-15"]
	PagesPerFile int      `json:"pages_per_file,omitempty"` // Alternative to PageRanges
}

SplitConfig defines how to split a PDF file

type ToolPaths

type ToolPaths map[ConvertTool]string

ToolPaths contains custom paths for conversion tools

type WindowsDriver

type WindowsDriver struct {
	// contains filtered or unexported fields
}

WindowsDriver implements Command for Windows systems

func NewWindowsDriver

func NewWindowsDriver(customPaths ToolPaths) *WindowsDriver

NewWindowsDriver creates a new Windows driver with optional custom tool paths

func (*WindowsDriver) ConvertWithImageMagick

func (d *WindowsDriver) ConvertWithImageMagick(ctx context.Context, filePath string, config ConvertConfig, pageCount int) ([]string, error)

ConvertWithImageMagick converts PDF to images using ImageMagick on Windows

func (*WindowsDriver) ConvertWithMutool

func (d *WindowsDriver) ConvertWithMutool(ctx context.Context, filePath string, config ConvertConfig, pageCount int) ([]string, error)

ConvertWithMutool converts PDF to images using mutool on Windows

func (*WindowsDriver) ConvertWithPdftoppm

func (d *WindowsDriver) ConvertWithPdftoppm(ctx context.Context, filePath string, config ConvertConfig, pageCount int) ([]string, error)

ConvertWithPdftoppm converts PDF to images using pdftoppm on Windows

func (*WindowsDriver) GetToolPath

func (d *WindowsDriver) GetToolPath(tool ConvertTool) string

GetToolPath returns the executable path for a specific tool on Windows

func (*WindowsDriver) IsAvailable

func (d *WindowsDriver) IsAvailable(tool ConvertTool) bool

IsAvailable checks if a specific tool is available on Windows

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL