Compare commits
3 Commits
05e60cdfe3
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 8ccee3e9ac | |||
| 6bec06c470 | |||
| 22edd37352 |
@@ -15,7 +15,7 @@ RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /zplgfa-web ./cmd/web
|
||||
# ─── Final stage ────────────────────────────────────────────────────────────
|
||||
FROM alpine:3.20
|
||||
|
||||
RUN apk add --no-cache ca-certificates
|
||||
RUN apk add --no-cache ca-certificates poppler-utils
|
||||
|
||||
COPY --from=builder /zplgfa-web /usr/local/bin/zplgfa-web
|
||||
|
||||
|
||||
512
cmd/web/main.go
512
cmd/web/main.go
@@ -7,12 +7,17 @@ import (
|
||||
"image/color"
|
||||
_ "image/gif"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"image/png"
|
||||
"io"
|
||||
"log"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/anthonynsimon/bild/blur"
|
||||
"github.com/anthonynsimon/bild/effect"
|
||||
@@ -24,6 +29,71 @@ import (
|
||||
|
||||
const maxUploadSize = 20 << 20 // 20 MB
|
||||
|
||||
func isPDF(data []byte) bool {
|
||||
return len(data) >= 4 && string(data[:4]) == "%PDF"
|
||||
}
|
||||
|
||||
// pdfPageToImage renders one page of a PDF to an image using pdftoppm.
|
||||
// dpi controls the render resolution (use 150 for thumbnails, 300 for conversion).
|
||||
// Returns the image, total page count, and any error.
|
||||
func pdfPageToImage(data []byte, page, dpi int) (image.Image, int, error) {
|
||||
tmpDir, err := os.MkdirTemp("", "zplgfa-*")
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
pdfPath := filepath.Join(tmpDir, "input.pdf")
|
||||
if err := os.WriteFile(pdfPath, data, 0600); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Get total page count via pdfinfo
|
||||
pageCount := 1
|
||||
if out, err := exec.Command("pdfinfo", pdfPath).Output(); err == nil {
|
||||
for _, line := range strings.Split(string(out), "\n") {
|
||||
if strings.HasPrefix(line, "Pages:") {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(line, "Pages:"))); err == nil {
|
||||
pageCount = n
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if page > pageCount {
|
||||
page = pageCount
|
||||
}
|
||||
|
||||
// Convert the requested page to PNG
|
||||
outBase := filepath.Join(tmpDir, "out")
|
||||
cmd := exec.Command("pdftoppm",
|
||||
"-png",
|
||||
"-r", strconv.Itoa(dpi),
|
||||
"-f", strconv.Itoa(page),
|
||||
"-l", strconv.Itoa(page),
|
||||
pdfPath, outBase)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
return nil, pageCount, fmt.Errorf("pdftoppm: %s", string(out))
|
||||
}
|
||||
|
||||
matches, err := filepath.Glob(filepath.Join(tmpDir, "out-*.png"))
|
||||
if err != nil || len(matches) == 0 {
|
||||
return nil, pageCount, fmt.Errorf("pdftoppm produced no output")
|
||||
}
|
||||
|
||||
f, err := os.Open(matches[0])
|
||||
if err != nil {
|
||||
return nil, pageCount, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
img, _, err := image.Decode(f)
|
||||
return img, pageCount, err
|
||||
}
|
||||
|
||||
func getGraphicType(t string) zplgfa.GraphicType {
|
||||
switch strings.ToUpper(t) {
|
||||
case "ASCII":
|
||||
@@ -109,12 +179,31 @@ func convertHandler(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
img, _, err := image.Decode(file)
|
||||
data, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("cannot decode image: %s", err), http.StatusBadRequest)
|
||||
http.Error(w, "failed to read file", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var img image.Image
|
||||
if isPDF(data) {
|
||||
page := 1
|
||||
if p, e2 := strconv.Atoi(r.FormValue("page")); e2 == nil && p > 0 {
|
||||
page = p
|
||||
}
|
||||
img, _, err = pdfPageToImage(data, page, 300)
|
||||
if err != nil {
|
||||
http.Error(w, "PDF conversion failed: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
img, _, err = image.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("cannot decode image: %s", err), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var w2, h2 uint
|
||||
if v, err := strconv.ParseUint(r.FormValue("width"), 10, 32); err == nil {
|
||||
w2 = uint(v)
|
||||
@@ -154,19 +243,130 @@ func previewHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var buf bytes.Buffer
|
||||
buf.ReadFrom(file)
|
||||
cfg, _, err := image.DecodeConfig(bytes.NewReader(buf.Bytes()))
|
||||
data := buf.Bytes()
|
||||
|
||||
if isPDF(data) {
|
||||
page := 1
|
||||
if p, e2 := strconv.Atoi(r.FormValue("page")); e2 == nil && p > 0 {
|
||||
page = p
|
||||
}
|
||||
img, pageCount, err := pdfPageToImage(data, page, 150)
|
||||
if err != nil {
|
||||
http.Error(w, "PDF conversion failed: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
b := img.Bounds()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, `{"width":%d,"height":%d,"pages":%d,"isPDF":true}`, b.Dx(), b.Dy(), pageCount)
|
||||
return
|
||||
}
|
||||
|
||||
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
http.Error(w, "cannot decode image", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, `{"width":%d,"height":%d}`, cfg.Width, cfg.Height)
|
||||
fmt.Fprintf(w, `{"width":%d,"height":%d,"pages":1,"isPDF":false}`, cfg.Width, cfg.Height)
|
||||
}
|
||||
|
||||
func pageThumbHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if err := r.ParseMultipartForm(maxUploadSize); err != nil {
|
||||
http.Error(w, "file too large", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
file, _, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
http.Error(w, "missing file", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
data, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to read file", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !isPDF(data) {
|
||||
http.Error(w, "not a PDF", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
page := 1
|
||||
if p, e2 := strconv.Atoi(r.FormValue("page")); e2 == nil && p > 0 {
|
||||
page = p
|
||||
}
|
||||
|
||||
img, _, err := pdfPageToImage(data, page, 150)
|
||||
if err != nil {
|
||||
http.Error(w, "PDF conversion failed: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
png.Encode(w, img)
|
||||
}
|
||||
|
||||
var labelaryClient = &http.Client{Timeout: 15 * time.Second}
|
||||
|
||||
func renderHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
dpmm := r.URL.Query().Get("dpmm")
|
||||
width := r.URL.Query().Get("width")
|
||||
height := r.URL.Query().Get("height")
|
||||
if dpmm == "" {
|
||||
dpmm = "8"
|
||||
}
|
||||
if width == "" {
|
||||
width = "4"
|
||||
}
|
||||
if height == "" {
|
||||
height = "6"
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to read body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("http://api.labelary.com/v1/printers/%s/labels/%sx%s/0/", dpmm, width, height)
|
||||
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
http.Error(w, "failed to build request", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "image/png")
|
||||
|
||||
resp, err := labelaryClient.Do(req)
|
||||
if err != nil {
|
||||
http.Error(w, "labelary unreachable: "+err.Error(), http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
http.Error(w, "labelary returned "+resp.Status, http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
io.Copy(w, resp.Body)
|
||||
}
|
||||
|
||||
func main() {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/convert", convertHandler)
|
||||
mux.HandleFunc("/preview", previewHandler)
|
||||
mux.HandleFunc("/page-thumb", pageThumbHandler)
|
||||
mux.HandleFunc("/render", renderHandler)
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(indexHTML))
|
||||
@@ -223,6 +423,7 @@ const indexHTML = `<!DOCTYPE html>
|
||||
.preview-info { margin-top: 0.75rem; font-size: 0.8rem; color: #a0aec0; min-height: 1.2em; }
|
||||
|
||||
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1rem; }
|
||||
.grid3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 1rem; margin-bottom: 1rem; }
|
||||
label { display: block; font-size: 0.8rem; font-weight: 600; color: #a0aec0; margin-bottom: 0.35rem; }
|
||||
input[type=number], select {
|
||||
width: 100%;
|
||||
@@ -237,6 +438,22 @@ const indexHTML = `<!DOCTYPE html>
|
||||
}
|
||||
input[type=number]:focus, select:focus { border-color: #6366f1; }
|
||||
|
||||
/* unit toggle */
|
||||
.unit-row {
|
||||
display: flex; align-items: center; gap: 0.5rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
.unit-row span { font-size: 0.8rem; color: #a0aec0; font-weight: 600; }
|
||||
.toggle-group { display: flex; border: 1px solid #3a4060; border-radius: 6px; overflow: hidden; }
|
||||
.toggle-group button {
|
||||
flex: 1; background: #252a3d; color: #a0aec0;
|
||||
border: none; border-radius: 0; padding: 0.3rem 0.8rem;
|
||||
font-size: 0.8rem; font-weight: 600; cursor: pointer; width: auto;
|
||||
transition: background .15s, color .15s;
|
||||
}
|
||||
.toggle-group button.active { background: #6366f1; color: #fff; }
|
||||
.sub-label { font-size: 0.7rem; color: #718096; font-weight: 400; margin-top: 0.15rem; }
|
||||
|
||||
.checks { display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 1.5rem; }
|
||||
.checks label {
|
||||
display: flex; align-items: center; gap: 0.4rem;
|
||||
@@ -264,10 +481,7 @@ const indexHTML = `<!DOCTYPE html>
|
||||
button:hover { background: #4f52d0; }
|
||||
button:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
|
||||
.output {
|
||||
margin-top: 1.5rem;
|
||||
display: none;
|
||||
}
|
||||
.output { margin-top: 1.5rem; display: none; }
|
||||
.output-header {
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
margin-bottom: 0.5rem;
|
||||
@@ -285,12 +499,37 @@ const indexHTML = `<!DOCTYPE html>
|
||||
color: #7dd3fc; font-family: monospace; font-size: 0.75rem;
|
||||
padding: 0.75rem; resize: vertical; outline: none;
|
||||
}
|
||||
.dl-btn {
|
||||
margin-top: 0.75rem;
|
||||
background: #2d6a4f;
|
||||
}
|
||||
.dl-btn { margin-top: 0.75rem; background: #2d6a4f; }
|
||||
.dl-btn:hover { background: #215040; }
|
||||
.error { color: #fc8181; font-size: 0.85rem; margin-top: 0.75rem; display: none; }
|
||||
|
||||
/* previews */
|
||||
.preview-panel {
|
||||
margin-bottom: 1.5rem; display: none;
|
||||
}
|
||||
.preview-panel .panel-header {
|
||||
font-size: 0.8rem; font-weight: 600; color: #a0aec0; margin-bottom: 0.5rem;
|
||||
}
|
||||
.preview-panel img {
|
||||
max-width: 100%; max-height: 260px; object-fit: contain;
|
||||
border-radius: 6px; border: 1px solid #2d3348; background: #fff;
|
||||
display: block;
|
||||
}
|
||||
.preview-panel .panel-meta {
|
||||
font-size: 0.75rem; color: #718096; margin-top: 0.35rem;
|
||||
}
|
||||
.label-preview-wrap {
|
||||
margin-top: 1.25rem; display: none;
|
||||
}
|
||||
.label-preview-wrap .panel-header {
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
font-size: 0.8rem; font-weight: 600; color: #a0aec0; margin-bottom: 0.5rem;
|
||||
}
|
||||
.label-preview-wrap img {
|
||||
max-width: 100%; border-radius: 6px; border: 1px solid #2d3348;
|
||||
background: #fff; display: block;
|
||||
}
|
||||
.render-status { font-size: 0.75rem; color: #718096; font-weight: 400; }
|
||||
.spinner {
|
||||
display: none; width: 18px; height: 18px;
|
||||
border: 2px solid #ffffff40; border-top-color: #fff;
|
||||
@@ -306,21 +545,54 @@ const indexHTML = `<!DOCTYPE html>
|
||||
<p class="subtitle">Convert images to ZPL Graphic Fields for Zebra label printers</p>
|
||||
|
||||
<div class="drop-zone" id="dropZone">
|
||||
<input type="file" id="fileInput" accept="image/png,image/jpeg,image/gif">
|
||||
<input type="file" id="fileInput" accept="image/png,image/jpeg,image/gif,application/pdf,.pdf">
|
||||
<div class="icon">🖼️</div>
|
||||
<div>Drop an image here or <strong>click to browse</strong></div>
|
||||
<div class="hint">PNG, JPEG, GIF — max 20 MB</div>
|
||||
<div class="hint">PNG, JPEG, GIF, PDF — max 20 MB</div>
|
||||
<div class="preview-info" id="previewInfo"></div>
|
||||
</div>
|
||||
|
||||
<!-- PDF page selector (shown only for PDFs) -->
|
||||
<div id="pdfPageRow" style="display:none; margin-bottom:1rem;">
|
||||
<label for="pdfPage">PDF Page <span id="pdfPageMax" style="font-weight:400;color:#718096"></span></label>
|
||||
<div style="display:flex; gap:0.5rem; align-items:center;">
|
||||
<input type="number" id="pdfPage" min="1" value="1" style="width:100px">
|
||||
<button id="pdfPageBtn" style="width:auto;padding:0.45rem 1rem;font-size:0.85rem;">Load Page</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Image preview (original) -->
|
||||
<div class="preview-panel" id="imgPreviewPanel">
|
||||
<div class="panel-header">Image Preview</div>
|
||||
<img id="imgPreviewEl" alt="preview">
|
||||
<div class="panel-meta" id="imgPreviewMeta"></div>
|
||||
</div>
|
||||
|
||||
<!-- Unit toggle + DPI -->
|
||||
<div class="unit-row">
|
||||
<span>Dimensions in</span>
|
||||
<div class="toggle-group">
|
||||
<button id="btnPx" class="active" onclick="setUnit('px')">px</button>
|
||||
<button id="btnCm" onclick="setUnit('cm')">cm</button>
|
||||
</div>
|
||||
<span style="margin-left:auto">Printer DPI</span>
|
||||
<select id="dpi" style="width:110px">
|
||||
<option value="203" selected>203 dpi</option>
|
||||
<option value="300">300 dpi</option>
|
||||
<option value="600">600 dpi</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<div>
|
||||
<label for="width">Width (px) <span style="font-weight:400;color:#718096">0 = auto</span></label>
|
||||
<input type="number" id="width" min="0" value="0" placeholder="0">
|
||||
<label id="labelW">Width (px)</label>
|
||||
<input type="number" id="width" min="0" step="1" value="0" placeholder="0">
|
||||
<div class="sub-label" id="subW"></div>
|
||||
</div>
|
||||
<div>
|
||||
<label for="height">Height (px) <span style="font-weight:400;color:#718096">0 = auto</span></label>
|
||||
<input type="number" id="height" min="0" value="0" placeholder="0">
|
||||
<label id="labelH">Height (px)</label>
|
||||
<input type="number" id="height" min="0" step="1" value="0" placeholder="0">
|
||||
<div class="sub-label" id="subH"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -354,6 +626,15 @@ const indexHTML = `<!DOCTYPE html>
|
||||
</div>
|
||||
<textarea id="zplOutput" readonly></textarea>
|
||||
<button class="dl-btn" id="dlBtn">⬇ Download .zpl</button>
|
||||
|
||||
<!-- Labelary rendered preview -->
|
||||
<div class="label-preview-wrap" id="labelPreviewWrap">
|
||||
<div class="panel-header">
|
||||
<span>Label Preview <span style="font-weight:400;color:#718096">(rendered by Labelary)</span></span>
|
||||
<span class="render-status" id="renderStatus"></span>
|
||||
</div>
|
||||
<img id="labelPreviewImg" alt="label preview">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -366,7 +647,72 @@ const spinner = document.getElementById('spinner');
|
||||
const output = document.getElementById('output');
|
||||
const zplOutput = document.getElementById('zplOutput');
|
||||
const errorEl = document.getElementById('error');
|
||||
|
||||
let selectedFile = null;
|
||||
let currentUnit = 'px'; // 'px' or 'cm'
|
||||
let origPxW = 0, origPxH = 0; // image native pixel dimensions
|
||||
let imgObjectURL = null;
|
||||
let fileIsPDF = false;
|
||||
let pdfPageCount = 1;
|
||||
|
||||
function getDPI() { return parseInt(document.getElementById('dpi').value, 10); }
|
||||
|
||||
// cm ↔ px helpers
|
||||
function pxToCm(px) { return +(px * 2.54 / getDPI()).toFixed(3); }
|
||||
function cmToPx(cm) { return Math.round(cm * getDPI() / 2.54); }
|
||||
|
||||
function setUnit(unit) {
|
||||
const wEl = document.getElementById('width');
|
||||
const hEl = document.getElementById('height');
|
||||
const curW = parseFloat(wEl.value) || 0;
|
||||
const curH = parseFloat(hEl.value) || 0;
|
||||
|
||||
if (unit === 'cm' && currentUnit === 'px') {
|
||||
wEl.step = '0.01';
|
||||
hEl.step = '0.01';
|
||||
wEl.value = curW > 0 ? pxToCm(curW) : 0;
|
||||
hEl.value = curH > 0 ? pxToCm(curH) : 0;
|
||||
} else if (unit === 'px' && currentUnit === 'cm') {
|
||||
wEl.step = '1';
|
||||
hEl.step = '1';
|
||||
wEl.value = curW > 0 ? cmToPx(curW) : 0;
|
||||
hEl.value = curH > 0 ? cmToPx(curH) : 0;
|
||||
}
|
||||
currentUnit = unit;
|
||||
document.getElementById('btnPx').classList.toggle('active', unit === 'px');
|
||||
document.getElementById('btnCm').classList.toggle('active', unit === 'cm');
|
||||
updateLabels();
|
||||
}
|
||||
|
||||
function updateLabels() {
|
||||
const unit = currentUnit;
|
||||
document.getElementById('labelW').textContent = 'Width (' + unit + ')' + (unit === 'px' ? ' — 0 = auto' : '');
|
||||
document.getElementById('labelH').textContent = 'Height (' + unit + ')' + (unit === 'px' ? ' — 0 = auto' : '');
|
||||
updateSubLabels();
|
||||
}
|
||||
|
||||
function updateSubLabels() {
|
||||
if (!origPxW) return;
|
||||
if (currentUnit === 'px') {
|
||||
document.getElementById('subW').textContent = pxToCm(origPxW) + ' cm at ' + getDPI() + ' dpi';
|
||||
document.getElementById('subH').textContent = pxToCm(origPxH) + ' cm at ' + getDPI() + ' dpi';
|
||||
} else {
|
||||
document.getElementById('subW').textContent = origPxW + ' px native';
|
||||
document.getElementById('subH').textContent = origPxH + ' px native';
|
||||
}
|
||||
}
|
||||
|
||||
// Recalc sub-labels when DPI changes
|
||||
document.getElementById('dpi').addEventListener('change', () => {
|
||||
if (currentUnit === 'cm') {
|
||||
// re-fill cm fields based on original px
|
||||
if (origPxW) {
|
||||
document.getElementById('width').value = pxToCm(origPxW);
|
||||
document.getElementById('height').value = pxToCm(origPxH);
|
||||
}
|
||||
}
|
||||
updateSubLabels();
|
||||
});
|
||||
|
||||
dropZone.addEventListener('click', () => fileInput.click());
|
||||
dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('over'); });
|
||||
@@ -382,16 +728,53 @@ function setFile(file) {
|
||||
selectedFile = file;
|
||||
previewInfo.textContent = 'Loading…';
|
||||
convertBtn.disabled = true;
|
||||
fileIsPDF = file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf');
|
||||
|
||||
// For non-PDFs show the image immediately; for PDFs we wait for the server thumb
|
||||
if (!fileIsPDF) {
|
||||
if (imgObjectURL) URL.revokeObjectURL(imgObjectURL);
|
||||
imgObjectURL = URL.createObjectURL(file);
|
||||
document.getElementById('imgPreviewEl').src = imgObjectURL;
|
||||
document.getElementById('imgPreviewPanel').style.display = 'block';
|
||||
}
|
||||
document.getElementById('pdfPageRow').style.display = fileIsPDF ? 'block' : 'none';
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('file', file);
|
||||
fetch('/preview', { method: 'POST', body: fd })
|
||||
.then(r => r.ok ? r.json() : Promise.reject())
|
||||
.then(info => {
|
||||
previewInfo.textContent = file.name + ' — ' + info.width + ' × ' + info.height + ' px';
|
||||
// Pre-fill dimensions
|
||||
document.getElementById('width').value = info.width;
|
||||
document.getElementById('height').value = info.height;
|
||||
origPxW = info.width;
|
||||
origPxH = info.height;
|
||||
|
||||
if (info.isPDF) {
|
||||
pdfPageCount = info.pages;
|
||||
document.getElementById('pdfPageMax').textContent = '(1 – ' + info.pages + ')';
|
||||
document.getElementById('pdfPage').max = info.pages;
|
||||
document.getElementById('pdfPage').value = 1;
|
||||
loadPDFPageThumb(1);
|
||||
}
|
||||
|
||||
const wEl = document.getElementById('width');
|
||||
const hEl = document.getElementById('height');
|
||||
if (currentUnit === 'px') {
|
||||
wEl.value = origPxW;
|
||||
hEl.value = origPxH;
|
||||
} else {
|
||||
wEl.value = pxToCm(origPxW);
|
||||
hEl.value = pxToCm(origPxH);
|
||||
}
|
||||
|
||||
const cmW = pxToCm(origPxW), cmH = pxToCm(origPxH);
|
||||
const pageInfo = info.isPDF ? ' — ' + info.pages + ' page' + (info.pages !== 1 ? 's' : '') : '';
|
||||
previewInfo.textContent =
|
||||
file.name + pageInfo + ' — ' + origPxW + ' × ' + origPxH + ' px' +
|
||||
' (' + cmW + ' × ' + cmH + ' cm at ' + getDPI() + ' dpi)';
|
||||
|
||||
document.getElementById('imgPreviewMeta').textContent =
|
||||
origPxW + ' × ' + origPxH + ' px | ' + cmW + ' × ' + cmH + ' cm at ' + getDPI() + ' dpi';
|
||||
|
||||
updateSubLabels();
|
||||
convertBtn.disabled = false;
|
||||
})
|
||||
.catch(() => {
|
||||
@@ -400,20 +783,95 @@ function setFile(file) {
|
||||
});
|
||||
}
|
||||
|
||||
async function loadPDFPageThumb(page) {
|
||||
if (!selectedFile) return;
|
||||
const fd = new FormData();
|
||||
fd.append('file', selectedFile);
|
||||
fd.append('page', page);
|
||||
document.getElementById('imgPreviewPanel').style.display = 'block';
|
||||
document.getElementById('imgPreviewMeta').textContent = 'Loading page ' + page + '…';
|
||||
try {
|
||||
const res = await fetch('/page-thumb', { method: 'POST', body: fd });
|
||||
if (!res.ok) throw new Error(await res.text());
|
||||
const blob = await res.blob();
|
||||
if (imgObjectURL) URL.revokeObjectURL(imgObjectURL);
|
||||
imgObjectURL = URL.createObjectURL(blob);
|
||||
document.getElementById('imgPreviewEl').src = imgObjectURL;
|
||||
const cmW = pxToCm(origPxW), cmH = pxToCm(origPxH);
|
||||
document.getElementById('imgPreviewMeta').textContent =
|
||||
'Page ' + page + ' — ' + origPxW + ' × ' + origPxH + ' px | ' + cmW + ' × ' + cmH + ' cm at ' + getDPI() + ' dpi';
|
||||
} catch(e) {
|
||||
document.getElementById('imgPreviewMeta').textContent = 'Preview failed: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('pdfPageBtn').addEventListener('click', () => {
|
||||
const page = parseInt(document.getElementById('pdfPage').value, 10) || 1;
|
||||
loadPDFPageThumb(page);
|
||||
});
|
||||
|
||||
// Returns pixel values regardless of current unit
|
||||
function getPixelDimensions() {
|
||||
const w = parseFloat(document.getElementById('width').value) || 0;
|
||||
const h = parseFloat(document.getElementById('height').value) || 0;
|
||||
if (currentUnit === 'cm') {
|
||||
return { w: cmToPx(w), h: cmToPx(h) };
|
||||
}
|
||||
return { w: Math.round(w), h: Math.round(h) };
|
||||
}
|
||||
|
||||
function dpmmFromDPI(dpi) {
|
||||
const map = { 203: 8, 300: 12, 600: 24 };
|
||||
return map[dpi] || 8;
|
||||
}
|
||||
|
||||
async function fetchLabelPreview(zpl, pxW, pxH) {
|
||||
const dpi = getDPI();
|
||||
const dpmm = dpmmFromDPI(dpi);
|
||||
// Labelary needs label size in inches; clamp minimum to avoid API errors
|
||||
const wIn = Math.max(pxW / dpi, 0.1).toFixed(4);
|
||||
const hIn = Math.max(pxH / dpi, 0.1).toFixed(4);
|
||||
|
||||
const wrap = document.getElementById('labelPreviewWrap');
|
||||
const status = document.getElementById('renderStatus');
|
||||
wrap.style.display = 'block';
|
||||
status.textContent = 'Rendering…';
|
||||
document.getElementById('labelPreviewImg').src = '';
|
||||
|
||||
try {
|
||||
const res = await fetch(
|
||||
'/render?dpmm=' + dpmm + '&width=' + wIn + '&height=' + hIn,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: zpl }
|
||||
);
|
||||
if (!res.ok) throw new Error(await res.text());
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
document.getElementById('labelPreviewImg').src = url;
|
||||
status.textContent = wIn + '" × ' + hIn + '" at ' + dpi + ' dpi';
|
||||
} catch (e) {
|
||||
status.textContent = 'Preview unavailable: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
convertBtn.addEventListener('click', async () => {
|
||||
if (!selectedFile) return;
|
||||
errorEl.style.display = 'none';
|
||||
convertBtn.style.display = 'none';
|
||||
spinner.style.display = 'block';
|
||||
output.style.display = 'none';
|
||||
document.getElementById('labelPreviewWrap').style.display = 'none';
|
||||
|
||||
const { w, h } = getPixelDimensions();
|
||||
const edits = [...document.querySelectorAll('input[name=edit]:checked')].map(c => c.value);
|
||||
const fd = new FormData();
|
||||
fd.append('file', selectedFile);
|
||||
fd.append('width', document.getElementById('width').value);
|
||||
fd.append('height', document.getElementById('height').value);
|
||||
fd.append('width', w);
|
||||
fd.append('height', h);
|
||||
fd.append('type', document.getElementById('enctype').value);
|
||||
fd.append('edit', edits.join(','));
|
||||
if (fileIsPDF) {
|
||||
fd.append('page', document.getElementById('pdfPage').value || '1');
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('/convert', { method: 'POST', body: fd });
|
||||
@@ -424,6 +882,7 @@ convertBtn.addEventListener('click', async () => {
|
||||
const text = await res.text();
|
||||
zplOutput.value = text;
|
||||
output.style.display = 'block';
|
||||
fetchLabelPreview(text, w || origPxW, h || origPxH);
|
||||
} catch (e) {
|
||||
errorEl.textContent = 'Error: ' + e.message;
|
||||
errorEl.style.display = 'block';
|
||||
@@ -446,6 +905,9 @@ document.getElementById('dlBtn').addEventListener('click', () => {
|
||||
a.download = (selectedFile ? selectedFile.name.replace(/\.[^.]+$/, '') : 'label') + '.zpl';
|
||||
a.click();
|
||||
});
|
||||
|
||||
// init labels
|
||||
updateLabels();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user