okami.mom/web-extract-go
git clone https://git.nkp.pet/okami.mom/web-extract-go
5a90548
main
1package app 2 3import ( 4"bytes" 5"fmt" 6"strings" 7 8"github.com/ledongthuc/pdf" 9) 10 11// extractPDFText returns the plain text of an in-memory PDF. Extraction runs 12// in-process so the service has no runtime dependency on a pdftotext binary 13// being installed and present on PATH. 14// 15// The underlying library panics on malformed or hostile documents, so the 16// whole extraction is recoverable: a PDF this service cannot parse is 17// reported as a handled error, never as a crash. 18func extractPDFText (b []byte ) (text string ,err error ) { 19defer func () { 20if recovered := recover ();recovered != nil { 21text ,err = "" ,failure (422 ,"PDF_EXTRACTION_FAILED" ,"pdf text extraction failed" ) 22 } 23 }() 24r ,err := NewReader (bytes .NewReader (b ),int64 (len (b ))) 25if err != nil { 26return "" ,failure (422 ,"PDF_EXTRACTION_FAILED" ,"pdf text extraction failed" ) 27 } 28var sb strings.Builder 29total := r .NumPage () 30for i := 1 ;i <= total ;i ++ { 31page := r .Page (i ) 32// Damage is common in real PDFs; a page that cannot be read is 33// skipped rather than failing the whole document. 34if page .V .IsNull () { 35continue 36 } 37pageText ,err := page .GetPlainText (nil ) 38if err != nil { 39continue 40 } 41sb .WriteString (pageText ) 42 } 43text = strings .TrimSpace (sb .String ()) 44if text == "" { 45return "" ,failure (422 ,"NO_CONTENT_FOUND" ,fmt .Sprintf ("pdf contains no extractable text (%d pages)" ,total )) 46 } 47return text ,nil 48}