@cantoo/pdf-lib
Version:
Create and modify PDF files with JavaScript
72 lines • 2.55 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const PDFObject_1 = tslib_1.__importDefault(require("./PDFObject"));
const CharCodes_1 = tslib_1.__importDefault(require("../syntax/CharCodes"));
const utils_1 = require("../../utils");
const errors_1 = require("../errors");
class PDFHexString extends PDFObject_1.default {
constructor(value) {
super();
this.value = value;
}
asBytes() {
// Append a zero if the number of digits is odd. See PDF spec 7.3.4.3
const hex = this.value + (this.value.length % 2 === 1 ? '0' : '');
const hexLength = hex.length;
const bytes = new Uint8Array(hex.length / 2);
let hexOffset = 0;
let bytesOffset = 0;
// Interpret each pair of hex digits as a single byte
while (hexOffset < hexLength) {
const byte = parseInt(hex.substring(hexOffset, hexOffset + 2), 16);
bytes[bytesOffset] = byte;
hexOffset += 2;
bytesOffset += 1;
}
return bytes;
}
decodeText() {
const bytes = this.asBytes();
if ((0, utils_1.hasUtf16BOM)(bytes))
return (0, utils_1.utf16Decode)(bytes);
return (0, utils_1.pdfDocEncodingDecode)(bytes);
}
decodeDate() {
const text = this.decodeText();
const date = (0, utils_1.parseDate)(text);
if (!date)
throw new errors_1.InvalidPDFDateStringError(text);
return date;
}
asString() {
return this.value;
}
clone() {
return PDFHexString.of(this.value);
}
toString() {
return `<${this.value}>`;
}
sizeInBytes() {
return this.value.length + 2;
}
copyBytesInto(buffer, offset) {
buffer[offset++] = CharCodes_1.default.LessThan;
offset += (0, utils_1.copyStringIntoBuffer)(this.value, buffer, offset);
buffer[offset++] = CharCodes_1.default.GreaterThan;
return this.value.length + 2;
}
}
PDFHexString.of = (value) => new PDFHexString(value);
PDFHexString.fromText = (value) => {
const encoded = (0, utils_1.utf16Encode)(value);
let hex = '';
for (let idx = 0, len = encoded.length; idx < len; idx++) {
hex += (0, utils_1.toHexStringOfMinLength)(encoded[idx], 4);
}
return new PDFHexString(hex);
};
PDFHexString.fromBytes = (bytes) => PDFHexString.of((0, utils_1.byteArrayToHexString)(bytes));
exports.default = PDFHexString;
//# sourceMappingURL=PDFHexString.js.map