Files

290 lines
7.2 KiB
Go

package service
import (
"bytes"
"compress/zlib"
"encoding/hex"
"io"
"regexp"
"strconv"
"strings"
"unicode/utf16"
)
type pdfObjectStream struct {
object int
body []byte
data []byte
}
var (
pdfObjectRe = regexp.MustCompile(`(?s)(\d+)\s+0\s+obj(.*?)endobj`)
pdfStreamRe = regexp.MustCompile(`(?s)stream\s*(.*?)\s*endstream`)
pdfTextOpRe = regexp.MustCompile(`(?s)\((?:\\.|[^\\()])*\)\s*Tj|<([0-9A-Fa-f\s]+)>\s*Tj|\[(.*?)\]\s*TJ`)
pdfStringRe = regexp.MustCompile(`(?s)\((?:\\.|[^\\()])*\)|<([0-9A-Fa-f\s]+)>`)
pdfBfCharRe = regexp.MustCompile(`(?s)beginbfchar(.*?)endbfchar`)
pdfBfRangeRe = regexp.MustCompile(`(?s)beginbfrange(.*?)endbfrange`)
pdfPairRe = regexp.MustCompile(`<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>`)
pdfRangeRe = regexp.MustCompile(`<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>`)
pdfArrayRe = regexp.MustCompile(`(?s)<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*\[(.*?)\]`)
pdfHexRe = regexp.MustCompile(`<([0-9A-Fa-f]+)>`)
)
func extractPDFText(content []byte) string {
streams := pdfStreams(content)
streams = append(streams, pdfObjectStream{object: 0, data: content})
cmap := map[int]string{}
for _, s := range streams {
if bytes.Contains(s.data, []byte("beginbf")) {
for k, v := range parsePDFCMap(s.data) {
cmap[k] = v
}
}
}
var b strings.Builder
for _, s := range streams {
if bytes.Contains(s.data, []byte("beginbf")) {
continue
}
for _, op := range pdfTextOpRe.FindAll(s.data, -1) {
for _, match := range pdfStringRe.FindAllSubmatch(op, -1) {
raw := match[0]
if len(raw) == 0 {
continue
}
if raw[0] == '(' {
b.WriteString(mapPDFTextBytes(unescapePDFLiteral(raw[1:len(raw)-1]), cmap))
continue
}
if len(match) > 1 && len(match[1]) > 0 {
decoded, ok := decodePDFHex(match[1])
if ok {
b.WriteString(mapPDFTextBytes(decoded, cmap))
}
}
}
}
}
return b.String()
}
func extractPDFRawText(content []byte) string {
streams := pdfStreams(content)
streams = append(streams, pdfObjectStream{object: 0, data: content})
var b strings.Builder
for _, s := range streams {
if bytes.Contains(s.data, []byte("beginbf")) {
continue
}
for _, op := range pdfTextOpRe.FindAll(s.data, -1) {
for _, match := range pdfStringRe.FindAllSubmatch(op, -1) {
raw := match[0]
if len(raw) == 0 {
continue
}
if raw[0] == '(' {
b.WriteString(decodeRawPDFBytes(unescapePDFLiteral(raw[1 : len(raw)-1])))
continue
}
if len(match) > 1 && len(match[1]) > 0 {
decoded, ok := decodePDFHex(match[1])
if ok {
b.WriteString(decodeRawPDFBytes(decoded))
}
}
}
}
}
return b.String()
}
func decodeRawPDFBytes(value []byte) string {
if len(value) >= 2 && value[0] == 0xfe && value[1] == 0xff {
return decodeUTF16BE(value[2:])
}
zeros := 0
for i := 0; i < len(value); i += 2 {
if value[i] == 0 {
zeros++
}
}
if len(value) > 2 && zeros > len(value)/4 {
return decodeUTF16BE(value)
}
return string(value)
}
func decodeUTF16BE(value []byte) string {
if len(value)%2 == 1 {
value = append([]byte{0}, value...)
}
u16 := make([]uint16, 0, len(value)/2)
for i := 0; i+1 < len(value); i += 2 {
u16 = append(u16, uint16(value[i])<<8|uint16(value[i+1]))
}
return string(utf16.Decode(u16))
}
func pdfStreams(content []byte) []pdfObjectStream {
matches := pdfObjectRe.FindAllSubmatch(content, -1)
out := make([]pdfObjectStream, 0, len(matches))
for _, m := range matches {
obj, _ := strconv.Atoi(string(m[1]))
body := m[2]
sm := pdfStreamRe.FindSubmatch(body)
if len(sm) == 0 {
continue
}
data := bytes.Trim(sm[1], "\r\n")
if bytes.Contains(body, []byte("/FlateDecode")) {
if inflated, err := inflatePDFStream(data); err == nil {
data = inflated
}
}
out = append(out, pdfObjectStream{object: obj, body: body, data: data})
}
return out
}
func inflatePDFStream(data []byte) ([]byte, error) {
r, err := zlib.NewReader(bytes.NewReader(data))
if err != nil {
return nil, err
}
defer r.Close()
return io.ReadAll(r)
}
func parsePDFCMap(data []byte) map[int]string {
out := map[int]string{}
for _, block := range pdfBfCharRe.FindAllSubmatch(data, -1) {
for _, pair := range pdfPairRe.FindAllSubmatch(block[1], -1) {
code, err := strconv.ParseInt(string(pair[1]), 16, 32)
if err == nil {
out[int(code)] = decodeUTF16BEHex(pair[2])
}
}
}
for _, block := range pdfBfRangeRe.FindAllSubmatch(data, -1) {
for _, arr := range pdfArrayRe.FindAllSubmatch(block[1], -1) {
start, err := strconv.ParseInt(string(arr[1]), 16, 32)
if err != nil {
continue
}
values := pdfHexRe.FindAllSubmatch(arr[3], -1)
for i, value := range values {
out[int(start)+i] = decodeUTF16BEHex(value[1])
}
}
for _, rng := range pdfRangeRe.FindAllSubmatch(block[1], -1) {
start, err1 := strconv.ParseInt(string(rng[1]), 16, 32)
end, err2 := strconv.ParseInt(string(rng[2]), 16, 32)
base, err3 := strconv.ParseInt(string(rng[3]), 16, 32)
if err1 != nil || err2 != nil || err3 != nil || end < start {
continue
}
width := len(rng[3])
for code := start; code <= end; code++ {
value := strconv.FormatInt(base+code-start, 16)
if len(value) < width {
value = strings.Repeat("0", width-len(value)) + value
}
out[int(code)] = decodeUTF16BEHex([]byte(value))
}
}
}
return out
}
func decodeUTF16BEHex(value []byte) string {
decoded, ok := decodePDFHex(value)
if !ok || len(decoded) == 0 {
return ""
}
if len(decoded)%2 == 1 {
decoded = append([]byte{0}, decoded...)
}
u16 := make([]uint16, 0, len(decoded)/2)
for i := 0; i+1 < len(decoded); i += 2 {
u16 = append(u16, uint16(decoded[i])<<8|uint16(decoded[i+1]))
}
return string(utf16.Decode(u16))
}
func decodePDFHex(value []byte) ([]byte, bool) {
clean := strings.Map(func(r rune) rune {
if r == ' ' || r == '\n' || r == '\r' || r == '\t' {
return -1
}
return r
}, string(value))
if len(clean)%2 == 1 {
clean += "0"
}
decoded, err := hex.DecodeString(clean)
return decoded, err == nil
}
func unescapePDFLiteral(value []byte) []byte {
out := make([]byte, 0, len(value))
for i := 0; i < len(value); i++ {
if value[i] != '\\' || i+1 >= len(value) {
out = append(out, value[i])
continue
}
i++
switch value[i] {
case 'n':
out = append(out, '\n')
case 'r':
out = append(out, '\r')
case 't':
out = append(out, '\t')
case 'b':
out = append(out, '\b')
case 'f':
out = append(out, '\f')
case '(', ')', '\\':
out = append(out, value[i])
default:
if value[i] >= '0' && value[i] <= '7' {
octal := []byte{value[i]}
for j := 0; j < 2 && i+1 < len(value) && value[i+1] >= '0' && value[i+1] <= '7'; j++ {
i++
octal = append(octal, value[i])
}
n, err := strconv.ParseInt(string(octal), 8, 16)
if err == nil {
out = append(out, byte(n))
}
} else {
out = append(out, value[i])
}
}
}
return out
}
func mapPDFTextBytes(value []byte, cmap map[int]string) string {
var b strings.Builder
for i := 0; i < len(value); {
if i+1 < len(value) {
code := int(value[i])<<8 | int(value[i+1])
if mapped, ok := cmap[code]; ok {
b.WriteString(mapped)
i += 2
continue
}
}
if mapped, ok := cmap[int(value[i])]; ok {
b.WriteString(mapped)
} else {
b.WriteByte(value[i])
}
i++
}
return b.String()
}