use of com.tom_roush.pdfbox.pdmodel.PDResources in project PdfBox-Android by TomRoush.
the class PDFreeTextAppearanceHandler method generateNormalAppearance.
@Override
public void generateNormalAppearance() {
PDAnnotationMarkup annotation = (PDAnnotationMarkup) getAnnotation();
float[] pathsArray = new float[0];
if (PDAnnotationMarkup.IT_FREE_TEXT_CALLOUT.equals(annotation.getIntent())) {
pathsArray = annotation.getCallout();
if (pathsArray == null || pathsArray.length != 4 && pathsArray.length != 6) {
pathsArray = new float[0];
}
}
AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(annotation, annotation.getBorderStyle());
PDAppearanceContentStream cs = null;
try {
cs = getNormalAppearanceAsContentStream(true);
// The fill color is the /C entry, there is no /IC entry defined
boolean hasBackground = cs.setNonStrokingColorOnDemand(annotation.getColor());
setOpacity(cs, annotation.getConstantOpacity());
// Adobe uses the last non stroking color from /DA as stroking color!
// But if there is a color in /DS, then that one is used for text.
PDColor strokingColor = extractNonStrokingColor(annotation);
boolean hasStroke = cs.setStrokingColorOnDemand(strokingColor);
PDColor textColor = strokingColor;
String defaultStyleString = annotation.getDefaultStyleString();
if (defaultStyleString != null) {
Matcher m = COLOR_PATTERN.matcher(defaultStyleString);
if (m.find()) {
int color = Integer.parseInt(m.group(1), 16);
float r = ((color >> 16) & 0xFF) / 255f;
float g = ((color >> 8) & 0xFF) / 255f;
float b = (color & 0xFF) / 255f;
textColor = new PDColor(new float[] { r, g, b }, PDDeviceRGB.INSTANCE);
}
}
if (ab.dashArray != null) {
cs.setLineDashPattern(ab.dashArray, 0);
}
cs.setLineWidth(ab.width);
// see CTAN-example-Annotations.pdf
for (int i = 0; i < pathsArray.length / 2; ++i) {
float x = pathsArray[i * 2];
float y = pathsArray[i * 2 + 1];
if (i == 0) {
if (SHORT_STYLES.contains(annotation.getLineEndingStyle())) {
// modify coordinate to shorten the segment
// https://stackoverflow.com/questions/7740507/extend-a-line-segment-a-specific-distance
float x1 = pathsArray[2];
float y1 = pathsArray[3];
float len = (float) (Math.sqrt(Math.pow(x - x1, 2) + Math.pow(y - y1, 2)));
if (Float.compare(len, 0) != 0) {
x += (x1 - x) / len * ab.width;
y += (y1 - y) / len * ab.width;
}
}
cs.moveTo(x, y);
} else {
cs.lineTo(x, y);
}
}
if (pathsArray.length > 0) {
cs.stroke();
}
// paint the styles here and after line(s) draw, to avoid line crossing a filled shape
if (PDAnnotationMarkup.IT_FREE_TEXT_CALLOUT.equals(annotation.getIntent()) && // check only needed to avoid q cm Q if LE_NONE
!LE_NONE.equals(annotation.getLineEndingStyle()) && pathsArray.length >= 4) {
float x2 = pathsArray[2];
float y2 = pathsArray[3];
float x1 = pathsArray[0];
float y1 = pathsArray[1];
cs.saveGraphicsState();
if (ANGLED_STYLES.contains(annotation.getLineEndingStyle())) {
// do a transform so that first "arm" is imagined flat,
// like in line handler.
// The alternative would be to apply the transform to the
// LE shape coordinates directly, which would be more work
// and produce code difficult to understand
double angle = Math.atan2(y2 - y1, x2 - x1);
cs.transform(Matrix.getRotateInstance(angle, x1, y1));
} else {
cs.transform(Matrix.getTranslateInstance(x1, y1));
}
drawStyle(annotation.getLineEndingStyle(), cs, 0, 0, ab.width, hasStroke, hasBackground, false);
cs.restoreGraphicsState();
}
PDRectangle borderBox;
PDBorderEffectDictionary borderEffect = annotation.getBorderEffect();
if (borderEffect != null && borderEffect.getStyle().equals(PDBorderEffectDictionary.STYLE_CLOUDY)) {
// Adobe draws the text with the original rectangle in mind.
// but if there is an /RD, then writing area get smaller.
// do this here because /RD is overwritten in a few lines
borderBox = applyRectDifferences(getRectangle(), annotation.getRectDifferences());
// TODO this segment was copied from square handler. Refactor?
CloudyBorder cloudyBorder = new CloudyBorder(cs, borderEffect.getIntensity(), ab.width, getRectangle());
cloudyBorder.createCloudyRectangle(annotation.getRectDifference());
annotation.setRectangle(cloudyBorder.getRectangle());
annotation.setRectDifference(cloudyBorder.getRectDifference());
PDAppearanceStream appearanceStream = annotation.getNormalAppearanceStream();
appearanceStream.setBBox(cloudyBorder.getBBox());
appearanceStream.setMatrix(cloudyBorder.getMatrix());
} else {
// handle the border box
//
// There are two options. The handling is not part of the PDF specification but
// implementation specific to Adobe Reader
// - if /RD is set the border box is the /Rect entry inset by the respective
// border difference.
// - if /RD is not set then we don't touch /RD etc because Adobe doesn't either.
borderBox = applyRectDifferences(getRectangle(), annotation.getRectDifferences());
annotation.getNormalAppearanceStream().setBBox(borderBox);
// note that borderBox is not modified
PDRectangle paddedRectangle = getPaddedRectangle(borderBox, ab.width / 2);
cs.addRect(paddedRectangle.getLowerLeftX(), paddedRectangle.getLowerLeftY(), paddedRectangle.getWidth(), paddedRectangle.getHeight());
}
cs.drawShape(ab.width, hasStroke, hasBackground);
// rotation is an undocumented feature, but Adobe uses it. Examples can be found
// in pdf_commenting_new.pdf file, page 3.
int rotation = annotation.getCOSObject().getInt(COSName.ROTATE, 0);
cs.transform(Matrix.getRotateInstance(Math.toRadians(rotation), 0, 0));
float xOffset;
float yOffset;
float width = rotation == 90 || rotation == 270 ? borderBox.getHeight() : borderBox.getWidth();
// strategy to write formatted text is somewhat inspired by
// AppearanceGeneratorHelper.insertGeneratedAppearance()
PDFont font = PDType1Font.HELVETICA;
float clipY;
float clipWidth = width - ab.width * 4;
float clipHeight = rotation == 90 || rotation == 270 ? borderBox.getWidth() - ab.width * 4 : borderBox.getHeight() - ab.width * 4;
extractFontDetails(annotation);
if (document != null && document.getDocumentCatalog().getAcroForm() != null) {
// Try to get font from AcroForm default resources
// Sample file: https://gitlab.freedesktop.org/poppler/poppler/issues/6
PDResources defaultResources = document.getDocumentCatalog().getAcroForm().getDefaultResources();
if (defaultResources != null) {
PDFont defaultResourcesFont = defaultResources.getFont(fontName);
if (defaultResourcesFont != null) {
font = defaultResourcesFont;
}
}
}
// value used by Adobe, no idea where it comes from, actual font bbox max y is 0.931
// gathered by creating an annotation with width 0.
float yDelta = 0.7896f;
switch(rotation) {
case 180:
xOffset = -borderBox.getUpperRightX() + ab.width * 2;
yOffset = -borderBox.getLowerLeftY() - ab.width * 2 - yDelta * fontSize;
clipY = -borderBox.getUpperRightY() + ab.width * 2;
break;
case 90:
xOffset = borderBox.getLowerLeftY() + ab.width * 2;
yOffset = -borderBox.getLowerLeftX() - ab.width * 2 - yDelta * fontSize;
clipY = -borderBox.getUpperRightX() + ab.width * 2;
break;
case 270:
xOffset = -borderBox.getUpperRightY() + ab.width * 2;
yOffset = borderBox.getUpperRightX() - ab.width * 2 - yDelta * fontSize;
clipY = borderBox.getLowerLeftX() + ab.width * 2;
break;
case 0:
default:
xOffset = borderBox.getLowerLeftX() + ab.width * 2;
yOffset = borderBox.getUpperRightY() - ab.width * 2 - yDelta * fontSize;
clipY = borderBox.getLowerLeftY() + ab.width * 2;
break;
}
// clip writing area
cs.addRect(xOffset, clipY, clipWidth, clipHeight);
cs.clip();
cs.beginText();
cs.setFont(font, fontSize);
cs.setNonStrokingColor(textColor.getComponents());
AppearanceStyle appearanceStyle = new AppearanceStyle();
appearanceStyle.setFont(font);
appearanceStyle.setFontSize(fontSize);
PlainTextFormatter formatter = new PlainTextFormatter.Builder(cs).style(appearanceStyle).text(new PlainText(annotation.getContents())).width(width - ab.width * 4).wrapLines(true).initialOffset(xOffset, yOffset).build();
try {
formatter.format();
} catch (IllegalArgumentException ex) {
throw new IOException(ex);
}
cs.endText();
if (pathsArray.length > 0) {
PDRectangle rect = getRectangle();
// Adjust rectangle
// important to do this after the rectangle has been painted, because the
// final rectangle will be bigger due to callout
// CTAN-example-Annotations.pdf p1
// TODO in a class structure this should be overridable
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE;
float maxX = Float.MIN_VALUE;
float maxY = Float.MIN_VALUE;
for (int i = 0; i < pathsArray.length / 2; ++i) {
float x = pathsArray[i * 2];
float y = pathsArray[i * 2 + 1];
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
// arrow length is 9 * width at about 30° => 10 * width seems to be enough
rect.setLowerLeftX(Math.min(minX - ab.width * 10, rect.getLowerLeftX()));
rect.setLowerLeftY(Math.min(minY - ab.width * 10, rect.getLowerLeftY()));
rect.setUpperRightX(Math.max(maxX + ab.width * 10, rect.getUpperRightX()));
rect.setUpperRightY(Math.max(maxY + ab.width * 10, rect.getUpperRightY()));
annotation.setRectangle(rect);
// need to set the BBox too, because rectangle modification came later
annotation.getNormalAppearanceStream().setBBox(getRectangle());
// TODO when callout is used, /RD should be so that the result is the writable part
}
} catch (IOException ex) {
Log.e("PdfBox-Android", ex.getMessage(), ex);
} finally {
IOUtils.closeQuietly(cs);
}
}
use of com.tom_roush.pdfbox.pdmodel.PDResources in project PdfBox-Android by TomRoush.
the class PDHighlightAppearanceHandler method generateNormalAppearance.
@Override
public void generateNormalAppearance() {
PDAnnotationTextMarkup annotation = (PDAnnotationTextMarkup) getAnnotation();
PDRectangle rect = annotation.getRectangle();
float[] pathsArray = annotation.getQuadPoints();
if (pathsArray == null) {
return;
}
AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(annotation, annotation.getBorderStyle());
PDColor color = annotation.getColor();
if (color == null || color.getComponents().length == 0) {
return;
}
// Adjust rectangle even if not empty, see PLPDF.com-MarkupAnnotations.pdf
// TODO in a class structure this should be overridable
// this is similar to polyline but different data type
// TODO padding should consider the curves too; needs to know in advance where the curve is
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE;
float maxX = Float.MIN_VALUE;
float maxY = Float.MIN_VALUE;
for (int i = 0; i < pathsArray.length / 2; ++i) {
float x = pathsArray[i * 2];
float y = pathsArray[i * 2 + 1];
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
// get the delta used for curves and use it for padding
float maxDelta = 0;
for (int i = 0; i < pathsArray.length / 8; ++i) {
// one of the two is 0, depending whether the rectangle is
// horizontal or vertical
// if it is diagonal then... uh...
float delta = Math.max((pathsArray[i + 0] - pathsArray[i + 4]) / 4, (pathsArray[i + 1] - pathsArray[i + 5]) / 4);
maxDelta = Math.max(delta, maxDelta);
}
rect.setLowerLeftX(Math.min(minX - ab.width / 2 - maxDelta, rect.getLowerLeftX()));
rect.setLowerLeftY(Math.min(minY - ab.width / 2 - maxDelta, rect.getLowerLeftY()));
rect.setUpperRightX(Math.max(maxX + ab.width + maxDelta, rect.getUpperRightX()));
rect.setUpperRightY(Math.max(maxY + ab.width + maxDelta, rect.getUpperRightY()));
annotation.setRectangle(rect);
PDAppearanceContentStream cs = null;
try {
cs = getNormalAppearanceAsContentStream();
PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
PDExtendedGraphicsState r1 = new PDExtendedGraphicsState();
r0.setAlphaSourceFlag(false);
r0.setStrokingAlphaConstant(annotation.getConstantOpacity());
r0.setNonStrokingAlphaConstant(annotation.getConstantOpacity());
r1.setAlphaSourceFlag(false);
r1.setBlendMode(BlendMode.MULTIPLY);
cs.setGraphicsStateParameters(r0);
cs.setGraphicsStateParameters(r1);
// TODO replace with document.getDocument().createCOSStream()
// or call new PDFormXObject(document)
PDFormXObject frm1 = new PDFormXObject(createCOSStream());
PDFormXObject frm2 = new PDFormXObject(createCOSStream());
frm1.setResources(new PDResources());
PDFormContentStream mwfofrmCS = null;
try {
mwfofrmCS = new PDFormContentStream(frm1);
mwfofrmCS.drawForm(frm2);
} finally {
IOUtils.closeQuietly(mwfofrmCS);
}
frm1.setBBox(annotation.getRectangle());
COSDictionary groupDict = new COSDictionary();
groupDict.setItem(COSName.S, COSName.TRANSPARENCY);
// TODO PDFormXObject.setGroup() is missing
frm1.getCOSObject().setItem(COSName.GROUP, groupDict);
cs.drawForm(frm1);
frm2.setBBox(annotation.getRectangle());
PDFormContentStream frm2CS = null;
try {
frm2CS = new PDFormContentStream(frm2);
frm2CS.setNonStrokingColor(color);
int of = 0;
while (of + 7 < pathsArray.length) {
// quadpoints spec sequence is incorrect, correct one is (4,5 0,1 2,3 6,7)
// https://stackoverflow.com/questions/9855814/pdf-spec-vs-acrobat-creation-quadpoints
// for "curvy" highlighting, two Bézier control points are used that seem to have a
// distance of about 1/4 of the height.
// note that curves won't appear if outside of the rectangle
float delta = 0;
if (Float.compare(pathsArray[of + 0], pathsArray[of + 4]) == 0 && Float.compare(pathsArray[of + 1], pathsArray[of + 3]) == 0 && Float.compare(pathsArray[of + 2], pathsArray[of + 6]) == 0 && Float.compare(pathsArray[of + 5], pathsArray[of + 7]) == 0) {
// horizontal highlight
delta = (pathsArray[of + 1] - pathsArray[of + 5]) / 4;
} else if (Float.compare(pathsArray[of + 1], pathsArray[of + 5]) == 0 && Float.compare(pathsArray[of + 0], pathsArray[of + 2]) == 0 && Float.compare(pathsArray[of + 3], pathsArray[of + 7]) == 0 && Float.compare(pathsArray[of + 4], pathsArray[of + 6]) == 0) {
// vertical highlight
delta = (pathsArray[of + 0] - pathsArray[of + 4]) / 4;
}
frm2CS.moveTo(pathsArray[of + 4], pathsArray[of + 5]);
if (Float.compare(pathsArray[of + 0], pathsArray[of + 4]) == 0) {
// horizontal highlight
frm2CS.curveTo(pathsArray[of + 4] - delta, pathsArray[of + 5] + delta, pathsArray[of + 0] - delta, pathsArray[of + 1] - delta, pathsArray[of + 0], pathsArray[of + 1]);
} else if (Float.compare(pathsArray[of + 5], pathsArray[of + 1]) == 0) {
// vertical highlight
frm2CS.curveTo(pathsArray[of + 4] + delta, pathsArray[of + 5] + delta, pathsArray[of + 0] - delta, pathsArray[of + 1] + delta, pathsArray[of + 0], pathsArray[of + 1]);
} else {
frm2CS.lineTo(pathsArray[of + 0], pathsArray[of + 1]);
}
frm2CS.lineTo(pathsArray[of + 2], pathsArray[of + 3]);
if (Float.compare(pathsArray[of + 2], pathsArray[of + 6]) == 0) {
// horizontal highlight
frm2CS.curveTo(pathsArray[of + 2] + delta, pathsArray[of + 3] - delta, pathsArray[of + 6] + delta, pathsArray[of + 7] + delta, pathsArray[of + 6], pathsArray[of + 7]);
} else if (Float.compare(pathsArray[of + 3], pathsArray[of + 7]) == 0) {
// vertical highlight
frm2CS.curveTo(pathsArray[of + 2] - delta, pathsArray[of + 3] - delta, pathsArray[of + 6] + delta, pathsArray[of + 7] - delta, pathsArray[of + 6], pathsArray[of + 7]);
} else {
frm2CS.lineTo(pathsArray[of + 6], pathsArray[of + 7]);
}
frm2CS.fill();
of += 8;
}
} finally {
IOUtils.closeQuietly(frm2CS);
}
} catch (IOException ex) {
Log.e("PdfBox-Android", ex.getMessage(), ex);
} finally {
IOUtils.closeQuietly(cs);
}
}
use of com.tom_roush.pdfbox.pdmodel.PDResources in project PdfBox-Android by TomRoush.
the class PDFStreamEngine method processAnnotation.
/**
* Process the given annotation with the specified appearance stream.
*
* @param annotation The annotation containing the appearance stream to process.
* @param appearance The appearance stream to process.
* @throws IOException If there is an error reading or parsing the appearance content stream.
*/
protected void processAnnotation(PDAnnotation annotation, PDAppearanceStream appearance) throws IOException {
PDResources parent = pushResources(appearance);
Deque<PDGraphicsState> savedStack = saveGraphicsStack();
PDRectangle bbox = appearance.getBBox();
PDRectangle rect = annotation.getRectangle();
Matrix matrix = appearance.getMatrix();
// zero-sized rectangles are not valid
if (rect != null && rect.getWidth() > 0 && rect.getHeight() > 0 && bbox != null) {
// transformed appearance box fixme: may be an arbitrary shape
RectF transformedBox = new RectF();
bbox.transform(matrix).computeBounds(transformedBox, true);
// compute a matrix which scales and translates the transformed appearance box to align
// with the edges of the annotation's rectangle
Matrix a = Matrix.getTranslateInstance(rect.getLowerLeftX(), rect.getLowerLeftY());
a.concatenate(Matrix.getScaleInstance((float) (rect.getWidth() / transformedBox.width()), (float) (rect.getHeight() / transformedBox.height())));
a.concatenate(Matrix.getTranslateInstance((float) -transformedBox.left, (float) -transformedBox.top));
// Matrix shall be concatenated with A to form a matrix AA that maps from the appearance's
// coordinate system to the annotation's rectangle in default user space
//
// HOWEVER only the opposite order works for rotated pages with
// filled fields / annotations that have a matrix in the appearance stream, see PDFBOX-3083
Matrix aa = Matrix.concatenate(a, matrix);
// make matrix AA the CTM
getGraphicsState().setCurrentTransformationMatrix(aa);
// clip to bounding box
clipToRect(bbox);
// needed for patterns in appearance streams, e.g. PDFBOX-2182
initialMatrix = aa.clone();
processStreamOperators(appearance);
}
restoreGraphicsStack(savedStack);
popResources(parent);
}
use of com.tom_roush.pdfbox.pdmodel.PDResources in project PdfBox-Android by TomRoush.
the class PDFStreamEngine method pushResources.
/**
* Pushes the given stream's resources, returning the previous resources.
*/
private PDResources pushResources(PDContentStream contentStream) {
// resource lookup: first look for stream resources, then fallback to the current page
PDResources parentResources = resources;
PDResources streamResources = contentStream.getResources();
if (streamResources != null) {
resources = streamResources;
} else if (resources != null) {
// inherit directly from parent stream, this is not in the PDF spec, but the file from
// PDFBOX-1359 does this and works in Acrobat
} else {
resources = currentPage.getResources();
}
// resources are required in PDF
if (resources == null) {
resources = new PDResources();
}
return parentResources;
}
Aggregations