forked from Hopding/pdf-lib
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdecode.ts
73 lines (68 loc) · 2.45 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
import {
UnexpectedObjectTypeError,
UnsupportedEncodingError,
} from 'src/core/errors';
import { PDFArray } from 'src/core/objects/PDFArray';
import { PDFDict } from 'src/core/objects/PDFDict';
import { PDFName } from 'src/core/objects/PDFName';
import type { PDFNull } from 'src/core/objects/PDFNull';
import { PDFNumber } from 'src/core/objects/PDFNumber';
import type { PDFRawStream } from 'src/core/objects/PDFRawStream';
import { Ascii85Stream } from 'src/core/streams/Ascii85Stream';
import { AsciiHexStream } from 'src/core/streams/AsciiHexStream';
import { FlateStream } from 'src/core/streams/FlateStream';
import { LZWStream } from 'src/core/streams/LZWStream';
import { RunLengthStream } from 'src/core/streams/RunLengthStream';
import { Stream, StreamType } from 'src/core/streams/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 }: PDFRawStream) => {
let stream: StreamType = new Stream(contents);
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;
};