package app import ( "bytes" "fmt" "strings" "github.com/ledongthuc/pdf" ) // extractPDFText returns the plain text of an in-memory PDF. Extraction runs // in-process so the service has no runtime dependency on a pdftotext binary // being installed and present on PATH. // // The underlying library panics on malformed or hostile documents, so the // whole extraction is recoverable: a PDF this service cannot parse is // reported as a handled error, never as a crash. func extractPDFText(b []byte) (text string, err error) { defer func() { if recovered := recover(); recovered != nil { text, err = "", failure(422, "PDF_EXTRACTION_FAILED", "pdf text extraction failed") } }() r, err := pdf.NewReader(bytes.NewReader(b), int64(len(b))) if err != nil { return "", failure(422, "PDF_EXTRACTION_FAILED", "pdf text extraction failed") } var sb strings.Builder total := r.NumPage() for i := 1; i <= total; i++ { page := r.Page(i) // Damage is common in real PDFs; a page that cannot be read is // skipped rather than failing the whole document. if page.V.IsNull() { continue } pageText, err := page.GetPlainText(nil) if err != nil { continue } sb.WriteString(pageText) } text = strings.TrimSpace(sb.String()) if text == "" { return "", failure(422, "NO_CONTENT_FOUND", fmt.Sprintf("pdf contains no extractable text (%d pages)", total)) } return text, nil }