15 Commits

Author SHA1 Message Date
d8ddbbb41d v0.1.14 2026-11-17 23:06:09 +06:30
fa8691c04e v0.1.13 2026-10-09 12:03:25 +06:30
016dad446f add CheckPrinter 2026-10-02 22:35:05 +06:30
06f38b707e v0.1.11 2026-09-09 22:43:57 +06:30
5f4a427f3b split big chunk of data to write to printer 2026-09-08 17:24:54 +06:30
7bb8778611 pump to 0.1.10 2026-09-03 09:23:58 +06:30
58c029b5f2 fix format time to MM timezone 2026-09-03 09:00:13 +06:30
8a23c7037f v0.1.9 - add <cut> element 2026-07-06 16:11:31 +06:30
29ec943d13 add date format 2026-06-04 11:16:13 +06:30
99189e4b51 add working dir 2026-06-04 00:10:32 +06:30
d8781c3981 add template functions 2026-06-03 00:23:08 +06:30
d7ffc17d71 update to latest 2026-06-02 10:08:24 +06:30
ecb03c1fb7 fix html to png 2026-04-08 15:31:23 +06:30
016cc5b6fe update build 2026-03-19 02:41:51 +06:30
9a0d1d098c add upload to space 2026-03-19 00:19:08 +06:30
20 changed files with 901 additions and 239 deletions

5
.gitignore vendored
View File

