mirror of
https://github.com/mozilla/pdf.js.git
synced 2025-04-22 16:18:08 +02:00
Merge text search with current master
This commit is contained in:
commit
3c77291013
89 changed files with 11599 additions and 3372 deletions
432
src/bidi.js
Normal file
432
src/bidi.js
Normal file
|
@ -0,0 +1,432 @@
|
|||
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
|
||||
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
|
||||
|
||||
'use strict';
|
||||
|
||||
var bidi = PDFJS.bidi = (function bidiClosure() {
|
||||
// Character types for symbols from 0000 to 00FF.
|
||||
var baseTypes = [
|
||||
'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'S', 'B', 'S', 'WS',
|
||||
'B', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
|
||||
'BN', 'BN', 'B', 'B', 'B', 'S', 'WS', 'ON', 'ON', 'ET', 'ET', 'ET', 'ON',
|
||||
'ON', 'ON', 'ON', 'ON', 'ON', 'CS', 'ON', 'CS', 'ON', 'EN', 'EN', 'EN',
|
||||
'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'ON', 'ON', 'ON', 'ON', 'ON',
|
||||
'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
|
||||
'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'ON',
|
||||
'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
|
||||
'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
|
||||
'L', 'ON', 'ON', 'ON', 'ON', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'B', 'BN',
|
||||
'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
|
||||
'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
|
||||
'BN', 'CS', 'ON', 'ET', 'ET', 'ET', 'ET', 'ON', 'ON', 'ON', 'ON', 'L', 'ON',
|
||||
'ON', 'ON', 'ON', 'ON', 'ET', 'ET', 'EN', 'EN', 'ON', 'L', 'ON', 'ON', 'ON',
|
||||
'EN', 'L', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
|
||||
'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
|
||||
'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
|
||||
'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
|
||||
'L', 'L', 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L'
|
||||
];
|
||||
|
||||
// Character types for symbols from 0600 to 06FF
|
||||
var arabicTypes = [
|
||||
'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
|
||||
'CS', 'AL', 'ON', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL',
|
||||
'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'AL', 'AL', 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
|
||||
'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'AL', 'AL', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN',
|
||||
'AN', 'ET', 'AN', 'AN', 'AL', 'AL', 'AL', 'NSM', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
|
||||
'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'ON', 'NSM',
|
||||
'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
|
||||
'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL'
|
||||
];
|
||||
|
||||
function isOdd(i) {
|
||||
return (i & 1) != 0;
|
||||
}
|
||||
|
||||
function isEven(i) {
|
||||
return (i & 1) == 0;
|
||||
}
|
||||
|
||||
function findUnequal(arr, start, value) {
|
||||
var j;
|
||||
for (var j = start, jj = arr.length; j < jj; ++j) {
|
||||
if (arr[j] != value)
|
||||
return j;
|
||||
}
|
||||
return j;
|
||||
}
|
||||
|
||||
function setValues(arr, start, end, value) {
|
||||
for (var j = start; j < end; ++j) {
|
||||
arr[j] = value;
|
||||
}
|
||||
}
|
||||
|
||||
function reverseValues(arr, start, end) {
|
||||
for (var i = start, j = end - 1; i < j; ++i, --j) {
|
||||
var temp = arr[i];
|
||||
arr[i] = arr[j];
|
||||
arr[j] = temp;
|
||||
}
|
||||
}
|
||||
|
||||
function mirrorGlyphs(c) {
|
||||
/*
|
||||
# BidiMirroring-1.txt
|
||||
0028; 0029 # LEFT PARENTHESIS
|
||||
0029; 0028 # RIGHT PARENTHESIS
|
||||
003C; 003E # LESS-THAN SIGN
|
||||
003E; 003C # GREATER-THAN SIGN
|
||||
005B; 005D # LEFT SQUARE BRACKET
|
||||
005D; 005B # RIGHT SQUARE BRACKET
|
||||
007B; 007D # LEFT CURLY BRACKET
|
||||
007D; 007B # RIGHT CURLY BRACKET
|
||||
00AB; 00BB # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
00BB; 00AB # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
|
||||
*/
|
||||
switch (c) {
|
||||
case '(':
|
||||
return ')';
|
||||
case ')':
|
||||
return '(';
|
||||
case '<':
|
||||
return '>';
|
||||
case '>':
|
||||
return '<';
|
||||
case ']':
|
||||
return '[';
|
||||
case '[':
|
||||
return ']';
|
||||
case '}':
|
||||
return '{';
|
||||
case '{':
|
||||
return '}';
|
||||
case '\u00AB':
|
||||
return '\u00BB';
|
||||
case '\u00BB':
|
||||
return '\u00AB';
|
||||
default:
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
function bidi(text, startLevel) {
|
||||
var str = text.str;
|
||||
var strLength = str.length;
|
||||
if (strLength == 0)
|
||||
return str;
|
||||
|
||||
// get types, fill arrays
|
||||
|
||||
var chars = [];
|
||||
var types = [];
|
||||
var oldtypes = [];
|
||||
var numBidi = 0;
|
||||
|
||||
for (var i = 0; i < strLength; ++i) {
|
||||
chars[i] = str.charAt(i);
|
||||
|
||||
var charCode = str.charCodeAt(i);
|
||||
var charType = 'L';
|
||||
if (charCode <= 0x00ff)
|
||||
charType = baseTypes[charCode];
|
||||
else if (0x0590 <= charCode && charCode <= 0x05f4)
|
||||
charType = 'R';
|
||||
else if (0x0600 <= charCode && charCode <= 0x06ff)
|
||||
charType = arabicTypes[charCode & 0xff];
|
||||
else if (0x0700 <= charCode && charCode <= 0x08AC)
|
||||
charType = 'AL';
|
||||
|
||||
if (charType == 'R' || charType == 'AL' || charType == 'AN')
|
||||
numBidi++;
|
||||
|
||||
oldtypes[i] = types[i] = charType;
|
||||
}
|
||||
|
||||
// detect the bidi method
|
||||
// if there are no rtl characters then no bidi needed
|
||||
// if less than 30% chars are rtl then string is primarily ltr
|
||||
// if more than 30% chars are rtl then string is primarily rtl
|
||||
if (numBidi == 0) {
|
||||
text.direction = 'ltr';
|
||||
return str;
|
||||
}
|
||||
|
||||
if (startLevel == -1) {
|
||||
if ((strLength / numBidi) < 0.3) {
|
||||
text.direction = 'ltr';
|
||||
startLevel = 0;
|
||||
} else {
|
||||
text.direction = 'rtl';
|
||||
startLevel = 1;
|
||||
}
|
||||
}
|
||||
|
||||
var levels = [];
|
||||
|
||||
for (var i = 0; i < strLength; ++i) {
|
||||
levels[i] = startLevel;
|
||||
}
|
||||
|
||||
/*
|
||||
X1-X10: skip most of this, since we are NOT doing the embeddings.
|
||||
*/
|
||||
|
||||
var e = isOdd(startLevel) ? 'R' : 'L';
|
||||
var sor = e;
|
||||
var eor = sor;
|
||||
|
||||
/*
|
||||
W1. Examine each non-spacing mark (NSM) in the level run, and change the
|
||||
type of the NSM to the type of the previous character. If the NSM is at the
|
||||
start of the level run, it will get the type of sor.
|
||||
*/
|
||||
|
||||
var lastType = sor;
|
||||
for (var i = 0; i < strLength; ++i) {
|
||||
if (types[i] == 'NSM')
|
||||
types[i] = lastType;
|
||||
else
|
||||
lastType = types[i];
|
||||
}
|
||||
|
||||
/*
|
||||
W2. Search backwards from each instance of a European number until the
|
||||
first strong type (R, L, AL, or sor) is found. If an AL is found, change
|
||||
the type of the European number to Arabic number.
|
||||
*/
|
||||
|
||||
var lastType = sor;
|
||||
for (var i = 0; i < strLength; ++i) {
|
||||
var t = types[i];
|
||||
if (t == 'EN')
|
||||
types[i] = (lastType == 'AL') ? 'AN' : 'EN';
|
||||
else if (t == 'R' || t == 'L' || t == 'AL')
|
||||
lastType = t;
|
||||
}
|
||||
|
||||
/*
|
||||
W3. Change all ALs to R.
|
||||
*/
|
||||
|
||||
for (var i = 0; i < strLength; ++i) {
|
||||
var t = types[i];
|
||||
if (t == 'AL')
|
||||
types[i] = 'R';
|
||||
}
|
||||
|
||||
/*
|
||||
W4. A single European separator between two European numbers changes to a
|
||||
European number. A single common separator between two numbers of the same
|
||||
type changes to that type:
|
||||
*/
|
||||
|
||||
for (var i = 1; i < strLength - 1; ++i) {
|
||||
if (types[i] == 'ES' && types[i - 1] == 'EN' && types[i + 1] == 'EN')
|
||||
types[i] = 'EN';
|
||||
if (types[i] == 'CS' && (types[i - 1] == 'EN' || types[i - 1] == 'AN') &&
|
||||
types[i + 1] == types[i - 1])
|
||||
types[i] = types[i - 1];
|
||||
}
|
||||
|
||||
/*
|
||||
W5. A sequence of European terminators adjacent to European numbers changes
|
||||
to all European numbers:
|
||||
*/
|
||||
|
||||
for (var i = 0; i < strLength; ++i) {
|
||||
if (types[i] == 'EN') {
|
||||
// do before
|
||||
for (var j = i - 1; j >= 0; --j) {
|
||||
if (types[j] != 'ET')
|
||||
break;
|
||||
types[j] = 'EN';
|
||||
}
|
||||
// do after
|
||||
for (var j = i + 1; j < strLength; --j) {
|
||||
if (types[j] != 'ET')
|
||||
break;
|
||||
types[j] = 'EN';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
W6. Otherwise, separators and terminators change to Other Neutral:
|
||||
*/
|
||||
|
||||
for (var i = 0; i < strLength; ++i) {
|
||||
var t = types[i];
|
||||
if (t == 'WS' || t == 'ES' || t == 'ET' || t == 'CS')
|
||||
types[i] = 'ON';
|
||||
}
|
||||
|
||||
/*
|
||||
W7. Search backwards from each instance of a European number until the
|
||||
first strong type (R, L, or sor) is found. If an L is found, then change
|
||||
the type of the European number to L.
|
||||
*/
|
||||
|
||||
var lastType = sor;
|
||||
for (var i = 0; i < strLength; ++i) {
|
||||
var t = types[i];
|
||||
if (t == 'EN')
|
||||
types[i] = (lastType == 'L') ? 'L' : 'EN';
|
||||
else if (t == 'R' || t == 'L')
|
||||
lastType = t;
|
||||
}
|
||||
|
||||
/*
|
||||
N1. A sequence of neutrals takes the direction of the surrounding strong
|
||||
text if the text on both sides has the same direction. European and Arabic
|
||||
numbers are treated as though they were R. Start-of-level-run (sor) and
|
||||
end-of-level-run (eor) are used at level run boundaries.
|
||||
*/
|
||||
|
||||
for (var i = 0; i < strLength; ++i) {
|
||||
if (types[i] == 'ON') {
|
||||
var end = findUnequal(types, i + 1, 'ON');
|
||||
var before = sor;
|
||||
if (i > 0)
|
||||
before = types[i - 1];
|
||||
var after = eor;
|
||||
if (end + 1 < strLength)
|
||||
after = types[end + 1];
|
||||
if (before != 'L')
|
||||
before = 'R';
|
||||
if (after != 'L')
|
||||
after = 'R';
|
||||
if (before == after)
|
||||
setValues(types, i, end, before);
|
||||
i = end - 1; // reset to end (-1 so next iteration is ok)
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
N2. Any remaining neutrals take the embedding direction.
|
||||
*/
|
||||
|
||||
for (var i = 0; i < strLength; ++i) {
|
||||
if (types[i] == 'ON')
|
||||
types[i] = e;
|
||||
}
|
||||
|
||||
/*
|
||||
I1. For all characters with an even (left-to-right) embedding direction,
|
||||
those of type R go up one level and those of type AN or EN go up two
|
||||
levels.
|
||||
I2. For all characters with an odd (right-to-left) embedding direction,
|
||||
those of type L, EN or AN go up one level.
|
||||
*/
|
||||
|
||||
for (var i = 0; i < strLength; ++i) {
|
||||
var t = types[i];
|
||||
if (isEven(levels[i])) {
|
||||
if (t == 'R') {
|
||||
levels[i] += 1;
|
||||
} else if (t == 'AN' || t == 'EN') {
|
||||
levels[i] += 2;
|
||||
}
|
||||
} else { // isOdd, so
|
||||
if (t == 'L' || t == 'AN' || t == 'EN') {
|
||||
levels[i] += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
L1. On each line, reset the embedding level of the following characters to
|
||||
the paragraph embedding level:
|
||||
|
||||
segment separators,
|
||||
paragraph separators,
|
||||
any sequence of whitespace characters preceding a segment separator or
|
||||
paragraph separator, and any sequence of white space characters at the end
|
||||
of the line.
|
||||
*/
|
||||
|
||||
// don't bother as text is only single line
|
||||
|
||||
/*
|
||||
L2. From the highest level found in the text to the lowest odd level on
|
||||
each line, reverse any contiguous sequence of characters that are at that
|
||||
level or higher.
|
||||
*/
|
||||
|
||||
// find highest level & lowest odd level
|
||||
|
||||
var highestLevel = -1;
|
||||
var lowestOddLevel = 99;
|
||||
for (var i = 0, ii = levels.length; i < ii; ++i) {
|
||||
var level = levels[i];
|
||||
if (highestLevel < level)
|
||||
highestLevel = level;
|
||||
if (lowestOddLevel > level && isOdd(level))
|
||||
lowestOddLevel = level;
|
||||
}
|
||||
|
||||
// now reverse between those limits
|
||||
|
||||
for (var level = highestLevel; level >= lowestOddLevel; --level) {
|
||||
// find segments to reverse
|
||||
var start = -1;
|
||||
for (var i = 0, ii = levels.length; i < ii; ++i) {
|
||||
if (levels[i] < level) {
|
||||
if (start >= 0) {
|
||||
reverseValues(chars, start, i);
|
||||
start = -1;
|
||||
}
|
||||
} else if (start < 0) {
|
||||
start = i;
|
||||
}
|
||||
}
|
||||
if (start >= 0) {
|
||||
reverseValues(chars, start, levels.length);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
L3. Combining marks applied to a right-to-left base character will at this
|
||||
point precede their base character. If the rendering engine expects them to
|
||||
follow the base characters in the final display process, then the ordering
|
||||
of the marks and the base character must be reversed.
|
||||
*/
|
||||
|
||||
// don't bother for now
|
||||
|
||||
/*
|
||||
L4. A character that possesses the mirrored property as specified by
|
||||
Section 4.7, Mirrored, must be depicted by a mirrored glyph if the resolved
|
||||
directionality of that character is R.
|
||||
*/
|
||||
|
||||
// don't mirror as characters are already mirrored in the pdf
|
||||
|
||||
// Finally, return string
|
||||
|
||||
var result = '';
|
||||
for (var i = 0, ii = chars.length; i < ii; ++i) {
|
||||
var ch = chars[i];
|
||||
if (ch != '<' && ch != '>')
|
||||
result += ch;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
return bidi;
|
||||
})();
|
||||
|
449
src/canvas.js
449
src/canvas.js
|
@ -17,55 +17,10 @@ var TextRenderingMode = {
|
|||
ADD_TO_PATH: 7
|
||||
};
|
||||
|
||||
var CanvasExtraState = (function CanvasExtraStateClosure() {
|
||||
function CanvasExtraState(old) {
|
||||
// Are soft masks and alpha values shapes or opacities?
|
||||
this.alphaIsShape = false;
|
||||
this.fontSize = 0;
|
||||
this.textMatrix = IDENTITY_MATRIX;
|
||||
this.leading = 0;
|
||||
// Current point (in user coordinates)
|
||||
this.x = 0;
|
||||
this.y = 0;
|
||||
// Start of text line (in text coordinates)
|
||||
this.lineX = 0;
|
||||
this.lineY = 0;
|
||||
// Character and word spacing
|
||||
this.charSpacing = 0;
|
||||
this.wordSpacing = 0;
|
||||
this.textHScale = 1;
|
||||
this.textRenderingMode = TextRenderingMode.FILL;
|
||||
// Color spaces
|
||||
this.fillColorSpace = new DeviceGrayCS();
|
||||
this.fillColorSpaceObj = null;
|
||||
this.strokeColorSpace = new DeviceGrayCS();
|
||||
this.strokeColorSpaceObj = null;
|
||||
this.fillColorObj = null;
|
||||
this.strokeColorObj = null;
|
||||
// Default fore and background colors
|
||||
this.fillColor = '#000000';
|
||||
this.strokeColor = '#000000';
|
||||
// Note: fill alpha applies to all non-stroking operations
|
||||
this.fillAlpha = 1;
|
||||
this.strokeAlpha = 1;
|
||||
this.lineWidth = 1;
|
||||
// Minimal font size that would be used during canvas fillText operations.
|
||||
var MIN_FONT_SIZE = 1;
|
||||
|
||||
this.old = old;
|
||||
}
|
||||
|
||||
CanvasExtraState.prototype = {
|
||||
clone: function canvasextra_clone() {
|
||||
return Object.create(this);
|
||||
},
|
||||
setCurrentPoint: function canvasextra_setCurrentPoint(x, y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
};
|
||||
return CanvasExtraState;
|
||||
})();
|
||||
|
||||
function ScratchCanvas(width, height) {
|
||||
function createScratchCanvas(width, height) {
|
||||
var canvas = document.createElement('canvas');
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
|
@ -182,10 +137,60 @@ function addContextCurrentTransform(ctx) {
|
|||
}
|
||||
}
|
||||
|
||||
var CanvasExtraState = (function CanvasExtraStateClosure() {
|
||||
function CanvasExtraState(old) {
|
||||
// Are soft masks and alpha values shapes or opacities?
|
||||
this.alphaIsShape = false;
|
||||
this.fontSize = 0;
|
||||
this.fontSizeScale = 1;
|
||||
this.textMatrix = IDENTITY_MATRIX;
|
||||
this.fontMatrix = IDENTITY_MATRIX;
|
||||
this.leading = 0;
|
||||
// Current point (in user coordinates)
|
||||
this.x = 0;
|
||||
this.y = 0;
|
||||
// Start of text line (in text coordinates)
|
||||
this.lineX = 0;
|
||||
this.lineY = 0;
|
||||
// Character and word spacing
|
||||
this.charSpacing = 0;
|
||||
this.wordSpacing = 0;
|
||||
this.textHScale = 1;
|
||||
this.textRenderingMode = TextRenderingMode.FILL;
|
||||
// Color spaces
|
||||
this.fillColorSpace = new DeviceGrayCS();
|
||||
this.fillColorSpaceObj = null;
|
||||
this.strokeColorSpace = new DeviceGrayCS();
|
||||
this.strokeColorSpaceObj = null;
|
||||
this.fillColorObj = null;
|
||||
this.strokeColorObj = null;
|
||||
// Default fore and background colors
|
||||
this.fillColor = '#000000';
|
||||
this.strokeColor = '#000000';
|
||||
// Note: fill alpha applies to all non-stroking operations
|
||||
this.fillAlpha = 1;
|
||||
this.strokeAlpha = 1;
|
||||
this.lineWidth = 1;
|
||||
|
||||
this.old = old;
|
||||
}
|
||||
|
||||
CanvasExtraState.prototype = {
|
||||
clone: function CanvasExtraState_clone() {
|
||||
return Object.create(this);
|
||||
},
|
||||
setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
};
|
||||
return CanvasExtraState;
|
||||
})();
|
||||
|
||||
var CanvasGraphics = (function CanvasGraphicsClosure() {
|
||||
// Defines the time the executeIRQueue is going to be executing
|
||||
// Defines the time the executeOperatorList is going to be executing
|
||||
// before it stops and shedules a continue of execution.
|
||||
var kExecutionTime = 50;
|
||||
var kExecutionTime = 15;
|
||||
|
||||
function CanvasGraphics(canvasCtx, objs, textLayer) {
|
||||
this.ctx = canvasCtx;
|
||||
|
@ -194,7 +199,6 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
this.pendingClip = null;
|
||||
this.res = null;
|
||||
this.xobjs = null;
|
||||
this.ScratchCanvas = ScratchCanvas;
|
||||
this.objs = objs;
|
||||
this.textLayer = textLayer;
|
||||
if (canvasCtx) {
|
||||
|
@ -224,7 +228,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
'setStrokeColor': true,
|
||||
'setStrokeColorN': true,
|
||||
'setFillColor': true,
|
||||
'setFillColorN_IR': true,
|
||||
'setFillColorN': true,
|
||||
'setStrokeGray': true,
|
||||
'setFillGray': true,
|
||||
'setStrokeRGBColor': true,
|
||||
|
@ -237,7 +241,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
'shadingFill': true
|
||||
},
|
||||
|
||||
beginDrawing: function canvasGraphicsBeginDrawing(mediaBox) {
|
||||
beginDrawing: function CanvasGraphics_beginDrawing(mediaBox) {
|
||||
var cw = this.ctx.canvas.width, ch = this.ctx.canvas.height;
|
||||
this.ctx.save();
|
||||
switch (mediaBox.rotate) {
|
||||
|
@ -263,14 +267,16 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
this.textLayer.beginLayout();
|
||||
},
|
||||
|
||||
executeIRQueue: function canvasGraphicsExecuteIRQueue(codeIR,
|
||||
executionStartIdx, continueCallback) {
|
||||
var argsArray = codeIR.argsArray;
|
||||
var fnArray = codeIR.fnArray;
|
||||
executeOperatorList: function CanvasGraphics_executeOperatorList(
|
||||
operatorList,
|
||||
executionStartIdx, continueCallback,
|
||||
stepper) {
|
||||
var argsArray = operatorList.argsArray;
|
||||
var fnArray = operatorList.fnArray;
|
||||
var i = executionStartIdx || 0;
|
||||
var argsArrayLen = argsArray.length;
|
||||
|
||||
// Sometimes the IRQueue to execute is empty.
|
||||
// Sometimes the OperatorList to execute is empty.
|
||||
if (argsArrayLen == i) {
|
||||
return i;
|
||||
}
|
||||
|
@ -283,6 +289,11 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
var slowCommands = this.slowCommands;
|
||||
|
||||
while (true) {
|
||||
if (stepper && i === stepper.nextBreakPoint) {
|
||||
stepper.breakIt(i, continueCallback);
|
||||
return i;
|
||||
}
|
||||
|
||||
fnName = fnArray[i];
|
||||
|
||||
if (fnName !== 'dependency') {
|
||||
|
@ -303,7 +314,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
|
||||
i++;
|
||||
|
||||
// If the entire IRQueue was executed, stop as were done.
|
||||
// If the entire operatorList was executed, stop as were done.
|
||||
if (i == argsArrayLen) {
|
||||
return i;
|
||||
}
|
||||
|
@ -316,12 +327,12 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
return i;
|
||||
}
|
||||
|
||||
// If the IRQueue isn't executed completly yet OR the execution time
|
||||
// was short enough, do another execution round.
|
||||
// If the operatorList isn't executed completely yet OR the execution
|
||||
// time was short enough, do another execution round.
|
||||
}
|
||||
},
|
||||
|
||||
endDrawing: function canvasGraphicsEndDrawing() {
|
||||
endDrawing: function CanvasGraphics_endDrawing() {
|
||||
this.ctx.restore();
|
||||
|
||||
if (this.textLayer)
|
||||
|
@ -329,32 +340,32 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
},
|
||||
|
||||
// Graphics state
|
||||
setLineWidth: function canvasGraphicsSetLineWidth(width) {
|
||||
setLineWidth: function CanvasGraphics_setLineWidth(width) {
|
||||
this.current.lineWidth = width;
|
||||
this.ctx.lineWidth = width;
|
||||
},
|
||||
setLineCap: function canvasGraphicsSetLineCap(style) {
|
||||
setLineCap: function CanvasGraphics_setLineCap(style) {
|
||||
this.ctx.lineCap = LINE_CAP_STYLES[style];
|
||||
},
|
||||
setLineJoin: function canvasGraphicsSetLineJoin(style) {
|
||||
setLineJoin: function CanvasGraphics_setLineJoin(style) {
|
||||
this.ctx.lineJoin = LINE_JOIN_STYLES[style];
|
||||
},
|
||||
setMiterLimit: function canvasGraphicsSetMiterLimit(limit) {
|
||||
setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
|
||||
this.ctx.miterLimit = limit;
|
||||
},
|
||||
setDash: function canvasGraphicsSetDash(dashArray, dashPhase) {
|
||||
setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
|
||||
this.ctx.mozDash = dashArray;
|
||||
this.ctx.mozDashOffset = dashPhase;
|
||||
this.ctx.webkitLineDash = dashArray;
|
||||
this.ctx.webkitLineDashOffset = dashPhase;
|
||||
},
|
||||
setRenderingIntent: function canvasGraphicsSetRenderingIntent(intent) {
|
||||
setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
|
||||
TODO('set rendering intent: ' + intent);
|
||||
},
|
||||
setFlatness: function canvasGraphicsSetFlatness(flatness) {
|
||||
setFlatness: function CanvasGraphics_setFlatness(flatness) {
|
||||
TODO('set flatness: ' + flatness);
|
||||
},
|
||||
setGState: function canvasGraphicsSetGState(states) {
|
||||
setGState: function CanvasGraphics_setGState(states) {
|
||||
for (var i = 0, ii = states.length; i < ii; i++) {
|
||||
var state = states[i];
|
||||
var key = state[0];
|
||||
|
@ -395,52 +406,52 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
}
|
||||
}
|
||||
},
|
||||
save: function canvasGraphicsSave() {
|
||||
save: function CanvasGraphics_save() {
|
||||
this.ctx.save();
|
||||
var old = this.current;
|
||||
this.stateStack.push(old);
|
||||
this.current = old.clone();
|
||||
},
|
||||
restore: function canvasGraphicsRestore() {
|
||||
restore: function CanvasGraphics_restore() {
|
||||
var prev = this.stateStack.pop();
|
||||
if (prev) {
|
||||
this.current = prev;
|
||||
this.ctx.restore();
|
||||
}
|
||||
},
|
||||
transform: function canvasGraphicsTransform(a, b, c, d, e, f) {
|
||||
transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
|
||||
this.ctx.transform(a, b, c, d, e, f);
|
||||
},
|
||||
|
||||
// Path
|
||||
moveTo: function canvasGraphicsMoveTo(x, y) {
|
||||
moveTo: function CanvasGraphics_moveTo(x, y) {
|
||||
this.ctx.moveTo(x, y);
|
||||
this.current.setCurrentPoint(x, y);
|
||||
},
|
||||
lineTo: function canvasGraphicsLineTo(x, y) {
|
||||
lineTo: function CanvasGraphics_lineTo(x, y) {
|
||||
this.ctx.lineTo(x, y);
|
||||
this.current.setCurrentPoint(x, y);
|
||||
},
|
||||
curveTo: function canvasGraphicsCurveTo(x1, y1, x2, y2, x3, y3) {
|
||||
curveTo: function CanvasGraphics_curveTo(x1, y1, x2, y2, x3, y3) {
|
||||
this.ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
|
||||
this.current.setCurrentPoint(x3, y3);
|
||||
},
|
||||
curveTo2: function canvasGraphicsCurveTo2(x2, y2, x3, y3) {
|
||||
curveTo2: function CanvasGraphics_curveTo2(x2, y2, x3, y3) {
|
||||
var current = this.current;
|
||||
this.ctx.bezierCurveTo(current.x, current.y, x2, y2, x3, y3);
|
||||
current.setCurrentPoint(x3, y3);
|
||||
},
|
||||
curveTo3: function canvasGraphicsCurveTo3(x1, y1, x3, y3) {
|
||||
curveTo3: function CanvasGraphics_curveTo3(x1, y1, x3, y3) {
|
||||
this.curveTo(x1, y1, x3, y3, x3, y3);
|
||||
this.current.setCurrentPoint(x3, y3);
|
||||
},
|
||||
closePath: function canvasGraphicsClosePath() {
|
||||
closePath: function CanvasGraphics_closePath() {
|
||||
this.ctx.closePath();
|
||||
},
|
||||
rectangle: function canvasGraphicsRectangle(x, y, width, height) {
|
||||
rectangle: function CanvasGraphics_rectangle(x, y, width, height) {
|
||||
this.ctx.rect(x, y, width, height);
|
||||
},
|
||||
stroke: function canvasGraphicsStroke(consumePath) {
|
||||
stroke: function CanvasGraphics_stroke(consumePath) {
|
||||
consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
|
||||
var ctx = this.ctx;
|
||||
var strokeColor = this.current.strokeColor;
|
||||
|
@ -465,11 +476,11 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
// Restore the global alpha to the fill alpha
|
||||
ctx.globalAlpha = this.current.fillAlpha;
|
||||
},
|
||||
closeStroke: function canvasGraphicsCloseStroke() {
|
||||
closeStroke: function CanvasGraphics_closeStroke() {
|
||||
this.closePath();
|
||||
this.stroke();
|
||||
},
|
||||
fill: function canvasGraphicsFill(consumePath) {
|
||||
fill: function CanvasGraphics_fill(consumePath) {
|
||||
consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
|
||||
var ctx = this.ctx;
|
||||
var fillColor = this.current.fillColor;
|
||||
|
@ -486,76 +497,99 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
if (consumePath)
|
||||
this.consumePath();
|
||||
},
|
||||
eoFill: function canvasGraphicsEoFill() {
|
||||
eoFill: function CanvasGraphics_eoFill() {
|
||||
var savedFillRule = this.setEOFillRule();
|
||||
this.fill();
|
||||
this.restoreFillRule(savedFillRule);
|
||||
},
|
||||
fillStroke: function canvasGraphicsFillStroke() {
|
||||
fillStroke: function CanvasGraphics_fillStroke() {
|
||||
this.fill(false);
|
||||
this.stroke(false);
|
||||
|
||||
this.consumePath();
|
||||
},
|
||||
eoFillStroke: function canvasGraphicsEoFillStroke() {
|
||||
eoFillStroke: function CanvasGraphics_eoFillStroke() {
|
||||
var savedFillRule = this.setEOFillRule();
|
||||
this.fillStroke();
|
||||
this.restoreFillRule(savedFillRule);
|
||||
},
|
||||
closeFillStroke: function canvasGraphicsCloseFillStroke() {
|
||||
closeFillStroke: function CanvasGraphics_closeFillStroke() {
|
||||
this.closePath();
|
||||
this.fillStroke();
|
||||
},
|
||||
closeEOFillStroke: function canvasGraphicsCloseEOFillStroke() {
|
||||
closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
|
||||
var savedFillRule = this.setEOFillRule();
|
||||
this.closePath();
|
||||
this.fillStroke();
|
||||
this.restoreFillRule(savedFillRule);
|
||||
},
|
||||
endPath: function canvasGraphicsEndPath() {
|
||||
endPath: function CanvasGraphics_endPath() {
|
||||
this.consumePath();
|
||||
},
|
||||
|
||||
// Clipping
|
||||
clip: function canvasGraphicsClip() {
|
||||
clip: function CanvasGraphics_clip() {
|
||||
this.pendingClip = NORMAL_CLIP;
|
||||
},
|
||||
eoClip: function canvasGraphicsEoClip() {
|
||||
eoClip: function CanvasGraphics_eoClip() {
|
||||
this.pendingClip = EO_CLIP;
|
||||
},
|
||||
|
||||
// Text
|
||||
beginText: function canvasGraphicsBeginText() {
|
||||
beginText: function CanvasGraphics_beginText() {
|
||||
this.current.textMatrix = IDENTITY_MATRIX;
|
||||
this.current.x = this.current.lineX = 0;
|
||||
this.current.y = this.current.lineY = 0;
|
||||
},
|
||||
endText: function canvasGraphicsEndText() {
|
||||
endText: function CanvasGraphics_endText() {
|
||||
},
|
||||
setCharSpacing: function canvasGraphicsSetCharSpacing(spacing) {
|
||||
setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
|
||||
this.current.charSpacing = spacing;
|
||||
},
|
||||
setWordSpacing: function canvasGraphicsSetWordSpacing(spacing) {
|
||||
setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
|
||||
this.current.wordSpacing = spacing;
|
||||
},
|
||||
setHScale: function canvasGraphicsSetHScale(scale) {
|
||||
setHScale: function CanvasGraphics_setHScale(scale) {
|
||||
this.current.textHScale = scale / 100;
|
||||
},
|
||||
setLeading: function canvasGraphicsSetLeading(leading) {
|
||||
setLeading: function CanvasGraphics_setLeading(leading) {
|
||||
this.current.leading = -leading;
|
||||
},
|
||||
setFont: function canvasGraphicsSetFont(fontRefName, size) {
|
||||
var fontObj = this.objs.get(fontRefName).fontObj;
|
||||
setFont: function CanvasGraphics_setFont(fontRefName, size) {
|
||||
var fontObj = this.objs.get(fontRefName);
|
||||
var current = this.current;
|
||||
|
||||
if (!fontObj) {
|
||||
throw 'Can\'t find font for ' + fontRefName;
|
||||
if (!fontObj)
|
||||
error('Can\'t find font for ' + fontRefName);
|
||||
|
||||
// Slice-clone matrix so we can manipulate it without affecting original
|
||||
if (fontObj.fontMatrix)
|
||||
current.fontMatrix = fontObj.fontMatrix.slice(0);
|
||||
else
|
||||
current.fontMatrix = IDENTITY_MATRIX.slice(0);
|
||||
|
||||
// A valid matrix needs all main diagonal elements to be non-zero
|
||||
// This also ensures we bypass FF bugzilla bug #719844.
|
||||
if (current.fontMatrix[0] === 0 ||
|
||||
current.fontMatrix[3] === 0) {
|
||||
warn('Invalid font matrix for font ' + fontRefName);
|
||||
}
|
||||
|
||||
var name = fontObj.loadedName || 'sans-serif';
|
||||
// The spec for Tf (setFont) says that 'size' specifies the font 'scale',
|
||||
// and in some docs this can be negative (inverted x-y axes).
|
||||
// We implement this condition with fontMatrix.
|
||||
if (size < 0) {
|
||||
size = -size;
|
||||
current.fontMatrix[0] *= -1;
|
||||
current.fontMatrix[3] *= -1;
|
||||
}
|
||||
|
||||
this.current.font = fontObj;
|
||||
this.current.fontSize = size;
|
||||
|
||||
if (fontObj.coded)
|
||||
return; // we don't need ctx.font for Type3 fonts
|
||||
|
||||
var name = fontObj.loadedName || 'sans-serif';
|
||||
var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
|
||||
(fontObj.bold ? 'bold' : 'normal');
|
||||
|
@ -563,39 +597,48 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
var italic = fontObj.italic ? 'italic' : 'normal';
|
||||
var serif = fontObj.isSerifFont ? 'serif' : 'sans-serif';
|
||||
var typeface = '"' + name + '", ' + serif;
|
||||
var rule = italic + ' ' + bold + ' ' + size + 'px ' + typeface;
|
||||
|
||||
// Some font backends cannot handle fonts below certain size.
|
||||
// Keeping the font at minimal size and using the fontSizeScale to change
|
||||
// the current transformation matrix before the fillText/strokeText.
|
||||
// See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
|
||||
var browserFontSize = size >= MIN_FONT_SIZE ? size : MIN_FONT_SIZE;
|
||||
this.current.fontSizeScale = browserFontSize != MIN_FONT_SIZE ? 1.0 :
|
||||
size / MIN_FONT_SIZE;
|
||||
|
||||
var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
|
||||
this.ctx.font = rule;
|
||||
},
|
||||
setTextRenderingMode: function canvasGraphicsSetTextRenderingMode(mode) {
|
||||
setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
|
||||
if (mode >= TextRenderingMode.FILL_ADD_TO_PATH)
|
||||
TODO('unsupported text rendering mode: ' + mode);
|
||||
this.current.textRenderingMode = mode;
|
||||
},
|
||||
setTextRise: function canvasGraphicsSetTextRise(rise) {
|
||||
setTextRise: function CanvasGraphics_setTextRise(rise) {
|
||||
TODO('text rise: ' + rise);
|
||||
},
|
||||
moveText: function canvasGraphicsMoveText(x, y) {
|
||||
moveText: function CanvasGraphics_moveText(x, y) {
|
||||
this.current.x = this.current.lineX += x;
|
||||
this.current.y = this.current.lineY += y;
|
||||
},
|
||||
setLeadingMoveText: function canvasGraphicsSetLeadingMoveText(x, y) {
|
||||
setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
|
||||
this.setLeading(-y);
|
||||
this.moveText(x, y);
|
||||
},
|
||||
setTextMatrix: function canvasGraphicsSetTextMatrix(a, b, c, d, e, f) {
|
||||
setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
|
||||
this.current.textMatrix = [a, b, c, d, e, f];
|
||||
|
||||
this.current.x = this.current.lineX = 0;
|
||||
this.current.y = this.current.lineY = 0;
|
||||
},
|
||||
nextLine: function canvasGraphicsNextLine() {
|
||||
nextLine: function CanvasGraphics_nextLine() {
|
||||
this.moveText(0, this.current.leading);
|
||||
},
|
||||
applyTextTransforms: function canvasApplyTransforms() {
|
||||
applyTextTransforms: function CanvasGraphics_applyTextTransforms() {
|
||||
var ctx = this.ctx;
|
||||
var current = this.current;
|
||||
var textHScale = current.textHScale;
|
||||
var fontMatrix = current.font.fontMatrix || IDENTITY_MATRIX;
|
||||
var fontMatrix = current.fontMatrix || IDENTITY_MATRIX;
|
||||
|
||||
ctx.transform.apply(ctx, current.textMatrix);
|
||||
ctx.scale(1, -1);
|
||||
|
@ -603,7 +646,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
ctx.transform.apply(ctx, fontMatrix);
|
||||
ctx.scale(textHScale, 1);
|
||||
},
|
||||
getTextGeometry: function canvasGetTextGeometry() {
|
||||
getTextGeometry: function CanvasGraphics_getTextGeometry() {
|
||||
var geometry = {};
|
||||
var ctx = this.ctx;
|
||||
var font = this.current.font;
|
||||
|
@ -620,16 +663,17 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
return geometry;
|
||||
},
|
||||
|
||||
showText: function canvasGraphicsShowText(str, skipTextSelection) {
|
||||
showText: function CanvasGraphics_showText(str, skipTextSelection) {
|
||||
var ctx = this.ctx;
|
||||
var current = this.current;
|
||||
var font = current.font;
|
||||
var glyphs = font.charsToGlyphs(str);
|
||||
var fontSize = current.fontSize;
|
||||
var fontSizeScale = current.fontSizeScale;
|
||||
var charSpacing = current.charSpacing;
|
||||
var wordSpacing = current.wordSpacing;
|
||||
var textHScale = current.textHScale;
|
||||
var fontMatrix = font.fontMatrix || IDENTITY_MATRIX;
|
||||
var fontMatrix = current.fontMatrix || IDENTITY_MATRIX;
|
||||
var textHScale2 = textHScale * fontMatrix[0];
|
||||
var glyphsLength = glyphs.length;
|
||||
var textLayer = this.textLayer;
|
||||
|
@ -663,11 +707,12 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
this.save();
|
||||
ctx.scale(fontSize, fontSize);
|
||||
ctx.transform.apply(ctx, fontMatrix);
|
||||
this.executeIRQueue(glyph.codeIRQueue);
|
||||
this.executeOperatorList(glyph.operatorList);
|
||||
this.restore();
|
||||
|
||||
var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
|
||||
var width = transformed[0] * fontSize + charSpacing;
|
||||
var width = transformed[0] * fontSize +
|
||||
Util.sign(current.fontMatrix[0]) * charSpacing;
|
||||
|
||||
ctx.translate(width, 0);
|
||||
current.x += width * textHScale;
|
||||
|
@ -688,49 +733,66 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
else
|
||||
lineWidth /= scale;
|
||||
|
||||
ctx.lineWidth = lineWidth;
|
||||
|
||||
if (textSelection)
|
||||
text.geom = this.getTextGeometry();
|
||||
|
||||
var width = 0;
|
||||
if (fontSizeScale != 1.0) {
|
||||
ctx.scale(fontSizeScale, fontSizeScale);
|
||||
lineWidth /= fontSizeScale;
|
||||
}
|
||||
|
||||
ctx.lineWidth = lineWidth;
|
||||
|
||||
var x = 0;
|
||||
for (var i = 0; i < glyphsLength; ++i) {
|
||||
var glyph = glyphs[i];
|
||||
if (glyph === null) {
|
||||
// word break
|
||||
width += wordSpacing;
|
||||
x += Util.sign(current.fontMatrix[0]) * wordSpacing;
|
||||
continue;
|
||||
}
|
||||
|
||||
var char = glyph.fontChar;
|
||||
var charWidth = glyph.width * fontSize * 0.001 + charSpacing;
|
||||
var character = glyph.fontChar;
|
||||
var charWidth = glyph.width * fontSize * 0.001 +
|
||||
Util.sign(current.fontMatrix[0]) * charSpacing;
|
||||
|
||||
switch (textRenderingMode) {
|
||||
default: // other unsupported rendering modes
|
||||
case TextRenderingMode.FILL:
|
||||
case TextRenderingMode.FILL_ADD_TO_PATH:
|
||||
ctx.fillText(char, width, 0);
|
||||
break;
|
||||
case TextRenderingMode.STROKE:
|
||||
case TextRenderingMode.STROKE_ADD_TO_PATH:
|
||||
ctx.strokeText(char, width, 0);
|
||||
break;
|
||||
case TextRenderingMode.FILL_STROKE:
|
||||
case TextRenderingMode.FILL_STROKE_ADD_TO_PATH:
|
||||
ctx.fillText(char, width, 0);
|
||||
ctx.strokeText(char, width, 0);
|
||||
break;
|
||||
case TextRenderingMode.INVISIBLE:
|
||||
break;
|
||||
if (!glyph.disabled) {
|
||||
var scaledX = x / fontSizeScale;
|
||||
switch (textRenderingMode) {
|
||||
default: // other unsupported rendering modes
|
||||
case TextRenderingMode.FILL:
|
||||
case TextRenderingMode.FILL_ADD_TO_PATH:
|
||||
ctx.fillText(character, scaledX, 0);
|
||||
break;
|
||||
case TextRenderingMode.STROKE:
|
||||
case TextRenderingMode.STROKE_ADD_TO_PATH:
|
||||
ctx.strokeText(character, scaledX, 0);
|
||||
break;
|
||||
case TextRenderingMode.FILL_STROKE:
|
||||
case TextRenderingMode.FILL_STROKE_ADD_TO_PATH:
|
||||
ctx.fillText(character, scaledX, 0);
|
||||
ctx.strokeText(character, scaledX, 0);
|
||||
break;
|
||||
case TextRenderingMode.INVISIBLE:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
width += charWidth;
|
||||
x += charWidth;
|
||||
|
||||
text.str += glyph.unicode === ' ' ? '\u00A0' : glyph.unicode;
|
||||
text.length++;
|
||||
var glyphUnicode = glyph.unicode === ' ' ? '\u00A0' : glyph.unicode;
|
||||
var glyphUnicodeLength = glyphUnicode.length;
|
||||
//reverse an arabic ligature
|
||||
if (glyphUnicodeLength > 1 &&
|
||||
isRTLRangeFor(glyphUnicode.charCodeAt(0))) {
|
||||
for (var ii = glyphUnicodeLength - 1; ii >= 0; ii--)
|
||||
text.str += glyphUnicode[ii];
|
||||
} else
|
||||
text.str += glyphUnicode;
|
||||
text.length += glyphUnicodeLength;
|
||||
text.canvasWidth += charWidth;
|
||||
}
|
||||
current.x += width * textHScale2;
|
||||
current.x += x * textHScale2;
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
|
@ -739,14 +801,14 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
|
||||
return text;
|
||||
},
|
||||
showSpacedText: function canvasGraphicsShowSpacedText(arr) {
|
||||
showSpacedText: function CanvasGraphics_showSpacedText(arr) {
|
||||
var ctx = this.ctx;
|
||||
var current = this.current;
|
||||
var font = current.font;
|
||||
var fontSize = current.fontSize;
|
||||
var textHScale = current.textHScale;
|
||||
if (!font.coded)
|
||||
textHScale *= (font.fontMatrix || IDENTITY_MATRIX)[0];
|
||||
textHScale *= (current.fontMatrix || IDENTITY_MATRIX)[0];
|
||||
var arrLength = arr.length;
|
||||
var textLayer = this.textLayer;
|
||||
var text = {str: '', length: 0, canvasWidth: 0, geom: {}};
|
||||
|
@ -793,7 +855,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
text.str += shownText.str;
|
||||
}
|
||||
text.canvasWidth += shownText.canvasWidth;
|
||||
text.length += e.length;
|
||||
text.length += shownText.length;
|
||||
}
|
||||
} else {
|
||||
malformed('TJ array element ' + e + ' is not string or num');
|
||||
|
@ -803,25 +865,25 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
if (textSelection)
|
||||
this.textLayer.appendText(text, font.loadedName, fontSize);
|
||||
},
|
||||
nextLineShowText: function canvasGraphicsNextLineShowText(text) {
|
||||
nextLineShowText: function CanvasGraphics_nextLineShowText(text) {
|
||||
this.nextLine();
|
||||
this.showText(text);
|
||||
},
|
||||
nextLineSetSpacingShowText:
|
||||
function canvasGraphicsNextLineSetSpacingShowText(wordSpacing,
|
||||
charSpacing,
|
||||
text) {
|
||||
function CanvasGraphics_nextLineSetSpacingShowText(wordSpacing,
|
||||
charSpacing,
|
||||
text) {
|
||||
this.setWordSpacing(wordSpacing);
|
||||
this.setCharSpacing(charSpacing);
|
||||
this.nextLineShowText(text);
|
||||
},
|
||||
|
||||
// Type3 fonts
|
||||
setCharWidth: function canvasGraphicsSetCharWidth(xWidth, yWidth) {
|
||||
setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
|
||||
// We can safely ignore this since the width should be the same
|
||||
// as the width in the Widths array.
|
||||
},
|
||||
setCharWidthAndBounds: function canvasGraphicsSetCharWidthAndBounds(xWidth,
|
||||
setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
|
||||
yWidth,
|
||||
llx,
|
||||
lly,
|
||||
|
@ -835,20 +897,20 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
},
|
||||
|
||||
// Color
|
||||
setStrokeColorSpace: function canvasGraphicsSetStrokeColorSpace(raw) {
|
||||
setStrokeColorSpace: function CanvasGraphics_setStrokeColorSpace(raw) {
|
||||
this.current.strokeColorSpace = ColorSpace.fromIR(raw);
|
||||
},
|
||||
setFillColorSpace: function canvasGraphicsSetFillColorSpace(raw) {
|
||||
setFillColorSpace: function CanvasGraphics_setFillColorSpace(raw) {
|
||||
this.current.fillColorSpace = ColorSpace.fromIR(raw);
|
||||
},
|
||||
setStrokeColor: function canvasGraphicsSetStrokeColor(/*...*/) {
|
||||
setStrokeColor: function CanvasGraphics_setStrokeColor(/*...*/) {
|
||||
var cs = this.current.strokeColorSpace;
|
||||
var rgbColor = cs.getRgb(arguments);
|
||||
var color = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
|
||||
this.ctx.strokeStyle = color;
|
||||
this.current.strokeColor = color;
|
||||
},
|
||||
getColorN_IR_Pattern: function canvasGraphicsGetColorN_IR_Pattern(IR, cs) {
|
||||
getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR, cs) {
|
||||
if (IR[0] == 'TilingPattern') {
|
||||
var args = IR[1];
|
||||
var base = cs.base;
|
||||
|
@ -864,38 +926,38 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
}
|
||||
var pattern = new TilingPattern(IR, color, this.ctx, this.objs);
|
||||
} else if (IR[0] == 'RadialAxial' || IR[0] == 'Dummy') {
|
||||
var pattern = Pattern.shadingFromIR(this.ctx, IR);
|
||||
var pattern = Pattern.shadingFromIR(IR);
|
||||
} else {
|
||||
throw 'Unkown IR type';
|
||||
error('Unkown IR type ' + IR[0]);
|
||||
}
|
||||
return pattern;
|
||||
},
|
||||
setStrokeColorN_IR: function canvasGraphicsSetStrokeColorN(/*...*/) {
|
||||
setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
|
||||
var cs = this.current.strokeColorSpace;
|
||||
|
||||
if (cs.name == 'Pattern') {
|
||||
this.current.strokeColor = this.getColorN_IR_Pattern(arguments, cs);
|
||||
this.current.strokeColor = this.getColorN_Pattern(arguments, cs);
|
||||
} else {
|
||||
this.setStrokeColor.apply(this, arguments);
|
||||
}
|
||||
},
|
||||
setFillColor: function canvasGraphicsSetFillColor(/*...*/) {
|
||||
setFillColor: function CanvasGraphics_setFillColor(/*...*/) {
|
||||
var cs = this.current.fillColorSpace;
|
||||
var rgbColor = cs.getRgb(arguments);
|
||||
var color = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
|
||||
this.ctx.fillStyle = color;
|
||||
this.current.fillColor = color;
|
||||
},
|
||||
setFillColorN_IR: function canvasGraphicsSetFillColorN(/*...*/) {
|
||||
setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
|
||||
var cs = this.current.fillColorSpace;
|
||||
|
||||
if (cs.name == 'Pattern') {
|
||||
this.current.fillColor = this.getColorN_IR_Pattern(arguments, cs);
|
||||
this.current.fillColor = this.getColorN_Pattern(arguments, cs);
|
||||
} else {
|
||||
this.setFillColor.apply(this, arguments);
|
||||
}
|
||||
},
|
||||
setStrokeGray: function canvasGraphicsSetStrokeGray(gray) {
|
||||
setStrokeGray: function CanvasGraphics_setStrokeGray(gray) {
|
||||
if (!(this.current.strokeColorSpace instanceof DeviceGrayCS))
|
||||
this.current.strokeColorSpace = new DeviceGrayCS();
|
||||
|
||||
|
@ -903,7 +965,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
this.ctx.strokeStyle = color;
|
||||
this.current.strokeColor = color;
|
||||
},
|
||||
setFillGray: function canvasGraphicsSetFillGray(gray) {
|
||||
setFillGray: function CanvasGraphics_setFillGray(gray) {
|
||||
if (!(this.current.fillColorSpace instanceof DeviceGrayCS))
|
||||
this.current.fillColorSpace = new DeviceGrayCS();
|
||||
|
||||
|
@ -911,7 +973,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
this.ctx.fillStyle = color;
|
||||
this.current.fillColor = color;
|
||||
},
|
||||
setStrokeRGBColor: function canvasGraphicsSetStrokeRGBColor(r, g, b) {
|
||||
setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
|
||||
if (!(this.current.strokeColorSpace instanceof DeviceRgbCS))
|
||||
this.current.strokeColorSpace = new DeviceRgbCS();
|
||||
|
||||
|
@ -919,7 +981,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
this.ctx.strokeStyle = color;
|
||||
this.current.strokeColor = color;
|
||||
},
|
||||
setFillRGBColor: function canvasGraphicsSetFillRGBColor(r, g, b) {
|
||||
setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
|
||||
if (!(this.current.fillColorSpace instanceof DeviceRgbCS))
|
||||
this.current.fillColorSpace = new DeviceRgbCS();
|
||||
|
||||
|
@ -927,7 +989,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
this.ctx.fillStyle = color;
|
||||
this.current.fillColor = color;
|
||||
},
|
||||
setStrokeCMYKColor: function canvasGraphicsSetStrokeCMYKColor(c, m, y, k) {
|
||||
setStrokeCMYKColor: function CanvasGraphics_setStrokeCMYKColor(c, m, y, k) {
|
||||
if (!(this.current.strokeColorSpace instanceof DeviceCmykCS))
|
||||
this.current.strokeColorSpace = new DeviceCmykCS();
|
||||
|
||||
|
@ -935,7 +997,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
this.ctx.strokeStyle = color;
|
||||
this.current.strokeColor = color;
|
||||
},
|
||||
setFillCMYKColor: function canvasGraphicsSetFillCMYKColor(c, m, y, k) {
|
||||
setFillCMYKColor: function CanvasGraphics_setFillCMYKColor(c, m, y, k) {
|
||||
if (!(this.current.fillColorSpace instanceof DeviceCmykCS))
|
||||
this.current.fillColorSpace = new DeviceCmykCS();
|
||||
|
||||
|
@ -944,11 +1006,12 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
this.current.fillColor = color;
|
||||
},
|
||||
|
||||
shadingFill: function canvasGraphicsShadingFill(patternIR) {
|
||||
shadingFill: function CanvasGraphics_shadingFill(patternIR) {
|
||||
var ctx = this.ctx;
|
||||
|
||||
this.save();
|
||||
ctx.fillStyle = Pattern.shadingFromIR(ctx, patternIR);
|
||||
var pattern = Pattern.shadingFromIR(patternIR);
|
||||
ctx.fillStyle = pattern.getPattern(ctx);
|
||||
|
||||
var inv = ctx.mozCurrentTransformInverse;
|
||||
if (inv) {
|
||||
|
@ -981,14 +1044,14 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
},
|
||||
|
||||
// Images
|
||||
beginInlineImage: function canvasGraphicsBeginInlineImage() {
|
||||
beginInlineImage: function CanvasGraphics_beginInlineImage() {
|
||||
error('Should not call beginInlineImage');
|
||||
},
|
||||
beginImageData: function canvasGraphicsBeginImageData() {
|
||||
beginImageData: function CanvasGraphics_beginImageData() {
|
||||
error('Should not call beginImageData');
|
||||
},
|
||||
|
||||
paintFormXObjectBegin: function canvasGraphicsPaintFormXObjectBegin(matrix,
|
||||
paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
|
||||
bbox) {
|
||||
this.save();
|
||||
|
||||
|
@ -1004,11 +1067,11 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
}
|
||||
},
|
||||
|
||||
paintFormXObjectEnd: function canvasGraphicsPaintFormXObjectEnd() {
|
||||
paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
|
||||
this.restore();
|
||||
},
|
||||
|
||||
paintJpegXObject: function canvasGraphicsPaintJpegXObject(objId, w, h) {
|
||||
paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
|
||||
var domImage = this.objs.get(objId);
|
||||
if (!domImage) {
|
||||
error('Dependent image isn\'t ready yet');
|
||||
|
@ -1026,7 +1089,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
this.restore();
|
||||
},
|
||||
|
||||
paintImageMaskXObject: function canvasGraphicsPaintImageMaskXObject(
|
||||
paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(
|
||||
imgArray, inverseDecode, width, height) {
|
||||
function applyStencilMask(buffer, inverseDecode) {
|
||||
var imgArrayPos = 0;
|
||||
|
@ -1056,7 +1119,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
// scale the image to the unit square
|
||||
ctx.scale(1 / w, -1 / h);
|
||||
|
||||
var tmpCanvas = new this.ScratchCanvas(w, h);
|
||||
var tmpCanvas = createScratchCanvas(w, h);
|
||||
var tmpCtx = tmpCanvas.getContext('2d');
|
||||
|
||||
var fillColor = this.current.fillColor;
|
||||
|
@ -1075,7 +1138,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
this.restore();
|
||||
},
|
||||
|
||||
paintImageXObject: function canvasGraphicsPaintImageXObject(objId) {
|
||||
paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
|
||||
var imgData = this.objs.get(objId);
|
||||
if (!imgData)
|
||||
error('Dependent image isn\'t ready yet');
|
||||
|
@ -1087,7 +1150,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
// scale the image to the unit square
|
||||
ctx.scale(1 / w, -1 / h);
|
||||
|
||||
var tmpCanvas = new this.ScratchCanvas(w, h);
|
||||
var tmpCanvas = createScratchCanvas(w, h);
|
||||
var tmpCtx = tmpCanvas.getContext('2d');
|
||||
this.putBinaryImageData(tmpCtx, imgData, w, h);
|
||||
|
||||
|
@ -1095,41 +1158,41 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
this.restore();
|
||||
},
|
||||
|
||||
putBinaryImageData: function canvasPutBinaryImageData() {
|
||||
putBinaryImageData: function CanvasGraphics_putBinaryImageData() {
|
||||
//
|
||||
},
|
||||
|
||||
// Marked content
|
||||
|
||||
markPoint: function canvasGraphicsMarkPoint(tag) {
|
||||
markPoint: function CanvasGraphics_markPoint(tag) {
|
||||
TODO('Marked content');
|
||||
},
|
||||
markPointProps: function canvasGraphicsMarkPointProps(tag, properties) {
|
||||
markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
|
||||
TODO('Marked content');
|
||||
},
|
||||
beginMarkedContent: function canvasGraphicsBeginMarkedContent(tag) {
|
||||
beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
|
||||
TODO('Marked content');
|
||||
},
|
||||
beginMarkedContentProps:
|
||||
function canvasGraphicsBeginMarkedContentProps(tag, properties) {
|
||||
beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
|
||||
tag, properties) {
|
||||
TODO('Marked content');
|
||||
},
|
||||
endMarkedContent: function canvasGraphicsEndMarkedContent() {
|
||||
endMarkedContent: function CanvasGraphics_endMarkedContent() {
|
||||
TODO('Marked content');
|
||||
},
|
||||
|
||||
// Compatibility
|
||||
|
||||
beginCompat: function canvasGraphicsBeginCompat() {
|
||||
beginCompat: function CanvasGraphics_beginCompat() {
|
||||
TODO('ignore undefined operators (should we do that anyway?)');
|
||||
},
|
||||
endCompat: function canvasGraphicsEndCompat() {
|
||||
endCompat: function CanvasGraphics_endCompat() {
|
||||
TODO('stop ignoring undefined operators');
|
||||
},
|
||||
|
||||
// Helper functions
|
||||
|
||||
consumePath: function canvasGraphicsConsumePath() {
|
||||
consumePath: function CanvasGraphics_consumePath() {
|
||||
if (this.pendingClip) {
|
||||
var savedFillRule = null;
|
||||
if (this.pendingClip == EO_CLIP)
|
||||
|
@ -1146,15 +1209,15 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
|
|||
// We generally keep the canvas context set for
|
||||
// nonzero-winding, and just set evenodd for the operations
|
||||
// that need them.
|
||||
setEOFillRule: function canvasGraphicsSetEOFillRule() {
|
||||
setEOFillRule: function CanvasGraphics_setEOFillRule() {
|
||||
var savedFillRule = this.ctx.mozFillRule;
|
||||
this.ctx.mozFillRule = 'evenodd';
|
||||
return savedFillRule;
|
||||
},
|
||||
restoreFillRule: function canvasGraphicsRestoreFillRule(rule) {
|
||||
restoreFillRule: function CanvasGraphics_restoreFillRule(rule) {
|
||||
this.ctx.mozFillRule = rule;
|
||||
},
|
||||
getSinglePixelWidth: function getSinglePixelWidth(scale) {
|
||||
getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
|
||||
var inverse = this.ctx.mozCurrentTransformInverse;
|
||||
return Math.abs(inverse[0] + inverse[2]);
|
||||
}
|
||||
|
|
|
@ -12,17 +12,17 @@ var ColorSpace = (function ColorSpaceClosure() {
|
|||
ColorSpace.prototype = {
|
||||
// Input: array of size numComps representing color component values
|
||||
// Output: array of rgb values, each value ranging from [0.1]
|
||||
getRgb: function colorSpaceGetRgb(color) {
|
||||
getRgb: function ColorSpace_getRgb(color) {
|
||||
error('Should not call ColorSpace.getRgb: ' + color);
|
||||
},
|
||||
// Input: Uint8Array of component values, each value scaled to [0,255]
|
||||
// Output: Uint8Array of rgb values, each value scaled to [0,255]
|
||||
getRgbBuffer: function colorSpaceGetRgbBuffer(input) {
|
||||
getRgbBuffer: function ColorSpace_getRgbBuffer(input) {
|
||||
error('Should not call ColorSpace.getRgbBuffer: ' + input);
|
||||
}
|
||||
};
|
||||
|
||||
ColorSpace.parse = function colorSpaceParse(cs, xref, res) {
|
||||
ColorSpace.parse = function ColorSpace_parse(cs, xref, res) {
|
||||
var IR = ColorSpace.parseToIR(cs, xref, res);
|
||||
if (IR instanceof AlternateCS)
|
||||
return IR;
|
||||
|
@ -30,7 +30,7 @@ var ColorSpace = (function ColorSpaceClosure() {
|
|||
return ColorSpace.fromIR(IR);
|
||||
};
|
||||
|
||||
ColorSpace.fromIR = function colorSpaceFromIR(IR) {
|
||||
ColorSpace.fromIR = function ColorSpace_fromIR(IR) {
|
||||
var name = isArray(IR) ? IR[0] : IR;
|
||||
|
||||
switch (name) {
|
||||
|
@ -57,15 +57,20 @@ var ColorSpace = (function ColorSpaceClosure() {
|
|||
|
||||
return new AlternateCS(numComps, ColorSpace.fromIR(alt),
|
||||
PDFFunction.fromIR(tintFnIR));
|
||||
case 'LabCS':
|
||||
var whitePoint = IR[1].WhitePoint;
|
||||
var blackPoint = IR[1].BlackPoint;
|
||||
var range = IR[1].Range;
|
||||
return new LabCS(whitePoint, blackPoint, range);
|
||||
default:
|
||||
error('Unkown name ' + name);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
ColorSpace.parseToIR = function colorSpaceParseToIR(cs, xref, res) {
|
||||
ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) {
|
||||
if (isName(cs)) {
|
||||
var colorSpaces = xref.fetchIfRef(res.get('ColorSpace'));
|
||||
var colorSpaces = res.get('ColorSpace');
|
||||
if (isDict(colorSpaces)) {
|
||||
var refcs = colorSpaces.get(cs.name);
|
||||
if (refcs)
|
||||
|
@ -130,6 +135,7 @@ var ColorSpace = (function ColorSpaceClosure() {
|
|||
basePatternCS = ColorSpace.parseToIR(basePatternCS, xref, res);
|
||||
return ['PatternCS', basePatternCS];
|
||||
case 'Indexed':
|
||||
case 'I':
|
||||
var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res);
|
||||
var hiVal = cs[2] + 1;
|
||||
var lookup = xref.fetchIfRef(cs[3]);
|
||||
|
@ -146,6 +152,8 @@ var ColorSpace = (function ColorSpaceClosure() {
|
|||
var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3]));
|
||||
return ['AlternateCS', numComps, alt, tintFnIR];
|
||||
case 'Lab':
|
||||
var params = cs[1].getAll();
|
||||
return ['LabCS', params];
|
||||
default:
|
||||
error('unimplemented color space object "' + mode + '"');
|
||||
}
|
||||
|
@ -163,7 +171,7 @@ var ColorSpace = (function ColorSpaceClosure() {
|
|||
* @param {Array} decode Decode map (usually from an image).
|
||||
* @param {Number} n Number of components the color space has.
|
||||
*/
|
||||
ColorSpace.isDefaultDecode = function colorSpaceIsDefaultDecode(decode, n) {
|
||||
ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) {
|
||||
if (!decode)
|
||||
return true;
|
||||
|
||||
|
@ -199,11 +207,11 @@ var AlternateCS = (function AlternateCSClosure() {
|
|||
}
|
||||
|
||||
AlternateCS.prototype = {
|
||||
getRgb: function altcs_getRgb(color) {
|
||||
getRgb: function AlternateCS_getRgb(color) {
|
||||
var tinted = this.tintFn(color);
|
||||
return this.base.getRgb(tinted);
|
||||
},
|
||||
getRgbBuffer: function altcs_getRgbBuffer(input, bits) {
|
||||
getRgbBuffer: function AlternateCS_getRgbBuffer(input, bits) {
|
||||
var tintFn = this.tintFn;
|
||||
var base = this.base;
|
||||
var scale = 1 / ((1 << bits) - 1);
|
||||
|
@ -212,7 +220,7 @@ var AlternateCS = (function AlternateCSClosure() {
|
|||
var baseNumComps = base.numComps;
|
||||
var baseBuf = new Uint8Array(baseNumComps * length);
|
||||
var numComps = this.numComps;
|
||||
var scaled = new Array(numComps);
|
||||
var scaled = [];
|
||||
|
||||
for (var i = 0; i < length; i += numComps) {
|
||||
for (var z = 0; z < numComps; ++z)
|
||||
|
@ -224,7 +232,7 @@ var AlternateCS = (function AlternateCSClosure() {
|
|||
}
|
||||
return base.getRgbBuffer(baseBuf, 8);
|
||||
},
|
||||
isDefaultDecode: function altcs_isDefaultDecode(decodeMap) {
|
||||
isDefaultDecode: function AlternateCS_isDefaultDecode(decodeMap) {
|
||||
return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
|
||||
}
|
||||
};
|
||||
|
@ -267,7 +275,7 @@ var IndexedCS = (function IndexedCSClosure() {
|
|||
}
|
||||
|
||||
IndexedCS.prototype = {
|
||||
getRgb: function indexcs_getRgb(color) {
|
||||
getRgb: function IndexedCS_getRgb(color) {
|
||||
var numComps = this.base.numComps;
|
||||
var start = color[0] * numComps;
|
||||
var c = [];
|
||||
|
@ -277,7 +285,7 @@ var IndexedCS = (function IndexedCSClosure() {
|
|||
|
||||
return this.base.getRgb(c);
|
||||
},
|
||||
getRgbBuffer: function indexcs_getRgbBuffer(input) {
|
||||
getRgbBuffer: function IndexedCS_getRgbBuffer(input) {
|
||||
var base = this.base;
|
||||
var numComps = base.numComps;
|
||||
var lookup = this.lookup;
|
||||
|
@ -294,7 +302,7 @@ var IndexedCS = (function IndexedCSClosure() {
|
|||
|
||||
return base.getRgbBuffer(baseBuf, 8);
|
||||
},
|
||||
isDefaultDecode: function indexcs_isDefaultDecode(decodeMap) {
|
||||
isDefaultDecode: function IndexedCS_isDefaultDecode(decodeMap) {
|
||||
// indexed color maps shouldn't be changed
|
||||
return true;
|
||||
}
|
||||
|
@ -310,11 +318,11 @@ var DeviceGrayCS = (function DeviceGrayCSClosure() {
|
|||
}
|
||||
|
||||
DeviceGrayCS.prototype = {
|
||||
getRgb: function graycs_getRgb(color) {
|
||||
getRgb: function DeviceGrayCS_getRgb(color) {
|
||||
var c = color[0];
|
||||
return [c, c, c];
|
||||
},
|
||||
getRgbBuffer: function graycs_getRgbBuffer(input, bits) {
|
||||
getRgbBuffer: function DeviceGrayCS_getRgbBuffer(input, bits) {
|
||||
var scale = 255 / ((1 << bits) - 1);
|
||||
var length = input.length;
|
||||
var rgbBuf = new Uint8Array(length * 3);
|
||||
|
@ -326,7 +334,7 @@ var DeviceGrayCS = (function DeviceGrayCSClosure() {
|
|||
}
|
||||
return rgbBuf;
|
||||
},
|
||||
isDefaultDecode: function graycs_isDefaultDecode(decodeMap) {
|
||||
isDefaultDecode: function DeviceGrayCS_isDefaultDecode(decodeMap) {
|
||||
return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
|
||||
}
|
||||
};
|
||||
|
@ -340,10 +348,10 @@ var DeviceRgbCS = (function DeviceRgbCSClosure() {
|
|||
this.defaultColor = [0, 0, 0];
|
||||
}
|
||||
DeviceRgbCS.prototype = {
|
||||
getRgb: function rgbcs_getRgb(color) {
|
||||
getRgb: function DeviceRgbCS_getRgb(color) {
|
||||
return color;
|
||||
},
|
||||
getRgbBuffer: function rgbcs_getRgbBuffer(input, bits) {
|
||||
getRgbBuffer: function DeviceRgbCS_getRgbBuffer(input, bits) {
|
||||
if (bits == 8)
|
||||
return input;
|
||||
var scale = 255 / ((1 << bits) - 1);
|
||||
|
@ -353,7 +361,7 @@ var DeviceRgbCS = (function DeviceRgbCSClosure() {
|
|||
rgbBuf[i] = (scale * input[i]) | 0;
|
||||
return rgbBuf;
|
||||
},
|
||||
isDefaultDecode: function rgbcs_isDefaultDecode(decodeMap) {
|
||||
isDefaultDecode: function DeviceRgbCS_isDefaultDecode(decodeMap) {
|
||||
return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
|
||||
}
|
||||
};
|
||||
|
@ -367,61 +375,22 @@ var DeviceCmykCS = (function DeviceCmykCSClosure() {
|
|||
this.defaultColor = [0, 0, 0, 1];
|
||||
}
|
||||
DeviceCmykCS.prototype = {
|
||||
getRgb: function cmykcs_getRgb(color) {
|
||||
getRgb: function DeviceCmykCS_getRgb(color) {
|
||||
var c = color[0], m = color[1], y = color[2], k = color[3];
|
||||
var c1 = 1 - c, m1 = 1 - m, y1 = 1 - y, k1 = 1 - k;
|
||||
|
||||
var x, r, g, b;
|
||||
// this is a matrix multiplication, unrolled for performance
|
||||
// code is taken from the poppler implementation
|
||||
x = c1 * m1 * y1 * k1; // 0 0 0 0
|
||||
r = g = b = x;
|
||||
x = c1 * m1 * y1 * k; // 0 0 0 1
|
||||
r += 0.1373 * x;
|
||||
g += 0.1216 * x;
|
||||
b += 0.1255 * x;
|
||||
x = c1 * m1 * y * k1; // 0 0 1 0
|
||||
r += x;
|
||||
g += 0.9490 * x;
|
||||
x = c1 * m1 * y * k; // 0 0 1 1
|
||||
r += 0.1098 * x;
|
||||
g += 0.1020 * x;
|
||||
x = c1 * m * y1 * k1; // 0 1 0 0
|
||||
r += 0.9255 * x;
|
||||
b += 0.5490 * x;
|
||||
x = c1 * m * y1 * k; // 0 1 0 1
|
||||
r += 0.1412 * x;
|
||||
x = c1 * m * y * k1; // 0 1 1 0
|
||||
r += 0.9294 * x;
|
||||
g += 0.1098 * x;
|
||||
b += 0.1412 * x;
|
||||
x = c1 * m * y * k; // 0 1 1 1
|
||||
r += 0.1333 * x;
|
||||
x = c * m1 * y1 * k1; // 1 0 0 0
|
||||
g += 0.6784 * x;
|
||||
b += 0.9373 * x;
|
||||
x = c * m1 * y1 * k; // 1 0 0 1
|
||||
g += 0.0588 * x;
|
||||
b += 0.1412 * x;
|
||||
x = c * m1 * y * k1; // 1 0 1 0
|
||||
g += 0.6510 * x;
|
||||
b += 0.3137 * x;
|
||||
x = c * m1 * y * k; // 1 0 1 1
|
||||
g += 0.0745 * x;
|
||||
x = c * m * y1 * k1; // 1 1 0 0
|
||||
r += 0.1804 * x;
|
||||
g += 0.1922 * x;
|
||||
b += 0.5725 * x;
|
||||
x = c * m * y1 * k; // 1 1 0 1
|
||||
b += 0.0078 * x;
|
||||
x = c * m * y * k1; // 1 1 1 0
|
||||
r += 0.2118 * x;
|
||||
g += 0.2119 * x;
|
||||
b += 0.2235 * x;
|
||||
// CMYK -> CMY: http://www.easyrgb.com/index.php?X=MATH&H=14#text14
|
||||
c = (c * (1 - k) + k);
|
||||
m = (m * (1 - k) + k);
|
||||
y = (y * (1 - k) + k);
|
||||
|
||||
// CMY -> RGB: http://www.easyrgb.com/index.php?X=MATH&H=12#text12
|
||||
var r = (1 - c);
|
||||
var g = (1 - m);
|
||||
var b = (1 - y);
|
||||
|
||||
return [r, g, b];
|
||||
},
|
||||
getRgbBuffer: function cmykcs_getRgbBuffer(colorBuf, bits) {
|
||||
getRgbBuffer: function DeviceCmykCS_getRgbBuffer(colorBuf, bits) {
|
||||
var scale = 1 / ((1 << bits) - 1);
|
||||
var length = colorBuf.length / 4;
|
||||
var rgbBuf = new Uint8Array(length * 3);
|
||||
|
@ -440,7 +409,7 @@ var DeviceCmykCS = (function DeviceCmykCSClosure() {
|
|||
|
||||
return rgbBuf;
|
||||
},
|
||||
isDefaultDecode: function cmykcs_isDefaultDecode(decodeMap) {
|
||||
isDefaultDecode: function DeviceCmykCS_isDefaultDecode(decodeMap) {
|
||||
return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
|
||||
}
|
||||
};
|
||||
|
@ -448,3 +417,116 @@ var DeviceCmykCS = (function DeviceCmykCSClosure() {
|
|||
return DeviceCmykCS;
|
||||
})();
|
||||
|
||||
//
|
||||
// LabCS: Based on "PDF Reference, Sixth Ed", p.250
|
||||
//
|
||||
var LabCS = (function LabCSClosure() {
|
||||
function LabCS(whitePoint, blackPoint, range) {
|
||||
this.name = 'Lab';
|
||||
this.numComps = 3;
|
||||
this.defaultColor = [0, 0, 0];
|
||||
|
||||
if (!whitePoint)
|
||||
error('WhitePoint missing - required for color space Lab');
|
||||
blackPoint = blackPoint || [0, 0, 0];
|
||||
range = range || [-100, 100, -100, 100];
|
||||
|
||||
// Translate args to spec variables
|
||||
this.XW = whitePoint[0];
|
||||
this.YW = whitePoint[1];
|
||||
this.ZW = whitePoint[2];
|
||||
this.amin = range[0];
|
||||
this.amax = range[1];
|
||||
this.bmin = range[2];
|
||||
this.bmax = range[3];
|
||||
|
||||
// These are here just for completeness - the spec doesn't offer any
|
||||
// formulas that use BlackPoint in Lab
|
||||
this.XB = blackPoint[0];
|
||||
this.YB = blackPoint[1];
|
||||
this.ZB = blackPoint[2];
|
||||
|
||||
// Validate vars as per spec
|
||||
if (this.XW < 0 || this.ZW < 0 || this.YW !== 1)
|
||||
error('Invalid WhitePoint components, no fallback available');
|
||||
|
||||
if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
|
||||
warn('Invalid BlackPoint, falling back to default');
|
||||
this.XB = this.YB = this.ZB = 0;
|
||||
}
|
||||
|
||||
if (this.amin > this.amax || this.bmin > this.bmax) {
|
||||
warn('Invalid Range, falling back to defaults');
|
||||
this.amin = -100;
|
||||
this.amax = 100;
|
||||
this.bmin = -100;
|
||||
this.bmax = 100;
|
||||
}
|
||||
};
|
||||
|
||||
// Function g(x) from spec
|
||||
function g(x) {
|
||||
if (x >= 6 / 29)
|
||||
return x * x * x;
|
||||
else
|
||||
return (108 / 841) * (x - 4 / 29);
|
||||
}
|
||||
|
||||
LabCS.prototype = {
|
||||
getRgb: function LabCS_getRgb(color) {
|
||||
// Ls,as,bs <---> L*,a*,b* in the spec
|
||||
var Ls = color[0], as = color[1], bs = color[2];
|
||||
|
||||
// Adjust limits of 'as' and 'bs'
|
||||
as = as > this.amax ? this.amax : as;
|
||||
as = as < this.amin ? this.amin : as;
|
||||
bs = bs > this.bmax ? this.bmax : bs;
|
||||
bs = bs < this.bmin ? this.bmin : bs;
|
||||
|
||||
// Computes intermediate variables X,Y,Z as per spec
|
||||
var M = (Ls + 16) / 116;
|
||||
var L = M + (as / 500);
|
||||
var N = M - (bs / 200);
|
||||
var X = this.XW * g(L);
|
||||
var Y = this.YW * g(M);
|
||||
var Z = this.ZW * g(N);
|
||||
|
||||
// XYZ to RGB 3x3 matrix, from:
|
||||
// http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html#RTFToC18
|
||||
var XYZtoRGB = [3.240479, -1.537150, -0.498535,
|
||||
-0.969256, 1.875992, 0.041556,
|
||||
0.055648, -0.204043, 1.057311];
|
||||
|
||||
return Util.apply3dTransform(XYZtoRGB, [X, Y, Z]);
|
||||
},
|
||||
getRgbBuffer: function LabCS_getRgbBuffer(input, bits) {
|
||||
if (bits == 8)
|
||||
return input;
|
||||
var scale = 255 / ((1 << bits) - 1);
|
||||
var i, length = input.length / 3;
|
||||
var rgbBuf = new Uint8Array(length);
|
||||
|
||||
var j = 0;
|
||||
for (i = 0; i < length; ++i) {
|
||||
// Convert L*, a*, s* into RGB
|
||||
var rgb = this.getRgb([input[i], input[i + 1], input[i + 2]]);
|
||||
rgbBuf[j++] = rgb[0];
|
||||
rgbBuf[j++] = rgb[1];
|
||||
rgbBuf[j++] = rgb[2];
|
||||
}
|
||||
|
||||
return rgbBuf;
|
||||
},
|
||||
isDefaultDecode: function LabCS_isDefaultDecode(decodeMap) {
|
||||
// From Table 90 in Adobe's:
|
||||
// "Document management - Portable document format", 1st ed, 2008
|
||||
if (decodeMap[0] === 0 && decodeMap[1] === 100 &&
|
||||
decodeMap[2] === this.amin && decodeMap[3] === this.amax &&
|
||||
decodeMap[4] === this.bmin && decodeMap[5] === this.bmax)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
};
|
||||
return LabCS;
|
||||
})();
|
||||
|
|
318
src/core.js
318
src/core.js
|
@ -33,7 +33,9 @@ function getPdf(arg, callback) {
|
|||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('GET', params.url);
|
||||
xhr.mozResponseType = xhr.responseType = 'arraybuffer';
|
||||
xhr.expected = (params.url.indexOf('file:') === 0) ? 0 : 200;
|
||||
var protocol = params.url.indexOf(':') < 0 ? window.location.protocol :
|
||||
params.url.substring(0, params.url.indexOf(':') + 1);
|
||||
xhr.expected = (protocol === 'http:' || protocol === 'https:') ? 200 : 0;
|
||||
|
||||
if ('progress' in params)
|
||||
xhr.onprogress = params.progress || undefined;
|
||||
|
@ -55,18 +57,14 @@ function getPdf(arg, callback) {
|
|||
xhr.send(null);
|
||||
}
|
||||
globalScope.PDFJS.getPdf = getPdf;
|
||||
globalScope.PDFJS.pdfBug = false;
|
||||
|
||||
var Page = (function PageClosure() {
|
||||
function Page(xref, pageNumber, pageDict, ref) {
|
||||
this.pageNumber = pageNumber;
|
||||
this.pageDict = pageDict;
|
||||
this.stats = {
|
||||
create: Date.now(),
|
||||
compile: 0.0,
|
||||
fonts: 0.0,
|
||||
images: 0.0,
|
||||
render: 0.0
|
||||
};
|
||||
this.stats = new StatTimer();
|
||||
this.stats.enabled = !!globalScope.PDFJS.enableStats;
|
||||
this.xref = xref;
|
||||
this.ref = ref;
|
||||
|
||||
|
@ -74,14 +72,14 @@ var Page = (function PageClosure() {
|
|||
}
|
||||
|
||||
Page.prototype = {
|
||||
getPageProp: function pageGetPageProp(key) {
|
||||
return this.xref.fetchIfRef(this.pageDict.get(key));
|
||||
getPageProp: function Page_getPageProp(key) {
|
||||
return this.pageDict.get(key);
|
||||
},
|
||||
inheritPageProp: function pageInheritPageProp(key) {
|
||||
inheritPageProp: function Page_inheritPageProp(key) {
|
||||
var dict = this.pageDict;
|
||||
var obj = dict.get(key);
|
||||
while (obj === undefined) {
|
||||
dict = this.xref.fetchIfRef(dict.get('Parent'));
|
||||
dict = dict.get('Parent');
|
||||
if (!dict)
|
||||
break;
|
||||
obj = dict.get(key);
|
||||
|
@ -102,25 +100,35 @@ var Page = (function PageClosure() {
|
|||
return shadow(this, 'mediaBox', obj);
|
||||
},
|
||||
get view() {
|
||||
var obj = this.inheritPageProp('CropBox');
|
||||
var cropBox = this.inheritPageProp('CropBox');
|
||||
var view = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: this.width,
|
||||
height: this.height
|
||||
};
|
||||
if (!isArray(cropBox) || cropBox.length !== 4)
|
||||
return shadow(this, 'view', view);
|
||||
|
||||
var mediaBox = this.mediaBox;
|
||||
var offsetX = mediaBox[0], offsetY = mediaBox[1];
|
||||
if (isArray(obj) && obj.length == 4) {
|
||||
var tl = this.rotatePoint(obj[0] - offsetX, obj[1] - offsetY);
|
||||
var br = this.rotatePoint(obj[2] - offsetX, obj[3] - offsetY);
|
||||
view.x = Math.min(tl.x, br.x);
|
||||
view.y = Math.min(tl.y, br.y);
|
||||
view.width = Math.abs(tl.x - br.x);
|
||||
view.height = Math.abs(tl.y - br.y);
|
||||
}
|
||||
|
||||
return shadow(this, 'cropBox', view);
|
||||
// From the spec, 6th ed., p.963:
|
||||
// "The crop, bleed, trim, and art boxes should not ordinarily
|
||||
// extend beyond the boundaries of the media box. If they do, they are
|
||||
// effectively reduced to their intersection with the media box."
|
||||
cropBox = Util.intersect(cropBox, mediaBox);
|
||||
if (!cropBox)
|
||||
return shadow(this, 'view', view);
|
||||
|
||||
var tl = this.rotatePoint(cropBox[0] - offsetX, cropBox[1] - offsetY);
|
||||
var br = this.rotatePoint(cropBox[2] - offsetX, cropBox[3] - offsetY);
|
||||
view.x = Math.min(tl.x, br.x);
|
||||
view.y = Math.min(tl.y, br.y);
|
||||
view.width = Math.abs(tl.x - br.x);
|
||||
view.height = Math.abs(tl.y - br.y);
|
||||
|
||||
return shadow(this, 'view', view);
|
||||
},
|
||||
get annotations() {
|
||||
return shadow(this, 'annotations', this.inheritPageProp('Annots'));
|
||||
|
@ -162,10 +170,10 @@ var Page = (function PageClosure() {
|
|||
return shadow(this, 'rotate', rotate);
|
||||
},
|
||||
|
||||
startRenderingFromIRQueue: function pageStartRenderingFromIRQueue(
|
||||
IRQueue, fonts) {
|
||||
startRenderingFromOperatorList:
|
||||
function Page_startRenderingFromOperatorList(operatorList, fonts) {
|
||||
var self = this;
|
||||
this.IRQueue = IRQueue;
|
||||
this.operatorList = operatorList;
|
||||
|
||||
var displayContinuation = function pageDisplayContinuation() {
|
||||
// Always defer call to display() to work around bug in
|
||||
|
@ -176,20 +184,23 @@ var Page = (function PageClosure() {
|
|||
};
|
||||
|
||||
this.ensureFonts(fonts,
|
||||
function pageStartRenderingFromIRQueueEnsureFonts() {
|
||||
displayContinuation();
|
||||
});
|
||||
function pageStartRenderingFromOperatorListEnsureFonts() {
|
||||
displayContinuation();
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
getIRQueue: function pageGetIRQueue(handler, dependency) {
|
||||
if (this.IRQueue) {
|
||||
getOperatorList: function Page_getOperatorList(handler, dependency) {
|
||||
if (this.operatorList) {
|
||||
// content was compiled
|
||||
return this.IRQueue;
|
||||
return this.operatorList;
|
||||
}
|
||||
|
||||
this.stats.time('Build IR Queue');
|
||||
|
||||
var xref = this.xref;
|
||||
var content = xref.fetchIfRef(this.content);
|
||||
var resources = xref.fetchIfRef(this.resources);
|
||||
var content = this.content;
|
||||
var resources = this.resources;
|
||||
if (isArray(content)) {
|
||||
// fetching items
|
||||
var i, n = content.length;
|
||||
|
@ -206,12 +217,13 @@ var Page = (function PageClosure() {
|
|||
|
||||
var pe = this.pe = new PartialEvaluator(
|
||||
xref, handler, 'p' + this.pageNumber + '_');
|
||||
var IRQueue = {};
|
||||
return (this.IRQueue = pe.getIRQueue(content, resources, IRQueue,
|
||||
dependency));
|
||||
|
||||
this.operatorList = pe.getOperatorList(content, resources, dependency);
|
||||
this.stats.timeEnd('Build IR Queue');
|
||||
return this.operatorList;
|
||||
},
|
||||
|
||||
extractTextContent: function pageExtractPageContent() {
|
||||
extractTextContent: function Page_extractTextContent() {
|
||||
if ('textContent' in this) {
|
||||
// text content was extracted
|
||||
return this.textContent;
|
||||
|
@ -241,28 +253,30 @@ var Page = (function PageClosure() {
|
|||
return (this.textContent = text);
|
||||
},
|
||||
|
||||
ensureFonts: function pageEnsureFonts(fonts, callback) {
|
||||
ensureFonts: function Page_ensureFonts(fonts, callback) {
|
||||
this.stats.time('Font Loading');
|
||||
// Convert the font names to the corresponding font obj.
|
||||
for (var i = 0, ii = fonts.length; i < ii; i++) {
|
||||
fonts[i] = this.objs.objs[fonts[i]].data;
|
||||
}
|
||||
|
||||
// Load all the fonts
|
||||
var fontObjs = FontLoader.bind(
|
||||
FontLoader.bind(
|
||||
fonts,
|
||||
function pageEnsureFontsFontObjs(fontObjs) {
|
||||
this.stats.fonts = Date.now();
|
||||
this.stats.timeEnd('Font Loading');
|
||||
|
||||
callback.call(this);
|
||||
}.bind(this),
|
||||
this.objs
|
||||
}.bind(this)
|
||||
);
|
||||
},
|
||||
|
||||
display: function pageDisplay(gfx, callback) {
|
||||
display: function Page_display(gfx, callback) {
|
||||
var stats = this.stats;
|
||||
stats.time('Rendering');
|
||||
var xref = this.xref;
|
||||
var resources = xref.fetchIfRef(this.resources);
|
||||
var mediaBox = xref.fetchIfRef(this.mediaBox);
|
||||
var resources = this.resources;
|
||||
var mediaBox = this.mediaBox;
|
||||
assertWellFormed(isDict(resources), 'invalid page resources');
|
||||
|
||||
gfx.xref = xref;
|
||||
|
@ -273,21 +287,29 @@ var Page = (function PageClosure() {
|
|||
rotate: this.rotate });
|
||||
|
||||
var startIdx = 0;
|
||||
var length = this.IRQueue.fnArray.length;
|
||||
var IRQueue = this.IRQueue;
|
||||
var length = this.operatorList.fnArray.length;
|
||||
var operatorList = this.operatorList;
|
||||
var stepper = null;
|
||||
if (PDFJS.pdfBug && StepperManager.enabled) {
|
||||
stepper = StepperManager.create(this.pageNumber);
|
||||
stepper.init(operatorList);
|
||||
stepper.nextBreakPoint = stepper.getNextBreakPoint();
|
||||
}
|
||||
|
||||
var self = this;
|
||||
function next() {
|
||||
startIdx = gfx.executeIRQueue(IRQueue, startIdx, next);
|
||||
startIdx =
|
||||
gfx.executeOperatorList(operatorList, startIdx, next, stepper);
|
||||
if (startIdx == length) {
|
||||
self.stats.render = Date.now();
|
||||
gfx.endDrawing();
|
||||
stats.timeEnd('Rendering');
|
||||
stats.timeEnd('Overall');
|
||||
if (callback) callback();
|
||||
}
|
||||
}
|
||||
next();
|
||||
},
|
||||
rotatePoint: function pageRotatePoint(x, y, reverse) {
|
||||
rotatePoint: function Page_rotatePoint(x, y, reverse) {
|
||||
var rotate = reverse ? (360 - this.rotate) : this.rotate;
|
||||
switch (rotate) {
|
||||
case 180:
|
||||
|
@ -302,7 +324,7 @@ var Page = (function PageClosure() {
|
|||
return {x: x, y: this.height - y};
|
||||
}
|
||||
},
|
||||
getLinks: function pageGetLinks() {
|
||||
getLinks: function Page_getLinks() {
|
||||
var links = [];
|
||||
var annotations = pageGetAnnotations();
|
||||
var i, n = annotations.length;
|
||||
|
@ -313,19 +335,35 @@ var Page = (function PageClosure() {
|
|||
}
|
||||
return links;
|
||||
},
|
||||
getAnnotations: function pageGetAnnotations() {
|
||||
getAnnotations: function Page_getAnnotations() {
|
||||
var xref = this.xref;
|
||||
function getInheritableProperty(annotation, name) {
|
||||
var item = annotation;
|
||||
while (item && !item.has(name)) {
|
||||
item = xref.fetchIfRef(item.get('Parent'));
|
||||
item = item.get('Parent');
|
||||
}
|
||||
if (!item)
|
||||
return null;
|
||||
return item.get(name);
|
||||
}
|
||||
function isValidUrl(url) {
|
||||
if (!url)
|
||||
return false;
|
||||
var colon = url.indexOf(':');
|
||||
if (colon < 0)
|
||||
return false;
|
||||
var protocol = url.substr(0, colon);
|
||||
switch (protocol) {
|
||||
case 'http':
|
||||
case 'https':
|
||||
case 'ftp':
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
var annotations = xref.fetchIfRef(this.annotations) || [];
|
||||
var annotations = this.annotations || [];
|
||||
var i, n = annotations.length;
|
||||
var items = [];
|
||||
for (i = 0; i < n; ++i) {
|
||||
|
@ -348,11 +386,16 @@ var Page = (function PageClosure() {
|
|||
item.height = Math.abs(topLeftCorner.y - bottomRightCorner.y);
|
||||
switch (subtype.name) {
|
||||
case 'Link':
|
||||
var a = this.xref.fetchIfRef(annotation.get('A'));
|
||||
var a = annotation.get('A');
|
||||
if (a) {
|
||||
switch (a.get('S').name) {
|
||||
case 'URI':
|
||||
item.url = a.get('URI');
|
||||
var url = a.get('URI');
|
||||
// TODO: pdf spec mentions urls can be relative to a Base
|
||||
// entry in the dictionary.
|
||||
if (!isValidUrl(url))
|
||||
url = '';
|
||||
item.url = url;
|
||||
break;
|
||||
case 'GoTo':
|
||||
item.dest = a.get('D');
|
||||
|
@ -376,21 +419,22 @@ var Page = (function PageClosure() {
|
|||
var fieldName = [];
|
||||
var namedItem = annotation, ref = annotationRef;
|
||||
while (namedItem) {
|
||||
var parentRef = namedItem.get('Parent');
|
||||
var parent = xref.fetchIfRef(parentRef);
|
||||
var parent = namedItem.get('Parent');
|
||||
var parentRef = namedItem.getRaw('Parent');
|
||||
var name = namedItem.get('T');
|
||||
if (name)
|
||||
if (name) {
|
||||
fieldName.unshift(stringToPDFString(name));
|
||||
else {
|
||||
} else {
|
||||
// The field name is absent, that means more than one field
|
||||
// with the same name may exist. Replacing the empty name
|
||||
// with the '`' plus index in the parent's 'Kids' array.
|
||||
// This is not in the PDF spec but necessary to id the
|
||||
// the input controls.
|
||||
var kids = xref.fetchIfRef(parent.get('Kids'));
|
||||
var kids = parent.get('Kids');
|
||||
var j, jj;
|
||||
for (j = 0, jj = kids.length; j < jj; j++) {
|
||||
if (kids[j].num == ref.num && kids[j].gen == ref.gen)
|
||||
var kidRef = kids[j];
|
||||
if (kidRef.num == ref.num && kidRef.gen == ref.gen)
|
||||
break;
|
||||
}
|
||||
fieldName.unshift('`' + j);
|
||||
|
@ -423,17 +467,17 @@ var Page = (function PageClosure() {
|
|||
}
|
||||
return items;
|
||||
},
|
||||
startRendering: function pageStartRendering(ctx, callback, textLayer) {
|
||||
this.startRenderingTime = Date.now();
|
||||
|
||||
// If there is no displayReadyPromise yet, then the IRQueue was never
|
||||
startRendering: function Page_startRendering(ctx, callback, textLayer) {
|
||||
var stats = this.stats;
|
||||
stats.time('Overall');
|
||||
// If there is no displayReadyPromise yet, then the operatorList was never
|
||||
// requested before. Make the request and create the promise.
|
||||
if (!this.displayReadyPromise) {
|
||||
this.pdf.startRendering(this);
|
||||
this.displayReadyPromise = new Promise();
|
||||
}
|
||||
|
||||
// Once the IRQueue and fonts are loaded, perform the actual rendering.
|
||||
// Once the operatorList and fonts are loaded, do the actual rendering.
|
||||
this.displayReadyPromise.then(
|
||||
function pageDisplayReadyPromise() {
|
||||
var gfx = new CanvasGraphics(ctx, this.objs, textLayer);
|
||||
|
@ -443,14 +487,14 @@ var Page = (function PageClosure() {
|
|||
if (callback)
|
||||
callback(e);
|
||||
else
|
||||
throw e;
|
||||
error(e);
|
||||
}
|
||||
}.bind(this),
|
||||
function pageDisplayReadPromiseError(reason) {
|
||||
if (callback)
|
||||
callback(reason);
|
||||
else
|
||||
throw reason;
|
||||
error(reason);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
@ -465,9 +509,6 @@ var Page = (function PageClosure() {
|
|||
* Right now there exists one PDFDocModel on the main thread + one object
|
||||
* for each worker. If there is no worker support enabled, there are two
|
||||
* `PDFDocModel` objects on the main thread created.
|
||||
* TODO: Refactor the internal object structure, such that there is no
|
||||
* need for the `PDFDocModel` anymore and there is only one object on the
|
||||
* main thread and not one entire copy on each worker instance.
|
||||
*/
|
||||
var PDFDocModel = (function PDFDocModelClosure() {
|
||||
function PDFDocModel(arg, callback) {
|
||||
|
@ -483,7 +524,7 @@ var PDFDocModel = (function PDFDocModelClosure() {
|
|||
assertWellFormed(stream.length > 0, 'stream must have data');
|
||||
this.stream = stream;
|
||||
this.setup();
|
||||
this.acroForm = this.xref.fetchIfRef(this.catalog.catDict.get('AcroForm'));
|
||||
this.acroForm = this.catalog.catDict.get('AcroForm');
|
||||
}
|
||||
|
||||
function find(stream, needle, limit, backwards) {
|
||||
|
@ -563,7 +604,7 @@ var PDFDocModel = (function PDFDocModelClosure() {
|
|||
},
|
||||
// Find the header, remove leading garbage and setup the stream
|
||||
// starting from the header.
|
||||
checkHeader: function pdfDocCheckHeader() {
|
||||
checkHeader: function PDFDocModel_checkHeader() {
|
||||
var stream = this.stream;
|
||||
stream.reset();
|
||||
if (find(stream, '%PDF-', 1024)) {
|
||||
|
@ -573,21 +614,13 @@ var PDFDocModel = (function PDFDocModelClosure() {
|
|||
}
|
||||
// May not be a PDF file, continue anyway.
|
||||
},
|
||||
setup: function pdfDocSetup(ownerPassword, userPassword) {
|
||||
setup: function PDFDocModel_setup(ownerPassword, userPassword) {
|
||||
this.checkHeader();
|
||||
var xref = new XRef(this.stream,
|
||||
this.startXRef,
|
||||
this.mainXRefEntriesOffset);
|
||||
this.xref = xref;
|
||||
this.catalog = new Catalog(xref);
|
||||
if (xref.trailer && xref.trailer.has('ID')) {
|
||||
var fileID = '';
|
||||
var id = xref.fetchIfRef(xref.trailer.get('ID'))[0];
|
||||
id.split('').forEach(function(el) {
|
||||
fileID += Number(el.charCodeAt(0)).toString(16);
|
||||
});
|
||||
this.fileID = fileID;
|
||||
}
|
||||
},
|
||||
get numPages() {
|
||||
var linearization = this.linearization;
|
||||
|
@ -595,23 +628,42 @@ var PDFDocModel = (function PDFDocModelClosure() {
|
|||
// shadow the prototype getter
|
||||
return shadow(this, 'numPages', num);
|
||||
},
|
||||
getFingerprint: function pdfDocGetFingerprint() {
|
||||
if (this.fileID) {
|
||||
return this.fileID;
|
||||
getDocumentInfo: function PDFDocModel_getDocumentInfo() {
|
||||
var info;
|
||||
if (this.xref.trailer.has('Info')) {
|
||||
var infoDict = this.xref.trailer.get('Info');
|
||||
|
||||
info = {};
|
||||
infoDict.forEach(function(key, value) {
|
||||
info[key] = typeof value !== 'string' ? value :
|
||||
stringToPDFString(value);
|
||||
});
|
||||
}
|
||||
|
||||
return shadow(this, 'getDocumentInfo', info);
|
||||
},
|
||||
getFingerprint: function PDFDocModel_getFingerprint() {
|
||||
var xref = this.xref, fileID;
|
||||
if (xref.trailer.has('ID')) {
|
||||
fileID = '';
|
||||
var id = xref.trailer.get('ID')[0];
|
||||
id.split('').forEach(function(el) {
|
||||
fileID += Number(el.charCodeAt(0)).toString(16);
|
||||
});
|
||||
} else {
|
||||
// If we got no fileID, then we generate one,
|
||||
// from the first 100 bytes of PDF
|
||||
var data = this.stream.bytes.subarray(0, 100);
|
||||
var hash = calculateMD5(data, 0, data.length);
|
||||
var strHash = '';
|
||||
fileID = '';
|
||||
for (var i = 0, length = hash.length; i < length; i++) {
|
||||
strHash += Number(hash[i]).toString(16);
|
||||
fileID += Number(hash[i]).toString(16);
|
||||
}
|
||||
|
||||
return strHash;
|
||||
}
|
||||
|
||||
return shadow(this, 'getFingerprint', fileID);
|
||||
},
|
||||
getPage: function pdfDocGetPage(n) {
|
||||
getPage: function PDFDocModel_getPage(n) {
|
||||
return this.catalog.getPage(n);
|
||||
}
|
||||
};
|
||||
|
@ -636,9 +688,10 @@ var PDFDoc = (function PDFDocClosure() {
|
|||
|
||||
this.data = data;
|
||||
this.stream = stream;
|
||||
this.pdf = new PDFDocModel(stream);
|
||||
this.fingerprint = this.pdf.getFingerprint();
|
||||
this.catalog = this.pdf.catalog;
|
||||
this.pdfModel = new PDFDocModel(stream);
|
||||
this.fingerprint = this.pdfModel.getFingerprint();
|
||||
this.info = this.pdfModel.getDocumentInfo();
|
||||
this.catalog = this.pdfModel.catalog;
|
||||
this.objs = new PDFObjects();
|
||||
|
||||
this.pageCache = [];
|
||||
|
@ -653,13 +706,23 @@ var PDFDoc = (function PDFDocClosure() {
|
|||
if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {
|
||||
var workerSrc = PDFJS.workerSrc;
|
||||
if (typeof workerSrc === 'undefined') {
|
||||
throw 'No PDFJS.workerSrc specified';
|
||||
error('No PDFJS.workerSrc specified');
|
||||
}
|
||||
|
||||
try {
|
||||
// Some versions of FF can't create a worker on localhost, see:
|
||||
// https://bugzilla.mozilla.org/show_bug.cgi?id=683280
|
||||
var worker = new Worker(workerSrc);
|
||||
var worker;
|
||||
if (PDFJS.isFirefoxExtension) {
|
||||
// The firefox extension can't load the worker from the resource://
|
||||
// url so we have to inline the script and then use the blob loader.
|
||||
var bb = new MozBlobBuilder();
|
||||
bb.append(document.querySelector('#PDFJS_SCRIPT_TAG').textContent);
|
||||
var blobUrl = window.URL.createObjectURL(bb.getBlob());
|
||||
worker = new Worker(blobUrl);
|
||||
} else {
|
||||
// Some versions of FF can't create a worker on localhost, see:
|
||||
// https://bugzilla.mozilla.org/show_bug.cgi?id=683280
|
||||
worker = new Worker(workerSrc);
|
||||
}
|
||||
|
||||
var messageHandler = new MessageHandler('main', worker);
|
||||
|
||||
|
@ -678,7 +741,9 @@ var PDFDoc = (function PDFDocClosure() {
|
|||
// serializing the typed array.
|
||||
messageHandler.send('test', testObj);
|
||||
return;
|
||||
} catch (e) {}
|
||||
} catch (e) {
|
||||
warn('The worker has been disabled.');
|
||||
}
|
||||
}
|
||||
// Either workers are disabled, not supported or have thrown an exception.
|
||||
// Thus, we fallback to a faked worker.
|
||||
|
@ -687,13 +752,13 @@ var PDFDoc = (function PDFDocClosure() {
|
|||
}
|
||||
|
||||
PDFDoc.prototype = {
|
||||
setupFakeWorker: function() {
|
||||
setupFakeWorker: function PDFDoc_setupFakeWorker() {
|
||||
// If we don't use a worker, just post/sendMessage to the main thread.
|
||||
var fakeWorker = {
|
||||
postMessage: function pdfDocPostMessage(obj) {
|
||||
postMessage: function PDFDoc_postMessage(obj) {
|
||||
fakeWorker.onmessage({data: obj});
|
||||
},
|
||||
terminate: function pdfDocTerminate() {}
|
||||
terminate: function PDFDoc_terminate() {}
|
||||
};
|
||||
|
||||
var messageHandler = new MessageHandler('main', fakeWorker);
|
||||
|
@ -705,7 +770,7 @@ var PDFDoc = (function PDFDocClosure() {
|
|||
},
|
||||
|
||||
|
||||
setupMessageHandler: function(messageHandler) {
|
||||
setupMessageHandler: function PDFDoc_setupMessageHandler(messageHandler) {
|
||||
this.messageHandler = messageHandler;
|
||||
|
||||
messageHandler.on('page', function pdfDocPage(data) {
|
||||
|
@ -713,7 +778,8 @@ var PDFDoc = (function PDFDocClosure() {
|
|||
var page = this.pageCache[pageNum];
|
||||
var depFonts = data.depFonts;
|
||||
|
||||
page.startRenderingFromIRQueue(data.IRQueue, depFonts);
|
||||
page.stats.timeEnd('Page Request');
|
||||
page.startRenderingFromOperatorList(data.operatorList, depFonts);
|
||||
}, this);
|
||||
|
||||
messageHandler.on('obj', function pdfDocObj(data) {
|
||||
|
@ -740,37 +806,22 @@ var PDFDoc = (function PDFDocClosure() {
|
|||
file = new Stream(file, 0, file.length, fontFileDict);
|
||||
}
|
||||
|
||||
// For now, resolve the font object here direclty. The real font
|
||||
// object is then created in FontLoader.bind().
|
||||
this.objs.resolve(id, {
|
||||
name: name,
|
||||
file: file,
|
||||
properties: properties
|
||||
});
|
||||
// At this point, only the font object is created but the font is
|
||||
// not yet attached to the DOM. This is done in `FontLoader.bind`.
|
||||
var font = new Font(name, file, properties);
|
||||
this.objs.resolve(id, font);
|
||||
break;
|
||||
default:
|
||||
throw 'Got unkown object type ' + type;
|
||||
error('Got unkown object type ' + type);
|
||||
}
|
||||
}, this);
|
||||
|
||||
messageHandler.on('font_ready', function pdfDocFontReady(data) {
|
||||
var id = data[0];
|
||||
var font = new FontShape(data[1]);
|
||||
|
||||
// If there is no string, then there is nothing to attach to the DOM.
|
||||
if (!font.str) {
|
||||
this.objs.resolve(id, font);
|
||||
} else {
|
||||
this.objs.setData(id, font);
|
||||
}
|
||||
}.bind(this));
|
||||
|
||||
messageHandler.on('page_error', function pdfDocError(data) {
|
||||
var page = this.pageCache[data.pageNum];
|
||||
if (page.displayReadyPromise)
|
||||
page.displayReadyPromise.reject(data.error);
|
||||
else
|
||||
throw data.error;
|
||||
error(data.error);
|
||||
}, this);
|
||||
|
||||
messageHandler.on('text_extracted', function pdfTextExtracted(data) {
|
||||
|
@ -786,13 +837,13 @@ var PDFDoc = (function PDFDocClosure() {
|
|||
error('Only 3 component or 1 component can be returned');
|
||||
|
||||
var img = new Image();
|
||||
img.onload = (function jpegImageLoaderOnload() {
|
||||
img.onload = (function messageHandler_onloadClosure() {
|
||||
var width = img.width;
|
||||
var height = img.height;
|
||||
var size = width * height;
|
||||
var rgbaLength = size * 4;
|
||||
var buf = new Uint8Array(size * components);
|
||||
var tmpCanvas = new ScratchCanvas(width, height);
|
||||
var tmpCanvas = createScratchCanvas(width, height);
|
||||
var tmpCtx = tmpCanvas.getContext('2d');
|
||||
tmpCtx.drawImage(img, 0, 0);
|
||||
var data = tmpCtx.getImageData(0, 0, width, height).data;
|
||||
|
@ -821,21 +872,22 @@ var PDFDoc = (function PDFDocClosure() {
|
|||
},
|
||||
|
||||
get numPages() {
|
||||
return this.pdf.numPages;
|
||||
return this.pdfModel.numPages;
|
||||
},
|
||||
|
||||
startRendering: function pdfDocStartRendering(page) {
|
||||
startRendering: function PDFDoc_startRendering(page) {
|
||||
// The worker might not be ready to receive the page request yet.
|
||||
this.workerReadyPromise.then(function pdfDocStartRenderingThen() {
|
||||
page.stats.time('Page Request');
|
||||
this.messageHandler.send('page_request', page.pageNumber + 1);
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
getPage: function pdfDocGetPage(n) {
|
||||
getPage: function PDFDoc_getPage(n) {
|
||||
if (this.pageCache[n])
|
||||
return this.pageCache[n];
|
||||
|
||||
var page = this.pdf.getPage(n);
|
||||
var page = this.pdfModel.getPage(n);
|
||||
// Add a reference to the objects such that Page can forward the reference
|
||||
// to the CanvasGraphics and so on.
|
||||
page.objs = this.objs;
|
||||
|
@ -843,13 +895,13 @@ var PDFDoc = (function PDFDocClosure() {
|
|||
return (this.pageCache[n] = page);
|
||||
},
|
||||
|
||||
extractText: function pdfDocExtractExtractText() {
|
||||
extractText: function PDFDoc_extractText() {
|
||||
this.workerReadyPromise.then(function pdfDocStartRenderingThen() {
|
||||
this.messageHandler.send('extract_text');
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
destroy: function pdfDocDestroy() {
|
||||
destroy: function PDFDoc_destroy() {
|
||||
if (this.worker)
|
||||
this.worker.terminate();
|
||||
|
||||
|
|
|
@ -21,7 +21,7 @@ var ARCFourCipher = (function ARCFourCipherClosure() {
|
|||
}
|
||||
|
||||
ARCFourCipher.prototype = {
|
||||
encryptBlock: function arcFourCipherEncryptBlock(data) {
|
||||
encryptBlock: function ARCFourCipher_encryptBlock(data) {
|
||||
var i, n = data.length, tmp, tmp2;
|
||||
var a = this.a, b = this.b, s = this.s;
|
||||
var output = new Uint8Array(n);
|
||||
|
@ -133,7 +133,7 @@ var NullCipher = (function NullCipherClosure() {
|
|||
}
|
||||
|
||||
NullCipher.prototype = {
|
||||
decryptBlock: function nullCipherDecryptBlock(data) {
|
||||
decryptBlock: function NullCipher_decryptBlock(data) {
|
||||
return data;
|
||||
}
|
||||
};
|
||||
|
@ -371,7 +371,7 @@ var AES128Cipher = (function AES128CipherClosure() {
|
|||
}
|
||||
|
||||
AES128Cipher.prototype = {
|
||||
decryptBlock: function aes128CipherDecryptBlock(data) {
|
||||
decryptBlock: function AES128Cipher_decryptBlock(data) {
|
||||
var i, sourceLength = data.length;
|
||||
var buffer = this.buffer, bufferLength = this.bufferPosition;
|
||||
// waiting for IV values -- they are at the start of the stream
|
||||
|
@ -400,7 +400,7 @@ var CipherTransform = (function CipherTransformClosure() {
|
|||
this.streamCipherConstructor = streamCipherConstructor;
|
||||
}
|
||||
CipherTransform.prototype = {
|
||||
createStream: function cipherTransformCreateStream(stream) {
|
||||
createStream: function CipherTransform_createStream(stream) {
|
||||
var cipher = new this.streamCipherConstructor();
|
||||
return new DecryptStream(stream,
|
||||
function cipherTransformDecryptStream(data) {
|
||||
|
@ -408,7 +408,7 @@ var CipherTransform = (function CipherTransformClosure() {
|
|||
}
|
||||
);
|
||||
},
|
||||
decryptString: function cipherTransformDecryptString(s) {
|
||||
decryptString: function CipherTransform_decryptString(s) {
|
||||
var cipher = new this.stringCipherConstructor();
|
||||
var data = stringToBytes(s);
|
||||
data = cipher.decryptBlock(data);
|
||||
|
@ -570,12 +570,11 @@ var CipherTransformFactory = (function CipherTransformFactoryClosure() {
|
|||
};
|
||||
}
|
||||
error('Unknown crypto method');
|
||||
return null;
|
||||
}
|
||||
|
||||
CipherTransformFactory.prototype = {
|
||||
createCipherTransform: function buildCipherCreateCipherTransform(num,
|
||||
gen) {
|
||||
createCipherTransform:
|
||||
function CipherTransformFactory_createCipherTransform(num, gen) {
|
||||
if (this.algorithm == 4) {
|
||||
return new CipherTransform(
|
||||
buildCipherConstructor(this.cf, this.stmf,
|
||||
|
|
231
src/evaluator.js
231
src/evaluator.js
|
@ -111,9 +111,22 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
EX: 'endCompat'
|
||||
};
|
||||
|
||||
function splitCombinedOperations(operations) {
|
||||
// Two operations can be combined together, trying to find which two
|
||||
// operations were concatenated.
|
||||
for (var i = operations.length - 1; i > 0; i--) {
|
||||
var op1 = operations.substring(0, i), op2 = operations.substring(i);
|
||||
if (op1 in OP_MAP && op2 in OP_MAP)
|
||||
return [op1, op2]; // operations found
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
PartialEvaluator.prototype = {
|
||||
getIRQueue: function partialEvaluatorGetIRQueue(stream, resources,
|
||||
queue, dependency) {
|
||||
getOperatorList: function PartialEvaluator_getOperatorList(stream,
|
||||
resources,
|
||||
dependency,
|
||||
queue) {
|
||||
|
||||
var self = this;
|
||||
var xref = this.xref;
|
||||
|
@ -131,18 +144,14 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
}
|
||||
}
|
||||
|
||||
function handleSetFont(fontName, fontRef) {
|
||||
function handleSetFont(fontName, font) {
|
||||
var loadedName = null;
|
||||
|
||||
var fontRes = resources.get('Font');
|
||||
|
||||
// TODO: TOASK: Is it possible to get here? If so, what does
|
||||
// args[0].name should be like???
|
||||
assert(fontRes, 'fontRes not available');
|
||||
|
||||
fontRes = xref.fetchIfRef(fontRes);
|
||||
fontRef = fontRef || fontRes.get(fontName);
|
||||
var font = xref.fetchIfRef(fontRef);
|
||||
font = xref.fetchIfRef(font) || fontRes.get(fontName);
|
||||
assertWellFormed(isDict(font));
|
||||
if (!font.loadedName) {
|
||||
font.translated = self.translateFont(font, xref, resources,
|
||||
|
@ -159,6 +168,10 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
// a Stream in the main thread.
|
||||
if (translated.file)
|
||||
translated.file = translated.file.getBytes();
|
||||
if (translated.properties.file) {
|
||||
translated.properties.file =
|
||||
translated.properties.file.getBytes();
|
||||
}
|
||||
|
||||
handler.send('obj', [
|
||||
loadedName,
|
||||
|
@ -173,7 +186,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
|
||||
// Ensure the font is ready before the font is set
|
||||
// and later on used for drawing.
|
||||
// TODO: This should get insert to the IRQueue only once per
|
||||
// OPTIMIZE: This should get insert to the operatorList only once per
|
||||
// page.
|
||||
insertDependency([loadedName]);
|
||||
return loadedName;
|
||||
|
@ -235,6 +248,9 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
}, handler, xref, resources, image, inline);
|
||||
}
|
||||
|
||||
if (!queue)
|
||||
queue = {};
|
||||
|
||||
if (!queue.argsArray) {
|
||||
queue.argsArray = [];
|
||||
}
|
||||
|
@ -245,45 +261,48 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
var fnArray = queue.fnArray, argsArray = queue.argsArray;
|
||||
var dependencyArray = dependency || [];
|
||||
|
||||
resources = xref.fetchIfRef(resources) || new Dict();
|
||||
var xobjs = xref.fetchIfRef(resources.get('XObject')) || new Dict();
|
||||
var patterns = xref.fetchIfRef(resources.get('Pattern')) || new Dict();
|
||||
var parser = new Parser(new Lexer(stream), false);
|
||||
resources = resources || new Dict();
|
||||
var xobjs = resources.get('XObject') || new Dict();
|
||||
var patterns = resources.get('Pattern') || new Dict();
|
||||
var parser = new Parser(new Lexer(stream), false, xref);
|
||||
var res = resources;
|
||||
var hasNextObj = false, nextObj;
|
||||
var args = [], obj;
|
||||
var getObjBt = function getObjBt() {
|
||||
parser = this.oldParser;
|
||||
return { name: 'BT' };
|
||||
};
|
||||
var TILING_PATTERN = 1, SHADING_PATTERN = 2;
|
||||
|
||||
while (!isEOF(obj = parser.getObj())) {
|
||||
while (true) {
|
||||
if (hasNextObj) {
|
||||
obj = nextObj;
|
||||
hasNextObj = false;
|
||||
} else {
|
||||
obj = parser.getObj();
|
||||
if (isEOF(obj))
|
||||
break;
|
||||
}
|
||||
|
||||
if (isCmd(obj)) {
|
||||
var cmd = obj.cmd;
|
||||
var fn = OP_MAP[cmd];
|
||||
if (!fn) {
|
||||
// invalid content command, trying to recover
|
||||
if (cmd.substr(-2) == 'BT') {
|
||||
fn = OP_MAP[cmd.substr(0, cmd.length - 2)];
|
||||
// feeding 'BT' on next interation
|
||||
parser = {
|
||||
getObj: getObjBt,
|
||||
oldParser: parser
|
||||
};
|
||||
var cmds = splitCombinedOperations(cmd);
|
||||
if (cmds) {
|
||||
cmd = cmds[0];
|
||||
fn = OP_MAP[cmd];
|
||||
// feeding other command on the next interation
|
||||
hasNextObj = true;
|
||||
nextObj = Cmd.get(cmds[1]);
|
||||
}
|
||||
}
|
||||
assertWellFormed(fn, 'Unknown command "' + cmd + '"');
|
||||
// TODO figure out how to type-check vararg functions
|
||||
|
||||
if ((cmd == 'SCN' || cmd == 'scn') && !args[args.length - 1].code) {
|
||||
// Use the IR version for setStroke/FillColorN.
|
||||
fn += '_IR';
|
||||
|
||||
// compile tiling patterns
|
||||
var patternName = args[args.length - 1];
|
||||
// SCN/scn applies patterns along with normal colors
|
||||
if (isName(patternName)) {
|
||||
var pattern = xref.fetchIfRef(patterns.get(patternName.name));
|
||||
var pattern = patterns.get(patternName.name);
|
||||
if (pattern) {
|
||||
var dict = isStream(pattern) ? pattern.dict : pattern;
|
||||
var typeNum = dict.get('PatternType');
|
||||
|
@ -291,21 +310,20 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
if (typeNum == TILING_PATTERN) {
|
||||
// Create an IR of the pattern code.
|
||||
var depIdx = dependencyArray.length;
|
||||
var queueObj = {};
|
||||
var codeIR = this.getIRQueue(pattern, dict.get('Resources') ||
|
||||
resources, queueObj, dependencyArray);
|
||||
var operatorList = this.getOperatorList(pattern,
|
||||
dict.get('Resources') || resources, dependencyArray);
|
||||
|
||||
// Add the dependencies that are required to execute the
|
||||
// codeIR.
|
||||
// operatorList.
|
||||
insertDependency(dependencyArray.slice(depIdx));
|
||||
|
||||
args = TilingPattern.getIR(codeIR, dict, args);
|
||||
args = TilingPattern.getIR(operatorList, dict, args);
|
||||
}
|
||||
else if (typeNum == SHADING_PATTERN) {
|
||||
var shading = xref.fetchIfRef(dict.get('Shading'));
|
||||
var shading = dict.get('Shading');
|
||||
var matrix = dict.get('Matrix');
|
||||
var pattern = Pattern.parseShading(shading, matrix, xref, res,
|
||||
null /*ctx*/);
|
||||
var pattern = Pattern.parseShading(shading, matrix, xref,
|
||||
res);
|
||||
args = pattern.getIR();
|
||||
} else {
|
||||
error('Unkown PatternType ' + typeNum);
|
||||
|
@ -317,7 +335,6 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
var name = args[0].name;
|
||||
var xobj = xobjs.get(name);
|
||||
if (xobj) {
|
||||
xobj = xref.fetchIfRef(xobj);
|
||||
assertWellFormed(isStream(xobj), 'XObject should be a stream');
|
||||
|
||||
var type = xobj.dict.get('Subtype');
|
||||
|
@ -333,14 +350,18 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
fnArray.push('paintFormXObjectBegin');
|
||||
argsArray.push([matrix, bbox]);
|
||||
|
||||
// This adds the IRQueue of the xObj to the current queue.
|
||||
// This adds the operatorList of the xObj to the current queue.
|
||||
var depIdx = dependencyArray.length;
|
||||
|
||||
this.getIRQueue(xobj, xobj.dict.get('Resources') || resources,
|
||||
queue, dependencyArray);
|
||||
// Pass in the current `queue` object. That means the `fnArray`
|
||||
// and the `argsArray` in this scope is reused and new commands
|
||||
// are added to them.
|
||||
this.getOperatorList(xobj,
|
||||
xobj.dict.get('Resources') || resources,
|
||||
dependencyArray, queue);
|
||||
|
||||
// Add the dependencies that are required to execute the
|
||||
// codeIR.
|
||||
// operatorList.
|
||||
insertDependency(dependencyArray.slice(depIdx));
|
||||
|
||||
fn = 'paintFormXObjectEnd';
|
||||
|
@ -364,28 +385,27 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
args = [ColorSpace.parseToIR(args[0], xref, resources)];
|
||||
break;
|
||||
case 'shadingFill':
|
||||
var shadingRes = xref.fetchIfRef(res.get('Shading'));
|
||||
var shadingRes = res.get('Shading');
|
||||
if (!shadingRes)
|
||||
error('No shading resource found');
|
||||
|
||||
var shading = xref.fetchIfRef(shadingRes.get(args[0].name));
|
||||
var shading = shadingRes.get(args[0].name);
|
||||
if (!shading)
|
||||
error('No shading object found');
|
||||
|
||||
var shadingFill = Pattern.parseShading(shading, null, xref, res,
|
||||
null);
|
||||
var shadingFill = Pattern.parseShading(shading, null, xref, res);
|
||||
var patternIR = shadingFill.getIR();
|
||||
args = [patternIR];
|
||||
fn = 'shadingFill';
|
||||
break;
|
||||
case 'setGState':
|
||||
var dictName = args[0];
|
||||
var extGState = xref.fetchIfRef(resources.get('ExtGState'));
|
||||
var extGState = resources.get('ExtGState');
|
||||
|
||||
if (!isDict(extGState) || !extGState.has(dictName.name))
|
||||
break;
|
||||
|
||||
var gsState = xref.fetchIfRef(extGState.get(dictName.name));
|
||||
var gsState = extGState.get(dictName.name);
|
||||
|
||||
// This array holds the converted/processed state data.
|
||||
var gsStateObj = [];
|
||||
|
@ -450,10 +470,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
}
|
||||
}
|
||||
|
||||
return {
|
||||
fnArray: fnArray,
|
||||
argsArray: argsArray
|
||||
};
|
||||
return queue;
|
||||
},
|
||||
|
||||
getTextContent: function partialEvaluatorGetIRQueue(stream, resources) {
|
||||
|
@ -532,7 +549,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
|
||||
if (properties.composite) {
|
||||
// CIDSystemInfo helps to match CID to glyphs
|
||||
var cidSystemInfo = xref.fetchIfRef(dict.get('CIDSystemInfo'));
|
||||
var cidSystemInfo = dict.get('CIDSystemInfo');
|
||||
if (isDict(cidSystemInfo)) {
|
||||
properties.cidSystemInfo = {
|
||||
registry: cidSystemInfo.get('Registry'),
|
||||
|
@ -541,16 +558,18 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
};
|
||||
}
|
||||
|
||||
var cidToGidMap = xref.fetchIfRef(dict.get('CIDToGIDMap'));
|
||||
var cidToGidMap = dict.get('CIDToGIDMap');
|
||||
if (isStream(cidToGidMap))
|
||||
properties.cidToGidMap = this.readCidToGidMap(cidToGidMap);
|
||||
}
|
||||
|
||||
var flags = properties.flags;
|
||||
var differences = [];
|
||||
var baseEncoding = Encodings.StandardEncoding;
|
||||
var baseEncoding = !!(flags & FontFlags.Symbolic) ?
|
||||
Encodings.symbolsEncoding : Encodings.StandardEncoding;
|
||||
var hasEncoding = dict.has('Encoding');
|
||||
if (hasEncoding) {
|
||||
var encoding = xref.fetchIfRef(dict.get('Encoding'));
|
||||
var encoding = dict.get('Encoding');
|
||||
if (isDict(encoding)) {
|
||||
var baseName = encoding.get('BaseEncoding');
|
||||
if (baseName)
|
||||
|
@ -582,9 +601,8 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
properties.hasEncoding = hasEncoding;
|
||||
},
|
||||
|
||||
readToUnicode:
|
||||
function partialEvaluatorReadToUnicode(toUnicode, xref) {
|
||||
var cmapObj = xref.fetchIfRef(toUnicode);
|
||||
readToUnicode: function PartialEvaluator_readToUnicode(toUnicode, xref) {
|
||||
var cmapObj = toUnicode;
|
||||
var charToUnicode = [];
|
||||
if (isName(cmapObj)) {
|
||||
var isIdentityMap = cmapObj.name.substr(0, 9) == 'Identity-';
|
||||
|
@ -597,9 +615,9 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
|
||||
var cmap = cmapObj.getBytes(cmapObj.length);
|
||||
for (var i = 0, ii = cmap.length; i < ii; i++) {
|
||||
var byte = cmap[i];
|
||||
if (byte == 0x20 || byte == 0x0D || byte == 0x0A ||
|
||||
byte == 0x3C || byte == 0x5B || byte == 0x5D) {
|
||||
var octet = cmap[i];
|
||||
if (octet == 0x20 || octet == 0x0D || octet == 0x0A ||
|
||||
octet == 0x3C || octet == 0x5B || octet == 0x5D) {
|
||||
switch (token) {
|
||||
case 'usecmap':
|
||||
error('usecmap is not implemented');
|
||||
|
@ -656,7 +674,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
tokens.push(token);
|
||||
token = '';
|
||||
}
|
||||
switch (byte) {
|
||||
switch (octet) {
|
||||
case 0x5B:
|
||||
// begin list parsing
|
||||
tokens.push(beginArrayToken);
|
||||
|
@ -670,7 +688,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
tokens.push(items);
|
||||
break;
|
||||
}
|
||||
} else if (byte == 0x3E) {
|
||||
} else if (octet == 0x3E) {
|
||||
if (token.length) {
|
||||
if (token.length <= 4) {
|
||||
// parsing hex number
|
||||
|
@ -679,21 +697,30 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
} else {
|
||||
// parsing hex UTF-16BE numbers
|
||||
var str = [];
|
||||
for (var i = 0, ii = token.length; i < ii; i += 4)
|
||||
str.push(parseInt(token.substr(i, 4), 16));
|
||||
for (var k = 0, kk = token.length; k < kk; k += 4) {
|
||||
var b = parseInt(token.substr(k, 4), 16);
|
||||
if (b <= 0x10) {
|
||||
k += 4;
|
||||
b = (b << 16) | parseInt(token.substr(k, 4), 16);
|
||||
b -= 0x10000;
|
||||
str.push(0xD800 | (b >> 10));
|
||||
str.push(0xDC00 | (b & 0x3FF));
|
||||
break;
|
||||
}
|
||||
str.push(b);
|
||||
}
|
||||
tokens.push(String.fromCharCode.apply(String, str));
|
||||
token = '';
|
||||
}
|
||||
}
|
||||
} else {
|
||||
token += String.fromCharCode(byte);
|
||||
token += String.fromCharCode(octet);
|
||||
}
|
||||
}
|
||||
}
|
||||
return charToUnicode;
|
||||
},
|
||||
readCidToGidMap:
|
||||
function partialEvaluatorReadCidToGidMap(cidToGidStream) {
|
||||
readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) {
|
||||
// Extract the encoding from the CIDToGIDMap
|
||||
var glyphsData = cidToGidStream.getBytes();
|
||||
|
||||
|
@ -710,16 +737,16 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
return result;
|
||||
},
|
||||
|
||||
extractWidths: function partialEvaluatorWidths(dict,
|
||||
extractWidths: function PartialEvaluator_extractWidths(dict,
|
||||
xref,
|
||||
descriptor,
|
||||
properties) {
|
||||
var glyphsWidths = [];
|
||||
var defaultWidth = 0;
|
||||
if (properties.composite) {
|
||||
defaultWidth = xref.fetchIfRef(dict.get('DW')) || 1000;
|
||||
defaultWidth = dict.get('DW') || 1000;
|
||||
|
||||
var widths = xref.fetchIfRef(dict.get('W'));
|
||||
var widths = dict.get('W');
|
||||
if (widths) {
|
||||
var start = 0, end = 0;
|
||||
for (var i = 0, ii = widths.length; i < ii; i++) {
|
||||
|
@ -740,7 +767,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
}
|
||||
} else {
|
||||
var firstChar = properties.firstChar;
|
||||
var widths = xref.fetchIfRef(dict.get('Widths'));
|
||||
var widths = dict.get('Widths');
|
||||
if (widths) {
|
||||
var j = firstChar;
|
||||
for (var i = 0, ii = widths.length; i < ii; i++)
|
||||
|
@ -762,7 +789,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
properties.widths = glyphsWidths;
|
||||
},
|
||||
|
||||
getBaseFontMetrics: function getBaseFontMetrics(name) {
|
||||
getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) {
|
||||
var defaultWidth = 0, widths = [];
|
||||
var glyphWidths = Metrics[stdFontMap[name] || name];
|
||||
if (isNum(glyphWidths)) {
|
||||
|
@ -777,8 +804,10 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
};
|
||||
},
|
||||
|
||||
translateFont: function partialEvaluatorTranslateFont(dict, xref, resources,
|
||||
dependency) {
|
||||
translateFont: function PartialEvaluator_translateFont(dict,
|
||||
xref,
|
||||
resources,
|
||||
dependency) {
|
||||
var baseDict = dict;
|
||||
var type = dict.get('Subtype');
|
||||
assertWellFormed(isName(type), 'invalid font Subtype');
|
||||
|
@ -793,10 +822,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
if (!df)
|
||||
return null;
|
||||
|
||||
if (isRef(df))
|
||||
df = xref.fetch(df);
|
||||
|
||||
dict = xref.fetchIfRef(isRef(df) ? df : df[0]);
|
||||
dict = isArray(df) ? xref.fetchIfRef(df[0]) : df;
|
||||
|
||||
type = dict.get('Subtype');
|
||||
assertWellFormed(isName(type), 'invalid font Subtype');
|
||||
|
@ -804,7 +830,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
}
|
||||
var maxCharIndex = composite ? 0xFFFF : 0xFF;
|
||||
|
||||
var descriptor = xref.fetchIfRef(dict.get('FontDescriptor'));
|
||||
var descriptor = dict.get('FontDescriptor');
|
||||
if (!descriptor) {
|
||||
if (type.name == 'Type3') {
|
||||
// FontDescriptor is only required for Type3 fonts when the document
|
||||
|
@ -826,8 +852,9 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
// Simulating descriptor flags attribute
|
||||
var fontNameWoStyle = baseFontName.split('-')[0];
|
||||
var flags = (serifFonts[fontNameWoStyle] ||
|
||||
(fontNameWoStyle.search(/serif/gi) != -1) ? 2 : 0) |
|
||||
(symbolsFonts[fontNameWoStyle] ? 4 : 32);
|
||||
(fontNameWoStyle.search(/serif/gi) != -1) ? FontFlags.Serif : 0) |
|
||||
(symbolsFonts[fontNameWoStyle] ? FontFlags.Symbolic :
|
||||
FontFlags.Nonsymbolic);
|
||||
|
||||
var properties = {
|
||||
type: type.name,
|
||||
|
@ -845,34 +872,31 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
properties: properties
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// According to the spec if 'FontDescriptor' is declared, 'FirstChar',
|
||||
// 'LastChar' and 'Widths' should exists too, but some PDF encoders seems
|
||||
// 'LastChar' and 'Widths' should exist too, but some PDF encoders seem
|
||||
// to ignore this rule when a variant of a standart font is used.
|
||||
// TODO Fill the width array depending on which of the base font this is
|
||||
// a variant.
|
||||
var firstChar = xref.fetchIfRef(dict.get('FirstChar')) || 0;
|
||||
var lastChar = xref.fetchIfRef(dict.get('LastChar')) || maxCharIndex;
|
||||
var fontName = xref.fetchIfRef(descriptor.get('FontName'));
|
||||
var firstChar = dict.get('FirstChar') || 0;
|
||||
var lastChar = dict.get('LastChar') || maxCharIndex;
|
||||
var fontName = descriptor.get('FontName');
|
||||
// Some bad pdf's have a string as the font name.
|
||||
if (isString(fontName))
|
||||
fontName = new Name(fontName);
|
||||
assertWellFormed(isName(fontName), 'invalid font name');
|
||||
|
||||
var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3');
|
||||
if (fontFile) {
|
||||
fontFile = xref.fetchIfRef(fontFile);
|
||||
if (fontFile.dict) {
|
||||
var subtype = fontFile.dict.get('Subtype');
|
||||
if (subtype)
|
||||
subtype = subtype.name;
|
||||
|
||||
var length1 = fontFile.dict.get('Length1');
|
||||
if (!isInt(length1))
|
||||
length1 = xref.fetchIfRef(length1);
|
||||
|
||||
var length2 = fontFile.dict.get('Length2');
|
||||
if (!isInt(length2))
|
||||
length2 = xref.fetchIfRef(length2);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -901,19 +925,14 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
|
|||
|
||||
if (type.name === 'Type3') {
|
||||
properties.coded = true;
|
||||
// read char procs only if dependency is specified
|
||||
if (dependency) {
|
||||
var charProcs = xref.fetchIfRef(dict.get('CharProcs'));
|
||||
var fontResources = xref.fetchIfRef(dict.get('Resources')) ||
|
||||
resources;
|
||||
properties.resources = fontResources;
|
||||
properties.charProcIRQueues = {};
|
||||
for (var key in charProcs.map) {
|
||||
var glyphStream = xref.fetchIfRef(charProcs.map[key]);
|
||||
var queueObj = {};
|
||||
properties.charProcIRQueues[key] =
|
||||
this.getIRQueue(glyphStream, fontResources, queueObj, dependency);
|
||||
}
|
||||
var charProcs = dict.get('CharProcs').getAll();
|
||||
var fontResources = dict.get('Resources') || resources;
|
||||
properties.resources = fontResources;
|
||||
properties.charProcOperatorList = {};
|
||||
for (var key in charProcs) {
|
||||
var glyphStream = charProcs[key];
|
||||
properties.charProcOperatorList[key] =
|
||||
this.getOperatorList(glyphStream, fontResources, dependency);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
2479
src/fonts.js
2479
src/fonts.js
File diff suppressed because it is too large
Load diff
230
src/function.js
230
src/function.js
|
@ -10,7 +10,7 @@ var PDFFunction = (function PDFFunctionClosure() {
|
|||
var CONSTRUCT_POSTSCRIPT = 4;
|
||||
|
||||
return {
|
||||
getSampleArray: function pdfFunctionGetSampleArray(size, outputSize, bps,
|
||||
getSampleArray: function PDFFunction_getSampleArray(size, outputSize, bps,
|
||||
str) {
|
||||
var length = 1;
|
||||
for (var i = 0, ii = size.length; i < ii; i++)
|
||||
|
@ -38,7 +38,7 @@ var PDFFunction = (function PDFFunctionClosure() {
|
|||
return array;
|
||||
},
|
||||
|
||||
getIR: function pdfFunctionGetIR(xref, fn) {
|
||||
getIR: function PDFFunction_getIR(xref, fn) {
|
||||
var dict = fn.dict;
|
||||
if (!dict)
|
||||
dict = fn;
|
||||
|
@ -57,7 +57,7 @@ var PDFFunction = (function PDFFunctionClosure() {
|
|||
return typeFn.call(this, fn, dict, xref);
|
||||
},
|
||||
|
||||
fromIR: function pdfFunctionFromIR(IR) {
|
||||
fromIR: function PDFFunction_fromIR(IR) {
|
||||
var type = IR[0];
|
||||
switch (type) {
|
||||
case CONSTRUCT_SAMPLED:
|
||||
|
@ -72,16 +72,16 @@ var PDFFunction = (function PDFFunctionClosure() {
|
|||
}
|
||||
},
|
||||
|
||||
parse: function pdfFunctionParse(xref, fn) {
|
||||
parse: function PDFFunction_parse(xref, fn) {
|
||||
var IR = this.getIR(xref, fn);
|
||||
return this.fromIR(IR);
|
||||
},
|
||||
|
||||
constructSampled: function pdfFunctionConstructSampled(str, dict) {
|
||||
constructSampled: function PDFFunction_constructSampled(str, dict) {
|
||||
function toMultiArray(arr) {
|
||||
var inputLength = arr.length;
|
||||
var outputLength = arr.length / 2;
|
||||
var out = new Array(outputLength);
|
||||
var out = [];
|
||||
var index = 0;
|
||||
for (var i = 0; i < inputLength; i += 2) {
|
||||
out[index] = [arr[i], arr[i + 1]];
|
||||
|
@ -125,114 +125,104 @@ var PDFFunction = (function PDFFunctionClosure() {
|
|||
else
|
||||
decode = toMultiArray(decode);
|
||||
|
||||
// Precalc the multipliers
|
||||
var inputMul = new Float64Array(inputSize);
|
||||
for (var i = 0; i < inputSize; ++i) {
|
||||
inputMul[i] = (encode[i][1] - encode[i][0]) /
|
||||
(domain[i][1] - domain[i][0]);
|
||||
}
|
||||
|
||||
var idxMul = new Int32Array(inputSize);
|
||||
idxMul[0] = outputSize;
|
||||
for (i = 1; i < inputSize; ++i) {
|
||||
idxMul[i] = idxMul[i - 1] * size[i - 1];
|
||||
}
|
||||
|
||||
var nSamples = outputSize;
|
||||
for (i = 0; i < inputSize; ++i)
|
||||
nSamples *= size[i];
|
||||
|
||||
var samples = this.getSampleArray(size, outputSize, bps, str);
|
||||
|
||||
return [
|
||||
CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size,
|
||||
outputSize, bps, range, inputMul, idxMul, nSamples
|
||||
outputSize, Math.pow(2, bps) - 1, range
|
||||
];
|
||||
},
|
||||
|
||||
constructSampledFromIR: function pdfFunctionConstructSampledFromIR(IR) {
|
||||
var inputSize = IR[1];
|
||||
var domain = IR[2];
|
||||
var encode = IR[3];
|
||||
var decode = IR[4];
|
||||
var samples = IR[5];
|
||||
var size = IR[6];
|
||||
var outputSize = IR[7];
|
||||
var bps = IR[8];
|
||||
var range = IR[9];
|
||||
var inputMul = IR[10];
|
||||
var idxMul = IR[11];
|
||||
var nSamples = IR[12];
|
||||
constructSampledFromIR: function PDFFunction_constructSampledFromIR(IR) {
|
||||
// See chapter 3, page 109 of the PDF reference
|
||||
function interpolate(x, xmin, xmax, ymin, ymax) {
|
||||
return ymin + ((x - xmin) * ((ymax - ymin) / (xmax - xmin)));
|
||||
}
|
||||
|
||||
return function constructSampledFromIRResult(args) {
|
||||
if (inputSize != args.length)
|
||||
// See chapter 3, page 110 of the PDF reference.
|
||||
var m = IR[1];
|
||||
var domain = IR[2];
|
||||
var encode = IR[3];
|
||||
var decode = IR[4];
|
||||
var samples = IR[5];
|
||||
var size = IR[6];
|
||||
var n = IR[7];
|
||||
var mask = IR[8];
|
||||
var range = IR[9];
|
||||
|
||||
if (m != args.length)
|
||||
error('Incorrect number of arguments: ' + inputSize + ' != ' +
|
||||
args.length);
|
||||
// Most of the below is a port of Poppler's implementation.
|
||||
// TODO: There's a few other ways to do multilinear interpolation such
|
||||
// as piecewise, which is much faster but an approximation.
|
||||
var out = new Float64Array(outputSize);
|
||||
var x;
|
||||
var e = new Array(inputSize);
|
||||
var efrac0 = new Float64Array(inputSize);
|
||||
var efrac1 = new Float64Array(inputSize);
|
||||
var sBuf = new Float64Array(1 << inputSize);
|
||||
var i, j, k, idx, t;
|
||||
|
||||
// map input values into sample array
|
||||
for (i = 0; i < inputSize; ++i) {
|
||||
x = (args[i] - domain[i][0]) * inputMul[i] + encode[i][0];
|
||||
if (x < 0) {
|
||||
x = 0;
|
||||
} else if (x > size[i] - 1) {
|
||||
x = size[i] - 1;
|
||||
}
|
||||
e[i] = [Math.floor(x), 0];
|
||||
if ((e[i][1] = e[i][0] + 1) >= size[i]) {
|
||||
// this happens if in[i] = domain[i][1]
|
||||
e[i][1] = e[i][0];
|
||||
}
|
||||
efrac1[i] = x - e[i][0];
|
||||
efrac0[i] = 1 - efrac1[i];
|
||||
}
|
||||
var x = args;
|
||||
|
||||
// for each output, do m-linear interpolation
|
||||
for (i = 0; i < outputSize; ++i) {
|
||||
// Building the cube vertices: its part and sample index
|
||||
// http://rjwagner49.com/Mathematics/Interpolation.pdf
|
||||
var cubeVertices = 1 << m;
|
||||
var cubeN = new Float64Array(cubeVertices);
|
||||
var cubeVertex = new Uint32Array(cubeVertices);
|
||||
for (var j = 0; j < cubeVertices; j++)
|
||||
cubeN[j] = 1;
|
||||
|
||||
// pull 2^m values out of the sample array
|
||||
for (j = 0; j < (1 << inputSize); ++j) {
|
||||
idx = i;
|
||||
for (k = 0, t = j; k < inputSize; ++k, t >>= 1) {
|
||||
idx += idxMul[k] * (e[k][t & 1]);
|
||||
}
|
||||
if (idx >= 0 && idx < nSamples) {
|
||||
sBuf[j] = samples[idx];
|
||||
var k = n, pos = 1;
|
||||
// Map x_i to y_j for 0 <= i < m using the sampled function.
|
||||
for (var i = 0; i < m; ++i) {
|
||||
// x_i' = min(max(x_i, Domain_2i), Domain_2i+1)
|
||||
var domain_2i = domain[i][0];
|
||||
var domain_2i_1 = domain[i][1];
|
||||
var xi = Math.min(Math.max(x[i], domain_2i), domain_2i_1);
|
||||
|
||||
// e_i = Interpolate(x_i', Domain_2i, Domain_2i+1,
|
||||
// Encode_2i, Encode_2i+1)
|
||||
var e = interpolate(xi, domain_2i, domain_2i_1,
|
||||
encode[i][0], encode[i][1]);
|
||||
|
||||
// e_i' = min(max(e_i, 0), Size_i - 1)
|
||||
var size_i = size[i];
|
||||
e = Math.min(Math.max(e, 0), size_i - 1);
|
||||
|
||||
// Adjusting the cube: N and vertex sample index
|
||||
var e0 = e < size_i - 1 ? Math.floor(e) : e - 1; // e1 = e0 + 1;
|
||||
var n0 = e0 + 1 - e; // (e1 - e) / (e1 - e0);
|
||||
var n1 = e - e0; // (e - e0) / (e1 - e0);
|
||||
var offset0 = e0 * k;
|
||||
var offset1 = offset0 + k; // e1 * k
|
||||
for (var j = 0; j < cubeVertices; j++) {
|
||||
if (j & pos) {
|
||||
cubeN[j] *= n1;
|
||||
cubeVertex[j] += offset1;
|
||||
} else {
|
||||
sBuf[j] = 0; // TODO Investigate if this is what Adobe does
|
||||
cubeN[j] *= n0;
|
||||
cubeVertex[j] += offset0;
|
||||
}
|
||||
}
|
||||
|
||||
// do m sets of interpolations
|
||||
for (j = 0, t = (1 << inputSize); j < inputSize; ++j, t >>= 1) {
|
||||
for (k = 0; k < t; k += 2) {
|
||||
sBuf[k >> 1] = efrac0[j] * sBuf[k] + efrac1[j] * sBuf[k + 1];
|
||||
}
|
||||
}
|
||||
|
||||
// map output value to range
|
||||
out[i] = (sBuf[0] * (decode[i][1] - decode[i][0]) + decode[i][0]);
|
||||
if (out[i] < range[i][0]) {
|
||||
out[i] = range[i][0];
|
||||
} else if (out[i] > range[i][1]) {
|
||||
out[i] = range[i][1];
|
||||
}
|
||||
k *= size_i;
|
||||
pos <<= 1;
|
||||
}
|
||||
return out;
|
||||
|
||||
var y = new Float64Array(n);
|
||||
for (var j = 0; j < n; ++j) {
|
||||
// Sum all cube vertices' samples portions
|
||||
var rj = 0;
|
||||
for (var i = 0; i < cubeVertices; i++)
|
||||
rj += samples[cubeVertex[i] + j] * cubeN[i];
|
||||
|
||||
// r_j' = Interpolate(r_j, 0, 2^BitsPerSample - 1,
|
||||
// Decode_2j, Decode_2j+1)
|
||||
rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
|
||||
|
||||
// y_j = min(max(r_j, range_2j), range_2j+1)
|
||||
y[j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);
|
||||
}
|
||||
|
||||
return y;
|
||||
}
|
||||
},
|
||||
|
||||
constructInterpolated:
|
||||
function pdfFunctionConstructInterpolated(str, dict) {
|
||||
constructInterpolated: function PDFFunction_constructInterpolated(str,
|
||||
dict) {
|
||||
var c0 = dict.get('C0') || [0];
|
||||
var c1 = dict.get('C1') || [1];
|
||||
var n = dict.get('N');
|
||||
|
@ -249,7 +239,7 @@ var PDFFunction = (function PDFFunctionClosure() {
|
|||
},
|
||||
|
||||
constructInterpolatedFromIR:
|
||||
function pdfFunctionconstructInterpolatedFromIR(IR) {
|
||||
function PDFFunction_constructInterpolatedFromIR(IR) {
|
||||
var c0 = IR[1];
|
||||
var diff = IR[2];
|
||||
var n = IR[3];
|
||||
|
@ -268,7 +258,7 @@ var PDFFunction = (function PDFFunctionClosure() {
|
|||
}
|
||||
},
|
||||
|
||||
constructStiched: function pdfFunctionConstructStiched(fn, dict, xref) {
|
||||
constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {
|
||||
var domain = dict.get('Domain');
|
||||
|
||||
if (!domain)
|
||||
|
@ -278,18 +268,18 @@ var PDFFunction = (function PDFFunctionClosure() {
|
|||
if (inputSize != 1)
|
||||
error('Bad domain for stiched function');
|
||||
|
||||
var fnRefs = xref.fetchIfRef(dict.get('Functions'));
|
||||
var fnRefs = dict.get('Functions');
|
||||
var fns = [];
|
||||
for (var i = 0, ii = fnRefs.length; i < ii; ++i)
|
||||
fns.push(PDFFunction.getIR(xref, xref.fetchIfRef(fnRefs[i])));
|
||||
|
||||
var bounds = xref.fetchIfRef(dict.get('Bounds'));
|
||||
var encode = xref.fetchIfRef(dict.get('Encode'));
|
||||
var bounds = dict.get('Bounds');
|
||||
var encode = dict.get('Encode');
|
||||
|
||||
return [CONSTRUCT_STICHED, domain, bounds, encode, fns];
|
||||
},
|
||||
|
||||
constructStichedFromIR: function pdfFunctionConstructStichedFromIR(IR) {
|
||||
constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) {
|
||||
var domain = IR[1];
|
||||
var bounds = IR[2];
|
||||
var encode = IR[3];
|
||||
|
@ -335,7 +325,7 @@ var PDFFunction = (function PDFFunctionClosure() {
|
|||
};
|
||||
},
|
||||
|
||||
constructPostScript: function pdfFunctionConstructPostScript(fn, dict,
|
||||
constructPostScript: function PDFFunction_constructPostScript(fn, dict,
|
||||
xref) {
|
||||
var domain = dict.get('Domain');
|
||||
var range = dict.get('Range');
|
||||
|
@ -353,8 +343,8 @@ var PDFFunction = (function PDFFunctionClosure() {
|
|||
return [CONSTRUCT_POSTSCRIPT, domain, range, code];
|
||||
},
|
||||
|
||||
constructPostScriptFromIR:
|
||||
function pdfFunctionConstructPostScriptFromIR(IR) {
|
||||
constructPostScriptFromIR: function PDFFunction_constructPostScriptFromIR(
|
||||
IR) {
|
||||
var domain = IR[1];
|
||||
var range = IR[2];
|
||||
var code = IR[3];
|
||||
|
@ -374,7 +364,7 @@ var PDFFunction = (function PDFFunctionClosure() {
|
|||
return cache.get(key);
|
||||
|
||||
var stack = evaluator.execute(initialStack);
|
||||
var transformed = new Array(numOutputs);
|
||||
var transformed = [];
|
||||
for (i = numOutputs - 1; i >= 0; --i) {
|
||||
var out = stack.pop();
|
||||
var rangeIndex = 2 * i;
|
||||
|
@ -400,13 +390,13 @@ var FunctionCache = (function FunctionCacheClosure() {
|
|||
this.total = 0;
|
||||
}
|
||||
FunctionCache.prototype = {
|
||||
has: function has(key) {
|
||||
has: function FunctionCache_has(key) {
|
||||
return key in this.cache;
|
||||
},
|
||||
get: function get(key) {
|
||||
get: function FunctionCache_get(key) {
|
||||
return this.cache[key];
|
||||
},
|
||||
set: function set(key, value) {
|
||||
set: function FunctionCache_set(key, value) {
|
||||
if (this.total < MAX_CACHE_SIZE) {
|
||||
this.cache[key] = value;
|
||||
this.total++;
|
||||
|
@ -423,28 +413,28 @@ var PostScriptStack = (function PostScriptStackClosure() {
|
|||
}
|
||||
|
||||
PostScriptStack.prototype = {
|
||||
push: function push(value) {
|
||||
push: function PostScriptStack_push(value) {
|
||||
if (this.stack.length >= MAX_STACK_SIZE)
|
||||
error('PostScript function stack overflow.');
|
||||
this.stack.push(value);
|
||||
},
|
||||
pop: function pop() {
|
||||
pop: function PostScriptStack_pop() {
|
||||
if (this.stack.length <= 0)
|
||||
error('PostScript function stack underflow.');
|
||||
return this.stack.pop();
|
||||
},
|
||||
copy: function copy(n) {
|
||||
copy: function PostScriptStack_copy(n) {
|
||||
if (this.stack.length + n >= MAX_STACK_SIZE)
|
||||
error('PostScript function stack overflow.');
|
||||
var stack = this.stack;
|
||||
for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++)
|
||||
stack.push(stack[i]);
|
||||
},
|
||||
index: function index(n) {
|
||||
index: function PostScriptStack_index(n) {
|
||||
this.push(this.stack[this.stack.length - n - 1]);
|
||||
},
|
||||
// rotate the last n stack elements p times
|
||||
roll: function roll(n, p) {
|
||||
roll: function PostScriptStack_roll(n, p) {
|
||||
var stack = this.stack;
|
||||
var l = stack.length - n;
|
||||
var r = stack.length - 1, c = l + (p - Math.floor(p / n) * n), i, j, t;
|
||||
|
@ -467,7 +457,7 @@ var PostScriptEvaluator = (function PostScriptEvaluatorClosure() {
|
|||
this.operands = operands;
|
||||
}
|
||||
PostScriptEvaluator.prototype = {
|
||||
execute: function execute(initialStack) {
|
||||
execute: function PostScriptEvaluator_execute(initialStack) {
|
||||
var stack = new PostScriptStack(initialStack);
|
||||
var counter = 0;
|
||||
var operators = this.operators;
|
||||
|
@ -701,31 +691,31 @@ var PostScriptParser = (function PostScriptParserClosure() {
|
|||
this.prev;
|
||||
}
|
||||
PostScriptParser.prototype = {
|
||||
nextToken: function nextToken() {
|
||||
nextToken: function PostScriptParser_nextToken() {
|
||||
this.prev = this.token;
|
||||
this.token = this.lexer.getToken();
|
||||
},
|
||||
accept: function accept(type) {
|
||||
accept: function PostScriptParser_accept(type) {
|
||||
if (this.token.type == type) {
|
||||
this.nextToken();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
expect: function expect(type) {
|
||||
expect: function PostScriptParser_expect(type) {
|
||||
if (this.accept(type))
|
||||
return true;
|
||||
error('Unexpected symbol: found ' + this.token.type + ' expected ' +
|
||||
type + '.');
|
||||
},
|
||||
parse: function parse() {
|
||||
parse: function PostScriptParser_parse() {
|
||||
this.nextToken();
|
||||
this.expect(PostScriptTokenTypes.LBRACE);
|
||||
this.parseBlock();
|
||||
this.expect(PostScriptTokenTypes.RBRACE);
|
||||
return this.operators;
|
||||
},
|
||||
parseBlock: function parseBlock() {
|
||||
parseBlock: function PostScriptParser_parseBlock() {
|
||||
while (true) {
|
||||
if (this.accept(PostScriptTokenTypes.NUMBER)) {
|
||||
this.operators.push(this.prev.value);
|
||||
|
@ -738,7 +728,7 @@ var PostScriptParser = (function PostScriptParserClosure() {
|
|||
}
|
||||
}
|
||||
},
|
||||
parseCondition: function parseCondition() {
|
||||
parseCondition: function PostScriptParser_parseCondition() {
|
||||
// Add two place holders that will be updated later
|
||||
var conditionLocation = this.operators.length;
|
||||
this.operators.push(null, null);
|
||||
|
@ -789,7 +779,7 @@ var PostScriptToken = (function PostScriptTokenClosure() {
|
|||
|
||||
var opCache = {};
|
||||
|
||||
PostScriptToken.getOperator = function getOperator(op) {
|
||||
PostScriptToken.getOperator = function PostScriptToken_getOperator(op) {
|
||||
var opValue = opCache[op];
|
||||
if (opValue)
|
||||
return opValue;
|
||||
|
@ -812,7 +802,7 @@ var PostScriptLexer = (function PostScriptLexerClosure() {
|
|||
this.stream = stream;
|
||||
}
|
||||
PostScriptLexer.prototype = {
|
||||
getToken: function getToken() {
|
||||
getToken: function PostScriptLexer_getToken() {
|
||||
var s = '';
|
||||
var ch;
|
||||
var comment = false;
|
||||
|
@ -862,7 +852,7 @@ var PostScriptLexer = (function PostScriptLexerClosure() {
|
|||
return PostScriptToken.getOperator(str);
|
||||
}
|
||||
},
|
||||
getNumber: function getNumber(ch) {
|
||||
getNumber: function PostScriptLexer_getNumber(ch) {
|
||||
var str = ch;
|
||||
var stream = this.stream;
|
||||
while (true) {
|
||||
|
|
|
@ -1508,27 +1508,7 @@ var GlyphsUnicode = {
|
|||
dalet: 0x05D3,
|
||||
daletdagesh: 0xFB33,
|
||||
daletdageshhebrew: 0xFB33,
|
||||
dalethatafpatah: 0x05D305B2,
|
||||
dalethatafpatahhebrew: 0x05D305B2,
|
||||
dalethatafsegol: 0x05D305B1,
|
||||
dalethatafsegolhebrew: 0x05D305B1,
|
||||
dalethebrew: 0x05D3,
|
||||
dalethiriq: 0x05D305B4,
|
||||
dalethiriqhebrew: 0x05D305B4,
|
||||
daletholam: 0x05D305B9,
|
||||
daletholamhebrew: 0x05D305B9,
|
||||
daletpatah: 0x05D305B7,
|
||||
daletpatahhebrew: 0x05D305B7,
|
||||
daletqamats: 0x05D305B8,
|
||||
daletqamatshebrew: 0x05D305B8,
|
||||
daletqubuts: 0x05D305BB,
|
||||
daletqubutshebrew: 0x05D305BB,
|
||||
daletsegol: 0x05D305B6,
|
||||
daletsegolhebrew: 0x05D305B6,
|
||||
daletsheva: 0x05D305B0,
|
||||
daletshevahebrew: 0x05D305B0,
|
||||
dalettsere: 0x05D305B5,
|
||||
dalettserehebrew: 0x05D305B5,
|
||||
dalfinalarabic: 0xFEAA,
|
||||
dammaarabic: 0x064F,
|
||||
dammalowarabic: 0x064F,
|
||||
|
@ -1845,10 +1825,6 @@ var GlyphsUnicode = {
|
|||
finalkafdagesh: 0xFB3A,
|
||||
finalkafdageshhebrew: 0xFB3A,
|
||||
finalkafhebrew: 0x05DA,
|
||||
finalkafqamats: 0x05DA05B8,
|
||||
finalkafqamatshebrew: 0x05DA05B8,
|
||||
finalkafsheva: 0x05DA05B0,
|
||||
finalkafshevahebrew: 0x05DA05B0,
|
||||
finalmem: 0x05DD,
|
||||
finalmemhebrew: 0x05DD,
|
||||
finalnun: 0x05DF,
|
||||
|
@ -2037,14 +2013,7 @@ var GlyphsUnicode = {
|
|||
hakatakanahalfwidth: 0xFF8A,
|
||||
halantgurmukhi: 0x0A4D,
|
||||
hamzaarabic: 0x0621,
|
||||
hamzadammaarabic: 0x0621064F,
|
||||
hamzadammatanarabic: 0x0621064C,
|
||||
hamzafathaarabic: 0x0621064E,
|
||||
hamzafathatanarabic: 0x0621064B,
|
||||
hamzalowarabic: 0x0621,
|
||||
hamzalowkasraarabic: 0x06210650,
|
||||
hamzalowkasratanarabic: 0x0621064D,
|
||||
hamzasukunarabic: 0x06210652,
|
||||
hangulfiller: 0x3164,
|
||||
hardsigncyrillic: 0x044A,
|
||||
harpoonleftbarbup: 0x21BC,
|
||||
|
@ -2476,10 +2445,6 @@ var GlyphsUnicode = {
|
|||
lameddagesh: 0xFB3C,
|
||||
lameddageshhebrew: 0xFB3C,
|
||||
lamedhebrew: 0x05DC,
|
||||
lamedholam: 0x05DC05B9,
|
||||
lamedholamdagesh: '05DC 05B9 05BC',
|
||||
lamedholamdageshhebrew: '05DC 05B9 05BC',
|
||||
lamedholamhebrew: 0x05DC05B9,
|
||||
lamfinalarabic: 0xFEDE,
|
||||
lamhahinitialarabic: 0xFCCA,
|
||||
laminitialarabic: 0xFEDF,
|
||||
|
@ -2489,8 +2454,6 @@ var GlyphsUnicode = {
|
|||
lammedialarabic: 0xFEE0,
|
||||
lammeemhahinitialarabic: 0xFD88,
|
||||
lammeeminitialarabic: 0xFCCC,
|
||||
lammeemjeeminitialarabic: 'FEDF FEE4 FEA0',
|
||||
lammeemkhahinitialarabic: 'FEDF FEE4 FEA8',
|
||||
largecircle: 0x25EF,
|
||||
lbar: 0x019A,
|
||||
lbelt: 0x026C,
|
||||
|
@ -2787,7 +2750,6 @@ var GlyphsUnicode = {
|
|||
noonfinalarabic: 0xFEE6,
|
||||
noonghunnaarabic: 0x06BA,
|
||||
noonghunnafinalarabic: 0xFB9F,
|
||||
noonhehinitialarabic: 0xFEE7FEEC,
|
||||
nooninitialarabic: 0xFEE7,
|
||||
noonjeeminitialarabic: 0xFCD2,
|
||||
noonjeemisolatedarabic: 0xFC4B,
|
||||
|
@ -3159,27 +3121,7 @@ var GlyphsUnicode = {
|
|||
qof: 0x05E7,
|
||||
qofdagesh: 0xFB47,
|
||||
qofdageshhebrew: 0xFB47,
|
||||
qofhatafpatah: 0x05E705B2,
|
||||
qofhatafpatahhebrew: 0x05E705B2,
|
||||
qofhatafsegol: 0x05E705B1,
|
||||
qofhatafsegolhebrew: 0x05E705B1,
|
||||
qofhebrew: 0x05E7,
|
||||
qofhiriq: 0x05E705B4,
|
||||
qofhiriqhebrew: 0x05E705B4,
|
||||
qofholam: 0x05E705B9,
|
||||
qofholamhebrew: 0x05E705B9,
|
||||
qofpatah: 0x05E705B7,
|
||||
qofpatahhebrew: 0x05E705B7,
|
||||
qofqamats: 0x05E705B8,
|
||||
qofqamatshebrew: 0x05E705B8,
|
||||
qofqubuts: 0x05E705BB,
|
||||
qofqubutshebrew: 0x05E705BB,
|
||||
qofsegol: 0x05E705B6,
|
||||
qofsegolhebrew: 0x05E705B6,
|
||||
qofsheva: 0x05E705B0,
|
||||
qofshevahebrew: 0x05E705B0,
|
||||
qoftsere: 0x05E705B5,
|
||||
qoftserehebrew: 0x05E705B5,
|
||||
qparen: 0x24AC,
|
||||
quarternote: 0x2669,
|
||||
qubuts: 0x05BB,
|
||||
|
@ -3253,32 +3195,11 @@ var GlyphsUnicode = {
|
|||
reharmenian: 0x0580,
|
||||
rehfinalarabic: 0xFEAE,
|
||||
rehiragana: 0x308C,
|
||||
rehyehaleflamarabic: '0631 FEF3 FE8E 0644',
|
||||
rekatakana: 0x30EC,
|
||||
rekatakanahalfwidth: 0xFF9A,
|
||||
resh: 0x05E8,
|
||||
reshdageshhebrew: 0xFB48,
|
||||
reshhatafpatah: 0x05E805B2,
|
||||
reshhatafpatahhebrew: 0x05E805B2,
|
||||
reshhatafsegol: 0x05E805B1,
|
||||
reshhatafsegolhebrew: 0x05E805B1,
|
||||
reshhebrew: 0x05E8,
|
||||
reshhiriq: 0x05E805B4,
|
||||
reshhiriqhebrew: 0x05E805B4,
|
||||
reshholam: 0x05E805B9,
|
||||
reshholamhebrew: 0x05E805B9,
|
||||
reshpatah: 0x05E805B7,
|
||||
reshpatahhebrew: 0x05E805B7,
|
||||
reshqamats: 0x05E805B8,
|
||||
reshqamatshebrew: 0x05E805B8,
|
||||
reshqubuts: 0x05E805BB,
|
||||
reshqubutshebrew: 0x05E805BB,
|
||||
reshsegol: 0x05E805B6,
|
||||
reshsegolhebrew: 0x05E805B6,
|
||||
reshsheva: 0x05E805B0,
|
||||
reshshevahebrew: 0x05E805B0,
|
||||
reshtsere: 0x05E805B5,
|
||||
reshtserehebrew: 0x05E805B5,
|
||||
reversedtilde: 0x223D,
|
||||
reviahebrew: 0x0597,
|
||||
reviamugrashhebrew: 0x0597,
|
||||
|
@ -3477,7 +3398,6 @@ var GlyphsUnicode = {
|
|||
shaddadammaarabic: 0xFC61,
|
||||
shaddadammatanarabic: 0xFC5E,
|
||||
shaddafathaarabic: 0xFC60,
|
||||
shaddafathatanarabic: 0x0651064B,
|
||||
shaddakasraarabic: 0xFC62,
|
||||
shaddakasratanarabic: 0xFC5F,
|
||||
shade: 0x2592,
|
||||
|
@ -3674,7 +3594,6 @@ var GlyphsUnicode = {
|
|||
tchehfinalarabic: 0xFB7B,
|
||||
tchehinitialarabic: 0xFB7C,
|
||||
tchehmedialarabic: 0xFB7D,
|
||||
tchehmeeminitialarabic: 0xFB7CFEE4,
|
||||
tcircle: 0x24E3,
|
||||
tcircumflexbelow: 0x1E71,
|
||||
tcommaaccent: 0x0163,
|
||||
|
|
26
src/image.js
26
src/image.js
|
@ -94,7 +94,7 @@ var PDFImage = (function PDFImageClosure() {
|
|||
}
|
||||
}
|
||||
|
||||
var mask = xref.fetchIfRef(dict.get('Mask'));
|
||||
var mask = dict.get('Mask');
|
||||
|
||||
if (mask) {
|
||||
TODO('masked images');
|
||||
|
@ -106,8 +106,8 @@ var PDFImage = (function PDFImageClosure() {
|
|||
* Handles processing of image data and calls the callback with an argument
|
||||
* of a PDFImage when the image is ready to be used.
|
||||
*/
|
||||
PDFImage.buildImage = function buildImage(callback, handler, xref, res,
|
||||
image, inline) {
|
||||
PDFImage.buildImage = function PDFImage_buildImage(callback, handler, xref,
|
||||
res, image, inline) {
|
||||
var imageDataPromise = new Promise();
|
||||
var smaskPromise = new Promise();
|
||||
// The image data and smask data may not be ready yet, wait till both are
|
||||
|
@ -120,7 +120,7 @@ var PDFImage = (function PDFImageClosure() {
|
|||
|
||||
handleImageData(handler, xref, res, image, imageDataPromise);
|
||||
|
||||
var smask = xref.fetchIfRef(image.dict.get('SMask'));
|
||||
var smask = image.dict.get('SMask');
|
||||
if (smask)
|
||||
handleImageData(handler, xref, res, smask, smaskPromise);
|
||||
else
|
||||
|
@ -139,7 +139,8 @@ var PDFImage = (function PDFImageClosure() {
|
|||
* @param {Number} h2 New height.
|
||||
* @return {TypedArray} Resized image data.
|
||||
*/
|
||||
PDFImage.resize = function resize(pixels, bpc, components, w1, h1, w2, h2) {
|
||||
PDFImage.resize = function PDFImage_resize(pixels, bpc, components,
|
||||
w1, h1, w2, h2) {
|
||||
var length = w2 * h2 * components;
|
||||
var temp = bpc <= 8 ? new Uint8Array(length) :
|
||||
bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length);
|
||||
|
@ -177,7 +178,7 @@ var PDFImage = (function PDFImageClosure() {
|
|||
return this.height;
|
||||
return Math.max(this.height, this.smask.height);
|
||||
},
|
||||
getComponents: function getComponents(buffer) {
|
||||
getComponents: function PDFImage_getComponents(buffer) {
|
||||
var bpc = this.bpc;
|
||||
var needsDecode = this.needsDecode;
|
||||
var decodeMap = this.decode;
|
||||
|
@ -265,7 +266,7 @@ var PDFImage = (function PDFImageClosure() {
|
|||
}
|
||||
return output;
|
||||
},
|
||||
getOpacity: function getOpacity(width, height) {
|
||||
getOpacity: function PDFImage_getOpacity(width, height) {
|
||||
var smask = this.smask;
|
||||
var originalWidth = this.width;
|
||||
var originalHeight = this.height;
|
||||
|
@ -285,7 +286,8 @@ var PDFImage = (function PDFImageClosure() {
|
|||
}
|
||||
return buf;
|
||||
},
|
||||
applyStencilMask: function applyStencilMask(buffer, inverseDecode) {
|
||||
applyStencilMask: function PDFImage_applyStencilMask(buffer,
|
||||
inverseDecode) {
|
||||
var width = this.width, height = this.height;
|
||||
var bitStrideLength = (width + 7) >> 3;
|
||||
var imgArray = this.getImageBytes(bitStrideLength * height);
|
||||
|
@ -308,7 +310,7 @@ var PDFImage = (function PDFImageClosure() {
|
|||
}
|
||||
}
|
||||
},
|
||||
fillRgbaBuffer: function fillRgbaBuffer(buffer, width, height) {
|
||||
fillRgbaBuffer: function PDFImage_fillRgbaBuffer(buffer, width, height) {
|
||||
var numComps = this.numComps;
|
||||
var originalWidth = this.width;
|
||||
var originalHeight = this.height;
|
||||
|
@ -335,7 +337,7 @@ var PDFImage = (function PDFImageClosure() {
|
|||
buffer[i + 3] = opacity[opacityPos++];
|
||||
}
|
||||
},
|
||||
fillGrayBuffer: function fillGrayBuffer(buffer) {
|
||||
fillGrayBuffer: function PDFImage_fillGrayBuffer(buffer) {
|
||||
var numComps = this.numComps;
|
||||
if (numComps != 1)
|
||||
error('Reading gray scale from a color image: ' + numComps);
|
||||
|
@ -355,7 +357,7 @@ var PDFImage = (function PDFImageClosure() {
|
|||
for (var i = 0; i < length; ++i)
|
||||
buffer[i] = (scale * comps[i]) | 0;
|
||||
},
|
||||
getImageBytes: function getImageBytes(length) {
|
||||
getImageBytes: function PDFImage_getImageBytes(length) {
|
||||
this.image.reset();
|
||||
return this.image.getBytes(length);
|
||||
}
|
||||
|
@ -365,7 +367,7 @@ var PDFImage = (function PDFImageClosure() {
|
|||
|
||||
function loadJpegStream(id, imageData, objs) {
|
||||
var img = new Image();
|
||||
img.onload = (function jpegImageLoaderOnload() {
|
||||
img.onload = (function loadJpegStream_onloadClosure() {
|
||||
objs.resolve(id, img);
|
||||
});
|
||||
img.src = 'data:image/jpeg;base64,' + window.btoa(imageData);
|
||||
|
|
2250
src/jpx.js
2250
src/jpx.js
File diff suppressed because it is too large
Load diff
66
src/metadata.js
Normal file
66
src/metadata.js
Normal file
|
@ -0,0 +1,66 @@
|
|||
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
|
||||
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
|
||||
|
||||
'use strict';
|
||||
|
||||
var Metadata = PDFJS.Metadata = (function MetadataClosure() {
|
||||
function Metadata(meta) {
|
||||
if (typeof meta === 'string') {
|
||||
var parser = new DOMParser();
|
||||
meta = parser.parseFromString(meta, 'application/xml');
|
||||
} else if (!(meta instanceof Document)) {
|
||||
error('Metadata: Invalid metadata object');
|
||||
}
|
||||
|
||||
this.metaDocument = meta;
|
||||
this.metadata = {};
|
||||
this.parse();
|
||||
}
|
||||
|
||||
Metadata.prototype = {
|
||||
parse: function Metadata_parse() {
|
||||
var doc = this.metaDocument;
|
||||
var rdf = doc.documentElement;
|
||||
|
||||
if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
|
||||
rdf = rdf.firstChild;
|
||||
while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf')
|
||||
rdf = rdf.nextSibling;
|
||||
}
|
||||
|
||||
var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
|
||||
if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes())
|
||||
return;
|
||||
|
||||
var childNodes = rdf.childNodes, desc, namespace, entries, entry;
|
||||
|
||||
for (var i = 0, length = childNodes.length; i < length; i++) {
|
||||
desc = childNodes[i];
|
||||
if (desc.nodeName.toLowerCase() !== 'rdf:description')
|
||||
continue;
|
||||
|
||||
entries = [];
|
||||
for (var ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
|
||||
if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text')
|
||||
entries.push(desc.childNodes[ii]);
|
||||
}
|
||||
|
||||
for (ii = 0, iLength = entries.length; ii < iLength; ii++) {
|
||||
var entry = entries[ii];
|
||||
var name = entry.nodeName.toLowerCase();
|
||||
this.metadata[name] = entry.textContent.trim();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
get: function Metadata_get(name) {
|
||||
return this.metadata[name] || null;
|
||||
},
|
||||
|
||||
has: function Metadata_has(name) {
|
||||
return typeof this.metadata[name] !== 'undefined';
|
||||
}
|
||||
};
|
||||
|
||||
return Metadata;
|
||||
})();
|
312
src/obj.js
312
src/obj.js
|
@ -22,7 +22,7 @@ var Cmd = (function CmdClosure() {
|
|||
|
||||
var cmdCache = {};
|
||||
|
||||
Cmd.get = function cmdGet(cmd) {
|
||||
Cmd.get = function Cmd_get(cmd) {
|
||||
var cmdValue = cmdCache[cmd];
|
||||
if (cmdValue)
|
||||
return cmdValue;
|
||||
|
@ -34,36 +34,52 @@ var Cmd = (function CmdClosure() {
|
|||
})();
|
||||
|
||||
var Dict = (function DictClosure() {
|
||||
function Dict() {
|
||||
// xref is optional
|
||||
function Dict(xref) {
|
||||
// Map should only be used internally, use functions below to access.
|
||||
this.map = Object.create(null);
|
||||
this.xref = xref;
|
||||
}
|
||||
|
||||
Dict.prototype = {
|
||||
get: function dictGet(key1, key2, key3) {
|
||||
// automatically dereferences Ref objects
|
||||
get: function Dict_get(key1, key2, key3) {
|
||||
var value;
|
||||
var xref = this.xref;
|
||||
if (typeof (value = this.map[key1]) != 'undefined' || key1 in this.map ||
|
||||
typeof key2 == 'undefined') {
|
||||
return value;
|
||||
return xref ? this.xref.fetchIfRef(value) : value;
|
||||
}
|
||||
if (typeof (value = this.map[key2]) != 'undefined' || key2 in this.map ||
|
||||
typeof key3 == 'undefined') {
|
||||
return value;
|
||||
return xref ? this.xref.fetchIfRef(value) : value;
|
||||
}
|
||||
|
||||
return this.map[key3] || null;
|
||||
value = this.map[key3] || null;
|
||||
return xref ? this.xref.fetchIfRef(value) : value;
|
||||
},
|
||||
// no dereferencing
|
||||
getRaw: function Dict_getRaw(key) {
|
||||
return this.map[key];
|
||||
},
|
||||
// creates new map and dereferences all Refs
|
||||
getAll: function Dict_getAll() {
|
||||
var all = {};
|
||||
for (var key in this.map)
|
||||
all[key] = this.get(key);
|
||||
return all;
|
||||
},
|
||||
|
||||
set: function dictSet(key, value) {
|
||||
set: function Dict_set(key, value) {
|
||||
this.map[key] = value;
|
||||
},
|
||||
|
||||
has: function dictHas(key) {
|
||||
has: function Dict_has(key) {
|
||||
return key in this.map;
|
||||
},
|
||||
|
||||
forEach: function dictForEach(callback) {
|
||||
forEach: function Dict_forEach(callback) {
|
||||
for (var key in this.map) {
|
||||
callback(key, this.map[key]);
|
||||
callback(key, this.get(key));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
@ -90,11 +106,11 @@ var RefSet = (function RefSetClosure() {
|
|||
}
|
||||
|
||||
RefSet.prototype = {
|
||||
has: function refSetHas(ref) {
|
||||
has: function RefSet_has(ref) {
|
||||
return !!this.dict['R' + ref.num + '.' + ref.gen];
|
||||
},
|
||||
|
||||
put: function refSetPut(ref) {
|
||||
put: function RefSet_put(ref) {
|
||||
this.dict['R' + ref.num + '.' + ref.gen] = ref;
|
||||
}
|
||||
};
|
||||
|
@ -111,20 +127,33 @@ var Catalog = (function CatalogClosure() {
|
|||
}
|
||||
|
||||
Catalog.prototype = {
|
||||
get metadata() {
|
||||
var stream = this.catDict.get('Metadata');
|
||||
var metadata;
|
||||
if (stream && isDict(stream.dict)) {
|
||||
var type = stream.dict.get('Type');
|
||||
var subtype = stream.dict.get('Subtype');
|
||||
|
||||
if (isName(type) && isName(subtype) &&
|
||||
type.name === 'Metadata' && subtype.name === 'XML') {
|
||||
metadata = stringToPDFString(bytesToString(stream.getBytes()));
|
||||
}
|
||||
}
|
||||
|
||||
return shadow(this, 'metadata', metadata);
|
||||
},
|
||||
get toplevelPagesDict() {
|
||||
var pagesObj = this.catDict.get('Pages');
|
||||
assertWellFormed(isRef(pagesObj), 'invalid top-level pages reference');
|
||||
var xrefObj = this.xref.fetch(pagesObj);
|
||||
assertWellFormed(isDict(xrefObj), 'invalid top-level pages dictionary');
|
||||
assertWellFormed(isDict(pagesObj), 'invalid top-level pages dictionary');
|
||||
// shadow the prototype getter
|
||||
return shadow(this, 'toplevelPagesDict', xrefObj);
|
||||
return shadow(this, 'toplevelPagesDict', pagesObj);
|
||||
},
|
||||
get documentOutline() {
|
||||
var xref = this.xref;
|
||||
var obj = xref.fetchIfRef(this.catDict.get('Outlines'));
|
||||
var obj = this.catDict.get('Outlines');
|
||||
var root = { items: [] };
|
||||
if (isDict(obj)) {
|
||||
obj = obj.get('First');
|
||||
obj = obj.getRaw('First');
|
||||
var processed = new RefSet();
|
||||
if (isRef(obj)) {
|
||||
var queue = [{obj: obj, parent: root}];
|
||||
|
@ -133,18 +162,20 @@ var Catalog = (function CatalogClosure() {
|
|||
processed.put(obj);
|
||||
while (queue.length > 0) {
|
||||
var i = queue.shift();
|
||||
var outlineDict = xref.fetch(i.obj);
|
||||
var outlineDict = xref.fetchIfRef(i.obj);
|
||||
if (outlineDict === null)
|
||||
continue;
|
||||
if (!outlineDict.has('Title'))
|
||||
error('Invalid outline item');
|
||||
var dest = outlineDict.get('A');
|
||||
if (dest)
|
||||
dest = xref.fetchIfRef(dest).get('D');
|
||||
dest = dest.get('D');
|
||||
else if (outlineDict.has('Dest')) {
|
||||
dest = outlineDict.get('Dest');
|
||||
dest = outlineDict.getRaw('Dest');
|
||||
if (isName(dest))
|
||||
dest = dest.name;
|
||||
}
|
||||
var title = xref.fetchIfRef(outlineDict.get('Title'));
|
||||
var title = outlineDict.get('Title');
|
||||
var outlineItem = {
|
||||
dest: dest,
|
||||
title: stringToPDFString(title),
|
||||
|
@ -155,12 +186,12 @@ var Catalog = (function CatalogClosure() {
|
|||
items: []
|
||||
};
|
||||
i.parent.items.push(outlineItem);
|
||||
obj = outlineDict.get('First');
|
||||
obj = outlineDict.getRaw('First');
|
||||
if (isRef(obj) && !processed.has(obj)) {
|
||||
queue.push({obj: obj, parent: outlineItem});
|
||||
processed.put(obj);
|
||||
}
|
||||
obj = outlineDict.get('Next');
|
||||
obj = outlineDict.getRaw('Next');
|
||||
if (isRef(obj) && !processed.has(obj)) {
|
||||
queue.push({obj: obj, parent: i.parent});
|
||||
processed.put(obj);
|
||||
|
@ -180,7 +211,7 @@ var Catalog = (function CatalogClosure() {
|
|||
// shadow the prototype getter
|
||||
return shadow(this, 'num', obj);
|
||||
},
|
||||
traverseKids: function catalogTraverseKids(pagesDict) {
|
||||
traverseKids: function Catalog_traverseKids(pagesDict) {
|
||||
var pageCache = this.pageCache;
|
||||
var kids = pagesDict.get('Kids');
|
||||
assertWellFormed(isArray(kids),
|
||||
|
@ -188,7 +219,7 @@ var Catalog = (function CatalogClosure() {
|
|||
for (var i = 0, ii = kids.length; i < ii; ++i) {
|
||||
var kid = kids[i];
|
||||
assertWellFormed(isRef(kid),
|
||||
'page dictionary kid is not a reference');
|
||||
'page dictionary kid is not a reference');
|
||||
var obj = this.xref.fetch(kid);
|
||||
if (isDict(obj, 'Page') || (isDict(obj) && !obj.has('Kids'))) {
|
||||
pageCache.push(new Page(this.xref, pageCache.length, obj, kid));
|
||||
|
@ -202,8 +233,7 @@ var Catalog = (function CatalogClosure() {
|
|||
}
|
||||
},
|
||||
get destinations() {
|
||||
function fetchDestination(xref, ref) {
|
||||
var dest = xref.fetchIfRef(ref);
|
||||
function fetchDestination(dest) {
|
||||
return isDict(dest) ? dest.get('D') : dest;
|
||||
}
|
||||
|
||||
|
@ -211,16 +241,16 @@ var Catalog = (function CatalogClosure() {
|
|||
var dests = {}, nameTreeRef, nameDictionaryRef;
|
||||
var obj = this.catDict.get('Names');
|
||||
if (obj)
|
||||
nameTreeRef = xref.fetchIfRef(obj).get('Dests');
|
||||
nameTreeRef = obj.getRaw('Dests');
|
||||
else if (this.catDict.has('Dests'))
|
||||
nameDictionaryRef = this.catDict.get('Dests');
|
||||
|
||||
if (nameDictionaryRef) {
|
||||
// reading simple destination dictionary
|
||||
obj = xref.fetchIfRef(nameDictionaryRef);
|
||||
obj = nameDictionaryRef;
|
||||
obj.forEach(function catalogForEach(key, value) {
|
||||
if (!value) return;
|
||||
dests[key] = fetchDestination(xref, value);
|
||||
dests[key] = fetchDestination(value);
|
||||
});
|
||||
}
|
||||
if (nameTreeRef) {
|
||||
|
@ -244,13 +274,13 @@ var Catalog = (function CatalogClosure() {
|
|||
}
|
||||
var names = obj.get('Names');
|
||||
for (i = 0, n = names.length; i < n; i += 2) {
|
||||
dests[names[i]] = fetchDestination(xref, names[i + 1]);
|
||||
dests[names[i]] = fetchDestination(xref.fetchIfRef(names[i + 1]));
|
||||
}
|
||||
}
|
||||
}
|
||||
return shadow(this, 'destinations', dests);
|
||||
},
|
||||
getPage: function catalogGetPage(n) {
|
||||
getPage: function Catalog_getPage(n) {
|
||||
var pageCache = this.pageCache;
|
||||
if (!pageCache) {
|
||||
pageCache = this.pageCache = [];
|
||||
|
@ -269,6 +299,7 @@ var XRef = (function XRefClosure() {
|
|||
this.entries = [];
|
||||
this.xrefstms = {};
|
||||
var trailerDict = this.readXRef(startXRef);
|
||||
trailerDict.xref = this;
|
||||
this.trailer = trailerDict;
|
||||
// prepare the XRef cache
|
||||
this.cache = [];
|
||||
|
@ -276,89 +307,84 @@ var XRef = (function XRefClosure() {
|
|||
var encrypt = trailerDict.get('Encrypt');
|
||||
if (encrypt) {
|
||||
var fileId = trailerDict.get('ID');
|
||||
this.encrypt = new CipherTransformFactory(this.fetch(encrypt),
|
||||
this.encrypt = new CipherTransformFactory(encrypt,
|
||||
fileId[0] /*, password */);
|
||||
}
|
||||
|
||||
// get the root dictionary (catalog) object
|
||||
if (!isRef(this.root = trailerDict.get('Root')))
|
||||
if (!(this.root = trailerDict.get('Root')))
|
||||
error('Invalid root reference');
|
||||
}
|
||||
|
||||
XRef.prototype = {
|
||||
readXRefTable: function readXRefTable(parser) {
|
||||
readXRefTable: function XRef_readXRefTable(parser) {
|
||||
// Example of cross-reference table:
|
||||
// xref
|
||||
// 0 1 <-- subsection header (first obj #, obj count)
|
||||
// 0000000000 65535 f <-- actual object (offset, generation #, f/n)
|
||||
// 23 2 <-- subsection header ... and so on ...
|
||||
// 0000025518 00002 n
|
||||
// 0000025635 00000 n
|
||||
// trailer
|
||||
// ...
|
||||
|
||||
// Outer loop is over subsection headers
|
||||
var obj;
|
||||
while (true) {
|
||||
if (isCmd(obj = parser.getObj(), 'trailer'))
|
||||
break;
|
||||
if (!isInt(obj))
|
||||
error('Invalid XRef table');
|
||||
var first = obj;
|
||||
if (!isInt(obj = parser.getObj()))
|
||||
error('Invalid XRef table');
|
||||
var n = obj;
|
||||
if (first < 0 || n < 0 || (first + n) != ((first + n) | 0))
|
||||
error('Invalid XRef table: ' + first + ', ' + n);
|
||||
for (var i = first; i < first + n; ++i) {
|
||||
while (!isCmd(obj = parser.getObj(), 'trailer')) {
|
||||
var first = obj,
|
||||
count = parser.getObj();
|
||||
|
||||
if (!isInt(first) || !isInt(count))
|
||||
error('Invalid XRef table: wrong types in subsection header');
|
||||
|
||||
// Inner loop is over objects themselves
|
||||
for (var i = 0; i < count; i++) {
|
||||
var entry = {};
|
||||
if (!isInt(obj = parser.getObj()))
|
||||
error('Invalid XRef table: ' + first + ', ' + n);
|
||||
entry.offset = obj;
|
||||
if (!isInt(obj = parser.getObj()))
|
||||
error('Invalid XRef table: ' + first + ', ' + n);
|
||||
entry.gen = obj;
|
||||
obj = parser.getObj();
|
||||
if (isCmd(obj, 'n')) {
|
||||
entry.uncompressed = true;
|
||||
} else if (isCmd(obj, 'f')) {
|
||||
entry.offset = parser.getObj();
|
||||
entry.gen = parser.getObj();
|
||||
var type = parser.getObj();
|
||||
|
||||
if (isCmd(type, 'f'))
|
||||
entry.free = true;
|
||||
} else {
|
||||
error('Invalid XRef table: ' + first + ', ' + n);
|
||||
}
|
||||
if (!this.entries[i]) {
|
||||
// In some buggy PDF files the xref table claims to start at 1
|
||||
// instead of 0.
|
||||
if (i == 1 && first == 1 &&
|
||||
entry.offset == 0 && entry.gen == 65535 && entry.free) {
|
||||
i = first = 0;
|
||||
}
|
||||
this.entries[i] = entry;
|
||||
else if (isCmd(type, 'n'))
|
||||
entry.uncompressed = true;
|
||||
|
||||
// Validate entry obj
|
||||
if (!isInt(entry.offset) || !isInt(entry.gen) ||
|
||||
!(entry.free || entry.uncompressed)) {
|
||||
error('Invalid entry in XRef subsection: ' + first + ', ' + count);
|
||||
}
|
||||
|
||||
if (!this.entries[i + first])
|
||||
this.entries[i + first] = entry;
|
||||
}
|
||||
}
|
||||
|
||||
// read the trailer dictionary
|
||||
var dict;
|
||||
if (!isDict(dict = parser.getObj()))
|
||||
error('Invalid XRef table');
|
||||
// Sanity check: as per spec, first object must have these properties
|
||||
if (this.entries[0] &&
|
||||
!(this.entries[0].gen === 65535 && this.entries[0].free))
|
||||
error('Invalid XRef table: unexpected first object');
|
||||
|
||||
// get the 'Prev' pointer
|
||||
var prev;
|
||||
obj = dict.get('Prev');
|
||||
if (isInt(obj)) {
|
||||
prev = obj;
|
||||
} else if (isRef(obj)) {
|
||||
// certain buggy PDF generators generate "/Prev NNN 0 R" instead
|
||||
// of "/Prev NNN"
|
||||
prev = obj.num;
|
||||
}
|
||||
if (prev) {
|
||||
this.readXRef(prev);
|
||||
}
|
||||
// Sanity check
|
||||
if (!isCmd(obj, 'trailer'))
|
||||
error('Invalid XRef table: could not find trailer dictionary');
|
||||
|
||||
// check for 'XRefStm' key
|
||||
if (isInt(obj = dict.get('XRefStm'))) {
|
||||
var pos = obj;
|
||||
// ignore previously loaded xref streams (possible infinite recursion)
|
||||
if (!(pos in this.xrefstms)) {
|
||||
this.xrefstms[pos] = 1;
|
||||
this.readXRef(pos);
|
||||
}
|
||||
}
|
||||
// Read trailer dictionary, e.g.
|
||||
// trailer
|
||||
// << /Size 22
|
||||
// /Root 20R
|
||||
// /Info 10R
|
||||
// /ID [ <81b14aafa313db63dbd6f981e49f94f4> ]
|
||||
// >>
|
||||
// The parser goes through the entire stream << ... >> and provides
|
||||
// a getter interface for the key-value table
|
||||
var dict = parser.getObj();
|
||||
if (!isDict(dict))
|
||||
error('Invalid XRef table: could not parse trailer dictionary');
|
||||
|
||||
return dict;
|
||||
},
|
||||
readXRefStream: function readXRefStream(stream) {
|
||||
readXRefStream: function XRef_readXRefStream(stream) {
|
||||
var streamParameters = stream.parameters;
|
||||
var byteWidths = streamParameters.get('W');
|
||||
var range = streamParameters.get('Index');
|
||||
|
@ -407,12 +433,9 @@ var XRef = (function XRefClosure() {
|
|||
}
|
||||
range.splice(0, 2);
|
||||
}
|
||||
var prev = streamParameters.get('Prev');
|
||||
if (isInt(prev))
|
||||
this.readXRef(prev);
|
||||
return streamParameters;
|
||||
},
|
||||
indexObjects: function indexObjects() {
|
||||
indexObjects: function XRef_indexObjects() {
|
||||
// Simple scan through the PDF content to find objects,
|
||||
// trailers and XRef streams.
|
||||
function readToken(data, offset) {
|
||||
|
@ -504,7 +527,7 @@ var XRef = (function XRefClosure() {
|
|||
var dict;
|
||||
for (var i = 0, ii = trailers.length; i < ii; ++i) {
|
||||
stream.pos = trailers[i];
|
||||
var parser = new Parser(new Lexer(stream), true);
|
||||
var parser = new Parser(new Lexer(stream), true, null);
|
||||
var obj = parser.getObj();
|
||||
if (!isCmd(obj, 'trailer'))
|
||||
continue;
|
||||
|
@ -520,46 +543,73 @@ var XRef = (function XRefClosure() {
|
|||
return dict;
|
||||
// nothing helps
|
||||
error('Invalid PDF structure');
|
||||
return null;
|
||||
},
|
||||
readXRef: function readXref(startXRef) {
|
||||
readXRef: function XRef_readXRef(startXRef) {
|
||||
var stream = this.stream;
|
||||
stream.pos = startXRef;
|
||||
|
||||
try {
|
||||
var parser = new Parser(new Lexer(stream), true);
|
||||
var parser = new Parser(new Lexer(stream), true, null);
|
||||
var obj = parser.getObj();
|
||||
var dict;
|
||||
|
||||
// parse an old-style xref table
|
||||
if (isCmd(obj, 'xref'))
|
||||
return this.readXRefTable(parser);
|
||||
// Get dictionary
|
||||
if (isCmd(obj, 'xref')) {
|
||||
// Parse end-of-file XRef
|
||||
dict = this.readXRefTable(parser);
|
||||
|
||||
// parse an xref stream
|
||||
if (isInt(obj)) {
|
||||
// Recursively get other XRefs 'XRefStm', if any
|
||||
obj = dict.get('XRefStm');
|
||||
if (isInt(obj)) {
|
||||
var pos = obj;
|
||||
// ignore previously loaded xref streams
|
||||
// (possible infinite recursion)
|
||||
if (!(pos in this.xrefstms)) {
|
||||
this.xrefstms[pos] = 1;
|
||||
this.readXRef(pos);
|
||||
}
|
||||
}
|
||||
} else if (isInt(obj)) {
|
||||
// Parse in-stream XRef
|
||||
if (!isInt(parser.getObj()) ||
|
||||
!isCmd(parser.getObj(), 'obj') ||
|
||||
!isStream(obj = parser.getObj())) {
|
||||
error('Invalid XRef stream');
|
||||
}
|
||||
return this.readXRefStream(obj);
|
||||
dict = this.readXRefStream(obj);
|
||||
}
|
||||
|
||||
// Recursively get previous dictionary, if any
|
||||
obj = dict.get('Prev');
|
||||
if (isInt(obj))
|
||||
this.readXRef(obj);
|
||||
else if (isRef(obj)) {
|
||||
// The spec says Prev must not be a reference, i.e. "/Prev NNN"
|
||||
// This is a fallback for non-compliant PDFs, i.e. "/Prev NNN 0 R"
|
||||
this.readXRef(obj.num);
|
||||
}
|
||||
|
||||
return dict;
|
||||
} catch (e) {
|
||||
log('Reading of the xref table/stream failed: ' + e);
|
||||
log('(while reading XRef): ' + e);
|
||||
}
|
||||
|
||||
warn('Indexing all PDF objects');
|
||||
return this.indexObjects();
|
||||
},
|
||||
getEntry: function xRefGetEntry(i) {
|
||||
getEntry: function XRef_getEntry(i) {
|
||||
var e = this.entries[i];
|
||||
if (e === null)
|
||||
return null;
|
||||
return e.free ? null : e; // returns null is the entry is free
|
||||
},
|
||||
fetchIfRef: function xRefFetchIfRef(obj) {
|
||||
fetchIfRef: function XRef_fetchIfRef(obj) {
|
||||
if (!isRef(obj))
|
||||
return obj;
|
||||
return this.fetch(obj);
|
||||
},
|
||||
fetch: function xRefFetch(ref, suppressEncryption) {
|
||||
fetch: function XRef_fetch(ref, suppressEncryption) {
|
||||
assertWellFormed(isRef(ref), 'ref object is not a reference');
|
||||
var num = ref.num;
|
||||
if (num in this.cache)
|
||||
return this.cache[num];
|
||||
|
@ -574,7 +624,7 @@ var XRef = (function XRefClosure() {
|
|||
var stream, parser;
|
||||
if (e.uncompressed) {
|
||||
if (e.gen != gen)
|
||||
throw ('inconsistent generation in XRef');
|
||||
error('inconsistent generation in XRef');
|
||||
stream = this.stream.makeSubStream(e.offset);
|
||||
parser = new Parser(new Lexer(stream), true, this);
|
||||
var obj1 = parser.getObj();
|
||||
|
@ -621,7 +671,7 @@ var XRef = (function XRefClosure() {
|
|||
if (!isInt(first) || !isInt(n)) {
|
||||
error('invalid first and n parameters for ObjStm stream');
|
||||
}
|
||||
parser = new Parser(new Lexer(stream), false);
|
||||
parser = new Parser(new Lexer(stream), false, this);
|
||||
var i, entries = [], nums = [];
|
||||
// read the object numbers to populate cache
|
||||
for (i = 0; i < n; ++i) {
|
||||
|
@ -646,8 +696,8 @@ var XRef = (function XRefClosure() {
|
|||
}
|
||||
return e;
|
||||
},
|
||||
getCatalogObj: function xRefGetCatalogObj() {
|
||||
return this.fetch(this.root);
|
||||
getCatalogObj: function XRef_getCatalogObj() {
|
||||
return this.root;
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -673,7 +723,7 @@ var PDFObjects = (function PDFObjectsClosure() {
|
|||
* Ensures there is an object defined for `objId`. Stores `data` on the
|
||||
* object *if* it is created.
|
||||
*/
|
||||
ensureObj: function pdfObjectsEnsureObj(objId, data) {
|
||||
ensureObj: function PDFObjects_ensureObj(objId, data) {
|
||||
if (this.objs[objId])
|
||||
return this.objs[objId];
|
||||
return this.objs[objId] = new Promise(objId, data);
|
||||
|
@ -688,7 +738,7 @@ var PDFObjects = (function PDFObjectsClosure() {
|
|||
* function and the object is already resolved, the callback gets called
|
||||
* right away.
|
||||
*/
|
||||
get: function pdfObjectsGet(objId, callback) {
|
||||
get: function PDFObjects_get(objId, callback) {
|
||||
// If there is a callback, then the get can be async and the object is
|
||||
// not required to be resolved right now
|
||||
if (callback) {
|
||||
|
@ -702,18 +752,16 @@ var PDFObjects = (function PDFObjectsClosure() {
|
|||
|
||||
// If there isn't an object yet or the object isn't resolved, then the
|
||||
// data isn't ready yet!
|
||||
if (!obj || !obj.isResolved) {
|
||||
throw 'Requesting object that isn\'t resolved yet ' + objId;
|
||||
return null;
|
||||
} else {
|
||||
return obj.data;
|
||||
}
|
||||
if (!obj || !obj.isResolved)
|
||||
error('Requesting object that isn\'t resolved yet ' + objId);
|
||||
|
||||
return obj.data;
|
||||
},
|
||||
|
||||
/**
|
||||
* Resolves the object `objId` with optional `data`.
|
||||
*/
|
||||
resolve: function pdfObjectsResolve(objId, data) {
|
||||
resolve: function PDFObjects_resolve(objId, data) {
|
||||
var objs = this.objs;
|
||||
|
||||
// In case there is a promise already on this object, just resolve it.
|
||||
|
@ -724,11 +772,11 @@ var PDFObjects = (function PDFObjectsClosure() {
|
|||
}
|
||||
},
|
||||
|
||||
onData: function pdfObjectsOnData(objId, callback) {
|
||||
onData: function PDFObjects_onData(objId, callback) {
|
||||
this.ensureObj(objId).onData(callback);
|
||||
},
|
||||
|
||||
isResolved: function pdfObjectsIsResolved(objId) {
|
||||
isResolved: function PDFObjects_isResolved(objId) {
|
||||
var objs = this.objs;
|
||||
if (!objs[objId]) {
|
||||
return false;
|
||||
|
@ -737,7 +785,7 @@ var PDFObjects = (function PDFObjectsClosure() {
|
|||
}
|
||||
},
|
||||
|
||||
hasData: function pdfObjectsHasData(objId) {
|
||||
hasData: function PDFObjects_hasData(objId) {
|
||||
var objs = this.objs;
|
||||
if (!objs[objId]) {
|
||||
return false;
|
||||
|
@ -749,7 +797,7 @@ var PDFObjects = (function PDFObjectsClosure() {
|
|||
/**
|
||||
* Sets the data of an object but *doesn't* resolve it.
|
||||
*/
|
||||
setData: function pdfObjectsSetData(objId, data) {
|
||||
setData: function PDFObjects_setData(objId, data) {
|
||||
// Watchout! If you call `this.ensureObj(objId, data)` you're going to
|
||||
// create a *resolved* promise which shouldn't be the case!
|
||||
this.ensureObj(objId).data = data;
|
||||
|
|
114
src/parser.js
114
src/parser.js
|
@ -19,11 +19,11 @@ var Parser = (function ParserClosure() {
|
|||
}
|
||||
|
||||
Parser.prototype = {
|
||||
refill: function parserRefill() {
|
||||
refill: function Parser_refill() {
|
||||
this.buf1 = this.lexer.getObj();
|
||||
this.buf2 = this.lexer.getObj();
|
||||
},
|
||||
shift: function parserShift() {
|
||||
shift: function Parser_shift() {
|
||||
if (isCmd(this.buf2, 'ID')) {
|
||||
this.buf1 = this.buf2;
|
||||
this.buf2 = null;
|
||||
|
@ -34,7 +34,7 @@ var Parser = (function ParserClosure() {
|
|||
this.buf2 = this.lexer.getObj();
|
||||
}
|
||||
},
|
||||
getObj: function parserGetObj(cipherTransform) {
|
||||
getObj: function Parser_getObj(cipherTransform) {
|
||||
if (isCmd(this.buf1, 'BI')) { // inline image
|
||||
this.shift();
|
||||
return this.makeInlineImage(cipherTransform);
|
||||
|
@ -51,17 +51,16 @@ var Parser = (function ParserClosure() {
|
|||
}
|
||||
if (isCmd(this.buf1, '<<')) { // dictionary or stream
|
||||
this.shift();
|
||||
var dict = new Dict();
|
||||
var dict = new Dict(this.xref);
|
||||
while (!isCmd(this.buf1, '>>') && !isEOF(this.buf1)) {
|
||||
if (!isName(this.buf1)) {
|
||||
if (!isName(this.buf1))
|
||||
error('Dictionary key must be a name object');
|
||||
} else {
|
||||
var key = this.buf1.name;
|
||||
this.shift();
|
||||
if (isEOF(this.buf1))
|
||||
break;
|
||||
dict.set(key, this.getObj(cipherTransform));
|
||||
}
|
||||
|
||||
var key = this.buf1.name;
|
||||
this.shift();
|
||||
if (isEOF(this.buf1))
|
||||
break;
|
||||
dict.set(key, this.getObj(cipherTransform));
|
||||
}
|
||||
if (isEOF(this.buf1))
|
||||
error('End of file inside dictionary');
|
||||
|
@ -99,38 +98,37 @@ var Parser = (function ParserClosure() {
|
|||
this.shift();
|
||||
return obj;
|
||||
},
|
||||
makeInlineImage: function parserMakeInlineImage(cipherTransform) {
|
||||
makeInlineImage: function Parser_makeInlineImage(cipherTransform) {
|
||||
var lexer = this.lexer;
|
||||
var stream = lexer.stream;
|
||||
|
||||
// parse dictionary
|
||||
var dict = new Dict();
|
||||
while (!isCmd(this.buf1, 'ID') && !isEOF(this.buf1)) {
|
||||
if (!isName(this.buf1)) {
|
||||
if (!isName(this.buf1))
|
||||
error('Dictionary key must be a name object');
|
||||
} else {
|
||||
var key = this.buf1.name;
|
||||
this.shift();
|
||||
if (isEOF(this.buf1))
|
||||
break;
|
||||
dict.set(key, this.getObj(cipherTransform));
|
||||
}
|
||||
|
||||
var key = this.buf1.name;
|
||||
this.shift();
|
||||
if (isEOF(this.buf1))
|
||||
break;
|
||||
dict.set(key, this.getObj(cipherTransform));
|
||||
}
|
||||
|
||||
// parse image stream
|
||||
var startPos = stream.pos;
|
||||
|
||||
// searching for the /\sEI\s/
|
||||
// searching for the /EI\s/
|
||||
var state = 0, ch;
|
||||
while (state != 4 && (ch = stream.getByte()) != null) {
|
||||
switch (ch) {
|
||||
case 0x20:
|
||||
case 0x0D:
|
||||
case 0x0A:
|
||||
state = state === 3 ? 4 : 1;
|
||||
state = state === 3 ? 4 : 0;
|
||||
break;
|
||||
case 0x45:
|
||||
state = state === 1 ? 2 : 0;
|
||||
state = 2;
|
||||
break;
|
||||
case 0x49:
|
||||
state = state === 2 ? 3 : 0;
|
||||
|
@ -162,7 +160,11 @@ var Parser = (function ParserClosure() {
|
|||
|
||||
return imageStream;
|
||||
},
|
||||
makeStream: function parserMakeStream(dict, cipherTransform) {
|
||||
fetchIfRef: function Parser_fetchIfRef(obj) {
|
||||
// not relying on the xref.fetchIfRef -- xref might not be set
|
||||
return isRef(obj) ? this.xref.fetch(obj) : obj;
|
||||
},
|
||||
makeStream: function Parser_makeStream(dict, cipherTransform) {
|
||||
var lexer = this.lexer;
|
||||
var stream = lexer.stream;
|
||||
|
||||
|
@ -171,14 +173,9 @@ var Parser = (function ParserClosure() {
|
|||
var pos = stream.pos;
|
||||
|
||||
// get length
|
||||
var length = dict.get('Length');
|
||||
var xref = this.xref;
|
||||
if (xref)
|
||||
length = xref.fetchIfRef(length);
|
||||
if (!isInt(length)) {
|
||||
var length = this.fetchIfRef(dict.get('Length'));
|
||||
if (!isInt(length))
|
||||
error('Bad ' + length + ' attribute in stream');
|
||||
length = 0;
|
||||
}
|
||||
|
||||
// skip over the stream data
|
||||
stream.pos = pos + length;
|
||||
|
@ -195,9 +192,9 @@ var Parser = (function ParserClosure() {
|
|||
stream.parameters = dict;
|
||||
return stream;
|
||||
},
|
||||
filter: function parserFilter(stream, dict, length) {
|
||||
var filter = dict.get('Filter', 'F');
|
||||
var params = dict.get('DecodeParms', 'DP');
|
||||
filter: function Parser_filter(stream, dict, length) {
|
||||
var filter = this.fetchIfRef(dict.get('Filter', 'F'));
|
||||
var params = this.fetchIfRef(dict.get('DecodeParms', 'DP'));
|
||||
if (isName(filter))
|
||||
return this.makeFilter(stream, filter.name, length, params);
|
||||
if (isArray(filter)) {
|
||||
|
@ -207,19 +204,18 @@ var Parser = (function ParserClosure() {
|
|||
filter = filterArray[i];
|
||||
if (!isName(filter))
|
||||
error('Bad filter name: ' + filter);
|
||||
else {
|
||||
params = null;
|
||||
if (isArray(paramsArray) && (i in paramsArray))
|
||||
params = paramsArray[i];
|
||||
stream = this.makeFilter(stream, filter.name, length, params);
|
||||
// after the first stream the length variable is invalid
|
||||
length = null;
|
||||
}
|
||||
|
||||
params = null;
|
||||
if (isArray(paramsArray) && (i in paramsArray))
|
||||
params = paramsArray[i];
|
||||
stream = this.makeFilter(stream, filter.name, length, params);
|
||||
// after the first stream the length variable is invalid
|
||||
length = null;
|
||||
}
|
||||
}
|
||||
return stream;
|
||||
},
|
||||
makeFilter: function parserMakeFilter(stream, name, length, params) {
|
||||
makeFilter: function Parser_makeFilter(stream, name, length, params) {
|
||||
if (name == 'FlateDecode' || name == 'Fl') {
|
||||
if (params) {
|
||||
return new PredictorStream(new FlateStream(stream), params);
|
||||
|
@ -269,7 +265,7 @@ var Lexer = (function LexerClosure() {
|
|||
this.stream = stream;
|
||||
}
|
||||
|
||||
Lexer.isSpace = function lexerIsSpace(ch) {
|
||||
Lexer.isSpace = function Lexer_isSpace(ch) {
|
||||
return ch == ' ' || ch == '\t' || ch == '\x0d' || ch == '\x0a';
|
||||
};
|
||||
|
||||
|
@ -304,7 +300,7 @@ var Lexer = (function LexerClosure() {
|
|||
}
|
||||
|
||||
Lexer.prototype = {
|
||||
getNumber: function lexerGetNumber(ch) {
|
||||
getNumber: function Lexer_getNumber(ch) {
|
||||
var floating = false;
|
||||
var str = ch;
|
||||
var stream = this.stream;
|
||||
|
@ -332,7 +328,7 @@ var Lexer = (function LexerClosure() {
|
|||
error('Invalid floating point number: ' + value);
|
||||
return value;
|
||||
},
|
||||
getString: function lexerGetString() {
|
||||
getString: function Lexer_getString() {
|
||||
var numParen = 1;
|
||||
var done = false;
|
||||
var str = '';
|
||||
|
@ -416,7 +412,7 @@ var Lexer = (function LexerClosure() {
|
|||
} while (!done);
|
||||
return str;
|
||||
},
|
||||
getName: function lexerGetName(ch) {
|
||||
getName: function Lexer_getName(ch) {
|
||||
var str = '';
|
||||
var stream = this.stream;
|
||||
while (!!(ch = stream.lookChar()) && !specialChars[ch.charCodeAt(0)]) {
|
||||
|
@ -443,7 +439,7 @@ var Lexer = (function LexerClosure() {
|
|||
str.length);
|
||||
return new Name(str);
|
||||
},
|
||||
getHexString: function lexerGetHexString(ch) {
|
||||
getHexString: function Lexer_getHexString(ch) {
|
||||
var str = '';
|
||||
var stream = this.stream;
|
||||
for (;;) {
|
||||
|
@ -472,7 +468,7 @@ var Lexer = (function LexerClosure() {
|
|||
}
|
||||
return str;
|
||||
},
|
||||
getObj: function lexerGetObj() {
|
||||
getObj: function Lexer_getObj() {
|
||||
// skip whitespace and comments
|
||||
var comment = false;
|
||||
var stream = this.stream;
|
||||
|
@ -526,17 +522,15 @@ var Lexer = (function LexerClosure() {
|
|||
// fall through
|
||||
case ')':
|
||||
error('Illegal character: ' + ch);
|
||||
return Error;
|
||||
}
|
||||
|
||||
// command
|
||||
var str = ch;
|
||||
while (!!(ch = stream.lookChar()) && !specialChars[ch.charCodeAt(0)]) {
|
||||
stream.skip();
|
||||
if (str.length == 128) {
|
||||
if (str.length == 128)
|
||||
error('Command token too long: ' + str.length);
|
||||
break;
|
||||
}
|
||||
|
||||
str += ch;
|
||||
}
|
||||
if (str == 'true')
|
||||
|
@ -547,7 +541,7 @@ var Lexer = (function LexerClosure() {
|
|||
return null;
|
||||
return Cmd.get(str);
|
||||
},
|
||||
skipToNextLine: function lexerSkipToNextLine() {
|
||||
skipToNextLine: function Lexer_skipToNextLine() {
|
||||
var stream = this.stream;
|
||||
while (true) {
|
||||
var ch = stream.getChar();
|
||||
|
@ -560,7 +554,7 @@ var Lexer = (function LexerClosure() {
|
|||
}
|
||||
}
|
||||
},
|
||||
skip: function lexerSkip() {
|
||||
skip: function Lexer_skip() {
|
||||
this.stream.skip();
|
||||
}
|
||||
};
|
||||
|
@ -570,7 +564,7 @@ var Lexer = (function LexerClosure() {
|
|||
|
||||
var Linearization = (function LinearizationClosure() {
|
||||
function Linearization(stream) {
|
||||
this.parser = new Parser(new Lexer(stream), false);
|
||||
this.parser = new Parser(new Lexer(stream), false, null);
|
||||
var obj1 = this.parser.getObj();
|
||||
var obj2 = this.parser.getObj();
|
||||
var obj3 = this.parser.getObj();
|
||||
|
@ -584,7 +578,7 @@ var Linearization = (function LinearizationClosure() {
|
|||
}
|
||||
|
||||
Linearization.prototype = {
|
||||
getInt: function linearizationGetInt(name) {
|
||||
getInt: function Linearization_getInt(name) {
|
||||
var linDict = this.linDict;
|
||||
var obj;
|
||||
if (isDict(linDict) &&
|
||||
|
@ -593,9 +587,8 @@ var Linearization = (function LinearizationClosure() {
|
|||
return obj;
|
||||
}
|
||||
error('"' + name + '" field in linearization table is invalid');
|
||||
return 0;
|
||||
},
|
||||
getHint: function linearizationGetHint(index) {
|
||||
getHint: function Linearization_getHint(index) {
|
||||
var linDict = this.linDict;
|
||||
var obj1, obj2;
|
||||
if (isDict(linDict) &&
|
||||
|
@ -606,7 +599,6 @@ var Linearization = (function LinearizationClosure() {
|
|||
return obj2;
|
||||
}
|
||||
error('Hints table in linearization table is invalid: ' + index);
|
||||
return 0;
|
||||
},
|
||||
get length() {
|
||||
if (!isDict(this.linDict))
|
||||
|
|
|
@ -17,17 +17,17 @@ var Pattern = (function PatternClosure() {
|
|||
Pattern.prototype = {
|
||||
// Input: current Canvas context
|
||||
// Output: the appropriate fillStyle or strokeStyle
|
||||
getPattern: function pattern_getStyle(ctx) {
|
||||
getPattern: function Pattern_getPattern(ctx) {
|
||||
error('Should not call Pattern.getStyle: ' + ctx);
|
||||
}
|
||||
};
|
||||
|
||||
Pattern.shadingFromIR = function pattern_shadingFromIR(ctx, raw) {
|
||||
return Shadings[raw[0]].fromIR(ctx, raw);
|
||||
Pattern.shadingFromIR = function Pattern_shadingFromIR(raw) {
|
||||
return Shadings[raw[0]].fromIR(raw);
|
||||
};
|
||||
|
||||
Pattern.parseShading = function pattern_shading(shading, matrix, xref,
|
||||
res, ctx) {
|
||||
Pattern.parseShading = function Pattern_parseShading(shading, matrix, xref,
|
||||
res) {
|
||||
|
||||
var dict = isStream(shading) ? shading.dict : shading;
|
||||
var type = dict.get('ShadingType');
|
||||
|
@ -36,7 +36,7 @@ var Pattern = (function PatternClosure() {
|
|||
case PatternType.AXIAL:
|
||||
case PatternType.RADIAL:
|
||||
// Both radial and axial shadings are handled by RadialAxial shading.
|
||||
return new Shadings.RadialAxial(dict, matrix, xref, res, ctx);
|
||||
return new Shadings.RadialAxial(dict, matrix, xref, res);
|
||||
default:
|
||||
return new Shadings.Dummy();
|
||||
}
|
||||
|
@ -79,10 +79,9 @@ Shadings.RadialAxial = (function RadialAxialClosure() {
|
|||
this.extendEnd = extendEnd;
|
||||
|
||||
var fnObj = dict.get('Function');
|
||||
fnObj = xref.fetchIfRef(fnObj);
|
||||
if (isArray(fnObj))
|
||||
error('No support for array of functions');
|
||||
else if (!isPDFFunction(fnObj))
|
||||
if (!isPDFFunction(fnObj))
|
||||
error('Invalid function');
|
||||
var fn = PDFFunction.parse(xref, fnObj);
|
||||
|
||||
|
@ -102,40 +101,44 @@ Shadings.RadialAxial = (function RadialAxialClosure() {
|
|||
this.colorStops = colorStops;
|
||||
}
|
||||
|
||||
RadialAxial.fromIR = function radialAxialShadingGetIR(ctx, raw) {
|
||||
RadialAxial.fromIR = function RadialAxial_fromIR(raw) {
|
||||
var type = raw[1];
|
||||
var colorStops = raw[2];
|
||||
var p0 = raw[3];
|
||||
var p1 = raw[4];
|
||||
var r0 = raw[5];
|
||||
var r1 = raw[6];
|
||||
return {
|
||||
type: 'Pattern',
|
||||
getPattern: function(ctx) {
|
||||
var curMatrix = ctx.mozCurrentTransform;
|
||||
if (curMatrix) {
|
||||
var userMatrix = ctx.mozCurrentTransformInverse;
|
||||
|
||||
var curMatrix = ctx.mozCurrentTransform;
|
||||
if (curMatrix) {
|
||||
var userMatrix = ctx.mozCurrentTransformInverse;
|
||||
p0 = Util.applyTransform(p0, curMatrix);
|
||||
p0 = Util.applyTransform(p0, userMatrix);
|
||||
|
||||
p0 = Util.applyTransform(p0, curMatrix);
|
||||
p0 = Util.applyTransform(p0, userMatrix);
|
||||
p1 = Util.applyTransform(p1, curMatrix);
|
||||
p1 = Util.applyTransform(p1, userMatrix);
|
||||
}
|
||||
|
||||
p1 = Util.applyTransform(p1, curMatrix);
|
||||
p1 = Util.applyTransform(p1, userMatrix);
|
||||
}
|
||||
var grad;
|
||||
if (type == PatternType.AXIAL)
|
||||
grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
|
||||
else if (type == PatternType.RADIAL)
|
||||
grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
|
||||
|
||||
var grad;
|
||||
if (type == PatternType.AXIAL)
|
||||
grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
|
||||
else if (type == PatternType.RADIAL)
|
||||
grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
|
||||
|
||||
for (var i = 0, ii = colorStops.length; i < ii; ++i) {
|
||||
var c = colorStops[i];
|
||||
grad.addColorStop(c[0], c[1]);
|
||||
}
|
||||
return grad;
|
||||
for (var i = 0, ii = colorStops.length; i < ii; ++i) {
|
||||
var c = colorStops[i];
|
||||
grad.addColorStop(c[0], c[1]);
|
||||
}
|
||||
return grad;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
RadialAxial.prototype = {
|
||||
getIR: function radialAxialShadingGetIR() {
|
||||
getIR: function RadialAxial_getIR() {
|
||||
var coordsArr = this.coordsArr;
|
||||
var type = this.shadingType;
|
||||
if (type == PatternType.AXIAL) {
|
||||
|
@ -170,12 +173,12 @@ Shadings.Dummy = (function DummyClosure() {
|
|||
this.type = 'Pattern';
|
||||
}
|
||||
|
||||
Dummy.fromIR = function dummyShadingFromIR() {
|
||||
Dummy.fromIR = function Dummy_fromIR() {
|
||||
return 'hotpink';
|
||||
};
|
||||
|
||||
Dummy.prototype = {
|
||||
getIR: function dummyShadingGetIR() {
|
||||
getIR: function Dummy_getIR() {
|
||||
return ['Dummy'];
|
||||
}
|
||||
};
|
||||
|
@ -190,7 +193,7 @@ var TilingPattern = (function TilingPatternClosure() {
|
|||
var MAX_PATTERN_SIZE = 512;
|
||||
|
||||
function TilingPattern(IR, color, ctx, objs) {
|
||||
var IRQueue = IR[2];
|
||||
var operatorList = IR[2];
|
||||
this.matrix = IR[3];
|
||||
var bbox = IR[4];
|
||||
var xstep = IR[5];
|
||||
|
@ -222,7 +225,7 @@ var TilingPattern = (function TilingPatternClosure() {
|
|||
width = height = MAX_PATTERN_SIZE;
|
||||
}
|
||||
|
||||
var tmpCanvas = new ScratchCanvas(width, height);
|
||||
var tmpCanvas = createScratchCanvas(width, height);
|
||||
|
||||
// set the new canvas element context as the graphics context
|
||||
var tmpCtx = tmpCanvas.getContext('2d');
|
||||
|
@ -259,12 +262,12 @@ var TilingPattern = (function TilingPatternClosure() {
|
|||
graphics.endPath();
|
||||
}
|
||||
|
||||
graphics.executeIRQueue(IRQueue);
|
||||
graphics.executeOperatorList(operatorList);
|
||||
|
||||
this.canvas = tmpCanvas;
|
||||
}
|
||||
|
||||
TilingPattern.getIR = function tiling_getIR(codeIR, dict, args) {
|
||||
TilingPattern.getIR = function TilingPattern_getIR(operatorList, dict, args) {
|
||||
var matrix = dict.get('Matrix');
|
||||
var bbox = dict.get('BBox');
|
||||
var xstep = dict.get('XStep');
|
||||
|
@ -272,12 +275,12 @@ var TilingPattern = (function TilingPatternClosure() {
|
|||
var paintType = dict.get('PaintType');
|
||||
|
||||
return [
|
||||
'TilingPattern', args, codeIR, matrix, bbox, xstep, ystep, paintType
|
||||
'TilingPattern', args, operatorList, matrix, bbox, xstep, ystep, paintType
|
||||
];
|
||||
};
|
||||
|
||||
TilingPattern.prototype = {
|
||||
getPattern: function tiling_getPattern() {
|
||||
getPattern: function TilingPattern_getPattern() {
|
||||
var matrix = this.matrix;
|
||||
var curMatrix = this.curMatrix;
|
||||
var ctx = this.ctx;
|
||||
|
|
151
src/stream.js
151
src/stream.js
|
@ -18,14 +18,14 @@ var Stream = (function StreamClosure() {
|
|||
get length() {
|
||||
return this.end - this.start;
|
||||
},
|
||||
getByte: function stream_getByte() {
|
||||
getByte: function Stream_getByte() {
|
||||
if (this.pos >= this.end)
|
||||
return null;
|
||||
return this.bytes[this.pos++];
|
||||
},
|
||||
// returns subarray of original buffer
|
||||
// should only be read
|
||||
getBytes: function stream_getBytes(length) {
|
||||
getBytes: function Stream_getBytes(length) {
|
||||
var bytes = this.bytes;
|
||||
var pos = this.pos;
|
||||
var strEnd = this.end;
|
||||
|
@ -40,28 +40,28 @@ var Stream = (function StreamClosure() {
|
|||
this.pos = end;
|
||||
return bytes.subarray(pos, end);
|
||||
},
|
||||
lookChar: function stream_lookChar() {
|
||||
lookChar: function Stream_lookChar() {
|
||||
if (this.pos >= this.end)
|
||||
return null;
|
||||
return String.fromCharCode(this.bytes[this.pos]);
|
||||
},
|
||||
getChar: function stream_getChar() {
|
||||
getChar: function Stream_getChar() {
|
||||
if (this.pos >= this.end)
|
||||
return null;
|
||||
return String.fromCharCode(this.bytes[this.pos++]);
|
||||
},
|
||||
skip: function stream_skip(n) {
|
||||
skip: function Stream_skip(n) {
|
||||
if (!n)
|
||||
n = 1;
|
||||
this.pos += n;
|
||||
},
|
||||
reset: function stream_reset() {
|
||||
reset: function Stream_reset() {
|
||||
this.pos = this.start;
|
||||
},
|
||||
moveStart: function stream_moveStart() {
|
||||
moveStart: function Stream_moveStart() {
|
||||
this.start = this.pos;
|
||||
},
|
||||
makeSubStream: function stream_makeSubstream(start, length, dict) {
|
||||
makeSubStream: function Stream_makeSubStream(start, length, dict) {
|
||||
return new Stream(this.bytes.buffer, start, length, dict);
|
||||
},
|
||||
isStream: true
|
||||
|
@ -94,7 +94,7 @@ var DecodeStream = (function DecodeStreamClosure() {
|
|||
}
|
||||
|
||||
DecodeStream.prototype = {
|
||||
ensureBuffer: function decodestream_ensureBuffer(requested) {
|
||||
ensureBuffer: function DecodeStream_ensureBuffer(requested) {
|
||||
var buffer = this.buffer;
|
||||
var current = buffer ? buffer.byteLength : 0;
|
||||
if (requested < current)
|
||||
|
@ -107,7 +107,7 @@ var DecodeStream = (function DecodeStreamClosure() {
|
|||
buffer2[i] = buffer[i];
|
||||
return (this.buffer = buffer2);
|
||||
},
|
||||
getByte: function decodestream_getByte() {
|
||||
getByte: function DecodeStream_getByte() {
|
||||
var pos = this.pos;
|
||||
while (this.bufferLength <= pos) {
|
||||
if (this.eof)
|
||||
|
@ -116,7 +116,7 @@ var DecodeStream = (function DecodeStreamClosure() {
|
|||
}
|
||||
return this.buffer[this.pos++];
|
||||
},
|
||||
getBytes: function decodestream_getBytes(length) {
|
||||
getBytes: function DecodeStream_getBytes(length) {
|
||||
var end, pos = this.pos;
|
||||
|
||||
if (length) {
|
||||
|
@ -144,7 +144,7 @@ var DecodeStream = (function DecodeStreamClosure() {
|
|||
this.pos = end;
|
||||
return this.buffer.subarray(pos, end);
|
||||
},
|
||||
lookChar: function decodestream_lookChar() {
|
||||
lookChar: function DecodeStream_lookChar() {
|
||||
var pos = this.pos;
|
||||
while (this.bufferLength <= pos) {
|
||||
if (this.eof)
|
||||
|
@ -153,7 +153,7 @@ var DecodeStream = (function DecodeStreamClosure() {
|
|||
}
|
||||
return String.fromCharCode(this.buffer[this.pos]);
|
||||
},
|
||||
getChar: function decodestream_getChar() {
|
||||
getChar: function DecodeStream_getChar() {
|
||||
var pos = this.pos;
|
||||
while (this.bufferLength <= pos) {
|
||||
if (this.eof)
|
||||
|
@ -162,18 +162,18 @@ var DecodeStream = (function DecodeStreamClosure() {
|
|||
}
|
||||
return String.fromCharCode(this.buffer[this.pos++]);
|
||||
},
|
||||
makeSubStream: function decodestream_makeSubstream(start, length, dict) {
|
||||
makeSubStream: function DecodeStream_makeSubStream(start, length, dict) {
|
||||
var end = start + length;
|
||||
while (this.bufferLength <= end && !this.eof)
|
||||
this.readBlock();
|
||||
return new Stream(this.buffer, start, length, dict);
|
||||
},
|
||||
skip: function decodestream_skip(n) {
|
||||
skip: function DecodeStream_skip(n) {
|
||||
if (!n)
|
||||
n = 1;
|
||||
this.pos += n;
|
||||
},
|
||||
reset: function decodestream_reset() {
|
||||
reset: function DecodeStream_reset() {
|
||||
this.pos = 0;
|
||||
}
|
||||
};
|
||||
|
@ -188,14 +188,14 @@ var FakeStream = (function FakeStreamClosure() {
|
|||
}
|
||||
|
||||
FakeStream.prototype = Object.create(DecodeStream.prototype);
|
||||
FakeStream.prototype.readBlock = function fakeStreamReadBlock() {
|
||||
FakeStream.prototype.readBlock = function FakeStream_readBlock() {
|
||||
var bufferLength = this.bufferLength;
|
||||
bufferLength += 1024;
|
||||
var buffer = this.ensureBuffer(bufferLength);
|
||||
this.bufferLength = bufferLength;
|
||||
};
|
||||
|
||||
FakeStream.prototype.getBytes = function fakeStreamGetBytes(length) {
|
||||
FakeStream.prototype.getBytes = function FakeStream_getBytes(length) {
|
||||
var end, pos = this.pos;
|
||||
|
||||
if (length) {
|
||||
|
@ -368,7 +368,7 @@ var FlateStream = (function FlateStreamClosure() {
|
|||
|
||||
FlateStream.prototype = Object.create(DecodeStream.prototype);
|
||||
|
||||
FlateStream.prototype.getBits = function flateStreamGetBits(bits) {
|
||||
FlateStream.prototype.getBits = function FlateStream_getBits(bits) {
|
||||
var codeSize = this.codeSize;
|
||||
var codeBuf = this.codeBuf;
|
||||
var bytes = this.bytes;
|
||||
|
@ -388,7 +388,7 @@ var FlateStream = (function FlateStreamClosure() {
|
|||
return b;
|
||||
};
|
||||
|
||||
FlateStream.prototype.getCode = function flateStreamGetCode(table) {
|
||||
FlateStream.prototype.getCode = function FlateStream_getCode(table) {
|
||||
var codes = table[0];
|
||||
var maxLen = table[1];
|
||||
var codeSize = this.codeSize;
|
||||
|
@ -453,7 +453,7 @@ var FlateStream = (function FlateStreamClosure() {
|
|||
return [codes, maxLen];
|
||||
};
|
||||
|
||||
FlateStream.prototype.readBlock = function flateStreamReadBlock() {
|
||||
FlateStream.prototype.readBlock = function FlateStream_readBlock() {
|
||||
// read block header
|
||||
var hdr = this.getBits(3);
|
||||
if (hdr & 1)
|
||||
|
@ -623,7 +623,6 @@ var PredictorStream = (function PredictorStreamClosure() {
|
|||
|
||||
var bufferLength = this.bufferLength;
|
||||
var buffer = this.ensureBuffer(bufferLength + rowBytes);
|
||||
var currentRow = buffer.subarray(bufferLength, bufferLength + rowBytes);
|
||||
|
||||
var bits = this.bits;
|
||||
var colors = this.colors;
|
||||
|
@ -632,6 +631,7 @@ var PredictorStream = (function PredictorStreamClosure() {
|
|||
|
||||
var inbuf = 0, outbuf = 0;
|
||||
var inbits = 0, outbits = 0;
|
||||
var pos = bufferLength;
|
||||
|
||||
if (bits === 1) {
|
||||
for (var i = 0; i < rowBytes; ++i) {
|
||||
|
@ -639,19 +639,21 @@ var PredictorStream = (function PredictorStreamClosure() {
|
|||
inbuf = (inbuf << 8) | c;
|
||||
// bitwise addition is exclusive or
|
||||
// first shift inbuf and then add
|
||||
currentRow[i] = (c ^ (inbuf >> colors)) & 0xFF;
|
||||
buffer[pos++] = (c ^ (inbuf >> colors)) & 0xFF;
|
||||
// truncate inbuf (assumes colors < 16)
|
||||
inbuf &= 0xFFFF;
|
||||
}
|
||||
} else if (bits === 8) {
|
||||
for (var i = 0; i < colors; ++i)
|
||||
currentRow[i] = rawBytes[i];
|
||||
for (; i < rowBytes; ++i)
|
||||
currentRow[i] = currentRow[i - colors] + rawBytes[i];
|
||||
buffer[pos++] = rawBytes[i];
|
||||
for (; i < rowBytes; ++i) {
|
||||
buffer[pos] = buffer[pos - colors] + rawBytes[i];
|
||||
pos++;
|
||||
}
|
||||
} else {
|
||||
var compArray = new Uint8Array(colors + 1);
|
||||
var bitMask = (1 << bits) - 1;
|
||||
var j = 0, k = 0;
|
||||
var j = 0, k = bufferLength;
|
||||
var columns = this.columns;
|
||||
for (var i = 0; i < columns; ++i) {
|
||||
for (var kk = 0; kk < colors; ++kk) {
|
||||
|
@ -665,13 +667,13 @@ var PredictorStream = (function PredictorStreamClosure() {
|
|||
outbuf = (outbuf << bits) | compArray[kk];
|
||||
outbits += bits;
|
||||
if (outbits >= 8) {
|
||||
currentRow[k++] = (outbuf >> (outbits - 8)) & 0xFF;
|
||||
buffer[k++] = (outbuf >> (outbits - 8)) & 0xFF;
|
||||
outbits -= 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (outbits > 0) {
|
||||
currentRow[k++] = (outbuf << (8 - outbits)) +
|
||||
buffer[k++] = (outbuf << (8 - outbits)) +
|
||||
(inbuf & ((1 << (8 - outbits)) - 1));
|
||||
}
|
||||
}
|
||||
|
@ -690,32 +692,35 @@ var PredictorStream = (function PredictorStreamClosure() {
|
|||
var bufferLength = this.bufferLength;
|
||||
var buffer = this.ensureBuffer(bufferLength + rowBytes);
|
||||
|
||||
var currentRow = buffer.subarray(bufferLength, bufferLength + rowBytes);
|
||||
var prevRow = buffer.subarray(bufferLength - rowBytes, bufferLength);
|
||||
if (prevRow.length == 0)
|
||||
prevRow = new Uint8Array(rowBytes);
|
||||
|
||||
var j = bufferLength;
|
||||
switch (predictor) {
|
||||
case 0:
|
||||
for (var i = 0; i < rowBytes; ++i)
|
||||
currentRow[i] = rawBytes[i];
|
||||
buffer[j++] = rawBytes[i];
|
||||
break;
|
||||
case 1:
|
||||
for (var i = 0; i < pixBytes; ++i)
|
||||
currentRow[i] = rawBytes[i];
|
||||
for (; i < rowBytes; ++i)
|
||||
currentRow[i] = (currentRow[i - pixBytes] + rawBytes[i]) & 0xFF;
|
||||
buffer[j++] = rawBytes[i];
|
||||
for (; i < rowBytes; ++i) {
|
||||
buffer[j] = (buffer[j - pixBytes] + rawBytes[i]) & 0xFF;
|
||||
j++;
|
||||
}
|
||||
break;
|
||||
case 2:
|
||||
for (var i = 0; i < rowBytes; ++i)
|
||||
currentRow[i] = (prevRow[i] + rawBytes[i]) & 0xFF;
|
||||
buffer[j++] = (prevRow[i] + rawBytes[i]) & 0xFF;
|
||||
break;
|
||||
case 3:
|
||||
for (var i = 0; i < pixBytes; ++i)
|
||||
currentRow[i] = (prevRow[i] >> 1) + rawBytes[i];
|
||||
buffer[j++] = (prevRow[i] >> 1) + rawBytes[i];
|
||||
for (; i < rowBytes; ++i) {
|
||||
currentRow[i] = (((prevRow[i] + currentRow[i - pixBytes]) >> 1) +
|
||||
buffer[j] = (((prevRow[i] + buffer[j - pixBytes]) >> 1) +
|
||||
rawBytes[i]) & 0xFF;
|
||||
j++;
|
||||
}
|
||||
break;
|
||||
case 4:
|
||||
|
@ -724,12 +729,12 @@ var PredictorStream = (function PredictorStreamClosure() {
|
|||
for (var i = 0; i < pixBytes; ++i) {
|
||||
var up = prevRow[i];
|
||||
var c = rawBytes[i];
|
||||
currentRow[i] = up + c;
|
||||
buffer[j++] = up + c;
|
||||
}
|
||||
for (; i < rowBytes; ++i) {
|
||||
var up = prevRow[i];
|
||||
var upLeft = prevRow[i - pixBytes];
|
||||
var left = currentRow[i - pixBytes];
|
||||
var left = buffer[j - pixBytes];
|
||||
var p = left + up - upLeft;
|
||||
|
||||
var pa = p - left;
|
||||
|
@ -744,11 +749,11 @@ var PredictorStream = (function PredictorStreamClosure() {
|
|||
|
||||
var c = rawBytes[i];
|
||||
if (pa <= pb && pa <= pc)
|
||||
currentRow[i] = left + c;
|
||||
buffer[j++] = left + c;
|
||||
else if (pb <= pc)
|
||||
currentRow[i] = up + c;
|
||||
buffer[j++] = up + c;
|
||||
else
|
||||
currentRow[i] = upLeft + c;
|
||||
buffer[j++] = upLeft + c;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
|
@ -818,31 +823,35 @@ var JpegStream = (function JpegStreamClosure() {
|
|||
|
||||
JpegStream.prototype = Object.create(DecodeStream.prototype);
|
||||
|
||||
JpegStream.prototype.ensureBuffer = function jpegStreamEnsureBuffer(req) {
|
||||
JpegStream.prototype.ensureBuffer = function JpegStream_ensureBuffer(req) {
|
||||
if (this.bufferLength)
|
||||
return;
|
||||
var jpegImage = new JpegImage();
|
||||
if (this.colorTransform != -1)
|
||||
jpegImage.colorTransform = this.colorTransform;
|
||||
jpegImage.parse(this.bytes);
|
||||
var width = jpegImage.width;
|
||||
var height = jpegImage.height;
|
||||
var data = jpegImage.getData(width, height);
|
||||
this.buffer = data;
|
||||
this.bufferLength = data.length;
|
||||
try {
|
||||
var jpegImage = new JpegImage();
|
||||
if (this.colorTransform != -1)
|
||||
jpegImage.colorTransform = this.colorTransform;
|
||||
jpegImage.parse(this.bytes);
|
||||
var width = jpegImage.width;
|
||||
var height = jpegImage.height;
|
||||
var data = jpegImage.getData(width, height);
|
||||
this.buffer = data;
|
||||
this.bufferLength = data.length;
|
||||
} catch (e) {
|
||||
error('JPEG error: ' + e);
|
||||
}
|
||||
};
|
||||
JpegStream.prototype.getIR = function jpegStreamGetIR() {
|
||||
JpegStream.prototype.getIR = function JpegStream_getIR() {
|
||||
return bytesToString(this.bytes);
|
||||
};
|
||||
JpegStream.prototype.getChar = function jpegStreamGetChar() {
|
||||
JpegStream.prototype.getChar = function JpegStream_getChar() {
|
||||
error('internal error: getChar is not valid on JpegStream');
|
||||
};
|
||||
/**
|
||||
* Checks if the image can be decoded and displayed by the browser without any
|
||||
* further processing such as color space conversions.
|
||||
*/
|
||||
JpegStream.prototype.isNativelySupported = function isNativelySupported(xref,
|
||||
res) {
|
||||
JpegStream.prototype.isNativelySupported =
|
||||
function JpegStream_isNativelySupported(xref, res) {
|
||||
var cs = ColorSpace.parse(this.dict.get('ColorSpace'), xref, res);
|
||||
// when bug 674619 lands, let's check if browser can do
|
||||
// normal cmyk and then we won't need to decode in JS
|
||||
|
@ -856,8 +865,8 @@ var JpegStream = (function JpegStreamClosure() {
|
|||
/**
|
||||
* Checks if the image can be decoded by the browser.
|
||||
*/
|
||||
JpegStream.prototype.isNativelyDecodable = function isNativelyDecodable(xref,
|
||||
res) {
|
||||
JpegStream.prototype.isNativelyDecodable =
|
||||
function JpegStream_isNativelyDecodable(xref, res) {
|
||||
var cs = ColorSpace.parse(this.dict.get('ColorSpace'), xref, res);
|
||||
var numComps = cs.numComps;
|
||||
if (numComps == 1 || numComps == 3)
|
||||
|
@ -883,7 +892,7 @@ var JpxStream = (function JpxStreamClosure() {
|
|||
|
||||
JpxStream.prototype = Object.create(DecodeStream.prototype);
|
||||
|
||||
JpxStream.prototype.ensureBuffer = function jpxStreamEnsureBuffer(req) {
|
||||
JpxStream.prototype.ensureBuffer = function JpxStream_ensureBuffer(req) {
|
||||
if (this.bufferLength)
|
||||
return;
|
||||
|
||||
|
@ -963,7 +972,7 @@ var JpxStream = (function JpxStreamClosure() {
|
|||
this.buffer = data;
|
||||
this.bufferLength = data.length;
|
||||
};
|
||||
JpxStream.prototype.getChar = function jpxStreamGetChar() {
|
||||
JpxStream.prototype.getChar = function JpxStream_getChar() {
|
||||
error('internal error: getChar is not valid on JpxStream');
|
||||
};
|
||||
|
||||
|
@ -983,7 +992,7 @@ var DecryptStream = (function DecryptStreamClosure() {
|
|||
|
||||
DecryptStream.prototype = Object.create(DecodeStream.prototype);
|
||||
|
||||
DecryptStream.prototype.readBlock = function decryptStreamReadBlock() {
|
||||
DecryptStream.prototype.readBlock = function DecryptStream_readBlock() {
|
||||
var chunk = this.str.getBytes(chunkSize);
|
||||
if (!chunk || chunk.length == 0) {
|
||||
this.eof = true;
|
||||
|
@ -1014,7 +1023,7 @@ var Ascii85Stream = (function Ascii85StreamClosure() {
|
|||
|
||||
Ascii85Stream.prototype = Object.create(DecodeStream.prototype);
|
||||
|
||||
Ascii85Stream.prototype.readBlock = function ascii85StreamReadBlock() {
|
||||
Ascii85Stream.prototype.readBlock = function Ascii85Stream_readBlock() {
|
||||
var tildaCode = '~'.charCodeAt(0);
|
||||
var zCode = 'z'.charCodeAt(0);
|
||||
var str = this.str;
|
||||
|
@ -1109,7 +1118,7 @@ var AsciiHexStream = (function AsciiHexStreamClosure() {
|
|||
|
||||
AsciiHexStream.prototype = Object.create(DecodeStream.prototype);
|
||||
|
||||
AsciiHexStream.prototype.readBlock = function asciiHexStreamReadBlock() {
|
||||
AsciiHexStream.prototype.readBlock = function AsciiHexStream_readBlock() {
|
||||
var gtCode = '>'.charCodeAt(0), bytes = this.str.getBytes(), c, n,
|
||||
decodeLength, buffer, bufferLength, i, length;
|
||||
|
||||
|
@ -1152,7 +1161,7 @@ var RunLengthStream = (function RunLengthStreamClosure() {
|
|||
|
||||
RunLengthStream.prototype = Object.create(DecodeStream.prototype);
|
||||
|
||||
RunLengthStream.prototype.readBlock = function runLengthStreamReadBlock() {
|
||||
RunLengthStream.prototype.readBlock = function RunLengthStream_readBlock() {
|
||||
// The repeatHeader has following format. The first byte defines type of run
|
||||
// and amount of bytes to repeat/copy: n = 0 through 127 - copy next n bytes
|
||||
// (in addition to the second byte from the header), n = 129 through 255 -
|
||||
|
@ -1662,7 +1671,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {
|
|||
|
||||
CCITTFaxStream.prototype = Object.create(DecodeStream.prototype);
|
||||
|
||||
CCITTFaxStream.prototype.readBlock = function ccittFaxStreamReadBlock() {
|
||||
CCITTFaxStream.prototype.readBlock = function CCITTFaxStream_readBlock() {
|
||||
while (!this.eof) {
|
||||
var c = this.lookChar();
|
||||
this.buf = EOF;
|
||||
|
@ -1720,7 +1729,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {
|
|||
this.codingPos = codingPos;
|
||||
};
|
||||
|
||||
CCITTFaxStream.prototype.lookChar = function ccittFaxStreamLookChar() {
|
||||
CCITTFaxStream.prototype.lookChar = function CCITTFaxStream_lookChar() {
|
||||
if (this.buf != EOF)
|
||||
return this.buf;
|
||||
|
||||
|
@ -2047,7 +2056,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {
|
|||
if (this.eoblock) {
|
||||
code = this.lookBits(7);
|
||||
p = twoDimTable[code];
|
||||
if (p[0] > 0) {
|
||||
if (p && p[0] > 0) {
|
||||
this.eatBits(p[0]);
|
||||
return p[1];
|
||||
}
|
||||
|
@ -2131,7 +2140,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {
|
|||
return 1;
|
||||
};
|
||||
|
||||
CCITTFaxStream.prototype.lookBits = function ccittFaxStreamLookBits(n) {
|
||||
CCITTFaxStream.prototype.lookBits = function CCITTFaxStream_lookBits(n) {
|
||||
var c;
|
||||
while (this.inputBits < n) {
|
||||
if ((c = this.str.getByte()) == null) {
|
||||
|
@ -2146,7 +2155,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {
|
|||
return (this.inputBuf >> (this.inputBits - n)) & (0xFFFF >> (16 - n));
|
||||
};
|
||||
|
||||
CCITTFaxStream.prototype.eatBits = function ccittFaxStreamEatBits(n) {
|
||||
CCITTFaxStream.prototype.eatBits = function CCITTFaxStream_eatBits(n) {
|
||||
if ((this.inputBits -= n) < 0)
|
||||
this.inputBits = 0;
|
||||
};
|
||||
|
@ -2183,7 +2192,7 @@ var LZWStream = (function LZWStreamClosure() {
|
|||
|
||||
LZWStream.prototype = Object.create(DecodeStream.prototype);
|
||||
|
||||
LZWStream.prototype.readBits = function lzwStreamReadBits(n) {
|
||||
LZWStream.prototype.readBits = function LZWStream_readBits(n) {
|
||||
var bitsCached = this.bitsCached;
|
||||
var cachedData = this.cachedData;
|
||||
while (bitsCached < n) {
|
||||
|
@ -2201,7 +2210,7 @@ var LZWStream = (function LZWStreamClosure() {
|
|||
return (cachedData >>> bitsCached) & ((1 << n) - 1);
|
||||
};
|
||||
|
||||
LZWStream.prototype.readBlock = function lzwStreamReadBlock() {
|
||||
LZWStream.prototype.readBlock = function LZWStream_readBlock() {
|
||||
var blockSize = 512;
|
||||
var estimatedDecodedSize = blockSize * 2, decodedSizeDelta = blockSize;
|
||||
var i, j, q;
|
||||
|
|
164
src/util.js
164
src/util.js
|
@ -78,21 +78,99 @@ var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
|
|||
|
||||
var Util = (function UtilClosure() {
|
||||
function Util() {}
|
||||
Util.makeCssRgb = function makergb(r, g, b) {
|
||||
|
||||
Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
|
||||
var ri = (255 * r) | 0, gi = (255 * g) | 0, bi = (255 * b) | 0;
|
||||
return 'rgb(' + ri + ',' + gi + ',' + bi + ')';
|
||||
};
|
||||
Util.makeCssCmyk = function makecmyk(c, m, y, k) {
|
||||
|
||||
Util.makeCssCmyk = function Util_makeCssCmyk(c, m, y, k) {
|
||||
c = (new DeviceCmykCS()).getRgb([c, m, y, k]);
|
||||
var ri = (255 * c[0]) | 0, gi = (255 * c[1]) | 0, bi = (255 * c[2]) | 0;
|
||||
return 'rgb(' + ri + ',' + gi + ',' + bi + ')';
|
||||
};
|
||||
Util.applyTransform = function apply(p, m) {
|
||||
|
||||
// For 2d affine transforms
|
||||
Util.applyTransform = function Util_applyTransform(p, m) {
|
||||
var xt = p[0] * m[0] + p[1] * m[2] + m[4];
|
||||
var yt = p[0] * m[1] + p[1] * m[3] + m[5];
|
||||
return [xt, yt];
|
||||
};
|
||||
|
||||
// Apply a generic 3d matrix M on a 3-vector v:
|
||||
// | a b c | | X |
|
||||
// | d e f | x | Y |
|
||||
// | g h i | | Z |
|
||||
// M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
|
||||
// with v as [X,Y,Z]
|
||||
Util.apply3dTransform = function Util_apply3dTransform(m, v) {
|
||||
return [
|
||||
m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
|
||||
m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
|
||||
m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
|
||||
];
|
||||
}
|
||||
|
||||
// Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
|
||||
// For coordinate systems whose origin lies in the bottom-left, this
|
||||
// means normalization to (BL,TR) ordering. For systems with origin in the
|
||||
// top-left, this means (TL,BR) ordering.
|
||||
Util.normalizeRect = function Util_normalizeRect(rect) {
|
||||
var r = rect.slice(0); // clone rect
|
||||
if (rect[0] > rect[2]) {
|
||||
r[0] = rect[2];
|
||||
r[2] = rect[0];
|
||||
}
|
||||
if (rect[1] > rect[3]) {
|
||||
r[1] = rect[3];
|
||||
r[3] = rect[1];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
// Returns a rectangle [x1, y1, x2, y2] corresponding to the
|
||||
// intersection of rect1 and rect2. If no intersection, returns 'false'
|
||||
// The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
|
||||
Util.intersect = function Util_intersect(rect1, rect2) {
|
||||
function compare(a, b) {
|
||||
return a - b;
|
||||
};
|
||||
|
||||
// Order points along the axes
|
||||
var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
|
||||
orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
|
||||
result = [];
|
||||
|
||||
rect1 = Util.normalizeRect(rect1);
|
||||
rect2 = Util.normalizeRect(rect2);
|
||||
|
||||
// X: first and second points belong to different rectangles?
|
||||
if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
|
||||
(orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
|
||||
// Intersection must be between second and third points
|
||||
result[0] = orderedX[1];
|
||||
result[2] = orderedX[2];
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Y: first and second points belong to different rectangles?
|
||||
if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
|
||||
(orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
|
||||
// Intersection must be between second and third points
|
||||
result[1] = orderedY[1];
|
||||
result[3] = orderedY[2];
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
Util.sign = function Util_sign(num) {
|
||||
return num < 0 ? -1 : 1;
|
||||
};
|
||||
|
||||
return Util;
|
||||
})();
|
||||
|
||||
|
@ -226,7 +304,7 @@ var Promise = (function PromiseClosure() {
|
|||
* @param {Promise[]} promises Array of promises to wait for.
|
||||
* @return {Promise} New dependant promise.
|
||||
*/
|
||||
Promise.all = function(promises) {
|
||||
Promise.all = function Promise_all(promises) {
|
||||
var deferred = new Promise();
|
||||
var unresolved = promises.length;
|
||||
var results = [];
|
||||
|
@ -255,8 +333,8 @@ var Promise = (function PromiseClosure() {
|
|||
return;
|
||||
}
|
||||
if (this._data !== EMPTY_PROMISE) {
|
||||
throw 'Promise ' + this.name +
|
||||
': Cannot set the data of a promise twice';
|
||||
error('Promise ' + this.name +
|
||||
': Cannot set the data of a promise twice');
|
||||
}
|
||||
this._data = value;
|
||||
this.hasData = true;
|
||||
|
@ -268,12 +346,12 @@ var Promise = (function PromiseClosure() {
|
|||
|
||||
get data() {
|
||||
if (this._data === EMPTY_PROMISE) {
|
||||
throw 'Promise ' + this.name + ': Cannot get data that isn\'t set';
|
||||
error('Promise ' + this.name + ': Cannot get data that isn\'t set');
|
||||
}
|
||||
return this._data;
|
||||
},
|
||||
|
||||
onData: function promiseOnData(callback) {
|
||||
onData: function Promise_onData(callback) {
|
||||
if (this._data !== EMPTY_PROMISE) {
|
||||
callback(this._data);
|
||||
} else {
|
||||
|
@ -281,12 +359,12 @@ var Promise = (function PromiseClosure() {
|
|||
}
|
||||
},
|
||||
|
||||
resolve: function promiseResolve(data) {
|
||||
resolve: function Promise_resolve(data) {
|
||||
if (this.isResolved) {
|
||||
throw 'A Promise can be resolved only once ' + this.name;
|
||||
error('A Promise can be resolved only once ' + this.name);
|
||||
}
|
||||
if (this.isRejected) {
|
||||
throw 'The Promise was already rejected ' + this.name;
|
||||
error('The Promise was already rejected ' + this.name);
|
||||
}
|
||||
|
||||
this.isResolved = true;
|
||||
|
@ -298,12 +376,12 @@ var Promise = (function PromiseClosure() {
|
|||
}
|
||||
},
|
||||
|
||||
reject: function proimseReject(reason) {
|
||||
reject: function Promise_reject(reason) {
|
||||
if (this.isRejected) {
|
||||
throw 'A Promise can be rejected only once ' + this.name;
|
||||
error('A Promise can be rejected only once ' + this.name);
|
||||
}
|
||||
if (this.isResolved) {
|
||||
throw 'The Promise was already resolved ' + this.name;
|
||||
error('The Promise was already resolved ' + this.name);
|
||||
}
|
||||
|
||||
this.isRejected = true;
|
||||
|
@ -315,16 +393,16 @@ var Promise = (function PromiseClosure() {
|
|||
}
|
||||
},
|
||||
|
||||
then: function promiseThen(callback, errback) {
|
||||
then: function Promise_then(callback, errback) {
|
||||
if (!callback) {
|
||||
throw 'Requiring callback' + this.name;
|
||||
error('Requiring callback' + this.name);
|
||||
}
|
||||
|
||||
// If the promise is already resolved, call the callback directly.
|
||||
if (this.isResolved) {
|
||||
var data = this.data;
|
||||
callback.call(null, data);
|
||||
} else if (this.isRejected && errorback) {
|
||||
} else if (this.isRejected && errback) {
|
||||
var error = this.error;
|
||||
errback.call(null, error);
|
||||
} else {
|
||||
|
@ -338,3 +416,55 @@ var Promise = (function PromiseClosure() {
|
|||
return Promise;
|
||||
})();
|
||||
|
||||
var StatTimer = (function StatTimerClosure() {
|
||||
function rpad(str, pad, length) {
|
||||
while (str.length < length)
|
||||
str += pad;
|
||||
return str;
|
||||
}
|
||||
function StatTimer() {
|
||||
this.started = {};
|
||||
this.times = [];
|
||||
this.enabled = true;
|
||||
}
|
||||
StatTimer.prototype = {
|
||||
time: function StatTimer_time(name) {
|
||||
if (!this.enabled)
|
||||
return;
|
||||
if (name in this.started)
|
||||
throw 'Timer is already running for ' + name;
|
||||
this.started[name] = Date.now();
|
||||
},
|
||||
timeEnd: function StatTimer_timeEnd(name) {
|
||||
if (!this.enabled)
|
||||
return;
|
||||
if (!(name in this.started))
|
||||
throw 'Timer has not been started for ' + name;
|
||||
this.times.push({
|
||||
'name': name,
|
||||
'start': this.started[name],
|
||||
'end': Date.now()
|
||||
});
|
||||
// Remove timer from started so it can be called again.
|
||||
delete this.started[name];
|
||||
},
|
||||
toString: function StatTimer_toString() {
|
||||
var times = this.times;
|
||||
var out = '';
|
||||
// Find the longest name for padding purposes.
|
||||
var longest = 0;
|
||||
for (var i = 0, ii = times.length; i < ii; ++i) {
|
||||
var name = times[i]['name'];
|
||||
if (name.length > longest)
|
||||
longest = name.length;
|
||||
}
|
||||
for (var i = 0, ii = times.length; i < ii; ++i) {
|
||||
var span = times[i];
|
||||
var duration = span.end - span.start;
|
||||
out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
return StatTimer;
|
||||
})();
|
||||
|
|
|
@ -122,9 +122,9 @@ function readFontDictData(aString, aMap) {
|
|||
token = '';
|
||||
var parsed = false;
|
||||
while (!parsed) {
|
||||
var byte = aString[i++];
|
||||
var octet = aString[i++];
|
||||
|
||||
var nibbles = [parseInt(byte / 16, 10), parseInt(byte % 16, 10)];
|
||||
var nibbles = [parseInt(octet / 16, 10), parseInt(octet % 16, 10)];
|
||||
for (var j = 0; j < nibbles.length; j++) {
|
||||
var nibble = nibbles[j];
|
||||
switch (nibble) {
|
||||
|
@ -336,7 +336,7 @@ var Type2Parser = function type2Parser(aFilePath) {
|
|||
var privateDict = [];
|
||||
for (var i = 0; i < priv.size; i++)
|
||||
privateDict.push(aStream.getByte());
|
||||
dump('private:' + privateDict);
|
||||
dump('privateData:' + privateDict);
|
||||
parseAsToken(privateDict, CFFDictPrivateDataMap);
|
||||
|
||||
for (var p in font.map)
|
||||
|
|
110
src/worker.js
110
src/worker.js
|
@ -26,7 +26,7 @@ function MessageHandler(name, comObj) {
|
|||
delete callbacks[callbackId];
|
||||
callback(data.data);
|
||||
} else {
|
||||
throw 'Cannot resolve callback ' + callbackId;
|
||||
error('Cannot resolve callback ' + callbackId);
|
||||
}
|
||||
} else if (data.action in ah) {
|
||||
var action = ah[data.action];
|
||||
|
@ -44,7 +44,7 @@ function MessageHandler(name, comObj) {
|
|||
action[0].call(action[1], data.data);
|
||||
}
|
||||
} else {
|
||||
throw 'Unkown action from worker: ' + data.action;
|
||||
error('Unkown action from worker: ' + data.action);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
@ -53,7 +53,7 @@ MessageHandler.prototype = {
|
|||
on: function messageHandlerOn(actionName, handler, scope) {
|
||||
var ah = this.actionHandler;
|
||||
if (ah[actionName]) {
|
||||
throw 'There is already an actionName called "' + actionName + '"';
|
||||
error('There is already an actionName called "' + actionName + '"');
|
||||
}
|
||||
ah[actionName] = [handler, scope];
|
||||
},
|
||||
|
@ -79,7 +79,7 @@ MessageHandler.prototype = {
|
|||
|
||||
var WorkerMessageHandler = {
|
||||
setup: function wphSetup(handler) {
|
||||
var pdfDoc = null;
|
||||
var pdfModel = null;
|
||||
|
||||
handler.on('test', function wphSetupTest(data) {
|
||||
handler.send('test', data instanceof Uint8Array);
|
||||
|
@ -88,7 +88,7 @@ var WorkerMessageHandler = {
|
|||
handler.on('doc', function wphSetupDoc(data) {
|
||||
// Create only the model of the PDFDoc, which is enough for
|
||||
// processing the content of the pdf.
|
||||
pdfDoc = new PDFDocModel(new Stream(data));
|
||||
pdfModel = new PDFDocModel(new Stream(data));
|
||||
});
|
||||
|
||||
handler.on('page_request', function wphSetupPageRequest(pageNum) {
|
||||
|
@ -103,17 +103,33 @@ var WorkerMessageHandler = {
|
|||
var start = Date.now();
|
||||
|
||||
var dependency = [];
|
||||
var IRQueue = null;
|
||||
var operatorList = null;
|
||||
try {
|
||||
var page = pdfDoc.getPage(pageNum);
|
||||
var page = pdfModel.getPage(pageNum);
|
||||
// Pre compile the pdf page and fetch the fonts/images.
|
||||
IRQueue = page.getIRQueue(handler, dependency);
|
||||
operatorList = page.getOperatorList(handler, dependency);
|
||||
} catch (e) {
|
||||
var minimumStackMessage =
|
||||
'worker.js: while trying to getPage() and getOperatorList()';
|
||||
|
||||
// Turn the error into an obj that can be serialized
|
||||
e = {
|
||||
message: typeof e === 'object' ? e.message : e,
|
||||
stack: typeof e === 'object' ? e.stack : null
|
||||
};
|
||||
if (typeof e === 'string') {
|
||||
e = {
|
||||
message: e,
|
||||
stack: minimumStackMessage
|
||||
};
|
||||
} else if (typeof e === 'object') {
|
||||
e = {
|
||||
message: e.message || e.toString(),
|
||||
stack: e.stack || minimumStackMessage
|
||||
};
|
||||
} else {
|
||||
e = {
|
||||
message: 'Unknown exception type: ' + (typeof e),
|
||||
stack: minimumStackMessage
|
||||
};
|
||||
}
|
||||
|
||||
handler.send('page_error', {
|
||||
pageNum: pageNum,
|
||||
error: e
|
||||
|
@ -121,8 +137,8 @@ var WorkerMessageHandler = {
|
|||
return;
|
||||
}
|
||||
|
||||
console.log('page=%d - getIRQueue: time=%dms, len=%d', pageNum,
|
||||
Date.now() - start, IRQueue.fnArray.length);
|
||||
console.log('page=%d - getOperatorList: time=%dms, len=%d', pageNum,
|
||||
Date.now() - start, operatorList.fnArray.length);
|
||||
|
||||
// Filter the dependecies for fonts.
|
||||
var fonts = {};
|
||||
|
@ -135,62 +151,13 @@ var WorkerMessageHandler = {
|
|||
|
||||
handler.send('page', {
|
||||
pageNum: pageNum,
|
||||
IRQueue: IRQueue,
|
||||
operatorList: operatorList,
|
||||
depFonts: Object.keys(fonts)
|
||||
});
|
||||
}, this);
|
||||
|
||||
handler.on('font', function wphSetupFont(data) {
|
||||
var objId = data[0];
|
||||
var name = data[1];
|
||||
var file = data[2];
|
||||
var properties = data[3];
|
||||
|
||||
var font = {
|
||||
name: name,
|
||||
file: file,
|
||||
properties: properties
|
||||
};
|
||||
|
||||
// Some fonts don't have a file, e.g. the build in ones like Arial.
|
||||
if (file) {
|
||||
var fontFileDict = new Dict();
|
||||
fontFileDict.map = file.dict.map;
|
||||
|
||||
var fontFile = new Stream(file.bytes, file.start,
|
||||
file.end - file.start, fontFileDict);
|
||||
|
||||
// Check if this is a FlateStream. Otherwise just use the created
|
||||
// Stream one. This makes complex_ttf_font.pdf work.
|
||||
var cmf = file.bytes[0];
|
||||
if ((cmf & 0x0f) == 0x08) {
|
||||
font.file = new FlateStream(fontFile);
|
||||
} else {
|
||||
font.file = fontFile;
|
||||
}
|
||||
}
|
||||
|
||||
var obj = new Font(font.name, font.file, font.properties);
|
||||
|
||||
var str = '';
|
||||
var objData = obj.data;
|
||||
if (objData) {
|
||||
var length = objData.length;
|
||||
for (var j = 0; j < length; ++j)
|
||||
str += String.fromCharCode(objData[j]);
|
||||
}
|
||||
|
||||
obj.str = str;
|
||||
|
||||
// Remove the data array form the font object, as it's not needed
|
||||
// anymore as we sent over the ready str.
|
||||
delete obj.data;
|
||||
|
||||
handler.send('font_ready', [objId, obj]);
|
||||
});
|
||||
|
||||
handler.on('extract_text', function wphExtractText() {
|
||||
var numPages = pdfDoc.numPages;
|
||||
var numPages = pdfModel.numPages;
|
||||
var index = [];
|
||||
var start = Date.now();
|
||||
|
||||
|
@ -203,12 +170,12 @@ var WorkerMessageHandler = {
|
|||
}
|
||||
|
||||
var textContent = '';
|
||||
try {
|
||||
var page = pdfDoc.getPage(pageNum);
|
||||
// try {
|
||||
var page = pdfModel.getPage(pageNum);
|
||||
textContent = page.extractTextContent();
|
||||
} catch (e) {
|
||||
// Skip errored pages
|
||||
}
|
||||
// } catch (e) {
|
||||
// // Skip errored pages
|
||||
// }
|
||||
|
||||
index.push(textContent);
|
||||
|
||||
|
@ -241,6 +208,7 @@ var workerConsole = {
|
|||
action: 'console_error',
|
||||
data: args
|
||||
});
|
||||
throw 'pdf.js execution error';
|
||||
},
|
||||
|
||||
time: function time(name) {
|
||||
|
@ -250,7 +218,7 @@ var workerConsole = {
|
|||
timeEnd: function timeEnd(name) {
|
||||
var time = consoleTimer[name];
|
||||
if (time == null) {
|
||||
throw 'Unkown timer name ' + name;
|
||||
error('Unkown timer name ' + name);
|
||||
}
|
||||
this.log('Timer:', name, Date.now() - time);
|
||||
}
|
||||
|
|
|
@ -24,7 +24,8 @@ var files = [
|
|||
'stream.js',
|
||||
'worker.js',
|
||||
'../external/jpgjs/jpg.js',
|
||||
'jpx.js'
|
||||
'jpx.js',
|
||||
'bidi.js'
|
||||
];
|
||||
|
||||
// Load all the files.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue