Skip to content

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

feat: export audit report as pdf via existing printtopdf

Luigi Agostif7a60256e9de
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index b2027828..f7a38984 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -364,7 +364,7 @@ func configureBrowserFlags() {
auditCmd.Flags().Bool("json", false, "Print the full report JSON to stdout")
auditCmd.Flags().String("seaportal-report", "", "Audit pages from a SeaPortal results JSON file (array of Result objects)")
auditCmd.Flags().Bool("enrich-all", false, "Browser-enrich every seaportal page, ignoring browserRecommended routing")
- auditCmd.Flags().String("format", "json", "Report format: json, md, or html (md/html written next to report.json, or printed without --output-dir)")
+ auditCmd.Flags().String("format", "json", "Report format: json, md, html, or pdf (pdf needs --output-dir and the evaluate capability; on print failure report.json is still written and the exit code is non-zero)")
auditCmd.Flags().StringArray("cookie", nil, "Inject a cookie as name=value before the run (repeatable; the cookie jar is cleared afterwards)")
auditCmd.Flags().String("cookies-file", "", "Inject cookies from a JSON array of {name, value, domain, ...} objects")
auditCmd.Flags().String("profile", "", "Run against the instance of this browser profile")
diff --git a/internal/audit/report/html.go b/internal/audit/report/html.go
index 4b1bb623..2221635b 100644
--- a/internal/audit/report/html.go
+++ b/internal/audit/report/html.go
@@ -30,6 +30,10 @@ var htmlTemplate = template.Must(template.New("report").Funcs(template.FuncMap{
"formatCLS": formatCLS,
"sortedKeys": sortedKeys,
"pageErrors": pageConsoleErrors,
+ // Screenshot sources are our own artifact paths or data: URIs built by
+ // BuildPDFHTML, so they are trusted; html/template would otherwise
+ // reject data: URLs.
+ "safeURL": func(s string) template.URL { return template.URL(s) },
}).Parse(`<!doctype html>
<html lang="en">
<head>
@@ -91,7 +95,7 @@ var htmlTemplate = template.Must(template.New("report").Funcs(template.FuncMap{
{{end}}</ol>{{end}}
{{if .Screenshots}}<h2>Screenshots</h2>
-{{range .R.Pages}}{{if .Browser.ScreenshotPath}}<h3>{{pageLabel .}}</h3><img class="screenshot" src="{{.Browser.ScreenshotPath}}" alt="Screenshot of {{pageLabel .}}">{{end}}{{end}}{{end}}
+{{range .R.Pages}}{{if .Browser.ScreenshotPath}}<h3>{{pageLabel .}}</h3><img class="screenshot" src="{{safeURL .Browser.ScreenshotPath}}" alt="Screenshot of {{pageLabel .}}">{{end}}{{end}}{{end}}
</body>
</html>
`))
diff --git a/internal/audit/report/pdf.go b/internal/audit/report/pdf.go
new file mode 100644
index 00000000..fa74be59
--- /dev/null
+++ b/internal/audit/report/pdf.go
@@ -0,0 +1,58 @@
+package report
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+
+ "github.com/pinchtab/pinchtab/internal/audit"
+)
+
+// FormatPDF selects PDF export on the audit/compare CLIs. Rendering goes
+// through a PDFPrinter (a browser tab printing the HTML report), so it is
+// wired by the caller rather than Render.
+const FormatPDF = "pdf"
+
+// PDFPrinter renders self-contained HTML in a browser and returns the PDF
+// bytes. The CLI wires this through the running pinchtab server: a fresh
+// tab, content injected via the evaluate capability, printed with GET /pdf.
+type PDFPrinter func(html []byte) ([]byte, error)
+
+var pdfMagic = []byte("%PDF")
+
+// BuildPDFHTML renders the report HTML for printing. Inline screenshots are
+// embedded as data: URIs so the printed document needs no filesystem or
+// network access. The input report is not mutated.
+func BuildPDFHTML(r audit.AuditReport) ([]byte, error) {
+ pages := make([]audit.PageResult, len(r.Pages))
+ copy(pages, r.Pages)
+ for i := range pages {
+ if pages[i].Screenshot != "" {
+ pages[i].Browser.ScreenshotPath = "data:image/png;base64," + pages[i].Screenshot
+ }
+ }
+ r.Pages = pages
+ return Render(r, FormatHTML)
+}
+
+// ExportPDF builds the printable HTML report and prints it through printer.
+// Graceful-degradation contract (documented on the CLI help): callers write
+// report.json before attempting the PDF, surface any error here as a
+// warning, and exit non-zero only when pdf was the sole requested format.
+func ExportPDF(r audit.AuditReport, printer PDFPrinter) ([]byte, error) {
+ if printer == nil {
+ return nil, errors.New("no PDF printer available")
+ }
+ html, err := BuildPDFHTML(r)
+ if err != nil {
+ return nil, err
+ }
+ pdf, err := printer(html)
+ if err != nil {
+ return nil, err
+ }
+ if !bytes.HasPrefix(pdf, pdfMagic) {
+ return nil, fmt.Errorf("printer returned %d bytes that are not a PDF document", len(pdf))
+ }
+ return pdf, nil
+}
diff --git a/internal/audit/report/pdf_test.go b/internal/audit/report/pdf_test.go
new file mode 100644
index 00000000..2f386239
--- /dev/null
+++ b/internal/audit/report/pdf_test.go
@@ -0,0 +1,58 @@
+package report
+
+import (
+ "errors"
+ "strings"
+ "testing"
+)
+
+func TestBuildPDFHTMLEmbedsScreenshots(t *testing.T) {
+ r := sampleReport()
+ r.Pages[0].Screenshot = "aW1hZ2U="
+ r.Pages[0].Browser.ScreenshotPath = "screenshots/page-001.png"
+
+ html, err := BuildPDFHTML(r)
+ if err != nil {
+ t.Fatalf("BuildPDFHTML: %v", err)
+ }
+ if !strings.Contains(string(html), `src="data:image/png;base64,aW1hZ2U="`) {
+ t.Error("screenshot should be embedded as a data URI")
+ }
+ if r.Pages[0].Browser.ScreenshotPath != "screenshots/page-001.png" {
+ t.Error("BuildPDFHTML must not mutate the input report")
+ }
+}
+
+func TestExportPDFSuccess(t *testing.T) {
+ var printed []byte
+ pdf, err := ExportPDF(sampleReport(), func(html []byte) ([]byte, error) {
+ printed = html
+ return []byte("%PDF-1.7 fake"), nil
+ })
+ if err != nil {
+ t.Fatalf("ExportPDF: %v", err)
+ }
+ if len(pdf) == 0 || !strings.HasPrefix(string(pdf), "%PDF") {
+ t.Errorf("pdf = %q", pdf)
+ }
+ if !strings.Contains(string(printed), "<h1>Site Audit Report</h1>") {
+ t.Error("printer should receive the rendered HTML report")
+ }
+}
+
+func TestExportPDFFailurePaths(t *testing.T) {
+ if _, err := ExportPDF(sampleReport(), nil); err == nil {
+ t.Error("nil printer should error")
+ }
+
+ wantErr := errors.New("evaluate capability disabled")
+ if _, err := ExportPDF(sampleReport(), func([]byte) ([]byte, error) { return nil, wantErr }); !errors.Is(err, wantErr) {
+ t.Errorf("printer error = %v, want %v", err, wantErr)
+ }
+
+ if _, err := ExportPDF(sampleReport(), func([]byte) ([]byte, error) { return []byte("<html>not a pdf"), nil }); err == nil {
+ t.Error("non-PDF bytes should error")
+ } else if !strings.Contains(err.Error(), "not a PDF") {
+ t.Errorf("magic-bytes error should be clear, got %v", err)
+ }
+}
diff --git a/internal/cli/actions/actions_audit.go b/internal/cli/actions/actions_audit.go
index 9eefd887..be2e9490 100644
--- a/internal/cli/actions/actions_audit.go
+++ b/internal/cli/actions/actions_audit.go
@@ -4,7 +4,9 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
+ "io"
"net/http"
+ "net/url"
"os"
"path/filepath"
"strings"
@@ -185,17 +187,28 @@ func Audit(client *http.Client, base, token string, cmd *cobra.Command, target s
format := renderFormat(cmd)
if dir, _ := cmd.Flags().GetString("output-dir"); dir != "" {
+ var typedForPDF audit.AuditReport
+ if format == auditreport.FormatPDF {
+ // Captured before artifact writing strips the inline screenshots.
+ typedForPDF = typedAuditReport(report)
+ }
if err := writeAuditArtifacts(dir, report); err != nil {
fmt.Fprintf(os.Stderr, "write artifacts: %v\n", err)
os.Exit(1)
}
- if format != auditreport.FormatJSON {
+ switch {
+ case format == auditreport.FormatPDF:
+ exportAuditPDF(client, base, token, dir, typedForPDF)
+ case format != auditreport.FormatJSON:
if err := renderAuditReportFile(dir, report, format); err != nil {
fmt.Fprintf(os.Stderr, "render report: %v\n", err)
os.Exit(1)
}
}
fmt.Fprintf(os.Stderr, "report written to %s\n", filepath.Join(dir, "report.json"))
+ } else if format == auditreport.FormatPDF {
+ fmt.Fprintln(os.Stderr, "--format pdf requires --output-dir")
+ os.Exit(1)
} else if format != auditreport.FormatJSON {
rendered, err := auditreport.Render(typedAuditReport(report), format)
if err != nil {
@@ -232,6 +245,72 @@ func typedAuditReport(report map[string]any) audit.AuditReport {
return typed
}
+// exportAuditPDF prints the report to <dir>/report.pdf through the server.
+// Graceful-degradation contract: report.json is already on disk by the time
+// this runs; a print failure surfaces as a warning and a non-zero exit
+// (pdf being the sole requested format).
+func exportAuditPDF(client *http.Client, base, token, dir string, report audit.AuditReport) {
+ pdf, err := auditreport.ExportPDF(report, serverPDFPrinter(client, base, token))
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "warning: PDF export failed: %v (report.json was still written)\n", err)
+ os.Exit(1)
+ }
+ path := filepath.Join(dir, "report.pdf")
+ if err := os.WriteFile(path, pdf, 0o644); err != nil {
+ fmt.Fprintf(os.Stderr, "warning: write %s: %v (report.json was still written)\n", path, err)
+ os.Exit(1)
+ }
+}
+
+// serverPDFPrinter prints self-contained HTML through the running server:
+// a fresh tab, content injected via the evaluate capability, exported with
+// GET /pdf.
+func serverPDFPrinter(client *http.Client, base, token string) auditreport.PDFPrinter {
+ return func(html []byte) ([]byte, error) {
+ status, _, tab := apiclient.DoPostQuietWithStatus(client, base, token, "/tab", map[string]any{"action": "new"})
+ tabID, _ := tab["tabId"].(string)
+ if status >= 400 || tabID == "" {
+ return nil, fmt.Errorf("create print tab: HTTP %d", status)
+ }
+ defer func() {
+ _, _, _ = apiclient.DoPostQuietWithStatus(client, base, token, "/close", map[string]any{"tabId": tabID})
+ }()
+
+ doc, _ := json.Marshal(string(html))
+ status, body, _ := apiclient.DoPostQuietWithStatus(client, base, token, "/evaluate", map[string]any{
+ "tabId": tabID,
+ "expression": fmt.Sprintf("document.open(); document.write(%s); document.close(); true", doc),
+ })
+ if status >= 400 {
+ return nil, fmt.Errorf("inject report HTML (requires the evaluate capability): HTTP %d: %s", status, strings.TrimSpace(string(body)))
+ }
+ return fetchRawPDF(client, base, token, tabID)
+ }
+}
+
+func fetchRawPDF(client *http.Client, base, token, tabID string) ([]byte, error) {
+ req, err := http.NewRequest(http.MethodGet, base+"/pdf?raw=true&tabId="+url.QueryEscape(tabID), nil)
+ if err != nil {
+ return nil, err
+ }
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("print pdf: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ data, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, fmt.Errorf("read pdf: %w", err)
+ }
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("print pdf: HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(data)))
+ }
+ return data, nil
+}
+
// renderAuditReportFile writes report.md / report.html next to report.json.
func renderAuditReportFile(dir string, report map[string]any, format string) error {
rendered, err := auditreport.Render(typedAuditReport(report), format)
diff --git a/tests/e2e/scenarios/cli/audit-pdf-extended.sh b/tests/e2e/scenarios/cli/audit-pdf-extended.sh
new file mode 100755
index 00000000..64666787
--- /dev/null
+++ b/tests/e2e/scenarios/cli/audit-pdf-extended.sh
@@ -0,0 +1,43 @@
+#!/bin/bash
+# audit-pdf-extended.sh — pinchtab audit --format pdf export.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../../helpers/cli.sh"
+
+OUT_DIR=$(mktemp -d /tmp/audit-pdf.XXXXXX)
+
+# ─────────────────────────────────────────────────────────────────
+start_test "audit --format pdf writes a real report.pdf"
+
+pt_ok audit "http://fixtures/audit-site/index.html" --output-dir "$OUT_DIR" --format pdf
+
+if [ -f "$OUT_DIR/report.json" ]; then
+ pass_assert "report.json exists"
+else
+ fail_assert "report.json exists"
+fi
+
+PDF="$OUT_DIR/report.pdf"
+if [ -f "$PDF" ]; then
+ pass_assert "report.pdf exists"
+else
+ fail_assert "report.pdf exists"
+fi
+
+MAGIC=$(head -c 4 "$PDF" 2>/dev/null)
+if [ "$MAGIC" = "%PDF" ]; then
+ pass_assert "report.pdf starts with %PDF magic bytes"
+else
+ fail_assert "report.pdf starts with %PDF magic bytes (got: $MAGIC)"
+fi
+
+SIZE=$(wc -c < "$PDF" | tr -d ' ')
+if [ "$SIZE" -gt 10240 ]; then
+ pass_assert "report.pdf is > 10KB ($SIZE bytes)"
+else
+ fail_assert "report.pdf is > 10KB (got: $SIZE bytes)"
+fi
+
+end_test
+
+rm -rf "$OUT_DIR"