forked from Hopding/pdf-lib
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdecode.ts
78 lines (72 loc) · 2.36 KB
/
decode.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { UnexpectedObjectTypeError, UnsupportedEncodingError } from '../errors';
import PDFArray from '../objects/PDFArray';
import PDFDict from '../objects/PDFDict';
import PDFName from '../objects/PDFName';
import PDFNull from '../objects/PDFNull';
import PDFNumber from '../objects/PDFNumber';
import PDFRawStream from '../objects/PDFRawStream';
import Ascii85Stream from './Ascii85Stream';
import AsciiHexStream from './AsciiHexStream';
import FlateStream from './FlateStream';
import LZWStream from './LZWStream';
import RunLengthStream from './RunLengthStream';
import Stream, { StreamType } from './Stream';
const decodeStream = (
stream: StreamType,
encoding: PDFName,
params: undefined | typeof PDFNull | PDFDict,
) => {
if (encoding === PDFName.of('FlateDecode')) {
return new FlateStream(stream);
}
if (encoding === PDFName.of('LZWDecode')) {
let earlyChange = 1;
if (params instanceof PDFDict) {
const EarlyChange = params.lookup(PDFName.of('EarlyChange'));
if (EarlyChange instanceof PDFNumber) {
earlyChange = EarlyChange.asNumber();
}
}
return new LZWStream(stream, undefined, earlyChange as 0 | 1);
}
if (encoding === PDFName.of('ASCII85Decode')) {
return new Ascii85Stream(stream);
}
if (encoding === PDFName.of('ASCIIHexDecode')) {
return new AsciiHexStream(stream);
}
if (encoding === PDFName.of('RunLengthDecode')) {
return new RunLengthStream(stream);
}
throw new UnsupportedEncodingError(encoding.asString());
};
export const decodePDFRawStream = ({
dict,
contents,
transform,
}: PDFRawStream) => {
let stream: StreamType = new Stream(contents);
if (transform) {
stream = transform.createStream(stream, contents.length);
}
const Filter = dict.lookup(PDFName.of('Filter'));
const DecodeParms = dict.lookup(PDFName.of('DecodeParms'));
if (Filter instanceof PDFName) {
stream = decodeStream(
stream,
Filter,
DecodeParms as PDFDict | typeof PDFNull | undefined,
);
} else if (Filter instanceof PDFArray) {
for (let idx = 0, len = Filter.size(); idx < len; idx++) {
stream = decodeStream(
stream,
Filter.lookup(idx, PDFName),
DecodeParms && (DecodeParms as PDFArray).lookupMaybe(idx, PDFDict),
);
}
} else if (!!Filter) {
throw new UnexpectedObjectTypeError([PDFName, PDFArray], Filter);
}
return stream;
};