Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat: add /pdf endpoint for page-to-PDF export (#22)

luigiagentb0d559f98287
diff --git a/README.md b/README.md
index bb1471dd..46e0dd0a 100644
--- a/README.md
+++ b/README.md
@@ -215,6 +215,7 @@ In headed mode, log into sites in the visible Chrome window once; cookies and lo
| `GET` | `/tabs` | List open tabs |
| `GET` | `/snapshot` | Accessibility tree (primary interface) |
| `GET` | `/screenshot` | JPEG screenshot (opt-in) |
+| `GET` | `/pdf` | PDF export of current page |
| `GET` | `/text` | Readable page text (readability or raw) |
| `POST` | `/navigate` | Go to URL |
| `POST` | `/action` | Click, type, fill, press, focus, hover, select, scroll |
@@ -248,6 +249,16 @@ In headed mode, log into sites in the visible Chrome window once; cookies and lo
| `noAnimations=true` | Disable CSS animations before capture |
| `output=file` | Save screenshot to disk instead of returning |
+### Query Parameters (pdf)
+| Param | Description |
+|-------|-------------|
+| `tabId` | Target tab (default: first tab) |
+| `landscape=true` | Landscape orientation |
+| `scale=N` | Print scale (default: 1.0) |
+| `raw=true` | Return raw PDF bytes |
+| `output=file` | Save PDF to disk |
+| `path=/custom/path` | Custom file path (with `output=file`) |
+
### Query Parameters (text)
| Param | Description |
|-------|-------------|
diff --git a/internal/handlers/handler_pdf_test.go b/internal/handlers/handler_pdf_test.go
new file mode 100644
index 00000000..d8876db0
--- /dev/null
+++ b/internal/handlers/handler_pdf_test.go
@@ -0,0 +1,29 @@
+package handlers
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestHandlePDF_NoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/pdf", nil)
+ w := httptest.NewRecorder()
+ h.HandlePDF(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Errorf("expected 404, got %d", w.Code)
+ }
+}
+
+func TestHandlePDF_NoTab_WithTabId(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/pdf?tabId=nonexistent", nil)
+ w := httptest.NewRecorder()
+ h.HandlePDF(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Errorf("expected 404, got %d", w.Code)
+ }
+}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 3209c5f5..e24460b3 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -33,6 +33,7 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
mux.HandleFunc("GET /tabs", h.HandleTabs)
mux.HandleFunc("GET /snapshot", h.HandleSnapshot)
mux.HandleFunc("GET /screenshot", h.HandleScreenshot)
+ mux.HandleFunc("GET /pdf", h.HandlePDF)
mux.HandleFunc("GET /text", h.HandleText)
mux.HandleFunc("POST /navigate", h.HandleNavigate)
mux.HandleFunc("POST /action", h.HandleAction)
diff --git a/internal/handlers/media.go b/internal/handlers/media.go
index 79f43bb1..3acfbb92 100644
--- a/internal/handlers/media.go
+++ b/internal/handlers/media.go
@@ -98,6 +98,82 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
})
}
+func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {
+ tabID := r.URL.Query().Get("tabId")
+ output := r.URL.Query().Get("output")
+
+ ctx, _, err := h.Bridge.TabContext(tabID)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+
+ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
+ defer tCancel()
+ go web.CancelOnClientDone(r.Context(), tCancel)
+
+ landscape := r.URL.Query().Get("landscape") == "true"
+ scale := 1.0
+ if s := r.URL.Query().Get("scale"); s != "" {
+ if sn, err := strconv.ParseFloat(s, 64); err == nil && sn > 0 {
+ scale = sn
+ }
+ }
+
+ var buf []byte
+ if err := chromedp.Run(tCtx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ var err error
+ p := page.PrintToPDF().
+ WithPrintBackground(true).
+ WithScale(scale).
+ WithLandscape(landscape)
+ buf, _, err = p.Do(ctx)
+ return err
+ }),
+ ); err != nil {
+ web.Error(w, 500, fmt.Errorf("pdf: %w", err))
+ return
+ }
+
+ if output == "file" {
+ savePath := r.URL.Query().Get("path")
+ if savePath == "" {
+ pdfDir := filepath.Join(h.Config.StateDir, "pdfs")
+ if err := os.MkdirAll(pdfDir, 0755); err != nil {
+ web.Error(w, 500, fmt.Errorf("create pdf dir: %w", err))
+ return
+ }
+ timestamp := time.Now().Format("20060102-150405")
+ savePath = filepath.Join(pdfDir, fmt.Sprintf("page-%s.pdf", timestamp))
+ }
+
+ if err := os.WriteFile(savePath, buf, 0644); err != nil {
+ web.Error(w, 500, fmt.Errorf("write pdf: %w", err))
+ return
+ }
+
+ web.JSON(w, 200, map[string]any{
+ "path": savePath,
+ "size": len(buf),
+ })
+ return
+ }
+
+ if r.URL.Query().Get("raw") == "true" {
+ w.Header().Set("Content-Type", "application/pdf")
+ if _, err := w.Write(buf); err != nil {
+ slog.Error("pdf write", "err", err)
+ }
+ return
+ }
+
+ web.JSON(w, 200, map[string]any{
+ "format": "pdf",
+ "base64": base64.StdEncoding.EncodeToString(buf),
+ })
+}
+
func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
mode := r.URL.Query().Get("mode")
diff --git a/skill/pinchtab/references/api.md b/skill/pinchtab/references/api.md
index 42e3b23b..ea6e1aba 100644
--- a/skill/pinchtab/references/api.md
+++ b/skill/pinchtab/references/api.md
@@ -129,6 +129,24 @@ curl "/text?mode=raw"
Returns `{url, title, text}`. Cheapest option (~1K tokens for most pages).
+## PDF export
+
+```bash
+# Returns base64 JSON
+curl /pdf
+
+# Raw PDF bytes
+curl "/pdf?raw=true" -o page.pdf
+
+# Save to disk
+curl "/pdf?output=file&path=/tmp/page.pdf"
+
+# Landscape with custom scale
+curl "/pdf?landscape=true&scale=0.8&raw=true" -o page.pdf
+```
+
+Wraps `Page.printToPDF`. Prints background graphics by default.
+
## Download files
```bash
diff --git a/tests/TEST-PLAN.md b/tests/TEST-PLAN.md
index bc2c79db..4a96d349 100644
--- a/tests/TEST-PLAN.md
+++ b/tests/TEST-PLAN.md
@@ -143,7 +143,20 @@ Navigate to the test page first: `POST /navigate {"url":"file://<repo>/tests/ass
| UP11 | Bad JSON body | `POST /upload {broken` | 400, parse error |
| UP12 | No tab | `POST /upload {"paths":["tests/assets/test-upload.png"]}` with no tabs | Error |
-### 1.11 Stealth
+### 1.11 PDF Export
+
+| # | Scenario | Steps | Expected |
+|---|----------|-------|----------|
+| PD1 | PDF base64 | Navigate to page, `GET /pdf` | JSON with `format: "pdf"` and `base64` field |
+| PD2 | PDF raw bytes | `GET /pdf?raw=true` | Content-Type `application/pdf`, valid PDF bytes |
+| PD3 | PDF save to file | `GET /pdf?output=file` | JSON with `path` and `size` |
+| PD4 | PDF custom path | `GET /pdf?output=file&path=/tmp/test.pdf` | File written to `/tmp/test.pdf` |
+| PD5 | PDF landscape | `GET /pdf?landscape=true&raw=true` | Valid PDF in landscape |
+| PD6 | PDF scale | `GET /pdf?scale=0.5&raw=true` | Valid PDF with scaled content |
+| PD7 | PDF no tab | `GET /pdf` with no tabs | 404 error |
+| PD8 | PDF specific tab | `GET /pdf?tabId=TAB_ID` | PDF of specified tab |
+
+### 1.12 Stealth
| # | Scenario | Steps | Expected |
|---|----------|-------|----------|
@@ -156,7 +169,7 @@ Navigate to the test page first: `POST /navigate {"url":"file://<repo>/tests/ass
| ST7 | Fingerprint no tab | `POST /fingerprint/rotate {}` with no tabs | Error |
| ST8 | Bot detection site | Navigate to `bot.sannysoft.com` | Most checks pass (green) |
-### 1.12 Configuration
+### 1.13 Configuration
| # | Scenario | Steps | Expected |
|---|----------|-------|----------|
@@ -166,7 +179,7 @@ Navigate to the test page first: `POST /navigate {"url":"file://<repo>/tests/ass
| CF4 | Custom profile dir | `BRIDGE_PROFILE=/tmp/test-profile ./pinchtab` | Uses specified profile |
| CF5 | No restore | `BRIDGE_NO_RESTORE=true ./pinchtab` | Doesn't restore previous tabs |
-### 1.13 Session Persistence
+### 1.14 Session Persistence
| # | Scenario | Steps | Expected |
|---|----------|-------|----------|