generator

package
v2.39.1 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: CC0-1.0 Imports: 26 Imported by: 0

Documentation

Overview

Example (BannerGenerator)
package main

import (
	"fmt"
	"image/color"
	"log"

	"github.com/kodekoding/phastos/v2/go/generator"
)

func main() {
	banner := generator.NewBanner(
		generator.WithWidth(800),
		generator.WithHeight(400),
		generator.WithBackgroudColor("#1a1a2e"),
	)

	banner.
		AddLabel(&generator.Label{
			Text:     "Welcome to Phastos",
			FontPath: "assets/fonts/Roboto-Bold.ttf",
			Size:     48,
			Color:    color.White,
			XPos:     50,
			YPos:     150,
			Spacing:  1.5,
		}).
		Generate()

	if err := banner.Save("output/banner.png"); err != nil {
		log.Fatalf("Banner save error: %v", err)
	}

	fmt.Println("Banner saved:", banner.FileName())
}
Example (BulkGenerateAll)
package main

import (
	"fmt"
	"os"

	"github.com/kodekoding/phastos/v2/go/generator"
)

func main() {
	csv1 := generator.NewCSV()
	csv1.SetFileName("output/data1").
		SetHeader([]string{"Col1", "Col2"}).
		AppendDataRow([]string{"a", "b"})

	csv2 := generator.NewCSV()
	csv2.SetFileName("output/data2").
		SetHeader([]string{"Col1", "Col2"}).
		AppendDataRow([]string{"c", "d"})

	bulk := generator.NewBulkGenerator()
	bulk.Add(csv1, csv2)

	results := bulk.GenerateAll()
	for _, r := range results {
		if r.Error != nil {
			fmt.Fprintf(os.Stderr, "Error generating %s: %v\n", r.FilePath, r.Error)
			continue
		}
		fmt.Println("Generated:", r.FilePath)
	}
}
Example (BulkGenerateZip)
package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/kodekoding/phastos/v2/go/generator"
)

func main() {
	// siapkan beberapa generator
	csv1 := generator.NewCSV()
	csv1.SetFileName("output/report-jan").
		SetHeader([]string{"Date", "Amount"}).
		AppendDataRow([]string{"2026-01-01", "100000"}).
		AppendDataRow([]string{"2026-01-15", "250000"})

	csv2 := generator.NewCSV()
	csv2.SetFileName("output/report-feb").
		SetHeader([]string{"Date", "Amount"}).
		AppendDataRow([]string{"2026-02-01", "175000"})

	excelGen := generator.NewExcel(&generator.ExcelOptions{Source: "new"})
	excelGen.SetFileName("output/summary").
		SetHeader([]string{"Month", "Total"}).
		AppendDataRow([]string{"January", "350000"}).
		AppendDataRow([]string{"February", "175000"})

	// bulk generate dengan 3 concurrent workers, lalu zip
	bulk := generator.NewBulkGenerator(generator.WithBulkWorker(3))
	bulk.Add(csv1, csv2, excelGen)

	zipBytes, results, err := bulk.GenerateZip("reports.zip")
	if err != nil {
		log.Fatalf("Zip error: %v", err)
	}

	// cek hasil per-file
	for _, r := range results {
		if r.Error != nil {
			fmt.Printf("FAILED: %s -> %v\n", r.FilePath, r.Error)
		} else {
			fmt.Printf("OK: %s\n", r.FilePath)
		}
	}

	// zipBytes bisa langsung dikirim sebagai HTTP response
	fmt.Printf("Zip size: %d bytes\n", len(zipBytes))

	// contoh kirim zip sebagai HTTP response (dalam handler):
	_ = func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/zip")
		w.Header().Set("Content-Disposition", `attachment; filename="reports.zip"`)
		w.Write(zipBytes)
	}
}
Example (CsvGenerator)
package main

import (
	"fmt"
	"log"

	"github.com/kodekoding/phastos/v2/go/generator"
)