@@ -26,3 +26,8 @@ go.work.sum
.env
build
assets
libgofunc
libgo
cmd/out.png
cmd/*.png

15
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,15 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Dev",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd",
},
]
}

View File

@@ -1,9 +1,9 @@
#!/bin/bash
APP_NAME="libgofunc"
VERSION="${1:-v0.1.1}"
OUTPUT_DIR="assets"
BUILD_DIR="build"
VERSION="${1:-v0.1.13}"
OUTPUT_DIR="../assets"
BUILD_DIR="../build"
# need Android NDK
NDK_HOME="$HOME/Android/Sdk/ndk/28.2.13676358" # <--- CHECK YOUR VERSION
@@ -11,7 +11,7 @@ API=21
TOOLCHAIN="$NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin"
OS="$(uname -s)"
cd cmd
if [ "$OS" = "Darwin" ]; then
export IOS_SDK=$(xcrun --sdk iphoneos --show-sdk-path)
export IOS_SIM_SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)
@@ -27,7 +27,7 @@ if [ "$OS" = "Darwin" ]; then
CC="$(xcrun --sdk iphonesimulator --find clang)" \
CGO_CFLAGS="-isysroot $IOS_SIM_SDK -arch x86_64" \
CGO_LDFLAGS="-isysroot $IOS_SIM_SDK -arch x86_64" \
go build -buildmode=c-archive -o build/ios/sim/libgofunc_arm64_sim.a .
go build ./cmd -buildmode=c-archive -o build/ios/sim/libgofunc_arm64_sim.a .
# xcodebuild -create-xcframework \
# -library build/ios/device/libgofunc_arm64.a -headers build/ios/device/ \
@@ -46,34 +46,35 @@ if [ "$OS" = "Darwin" ]; then
elif [ "$OS" = "Linux" ]; then
mkdir -p "${OUTPUT_DIR}/${VERSION}"
echo "Building for Android amd64..."
ARCH="amd64"
echo "Building for Android $ARCH..."
CC="$TOOLCHAIN/x86_64-linux-android$API-clang" \
CGO_ENABLED=1 GOOS=android GOARCH=amd64 \
go build -buildmode=c-shared -o $BUILD_DIR/libgofunc_amd64.so .
go build -buildmode=c-shared -o $BUILD_DIR/$VERSION/$ARCH/libgofunc.so .
ARCHIVE_NAME="${APP_NAME}-${VERSION}-amd64.tar.gz"
tar -czf "${OUTPUT_DIR}/${VERSION}/${ARCHIVE_NAME}" -C "${BUILD_DIR}" libgofunc_amd64.so
tar -czf "${OUTPUT_DIR}/${VERSION}/${ARCHIVE_NAME}" -C "${BUILD_DIR}" ./${VERSION}/${ARCH}
echo "Building for Android arm64..."
ARCH="arm64"
echo "Building for Android $ARCH..."
CC="$TOOLCHAIN/aarch64-linux-android$API-clang" \
CGO_ENABLED=1 GOOS=android GOARCH=arm64 \
go build -buildmode=c-shared -o $BUILD_DIR/libgofunc_arm64.so .
go build -buildmode=c-shared -o $BUILD_DIR/$VERSION/$ARCH/libgofunc.so .
ARCHIVE_NAME="${APP_NAME}-${VERSION}-arm64.tar.gz"
tar -czf "${OUTPUT_DIR}/${VERSION}/${ARCHIVE_NAME}" -C "${BUILD_DIR}" libgofunc_arm64.so
ARCHIVE_NAME="${APP_NAME}-${VERSION}-${ARCH}.tar.gz"
tar -czf "${OUTPUT_DIR}/${VERSION}/${ARCHIVE_NAME}" -C "${BUILD_DIR}" ./${VERSION}/${ARCH}
ARCH="armv7a"
echo "Building for Android armv7a..."
CC="$TOOLCHAIN/armv7a-linux-androideabi$API-clang" \
CGO_ENABLED=1 GOOS=android GOARCH=arm GOARM=7 \
go build -buildmode=c-shared -o $BUILD_DIR/libgofunc_armv7a.so .
go build -buildmode=c-shared -o $BUILD_DIR/$VERSION/$ARCH/libgofunc.so .
ARCHIVE_NAME="${APP_NAME}-${VERSION}-armv7a.tar.gz"
tar -czf "${OUTPUT_DIR}/${VERSION}/${ARCHIVE_NAME}" -C "${BUILD_DIR}" libgofunc_armv7a.so
# cp ./assets/libgofunc_x64.so $HOME/ws/forward_pos/native/android/x86_64/libgofunc.so
# cp ./assets/libgofunc_arm64.so $HOME/ws/forward_pos/native/android/arm64-v8a/libgofunc.so
# cp ./assets/libgofunc_armv7a.so $HOME/ws/forward_pos/native/android/armeabi-v7a/libgofunc.so
tar -czf "${OUTPUT_DIR}/${VERSION}/${ARCHIVE_NAME}" -C "${BUILD_DIR}" ./${VERSION}/${ARCH}
export HTTPS_PROXY="socks5://localhost:8080"
rclone copy ../assets/${VERSION} s3:mokkon/libs/libgofunc/${VERSION}
else
echo "Unsupported OS: $OS"
exit 1

141
canvas.go Normal file
View File

@@ -0,0 +1,141 @@
package libgofunc
import (
"strconv"
"strings"
"github.com/fogleman/gg"
"golang.org/x/image/font"
"golang.org/x/net/html"
)
// -------------------- STYLE --------------------
type Style struct {
PaddingLeft float64
PaddingRight float64
PaddingTop float64
PaddingBottom float64
FontSize float64
Width float64
Height float64
TextAlign string
VerticalAlign string
Border float64
}
func parseStyle(styleStr string) Style {
style := Style{
FontSize: 16,
TextAlign: "left",
VerticalAlign: "top",
}
parts := strings.Split(styleStr, ";")
for _, p := range parts {
kv := strings.SplitN(strings.TrimSpace(p), ":", 2)
if len(kv) != 2 {
continue
}
key := strings.TrimSpace(kv[0])
val := strings.TrimSpace(kv[1])
switch key {
case "padding":
v := parsePx(val)
style.PaddingLeft, style.PaddingRight, style.PaddingTop, style.PaddingBottom = v, v, v, v
case "padding-left":
v := parsePx(val)
style.PaddingLeft = v
case "padding-right":
v := parsePx(val)
style.PaddingRight = v
case "padding-top":
v := parsePx(val)
style.PaddingTop = v
case "padding-bottom":
v := parsePx(val)
style.PaddingBottom = v
case "font-size":
style.FontSize = parsePx(val)
case "width":
style.Width = parsePx(val)
case "height":
style.Height = parsePx(val)
case "text-align":
style.TextAlign = val
case "vertical-align":
style.VerticalAlign = val
case "border":
style.Border = parsePx(val)
}
}
return style
}
func parsePx(v string) float64 {
v = strings.ReplaceAll(v, "px", "")
f, _ := strconv.ParseFloat(v, 64)
return f
}
// -------------------- NODE --------------------
type Node struct {
Tag string
Text string
Attr map[string]string
Style Style
Children []*Node
}
func (n Node) getSrc() string {
for k, v := range n.Attr {
if k == "src" {
return v
}
}
return ""
}
func (n Node) getHeight() int {
return int(n.Style.Height)
}
func BuildTree(n *html.Node, canvasWidth int, dc *gg.Context, face *font.Face) (*Node, int) {
if n.Type != html.ElementNode {
return nil, 0
}
text := ""
if n.Data == "h1" || n.Data == "h2" || n.Data == "h3" ||
n.Data == "p" || n.Data == "td" || n.Data == "th" ||
n.Type == html.TextNode {
text = getText(n)
}
node := &Node{
Tag: n.Data,
Text: text,
Attr: map[string]string{},
}
for _, a := range n.Attr {
node.Attr[a.Key] = a.Val
}
if s, ok := node.Attr["style"]; ok {
node.Style = parseStyle(s)
}
xPadding := node.Style.PaddingLeft + node.Style.PaddingRight
yPadding := node.Style.PaddingTop + node.Style.PaddingBottom
fontSize := node.Style.FontSize
h := nodeHeight(n, dc, canvasWidth, int(xPadding), int(yPadding),
face, fontSize, node.getHeight())
for c := n.FirstChild; c != nil; c = c.NextSibling {
child, ch := BuildTree(c, canvasWidth, dc, face)
if child != nil {
node.Children = append(node.Children, child)
}
h += ch
}
return node, h
}

143
cmd/main.go Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1,4 +1,4 @@
package main
package libgofunc
import (
"image"
@@ -91,7 +91,8 @@ func toMonochrome(img image.Image) *image.Gray {
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
r, g, b, _ := img.At(x, y).RGBA()
grayValue := uint8((r + g + b) / 3 >> 8)
// grayValue := uint8((r + g + b) / 3 >> 8)
grayValue := uint8((0.299*float64(r) + 0.587*float64(g) + 0.114*float64(b)) / 256.0)
if grayValue > 128 {
gray.Set(x, y, color.White)
} else {
@@ -138,7 +139,6 @@ func escposRaster(img *image.Gray) []byte {
data = append(data, b)
}
}
return data
}

11
go.mod
View File

@@ -1,16 +1,17 @@
module libgofunc
module gt.mokkon.com/sainw/libgofunc
go 1.22.0
go 1.26.0
require (
github.com/dlclark/regexp2 v1.11.5
github.com/fogleman/gg v1.3.0
github.com/kenshaw/escpos v0.0.0-20221114190919-df06b682a8fc
golang.org/x/image v0.24.0
golang.org/x/net v0.34.0
golang.org/x/image v0.38.0
golang.org/x/net v0.52.0
)
require (
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
golang.org/x/text v0.22.0 // indirect
github.com/google/uuid v1.6.0
golang.org/x/text v0.35.0 // indirect
)

14
go.sum
View File

@@ -4,11 +4,13 @@ github.com/fogleman/gg v1.3.0 h1:/7zJX8F6AaYQc57WQCyN9cAIz+4bCJGO9B+dyW29am8=
github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/kenshaw/escpos v0.0.0-20221114190919-df06b682a8fc h1:4JwmN2Scz1vR+hfSxkdy2IE/DzxX2Cftm2lhWHyN0k0=
github.com/kenshaw/escpos v0.0.0-20221114190919-df06b682a8fc/go.mod h1:M+GIBmg2MqaSWIJrXCZS+/wRFbr9fOguRz3SHn8DRPE=
golang.org/x/image v0.24.0 h1:AN7zRgVsbvmTfNyqIbbOraYL8mSwcKncEj8ofjgzcMQ=
golang.org/x/image v0.24.0/go.mod h1:4b/ITuLfqYq1hqZcjofwctIhi7sZh2WaCjvsBNjjya8=
golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=
golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
golang.org/x/image v0.38.0 h1:5l+q+Y9JDC7mBOMjo4/aPhMDcxEptsX+Tt3GgRQRPuE=
golang.org/x/image v0.38.0/go.mod h1:/3f6vaXC+6CEanU4KJxbcUZyEePbyKbaLoDOe4ehFYY=
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=

504
img.go
View File

@@ -1,4 +1,4 @@
package main
package libgofunc
import (
/*
@@ -11,10 +11,10 @@ import (
"image"
_ "image/png"
"os"
"strconv"
"strings"
"embed"
_ "time/tzdata"
"github.com/fogleman/gg"
"golang.org/x/image/font"
@@ -22,24 +22,38 @@ import (
"golang.org/x/net/html"
"encoding/json"
)
import (
"log"
"path"
"strconv"
"time"
"github.com/kenshaw/escpos"
"github.com/google/uuid"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
const (
canvasWidth = 550
padding = 5
defalutFontSize = 18.0
defalutTableBorder = 5
lineGap = 12
elePSize = 18
eleH1Size = 32
eleH2Size = 24
eleH3Size = 19
)
//go:embed static/*
var fontFs embed.FS
//export GenPNG
func GenPNG(outputPath *C.char, payload *C.char, tmpl *C.char) *C.char {
goPath := C.GoString(outputPath)
func GenPNG(width C.int, outDir *C.char, payload *C.char, tmpl *C.char, workingDirC *C.char) *C.char {
canvasWidth := int(width)
goOutDir := C.GoString(outDir)
goPayload := C.GoString(payload)
goTmpl := C.GoString(tmpl)
workingDir := C.GoString(workingDirC)
data := make(map[string]interface{})
err := json.Unmarshal([]byte(goPayload), &data)
@@ -53,59 +67,77 @@ func GenPNG(outputPath *C.char, payload *C.char, tmpl *C.char) *C.char {
}
htmlStr = uni2zg(htmlStr)
htmls := strings.Split(htmlStr, "<cut>")
result := make([]string, 0)
for _, html := range htmls {
out, err := GenPng(canvasWidth, goOutDir, html, workingDir)
if err != nil {
return NewErr(err)
}
result = append(result, out)
}
return NewOk(result)
}
func GenPng(canvasWidth int, outDir string, htmlStr string, workingDir string) (string, error) {
root, err := html.Parse(strings.NewReader(htmlStr))
if err != nil {
return NewErr(err)
return "", err
}
fontBytes, err := fontFs.ReadFile("static/Zawgyi-One.ttf")
face, err := LoadFont(defalutFontSize)
if err != nil {
return NewErr(err)
}
ttfFont, err := opentype.Parse(fontBytes)
if err != nil {
return NewErr(err)
}
face, err := opentype.NewFace(ttfFont, &opentype.FaceOptions{
Size: 24,
DPI: 72,
Hinting: font.HintingFull,
})
if err != nil {
return NewErr(err)
return "", err
}
// First pass: compute required height
dummyDC := gg.NewContext(canvasWidth, 150)
dummyDC.SetFontFace(face)
dummyDC.SetFontFace(*face)
bodyNode := findNode(root, "body")
if bodyNode == nil {
bodyNode = root
}
computedHeight := computeHeight(bodyNode, padding, dummyDC, face)
body, height := BuildTree(bodyNode, canvasWidth, dummyDC, face)
// Second pass: actual rendering
dc := gg.NewContext(canvasWidth, computedHeight+50)
dc := gg.NewContext(canvasWidth, height)
dc.SetRGB(1, 1, 1)
dc.Clear()
dc.SetFontFace(face)
dc.SetFontFace(*face)
y := padding
renderNode(dc, bodyNode, &y, face)
err = dc.SavePNG(goPath)
y := 0
err = renderNode(dc, canvasWidth, body, &y, *face, workingDir)
if err != nil {
return NewErr(err)
return "", err
}
// PrintReceipt(goPath)
return NewOk(nil)
outPath := path.Join(outDir, uuid.NewString()+".png")
err = dc.SavePNG(outPath)
if err != nil {
return "", err
}
return outPath, nil
}
func GenImg(width int, outputDir, payload, tmpl, workingDir string) string {
result := GenPNG(C.int(width), C.CString(outputDir), C.CString(payload), C.CString(tmpl), C.CString(workingDir))
r := C.GoString(result)
return r
}
var funcMap = template.FuncMap{
"formatNumber": FormatNumber,
"div": Div,
"formatDateFromSec": formatDateFromSec,
"formatDateFromStr": formatDateFromStr,
}
func renderTemplate(tmp string, data map[string]interface{}) (string, error) {
tmpl := template.Must(template.New("mytemplate").Parse(tmp))
tmpl, err := template.New("mytemplate").Funcs(funcMap).Parse(tmp)
if err != nil {
return "", err
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return "", err
@@ -113,34 +145,56 @@ func renderTemplate(tmp string, data map[string]interface{}) (string, error) {
return buf.String(), nil
}
func renderNode(dc *gg.Context, n *html.Node, y *int, face font.Face) {
if n.Type == html.ElementNode {
switch n.Data {
func renderNode(dc *gg.Context, canvasWidth int, n *Node, y *int, face font.Face, workingDir string) error {
before := *y
if n.Style.PaddingTop > 0 {
*y += int(n.Style.PaddingTop)
}
switch n.Tag {
case "h1":
drawTextBlock(dc, getText(n), 28, y, face)
drawTextBlock(dc, n, canvasWidth, eleH1Size, y, face)
case "h2":
drawTextBlock(dc, n, canvasWidth, eleH2Size, y, face)
case "h3":
drawTextBlock(dc, n, canvasWidth, eleH3Size, y, face)
case "p":
drawTextBlock(dc, getText(n), 24, y, face)
size := float64(elePSize)
if n.Style.FontSize > 0 {
size = n.Style.FontSize
}
drawTextBlock(dc, n, canvasWidth, size, y, face)
case "hr":
renderLine(dc, n, canvasWidth, y)
case "img":
drawImage(dc, n, y)
if err := drawImage(dc, n, y, workingDir); err != nil {
return err
}
case "table":
renderTable(dc, n, y, face)
renderTable(dc, canvasWidth, n, y, face)
}
if n.Style.PaddingBottom > 0 {
*y += int(n.Style.PaddingBottom)
}
_ = before
// log.Printf("render %s y, y', height: %d, %d, %d\n", n.Tag, before, *y, *y-before)
for c := n.FirstChild; c != nil; c = c.NextSibling {
renderNode(dc, c, y, face)
for _, c := range n.Children {
renderNode(dc, canvasWidth, c, y, face, workingDir)
}
return nil
}
func drawTextBlock(dc *gg.Context, text string, size float64, y *int, face font.Face) {
func drawTextBlock(dc *gg.Context, n *Node, canvasWidth int, size float64, y *int, face font.Face) {
dc.SetFontFace(face)
lines := wordWrap(dc, text, canvasWidth-padding*2)
padding := n.Style.PaddingLeft + n.Style.PaddingRight
lines := wordWrap(dc, n.Text, canvasWidth-int(padding))
SetFontSize(dc, size)
for _, line := range lines {
dc.SetRGB(0, 0, 0)
dc.DrawString(line, padding, float64(*y))
dc.DrawStringAnchored(line, padding, float64(*y), 0, 0.5)
// dc.DrawString(line, padding, float64(*y))
*y += int(size) + lineGap
}
*y += 5
}