Skip to content

Commit

Permalink
Support textfield and choice widgets for printing
Browse files Browse the repository at this point in the history
  • Loading branch information
calixteman committed Aug 5, 2020
1 parent 63e33a5 commit e9ae060
Show file tree
Hide file tree
Showing 7 changed files with 376 additions and 48 deletions.
233 changes: 193 additions & 40 deletions src/core/annotation.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ import {
AnnotationReplyType,
AnnotationType,
assert,
escapeString,
isString,
OPS,
stringToBytes,
stringToPDFString,
Util,
warn,
Expand All @@ -33,7 +33,7 @@ import { Dict, isDict, isName, isRef, isStream } from "./primitives.js";
import { ColorSpace } from "./colorspace.js";
import { getInheritableProperty } from "./core_utils.js";
import { OperatorList } from "./operator_list.js";
import { Stream } from "./stream.js";
import { StringStream } from "./stream.js";

class AnnotationFactory {
/**
Expand Down Expand Up @@ -888,17 +888,198 @@ class WidgetAnnotation extends Annotation {
}

getOperatorList(evaluator, task, renderForms, annotationStorage) {
// Do not render form elements on the canvas when interactive forms are
// enabled. The display layer is responsible for rendering them instead.
if (renderForms) {
return Promise.resolve(new OperatorList());
}
return super.getOperatorList(
evaluator,
task,
renderForms,
annotationStorage

if (!this.data.editable) {
return super.getOperatorList(
evaluator,
task,
renderForms,
annotationStorage
);
}

return this.getAppearance(evaluator, task, annotationStorage).then(
content => {
// Do not render form elements on the canvas when interactive forms are
// enabled. The display layer is responsible for rendering them instead.
if (this.appearance && content === null) {
return super.getOperatorList(
evaluator,
task,
renderForms,
annotationStorage
);
}

const operatorList = new OperatorList();

// Even if there is an appearance stream, ignore it. This is the
// behaviour used by Adobe Reader.
if (!this.data.defaultAppearance || content === null) {
return operatorList;
}

const matrix = [1, 0, 0, 1, 0, 0];
const bbox = [
0,
0,
this.data.rect[2] - this.data.rect[0],
this.data.rect[3] - this.data.rect[1],
];

const transform = getTransformMatrix(this.data.rect, bbox, matrix);
operatorList.addOp(OPS.beginAnnotation, [
this.data.rect,
transform,
matrix,
]);

const stream = new StringStream(content);
return evaluator
.getOperatorList({
stream,
task,
resources: this.fieldResources,
operatorList,
})
.then(function () {
operatorList.addOp(OPS.endAnnotation, []);
return operatorList;
});
}
);
}

async getAppearance(evaluator, task, annotationStorage) {
// If it's a password textfield then no rendering to avoid to leak it.
// see 12.7.4.3, table 228
if (!annotationStorage || this.data.isPassword) {
return null;
}
let value = annotationStorage[this.data.id] || "";
if (value === "") {
return null;
}
value = escapeString(value);

// Magic value
const defaultPadding = 2;

// Default horizontal padding: can we have an heuristic to guess it?
const hPadding = defaultPadding;
const totalHeight = this.data.rect[3] - this.data.rect[1];
const totalWidth = this.data.rect[2] - this.data.rect[0];

const fontInfo = await this.getFontData(evaluator, task);
const [font, fontName] = fontInfo;
let fontSize = fontInfo[2];

fontSize = this.computeAutoSizedFont(font, fontName, fontSize, totalHeight);

let descent = font.descent;
if (isNaN(descent)) {
descent = 0;
}

const vPadding = defaultPadding + Math.abs(descent) * fontSize;
const defaultAppearance = this.data.defaultAppearance;

const alignment = this.data.textAlignment;
if (alignment === 0 || alignment > 2) {
// Left alignment: nothing to do
return `/Tx BMC q BT ${defaultAppearance} 1 0 0 1 ${hPadding} ${vPadding} Tm (${value}) Tj ET Q EMC`;
}

const renderedText = this.renderPDFText(
value,
font,
fontSize,
totalWidth,
alignment,
hPadding,
vPadding
);
return `/Tx BMC q BT ${defaultAppearance} 1 0 0 1 0 0 Tm ${renderedText} ET Q EMC`;
}

async getFontData(evaluator, task) {
const operatorList = new OperatorList();
const initialState = {
fontSize: 0,
font: null,
fontName: null,
clone() {
return this;
},
};

await evaluator.getOperatorList({
stream: new StringStream(this.data.defaultAppearance),
task,
resources: this.fieldResources,
operatorList,
initialState,
});

return [initialState.font, initialState.fontName, initialState.fontSize];
}

computeAutoSizedFont(font, fontName, fontSize, height) {
if (fontSize === null || fontSize === 0) {
const em = font.charsToGlyphs("M", true)[0].width / 1000;
// According to https://en.wikipedia.org/wiki/Em_(typography)
// an average cap height should be 70% of 1em
const capHeight = 0.7 * em;
// 1.5 * capHeight * fontSize seems to be a good value for lineHeight
fontSize = Math.max(1, Math.floor(height / (1.5 * capHeight)));

let re = new RegExp(`/${fontName}\\s+[0-9\.]+\\s+Tf`);
if (this.data.defaultAppearance.search(re) === -1) {
// The font size is missing
re = new RegExp(`/${fontName}\\s+Tf`);
}
this.data.defaultAppearance = this.data.defaultAppearance.replace(
re,
`/${fontName} ${fontSize} Tf`
);
}
return fontSize;
}

renderPDFText(
text,
font,
fontSize,
totalWidth,
alignment,
hPadding,
vPadding
) {
// We need to get the width of the text in order to align it correctly
const glyphs = font.charsToGlyphs(text);
const scale = fontSize / 1000;
let width = 0;
for (const glyph of glyphs) {
width += glyph.width * scale;
}

let shift;
if (alignment === 1) {
// Center
shift = (totalWidth - width) / 2;
} else if (alignment === 2) {
// Right
shift = totalWidth - width - hPadding;
} else {
shift = hPadding;
}
shift = shift.toFixed(2);
vPadding = vPadding.toFixed(2);

return `${shift} ${vPadding} Td (${text}) Tj`;
}
}

Expand All @@ -924,6 +1105,8 @@ class TextWidgetAnnotation extends WidgetAnnotation {
maximumLength = null;
}
this.data.maxLen = maximumLength;
this.data.isPassword = this.hasFieldFlag(AnnotationFieldFlag.PASSWORD);
this.data.editable = true;

// Process field flags for the display layer.
this.data.multiLine = this.hasFieldFlag(AnnotationFieldFlag.MULTILINE);
Expand All @@ -934,37 +1117,6 @@ class TextWidgetAnnotation extends WidgetAnnotation {
!this.hasFieldFlag(AnnotationFieldFlag.FILESELECT) &&
this.data.maxLen !== null;
}

getOperatorList(evaluator, task, renderForms, annotationStorage) {
if (renderForms || this.appearance) {
return super.getOperatorList(
evaluator,
task,
renderForms,
annotationStorage
);
}

const operatorList = new OperatorList();

// Even if there is an appearance stream, ignore it. This is the
// behaviour used by Adobe Reader.
if (!this.data.defaultAppearance) {
return Promise.resolve(operatorList);
}

const stream = new Stream(stringToBytes(this.data.defaultAppearance));
return evaluator
.getOperatorList({
stream,
task,
resources: this.fieldResources,
operatorList,
})
.then(function () {
return operatorList;
});
}
}

class ButtonWidgetAnnotation extends WidgetAnnotation {
Expand Down Expand Up @@ -1148,6 +1300,7 @@ class ChoiceWidgetAnnotation extends WidgetAnnotation {
// Process field flags for the display layer.
this.data.combo = this.hasFieldFlag(AnnotationFieldFlag.COMBO);
this.data.multiSelect = this.hasFieldFlag(AnnotationFieldFlag.MULTISELECT);
this.data.editable = true;
}
}

Expand Down
6 changes: 5 additions & 1 deletion src/core/evaluator.js
Original file line number Diff line number Diff line change
Expand Up @@ -727,10 +727,12 @@ class PartialEvaluator {

handleSetFont(resources, fontArgs, fontRef, operatorList, task, state) {
// TODO(mack): Not needed?
var fontName;
var fontName,
fontSize = 0;
if (fontArgs) {
fontArgs = fontArgs.slice();
fontName = fontArgs[0].name;
fontSize = fontArgs[1];
}

return this.loadFont(fontName, fontRef, resources)
Expand Down Expand Up @@ -763,6 +765,8 @@ class PartialEvaluator {
})
.then(translated => {
state.font = translated.font;
state.fontSize = fontSize;
state.fontName = fontName;
translated.send(this.handler);
return translated.loadedName;
});
Expand Down
20 changes: 18 additions & 2 deletions src/display/annotation_layer.js
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,8 @@ class TextWidgetAnnotationElement extends WidgetAnnotationElement {
*/
render() {
const TEXT_ALIGNMENT = ["left", "center", "right"];
const storage = this.annotationStorage;
const id = this.data.id;

this.container.className = "textWidgetAnnotation";

Expand All @@ -449,15 +451,21 @@ class TextWidgetAnnotationElement extends WidgetAnnotationElement {
// NOTE: We cannot set the values using `element.value` below, since it
// prevents the AnnotationLayer rasterizer in `test/driver.js`
// from parsing the elements correctly for the reference tests.
const textContent = storage.getOrCreateValue(id, this.data.fieldValue);

if (this.data.multiLine) {
element = document.createElement("textarea");
element.textContent = this.data.fieldValue;
element.textContent = textContent;
} else {
element = document.createElement("input");
element.type = "text";
element.setAttribute("value", this.data.fieldValue);
element.setAttribute("value", textContent);
}

element.addEventListener("change", function (event) {
storage.setValue(id, event.target.value);
});

element.disabled = this.data.readOnly;
element.name = this.data.fieldName;

Expand Down Expand Up @@ -654,6 +662,8 @@ class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
*/
render() {
this.container.className = "choiceWidgetAnnotation";
const storage = this.annotationStorage;
const id = this.data.id;

const selectElement = document.createElement("select");
selectElement.disabled = this.data.readOnly;
Expand All @@ -678,6 +688,12 @@ class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
selectElement.appendChild(optionElement);
}

selectElement.addEventListener("change", function (event) {
const options = event.target.options;
const value = options[options.selectedIndex].text;
storage.setValue(id, value);
});

this.container.appendChild(selectElement);
return this.container;
}
Expand Down
6 changes: 6 additions & 0 deletions src/shared/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -793,6 +793,11 @@ function stringToPDFString(str) {
return strBuf.join("");
}

function escapeString(str) {
// replace "(", ")" and "\" by "\(", "\)" and "\\"
return str.replace(/([\(\)\\])/g, "\\$1");
}

function stringToUTF8String(str) {
return decodeURIComponent(escape(str));
}
Expand Down Expand Up @@ -948,4 +953,5 @@ export {
utf8StringToString,
warn,
unreachable,
escapeString,
};
Loading

0 comments on commit e9ae060

Please sign in to comment.