func main() {
	csvGen := generator.NewCSV()
	csvGen.
		SetFileName("output/report"). // akan jadi "output/report.csv"
		SetHeader([]string{"Name", "Email", "Role"}).
		AppendDataRow([]string{"Alice", "alice@mail.com", "Admin"}).
		AppendDataRow([]string{"Bob", "bob@mail.com", "User"}).
		AppendDataRow([]string{"Charlie", "charlie@mail.com", "User"})

	if err := csvGen.Error(); err != nil {
		log.Fatalf("CSV setup error: %v", err)
	}

	if err := csvGen.Generate(); err != nil {
		log.Fatalf("CSV generate error: %v", err)
	}

	fmt.Println("CSV generated:", csvGen.FileName())
}
Example (ExcelGenerator)
package main

import (
	"fmt"
	"log"

	"github.com/kodekoding/phastos/v2/go/generator"
)

func main() {
	excelGen := generator.NewExcel(&generator.ExcelOptions{Source: "new"})
	excelGen.
		SetFileName("output/report"). // akan jadi "output/report.xlsx"
		SetSheetName("Data Karyawan").
		SetHeader([]string{"Name", "Email", "Role"}).
		AppendDataRow([]string{"Alice", "alice@mail.com", "Admin"}).
		AppendDataRow([]string{"Bob", "bob@mail.com", "User"})

	if err := excelGen.Error(); err != nil {
		log.Fatalf("Excel setup error: %v", err)
	}

	if err := excelGen.Generate(); err != nil {
		log.Fatalf("Excel generate error: %v", err)
	}

	fmt.Println("Excel generated:", excelGen.FileName())
}
Example (PdfGenerator)
package main

import (
	"fmt"
	"log"

	"github.com/kodekoding/phastos/v2/go/generator"
)

func main() {
	pdfGen, err := generator.NewPDF() // default A4, margin 10/11
	if err != nil {
		log.Fatalf("PDF init error: %v", err)
	}

	// custom template function (opsional)
	pdfGen.AddCustomFunction("formatCurrency", func(amount float64) string {
		return fmt.Sprintf("Rp %.0f", amount)
	})

	// data untuk template HTML
	data := map[string]any{
		"InvoiceNumber": "INV-2026-001",
		"CustomerName":  "PT Maju Jaya",
		"Items": []map[string]any{
			{"Name": "Product A", "Qty": 2, "Price": 150000},
			{"Name": "Product B", "Qty": 1, "Price": 300000},
		},
		"Total": 600000,
	}

	fileName := "invoice-001.pdf"
	pdfGen.
		SetTemplate("templates/invoice.html", data).
		SetFooterHTMLTemplate("templates/footer.html"). // opsional
		SetFileName(&fileName)

	if err = pdfGen.Generate(); err != nil {
		log.Fatalf("PDF generate error: %v", err)
	}

	fmt.Println("PDF generated:", pdfGen.FileName())
	// fileName juga sudah ter-update dengan full path (side effect dari SetFileName)
	fmt.Println("Full path:", fileName)
}
Example (PdfGeneratorCustomOptions)

Dengan custom options

package main

import (
	"log"

	"github.com/kodekoding/phastos/v2/go/generator"
)

func main() {
	pdfGen, err := generator.NewPDF(&generator.ConverterOptions{
		PageSize:     "Legal",
		MarginTop:    20,
		MarginBottom: 20,
		MarginLeft:   15,
		MarginRight:  15,
	})
	if err != nil {
		log.Fatalf("PDF init error: %v", err)
	}
	_ = pdfGen
}
Example (QrGenerator)
package main

import (
	"fmt"
	"log"

	"github.com/kodekoding/phastos/v2/go/generator"
)

func main() {
	qrGen, err := generator.NewQR("https://example.com/verify?token=abc123")
	if err != nil {
		log.Fatalf("QR init error: %v", err)
	}

	fileName := "verification-qr"
	qrGen.
		SetFileName(&fileName) // akan jadi "/tmp/qr/<md5>.jpeg"

	if err = qrGen.Generate(); err != nil {
		log.Fatalf("QR generate error: %v", err)
	}

	fmt.Println("QR generated:", qrGen.FileName())
}
Example (UnifiedInterface)
package main

import (
	"fmt"
	"log"

	"github.com/kodekoding/phastos/v2/go/generator"
)

func main() {
	outputType := "csv" // bisa diganti "excel", "pdf", dll sesuai kebutuhan

	var gen generator.FileGenerator

	switch outputType {
	case "csv":
		csvGen := generator.NewCSV()
		csvGen.
			SetFileName("output/export").
			SetHeader([]string{"ID", "Name"}).
			AppendDataRow([]string{"1", "Alice"}).
			AppendDataRow([]string{"2", "Bob"})
		gen = csvGen

	case "excel":
		excelGen := generator.NewExcel(&generator.ExcelOptions{Source: "new"})
		excelGen.
			SetFileName("output/export").
			SetHeader([]string{"ID", "Name"}).
			AppendDataRow([]string{"1", "Alice"}).
			AppendDataRow([]string{"2", "Bob"})
		gen = excelGen

	case "pdf":
		pdfGen, err := generator.NewPDF()
		if err != nil {
			log.Fatal(err)
		}
		fileName := "export.pdf"
		pdfGen.
			SetTemplate("templates/report.html", map[string]any{"Title": "Report"}).
			SetFileName(&fileName)
		gen = pdfGen
	}

	// dari sini, kode tidak perlu tahu tipe generator apa yang dipakai
	if err := gen.Generate(); err != nil {
		log.Fatalf("Generate error: %v", err)
	}

	fmt.Printf("Generated [%s]: %s\n", outputType, gen.FileName())
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewCSV

func NewCSV() *csv

New - to initialize CSV struct object fileName: by default should be "generated-csv.csv"

func NewExcel

func NewExcel(options *ExcelOptions) *excel

New - to initialize Excel struct object fileName: by default should be "generated.xlsx"

Types

type Banner struct {
	BgProperty
	// contains filtered or unexported fields
}

func NewBanner

func NewBanner(opts ...Options) *Banner

NewBanner - by default will be w: 1200, h: 400, bgColor: white

func (*Banner) AddImageLayer

func (b *Banner) AddImageLayer(img *ImageLayer) Banners

func (*Banner) AddLabel

func (b *Banner) AddLabel(labelText *Label) Banners

func (*Banner) FileName added in v2.38.0

func (b *Banner) FileName() string

func (*Banner) Generate

func (b *Banner) Generate() Banners

func (*Banner) Image

func (b *Banner) Image() image.Image

func (*Banner) Save

func (b *Banner) Save(destPath string) error

func (*Banner) SetDestPath added in v2.38.0

func (b *Banner) SetDestPath(destPath string) Banners

type Banners

type Banners interface {
	AddImageLayer(img *ImageLayer) Banners
	AddLabel(labelText *Label) Banners
	Generate() Banners
	Image() image.Image
	Save(destPath string) error
	SetDestPath(destPath string) Banners
	FileName() string
}

type BgProperty

type BgProperty struct {
	Width   int
	Height  int
	BgColor color.Color
}

BgProperty is background property struct

type BulkGenerator added in v2.38.0

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

BulkGenerator runs multiple FileGenerator instances concurrently and can compress all successful outputs into a single zip archive.

func NewBulkGenerator added in v2.38.0

func NewBulkGenerator(opts ...BulkOption) *BulkGenerator

NewBulkGenerator creates a new BulkGenerator. Default worker pool size is 5.

func (*BulkGenerator) Add added in v2.38.0

func (bg *BulkGenerator) Add(generators ...FileGenerator) *BulkGenerator

Add appends one or more FileGenerator to the bulk queue.

func (*BulkGenerator) GenerateAll added in v2.38.0

func (bg *BulkGenerator) GenerateAll() []BulkResult

GenerateAll runs all generators concurrently using a worker pool and returns the result for each generator (preserving the original order).

func (*BulkGenerator) GenerateZip added in v2.38.0

func (bg *BulkGenerator) GenerateZip(zipFileName string) ([]byte, []BulkResult, error)

GenerateZip runs all generators concurrently, then compresses every successfully generated file into a single zip archive. Returns the zip content as bytes.

Files that fail to generate are skipped from the archive but included in the returned BulkResult slice so the caller can inspect errors.

type BulkOption added in v2.38.0

type BulkOption func(*BulkGenerator)

BulkOption configures the BulkGenerator.

func WithBulkWorker added in v2.38.0

func WithBulkWorker(n int) BulkOption

WithBulkWorker sets the number of concurrent workers for bulk generation.

type BulkResult added in v2.38.0

type BulkResult struct {
	FilePath string `json:"file_path"`
	Error    error  `json:"error,omitempty"`
}

BulkResult holds the outcome of a single generator within a bulk operation.

type CSVs

type CSVs interface {
	FileGenerator
	SetFileName(fileName string) CSVs
	AppendDataRow(data []string) CSVs
	SetHeader(data []string) CSVs
	Error() error
}

type ConverterOptions

type ConverterOptions struct {
	PageSize     string
	MarginBottom uint
	MarginTop    uint
	MarginLeft   uint
	MarginRight  uint
}

type ExcelOptions

type ExcelOptions struct {
	Source string
	File   interface{}
}

type Excels

type Excels interface {
	FileGenerator
	SetFileName(fileName string) Excels
	GetExcelFile() *excelize.File
	Error() error
	SetSheetName(sheetName string) Excels
	AppendDataRow(data []string) Excels
	SetHeader(data []string) Excels
	ScanContentToStruct(sheetName string, destinationStruct interface{}) error
	GetContents(sheetName string) ([]map[string]string, error)
	GetMergeCell(sheetName string) ([]excelize.MergeCell, error)
}

type FileGenerator added in v2.38.0

type FileGenerator interface {
	// Generate produces the output file. Returns an error if generation fails.
	Generate() error
	// FileName returns the path/name of the generated output file.
	FileName() string
}

FileGenerator is the unified contract for all generator types (PDF, CSV, Excel, QR, Banner). It provides the common operations shared across all generators, allowing callers to switch between generator types without changing the generation/consumption logic.

Usage example:

var gen generator.FileGenerator
switch outputType {
case "pdf":
    gen = pdfInstance
case "csv":
    gen = csvInstance
case "excel":
    gen = excelInstance
}
if err := gen.Generate(); err != nil { ... }
fmt.Println("output:", gen.FileName())

type ImageLayer

type ImageLayer struct {
	Image image.Image
	XPos  int
	YPos  int
}

ImageLayer is a struct

type Label

type Label struct {
	Text        string
	FontPath    string
	FontType    string
	Size        float64
	Color       color.Color
	DPI         float64
	Spacing     float64
	XPos        int
	YPos        int
	RightMargin float64
}

Label is a struct

type Options

type Options func(*Banner)

func WithBackgroudColor

func WithBackgroudColor(hexColor string) Options

func WithHeight

func WithHeight(height int) Options

func WithWidth

func WithWidth(width int) Options

type PDF

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

func NewPDF

func NewPDF(options ...*ConverterOptions) (*PDF, error)

func (*PDF) AddCustomFunction added in v2.33.0

func (c *PDF) AddCustomFunction(aliasName string, function any) PDFs

func (*PDF) Error

func (c *PDF) Error() error

func (*PDF) FileName added in v2.38.0

func (c *PDF) FileName() string

func (*PDF) Generate

func (c *PDF) Generate() error

func (*PDF) SetFileName

func (c *PDF) SetFileName(fileName *string) PDFs

func (*PDF) SetFooterHTMLTemplate

func (c *PDF) SetFooterHTMLTemplate(footerHTMLPath string) PDFs

func (*PDF) SetTemplate

func (c *PDF) SetTemplate(templatePath string, data interface{}) PDFs

type PDFs

type PDFs interface {
	FileGenerator
	SetTemplate(templatePath string, data interface{}) PDFs
	SetFooterHTMLTemplate(footerHTMLPath string) PDFs
	SetFileName(fileName *string) PDFs
	AddCustomFunction(aliasName string, function any) PDFs
	Error() error
}

type QR

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

func (*QR) FileName added in v2.38.0

func (q *QR) FileName() string

func (*QR) Generate

func (q *QR) Generate() error

func (*QR) SetFileName

func (q *QR) SetFileName(fileName *string) QRs

func (*QR) SetLogoImg

func (q *QR) SetLogoImg(logoPath string) QRs

type QRs

type QRs interface {
	FileGenerator
	SetLogoImg(logoPath string) QRs
	SetFileName(fileName *string) QRs
}

func NewQR

func NewQR(content string) (QRs, error)

Jump to

Keyboard shortcuts

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