Skip to content

Commit 769b2e4

Browse files
committed
Fix locating lastxref (#64)
1 parent 218b6e0 commit 769b2e4

File tree

1 file changed

+40
-24
lines changed

1 file changed

+40
-24
lines changed

pkg/pdfcpu/read.go

Lines changed: 40 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -155,37 +155,53 @@ func newPositionedReader(rs io.ReadSeeker, offset *int64) (*bufio.Reader, error)
155155
func offsetLastXRefSection(ctx *Context) (*int64, error) {
156156

157157
rs := ctx.Read.rs
158-
var bufSize int64 = 512
159158

160-
off, err := rs.Seek(-bufSize, io.SeekEnd)
161-
if err != nil {
162-
return nil, err
163-
}
159+
var (
160+
prevBuf, workBuf []byte
161+
bufSize int64 = 512
162+
offset int64
163+
)
164164

165-
buf := make([]byte, bufSize)
165+
for i := 1; offset == 0; i++ {
166166

167-
log.Read.Printf("scanning for offsetLastXRefSection starting at %d\n", off)
167+
off, err := rs.Seek(-int64(i)*bufSize, io.SeekEnd)
168+
if err != nil {
169+
return nil, errors.New("can't find last xref section")
170+
}
168171

169-
_, err = rs.Read(buf)
170-
if err != nil {
171-
return nil, err
172-
}
172+
log.Read.Printf("scanning for offsetLastXRefSection starting at %d\n", off)
173173

174-
i := strings.LastIndex(string(buf), "startxref")
175-
if i == -1 {
176-
return nil, errors.New("cannot find last xrefsection pointer")
177-
}
174+
curBuf := make([]byte, bufSize)
178175

179-
buf = buf[i+len("startxref"):]
180-
posEOF := strings.Index(string(buf), "%%EOF")
181-
if posEOF == -1 {
182-
return nil, errors.New("no matching %%EOF for startxref")
183-
}
176+
_, err = rs.Read(curBuf)
177+
if err != nil {
178+
return nil, err
179+
}
180+
181+
workBuf = curBuf
182+
if prevBuf != nil {
183+
workBuf = append(curBuf, prevBuf...)
184+
}
185+
186+
j := strings.LastIndex(string(workBuf), "startxref")
187+
if j == -1 {
188+
//return nil, errors.New("cannot find last xrefsection pointer")
189+
prevBuf = curBuf
190+
continue
191+
}
192+
193+
p := workBuf[j+len("startxref"):]
194+
posEOF := strings.Index(string(p), "%%EOF")
195+
if posEOF == -1 {
196+
return nil, errors.New("no matching %%EOF for startxref")
197+
}
198+
199+
p = p[:posEOF]
200+
offset, err = strconv.ParseInt(strings.TrimSpace(string(p)), 10, 64)
201+
if err != nil {
202+
return nil, errors.New("corrupted last xref section")
203+
}
184204

185-
buf = buf[:posEOF]
186-
offset, err := strconv.ParseInt(strings.TrimSpace(string(buf)), 10, 64)
187-
if err != nil {
188-
return nil, errors.New("corrupted xref section")
189205
}
190206

191207
log.Read.Printf("Offset last xrefsection: %d\n", offset)

0 commit comments

Comments
 (0)