proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/IntPoint.java
IntPoint
equals
class IntPoint extends Point { private static final Logger LOG = LogManager.getLogger(IntPoint.class); IntPoint(int x, int y) { super(x, y); } @Override public int hashCode() { return 89 * (623 + this.x) + this.y; } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} }
if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { if (obj instanceof Point2D) { // hitting this branch means that the warning on top of the class wasn't read LOG.error("IntPoint should not be used together with its base class"); } return false; } final IntPoint other = (IntPoint) obj; return this.x == other.x && this.y == other.y;
124
151
275
<methods>public void <init>() ,public void <init>(java.awt.Point) ,public void <init>(int, int) ,public boolean equals(java.lang.Object) ,public java.awt.Point getLocation() ,public double getX() ,public double getY() ,public void move(int, int) ,public void setLocation(java.awt.Point) ,public void setLocation(int, int) ,public void setLocation(double, double) ,public java.lang.String toString() ,public void translate(int, int) <variables>private static final long serialVersionUID,public int x,public int y
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/Line.java
Line
calcLine
class Line { private final Point point0; private final Point point1; private final float[] color0; private final float[] color1; protected final Set<Point> linePoints; // all the points in this rasterized line /** * Constructor of class Line. * * @param p0 one end of a line * @param p1 the other end of the line * @param c0 color of point p0 * @param c1 color of point p1 */ Line(Point p0, Point p1, float[] c0, float[] c1) { point0 = p0; point1 = p1; color0 = c0.clone(); color1 = c1.clone(); linePoints = calcLine(point0.x, point0.y, point1.x, point1.y); } /** * Calculate the points of a line with Bresenham's line algorithm * <a * href="http://en.wikipedia.org/wiki/Bresenham's_line_algorithm">Bresenham's * line algorithm</a> * * @param x0 coordinate * @param y0 coordinate * @param x1 coordinate * @param y1 coordinate * @return all the points on the rasterized line from (x0, y0) to (x1, y1) */ private Set<Point> calcLine(int x0, int y0, int x1, int y1) {<FILL_FUNCTION_BODY>} /** * Calculate the color of a point on a rasterized line by linear * interpolation. * * @param p target point, p should always be contained in linePoints * @return color */ protected float[] calcColor(Point p) { if (point0.x == point1.x && point0.y == point1.y) { return color0; } int numberOfColorComponents = color0.length; float[] pc = new float[numberOfColorComponents]; if (point0.x == point1.x) { float l = point1.y - point0.y; for (int i = 0; i < numberOfColorComponents; i++) { pc[i] = (color0[i] * (point1.y - p.y) / l + color1[i] * (p.y - point0.y) / l); } } else { float l = point1.x - point0.x; for (int i = 0; i < numberOfColorComponents; i++) { pc[i] = (color0[i] * (point1.x - p.x) / l + color1[i] * (p.x - point0.x) / l); } } return pc; } }
Set<Point> points = new HashSet<>(3); int dx = Math.abs(x1 - x0); int dy = Math.abs(y1 - y0); int sx = x0 < x1 ? 1 : -1; int sy = y0 < y1 ? 1 : -1; int err = dx - dy; while (true) { points.add(new IntPoint(x0, y0)); if (x0 == x1 && y0 == y1) { break; } int e2 = 2 * err; if (e2 > -dy) { err -= dy; x0 += sx; } if (e2 < dx) { err += dx; y0 += sy; } } return points;
752
220
972
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/PDShadingType1.java
PDShadingType1
setMatrix
class PDShadingType1 extends PDShading { private COSArray domain = null; /** * Constructor using the given shading dictionary. * * @param shadingDictionary the dictionary for this shading */ public PDShadingType1(COSDictionary shadingDictionary) { super(shadingDictionary); } @Override public int getShadingType() { return PDShading.SHADING_TYPE1; } /** * This will get the optional Matrix of a function based shading. * * @return the matrix */ public Matrix getMatrix() { return Matrix.createMatrix(getCOSObject().getDictionaryObject(COSName.MATRIX)); } /** * Sets the optional Matrix entry for the function based shading. * * @param transform the transformation matrix */ public void setMatrix(AffineTransform transform) {<FILL_FUNCTION_BODY>} /** * This will get the optional Domain values of a function based shading. * * @return the domain values */ public COSArray getDomain() { if (domain == null) { domain = getCOSObject().getCOSArray(COSName.DOMAIN); } return domain; } /** * Sets the optional Domain entry for the function based shading. * * @param newDomain the domain array */ public void setDomain(COSArray newDomain) { domain = newDomain; getCOSObject().setItem(COSName.DOMAIN, newDomain); } @Override public Paint toPaint(Matrix matrix) { return new Type1ShadingPaint(this, matrix); } }
COSArray matrix = new COSArray(); double[] values = new double[6]; transform.getMatrix(values); for (double v : values) { matrix.add(new COSFloat((float) v)); } getCOSObject().setItem(COSName.MATRIX, matrix);
474
86
560
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public static org.apache.pdfbox.pdmodel.graphics.shading.PDShading create(org.apache.pdfbox.cos.COSDictionary) throws java.io.IOException,public float[] evalFunction(float) throws java.io.IOException,public float[] evalFunction(float[]) throws java.io.IOException,public boolean getAntiAlias() ,public org.apache.pdfbox.pdmodel.common.PDRectangle getBBox() ,public org.apache.pdfbox.cos.COSArray getBackground() ,public java.awt.geom.Rectangle2D getBounds(java.awt.geom.AffineTransform, org.apache.pdfbox.util.Matrix) throws java.io.IOException,public org.apache.pdfbox.cos.COSDictionary getCOSObject() ,public org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace getColorSpace() throws java.io.IOException,public org.apache.pdfbox.pdmodel.common.function.PDFunction getFunction() throws java.io.IOException,public abstract int getShadingType() ,public java.lang.String getType() ,public void setAntiAlias(boolean) ,public void setBBox(org.apache.pdfbox.pdmodel.common.PDRectangle) ,public void setBackground(org.apache.pdfbox.cos.COSArray) ,public void setColorSpace(org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace) ,public void setFunction(org.apache.pdfbox.pdmodel.common.function.PDFunction) ,public void setFunction(org.apache.pdfbox.cos.COSArray) ,public void setShadingType(int) ,public abstract java.awt.Paint toPaint(org.apache.pdfbox.util.Matrix) <variables>public static final int SHADING_TYPE1,public static final int SHADING_TYPE2,public static final int SHADING_TYPE3,public static final int SHADING_TYPE4,public static final int SHADING_TYPE5,public static final int SHADING_TYPE6,public static final int SHADING_TYPE7,private org.apache.pdfbox.pdmodel.common.PDRectangle bBox,private org.apache.pdfbox.cos.COSArray background,private org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace colorSpace,private final non-sealed org.apache.pdfbox.cos.COSDictionary dictionary,private org.apache.pdfbox.pdmodel.common.function.PDFunction function,private org.apache.pdfbox.pdmodel.common.function.PDFunction[] functionArray
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/PDShadingType2.java
PDShadingType2
getDomain
class PDShadingType2 extends PDShading { private COSArray coords = null; private COSArray domain = null; private COSArray extend = null; /** * Constructor using the given shading dictionary. * * @param shadingDictionary the dictionary for this shading */ public PDShadingType2(COSDictionary shadingDictionary) { super(shadingDictionary); } @Override public int getShadingType() { return PDShading.SHADING_TYPE2; } /** * This will get the optional Extend values for this shading. * * @return the extend values */ public COSArray getExtend() { if (extend == null) { extend = getCOSObject().getCOSArray(COSName.EXTEND); } return extend; } /** * Sets the optional Extend entry for this shading. * * @param newExtend the extend array */ public void setExtend(COSArray newExtend) { extend = newExtend; getCOSObject().setItem(COSName.EXTEND, newExtend); } /** * This will get the optional Domain values for this shading. * * @return the domain values */ public COSArray getDomain() {<FILL_FUNCTION_BODY>} /** * Sets the optional Domain entry for this shading. * * @param newDomain the domain array */ public void setDomain(COSArray newDomain) { domain = newDomain; getCOSObject().setItem(COSName.DOMAIN, newDomain); } /** * This will get the Coords values for this shading. * * @return the coordinate values */ public COSArray getCoords() { if (coords == null) { coords = getCOSObject().getCOSArray(COSName.COORDS); } return coords; } /** * Sets the Coords entry for this shading. * * @param newCoords the coordinates array */ public void setCoords(COSArray newCoords) { coords = newCoords; getCOSObject().setItem(COSName.COORDS, newCoords); } @Override public Paint toPaint(Matrix matrix) { return new AxialShadingPaint(this, matrix); } }
if (domain == null) { domain = getCOSObject().getCOSArray(COSName.DOMAIN); } return domain;
681
43
724
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public static org.apache.pdfbox.pdmodel.graphics.shading.PDShading create(org.apache.pdfbox.cos.COSDictionary) throws java.io.IOException,public float[] evalFunction(float) throws java.io.IOException,public float[] evalFunction(float[]) throws java.io.IOException,public boolean getAntiAlias() ,public org.apache.pdfbox.pdmodel.common.PDRectangle getBBox() ,public org.apache.pdfbox.cos.COSArray getBackground() ,public java.awt.geom.Rectangle2D getBounds(java.awt.geom.AffineTransform, org.apache.pdfbox.util.Matrix) throws java.io.IOException,public org.apache.pdfbox.cos.COSDictionary getCOSObject() ,public org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace getColorSpace() throws java.io.IOException,public org.apache.pdfbox.pdmodel.common.function.PDFunction getFunction() throws java.io.IOException,public abstract int getShadingType() ,public java.lang.String getType() ,public void setAntiAlias(boolean) ,public void setBBox(org.apache.pdfbox.pdmodel.common.PDRectangle) ,public void setBackground(org.apache.pdfbox.cos.COSArray) ,public void setColorSpace(org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace) ,public void setFunction(org.apache.pdfbox.pdmodel.common.function.PDFunction) ,public void setFunction(org.apache.pdfbox.cos.COSArray) ,public void setShadingType(int) ,public abstract java.awt.Paint toPaint(org.apache.pdfbox.util.Matrix) <variables>public static final int SHADING_TYPE1,public static final int SHADING_TYPE2,public static final int SHADING_TYPE3,public static final int SHADING_TYPE4,public static final int SHADING_TYPE5,public static final int SHADING_TYPE6,public static final int SHADING_TYPE7,private org.apache.pdfbox.pdmodel.common.PDRectangle bBox,private org.apache.pdfbox.cos.COSArray background,private org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace colorSpace,private final non-sealed org.apache.pdfbox.cos.COSDictionary dictionary,private org.apache.pdfbox.pdmodel.common.function.PDFunction function,private org.apache.pdfbox.pdmodel.common.function.PDFunction[] functionArray
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/PDShadingType4.java
PDShadingType4
collectTriangles
class PDShadingType4 extends PDTriangleBasedShadingType { private static final Logger LOG = LogManager.getLogger(PDShadingType4.class); /** * Constructor using the given shading dictionary. * * @param shadingDictionary the dictionary for this shading */ public PDShadingType4(COSDictionary shadingDictionary) { super(shadingDictionary); } @Override public int getShadingType() { return PDShading.SHADING_TYPE4; } /** * The bits per flag of this shading. This will return -1 if one has not * been set. * * @return The number of bits per flag. */ public int getBitsPerFlag() { return getCOSObject().getInt(COSName.BITS_PER_FLAG, -1); } /** * Set the number of bits per flag. * * @param bitsPerFlag the number of bits per flag */ public void setBitsPerFlag(int bitsPerFlag) { getCOSObject().setInt(COSName.BITS_PER_FLAG, bitsPerFlag); } @Override public Paint toPaint(Matrix matrix) { return new Type4ShadingPaint(this, matrix); } @SuppressWarnings("squid:S1166") @Override List<ShadedTriangle> collectTriangles(AffineTransform xform, Matrix matrix) throws IOException {<FILL_FUNCTION_BODY>} }
int bitsPerFlag = getBitsPerFlag(); COSDictionary dict = getCOSObject(); if (!(dict instanceof COSStream)) { return Collections.emptyList(); } PDRange rangeX = getDecodeForParameter(0); PDRange rangeY = getDecodeForParameter(1); if (rangeX == null || rangeY == null || Float.compare(rangeX.getMin(), rangeX.getMax()) == 0 || Float.compare(rangeY.getMin(), rangeY.getMax()) == 0) { return Collections.emptyList(); } PDRange[] colRange = new PDRange[getNumberOfColorComponents()]; for (int i = 0; i < colRange.length; ++i) { colRange[i] = getDecodeForParameter(2 + i); if (colRange[i] == null) { throw new IOException("Range missing in shading /Decode entry"); } } List<ShadedTriangle> list = new ArrayList<>(); long maxSrcCoord = (long) Math.pow(2, getBitsPerCoordinate()) - 1; long maxSrcColor = (long) Math.pow(2, getBitsPerComponent()) - 1; COSStream stream = (COSStream) dict; try (ImageInputStream mciis = new MemoryCacheImageInputStream(stream.createInputStream())) { byte flag = (byte) 0; try { flag = (byte) (mciis.readBits(bitsPerFlag) & 3); } catch (EOFException ex) { LOG.error(ex); } boolean eof = false; while (!eof) { Vertex p0; Vertex p1; Vertex p2; Point2D[] ps; float[][] cs; int lastIndex; try { switch (flag) { case 0: p0 = readVertex(mciis, maxSrcCoord, maxSrcColor, rangeX, rangeY, colRange, matrix, xform); flag = (byte) (mciis.readBits(bitsPerFlag) & 3); if (flag != 0) { LOG.error("bad triangle: {}", flag); } p1 = readVertex(mciis, maxSrcCoord, maxSrcColor, rangeX, rangeY, colRange, matrix, xform); mciis.readBits(bitsPerFlag); if (flag != 0) { LOG.error("bad triangle: {}", flag); } p2 = readVertex(mciis, maxSrcCoord, maxSrcColor, rangeX, rangeY, colRange, matrix, xform); ps = new Point2D[] { p0.point, p1.point, p2.point }; cs = new float[][] { p0.color, p1.color, p2.color }; list.add(new ShadedTriangle(ps, cs)); flag = (byte) (mciis.readBits(bitsPerFlag) & 3); break; case 1: case 2: lastIndex = list.size() - 1; if (lastIndex < 0) { LOG.error("broken data stream: {}", list.size()); } else { ShadedTriangle preTri = list.get(lastIndex); p2 = readVertex(mciis, maxSrcCoord, maxSrcColor, rangeX, rangeY, colRange, matrix, xform); ps = new Point2D[] { flag == 1 ? preTri.corner[1] : preTri.corner[0], preTri.corner[2], p2.point }; cs = new float[][] { flag == 1 ? preTri.color[1] : preTri.color[0], preTri.color[2], p2.color }; list.add(new ShadedTriangle(ps, cs)); flag = (byte) (mciis.readBits(bitsPerFlag) & 3); } break; default: LOG.warn("bad flag: {}", flag); break; } } catch (EOFException ex) { eof = true; } } } return list;
473
1,256
1,729
<methods>public int getBitsPerComponent() ,public int getBitsPerCoordinate() ,public java.awt.geom.Rectangle2D getBounds(java.awt.geom.AffineTransform, org.apache.pdfbox.util.Matrix) throws java.io.IOException,public org.apache.pdfbox.pdmodel.common.PDRange getDecodeForParameter(int) ,public int getNumberOfColorComponents() throws java.io.IOException,public void setBitsPerComponent(int) ,public void setBitsPerCoordinate(int) ,public void setDecodeValues(org.apache.pdfbox.cos.COSArray) <variables>private static final Logger LOG,private int bitsPerColorComponent,private int bitsPerCoordinate,private org.apache.pdfbox.cos.COSArray decode,private int numberOfColorComponents
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/PDShadingType5.java
PDShadingType5
collectTriangles
class PDShadingType5 extends PDTriangleBasedShadingType { /** * Constructor using the given shading dictionary. * * @param shadingDictionary the dictionary for this shading */ public PDShadingType5(COSDictionary shadingDictionary) { super(shadingDictionary); } @Override public int getShadingType() { return PDShading.SHADING_TYPE5; } /** * The vertices per row of this shading. This will return -1 if one has not * been set. * * @return the number of vertices per row */ public int getVerticesPerRow() { return getCOSObject().getInt(COSName.VERTICES_PER_ROW, -1); } /** * Set the number of vertices per row. * * @param verticesPerRow the number of vertices per row */ public void setVerticesPerRow(int verticesPerRow) { getCOSObject().setInt(COSName.VERTICES_PER_ROW, verticesPerRow); } @Override public Paint toPaint(Matrix matrix) { return new Type5ShadingPaint(this, matrix); } @SuppressWarnings("squid:S1166") @Override List<ShadedTriangle> collectTriangles(AffineTransform xform, Matrix matrix) throws IOException {<FILL_FUNCTION_BODY>} private List<ShadedTriangle> createShadedTriangleList(int rowNum, int numPerRow, Vertex[][] latticeArray) { Point2D[] ps = new Point2D[3]; // array will be shallow-cloned in ShadedTriangle constructor float[][] cs = new float[3][]; List<ShadedTriangle> list = new ArrayList<>(); for (int i = 0; i < rowNum - 1; i++) { for (int j = 0; j < numPerRow - 1; j++) { ps[0] = latticeArray[i][j].point; ps[1] = latticeArray[i][j + 1].point; ps[2] = latticeArray[i + 1][j].point; cs[0] = latticeArray[i][j].color; cs[1] = latticeArray[i][j + 1].color; cs[2] = latticeArray[i + 1][j].color; list.add(new ShadedTriangle(ps, cs)); ps[0] = latticeArray[i][j + 1].point; ps[1] = latticeArray[i + 1][j].point; ps[2] = latticeArray[i + 1][j + 1].point; cs[0] = latticeArray[i][j + 1].color; cs[1] = latticeArray[i + 1][j].color; cs[2] = latticeArray[i + 1][j + 1].color; list.add(new ShadedTriangle(ps, cs)); } } return list; } }
COSDictionary dict = getCOSObject(); if (!(dict instanceof COSStream)) { return Collections.emptyList(); } PDRange rangeX = getDecodeForParameter(0); PDRange rangeY = getDecodeForParameter(1); if (rangeX == null || rangeY == null || Float.compare(rangeX.getMin(), rangeX.getMax()) == 0 || Float.compare(rangeY.getMin(), rangeY.getMax()) == 0) { return Collections.emptyList(); } int numPerRow = getVerticesPerRow(); PDRange[] colRange = new PDRange[getNumberOfColorComponents()]; for (int i = 0; i < colRange.length; ++i) { colRange[i] = getDecodeForParameter(2 + i); if (colRange[i] == null) { throw new IOException("Range missing in shading /Decode entry"); } } List<Vertex> vlist = new ArrayList<>(); long maxSrcCoord = (long) Math.pow(2, getBitsPerCoordinate()) - 1; long maxSrcColor = (long) Math.pow(2, getBitsPerComponent()) - 1; COSStream cosStream = (COSStream) dict; try (ImageInputStream mciis = new MemoryCacheImageInputStream(cosStream.createInputStream())) { boolean eof = false; while (!eof) { Vertex p; try { p = readVertex(mciis, maxSrcCoord, maxSrcColor, rangeX, rangeY, colRange, matrix, xform); vlist.add(p); } catch (EOFException ex) { eof = true; } } } int rowNum = vlist.size() / numPerRow; if (rowNum < 2) { // must have at least two rows; if not, return empty list return Collections.emptyList(); } Vertex[][] latticeArray = new Vertex[rowNum][numPerRow]; for (int i = 0; i < rowNum; i++) { for (int j = 0; j < numPerRow; j++) { latticeArray[i][j] = vlist.get(i * numPerRow + j); } } return createShadedTriangleList(rowNum, numPerRow, latticeArray);
897
703
1,600
<methods>public int getBitsPerComponent() ,public int getBitsPerCoordinate() ,public java.awt.geom.Rectangle2D getBounds(java.awt.geom.AffineTransform, org.apache.pdfbox.util.Matrix) throws java.io.IOException,public org.apache.pdfbox.pdmodel.common.PDRange getDecodeForParameter(int) ,public int getNumberOfColorComponents() throws java.io.IOException,public void setBitsPerComponent(int) ,public void setBitsPerCoordinate(int) ,public void setDecodeValues(org.apache.pdfbox.cos.COSArray) <variables>private static final Logger LOG,private int bitsPerColorComponent,private int bitsPerCoordinate,private org.apache.pdfbox.cos.COSArray decode,private int numberOfColorComponents
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/PatchMeshesShadingContext.java
PatchMeshesShadingContext
calcPixelTable
class PatchMeshesShadingContext extends TriangleBasedShadingContext { /** * patch list */ private List<Patch> patchList; /** * Constructor creates an instance to be used for fill operations. * * @param shading the shading type to be used * @param colorModel the color model to be used * @param xform transformation for user to device space * @param matrix the pattern matrix concatenated with that of the parent content stream * @param deviceBounds device bounds * @param controlPoints number of control points, 12 for type 6 shading and 16 for type 7 shading * @throws IOException if something went wrong */ protected PatchMeshesShadingContext(PDMeshBasedShadingType shading, ColorModel colorModel, AffineTransform xform, Matrix matrix, Rectangle deviceBounds, int controlPoints) throws IOException { super(shading, colorModel, xform, matrix); patchList = shading.collectPatches(xform, matrix, controlPoints); createPixelTable(deviceBounds); } @Override protected Map<Point, Integer> calcPixelTable(Rectangle deviceBounds) throws IOException {<FILL_FUNCTION_BODY>} @Override public void dispose() { patchList = null; super.dispose(); } @Override protected boolean isDataEmpty() { return patchList.isEmpty(); } }
Map<Point, Integer> map = new HashMap<>(); for (Patch it : patchList) { super.calcPixelTable(it.listOfTriangles, map, deviceBounds); } return map;
382
62
444
<methods>public final java.awt.image.Raster getRaster(int, int, int, int) <variables>private Map<java.awt.Point,java.lang.Integer> pixelTable
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/RadialShadingPaint.java
RadialShadingPaint
createContext
class RadialShadingPaint extends ShadingPaint<PDShadingType3> { private static final Logger LOG = LogManager.getLogger(RadialShadingPaint.class); /** * Constructor. * * @param shading the shading resources * @param matrix the pattern matrix concatenated with that of the parent content stream */ RadialShadingPaint(PDShadingType3 shading, Matrix matrix) { super(shading, matrix); } @Override public int getTransparency() { return 0; } @Override public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform xform, RenderingHints hints) {<FILL_FUNCTION_BODY>} }
try { return new RadialShadingContext(shading, cm, xform, matrix, deviceBounds); } catch (IOException e) { LOG.error("An error occurred while painting", e); return new Color(0, 0, 0, 0).createContext(cm, deviceBounds, userBounds, xform, hints); }
240
105
345
<methods>public org.apache.pdfbox.util.Matrix getMatrix() ,public org.apache.pdfbox.pdmodel.graphics.shading.PDShadingType3 getShading() <variables>protected final non-sealed org.apache.pdfbox.util.Matrix matrix,protected final non-sealed org.apache.pdfbox.pdmodel.graphics.shading.PDShadingType3 shading
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/ShadingContext.java
ShadingContext
convertToRGB
class ShadingContext implements PaintContext { private float[] background; private int rgbBackground; private final PDShading shading; private ColorModel outputColorModel; private PDColorSpace shadingColorSpace; /** * Constructor. * * @param shading the shading type to be used * @param cm the color model to be used * @param xform transformation for user to device space * @param matrix the pattern matrix concatenated with that of the parent content stream * @throws java.io.IOException if there is an error getting the color space * or doing background color conversion. */ public ShadingContext(PDShading shading, ColorModel cm, AffineTransform xform, Matrix matrix) throws IOException { this.shading = shading; shadingColorSpace = shading.getColorSpace(); // create the output color model using RGB+alpha as color space ColorSpace outputCS = ColorSpace.getInstance(ColorSpace.CS_sRGB); outputColorModel = new ComponentColorModel(outputCS, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); // get background values if available COSArray bg = shading.getBackground(); if (bg != null) { background = bg.toFloatArray(); rgbBackground = convertToRGB(background); } } PDColorSpace getShadingColorSpace() { return shadingColorSpace; } PDShading getShading() { return shading; } float[] getBackground() { return background; } int getRgbBackground() { return rgbBackground; } /** * Convert color values from shading colorspace to RGB color values encoded * into an integer. * * @param values color values in shading colorspace. * @return RGB values encoded in an integer. * @throws java.io.IOException if the color conversion fails. */ final int convertToRGB(float[] values) throws IOException {<FILL_FUNCTION_BODY>} @Override public ColorModel getColorModel() { return outputColorModel; } @Override public void dispose() { outputColorModel = null; shadingColorSpace = null; } }
int normRGBValues; float[] rgbValues = shadingColorSpace.toRGB(values); normRGBValues = (int) (rgbValues[0] * 255); normRGBValues |= (int) (rgbValues[1] * 255) << 8; normRGBValues |= (int) (rgbValues[2] * 255) << 16; return normRGBValues;
614
116
730
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/TriangleBasedShadingContext.java
TriangleBasedShadingContext
calcPixelTable
class TriangleBasedShadingContext extends ShadingContext { // map of pixels within triangles to their RGB color private Map<Point, Integer> pixelTable; /** * Constructor. * * @param shading the shading type to be used * @param cm the color model to be used * @param xform transformation for user to device space * @param matrix the pattern matrix concatenated with that of the parent content stream * @throws IOException if there is an error getting the color space or doing background color conversion. */ TriangleBasedShadingContext(PDShading shading, ColorModel cm, AffineTransform xform, Matrix matrix) throws IOException { super(shading, cm, xform, matrix); } /** * Creates the pixel table. */ protected final void createPixelTable(Rectangle deviceBounds) throws IOException { pixelTable = calcPixelTable(deviceBounds); } /** * Calculate every point and its color and store them in a Hash table. * * @return a Hash table which contains all the points' positions and colors of one image */ abstract Map<Point, Integer> calcPixelTable(Rectangle deviceBounds) throws IOException; /** * Get the points from the triangles, calculate their color and add point-color mappings. */ protected void calcPixelTable(List<ShadedTriangle> triangleList, Map<Point, Integer> map, Rectangle deviceBounds) throws IOException {<FILL_FUNCTION_BODY>} /** * Convert color to RGB color value, using function if required, then convert from the shading * color space to an RGB value, which is encoded into an integer. */ private int evalFunctionAndConvertToRGB(float[] values) throws IOException { if (getShading().getFunction() != null) { values = getShading().evalFunction(values); } return convertToRGB(values); } /** * Returns true if the shading has an empty data stream. */ abstract boolean isDataEmpty(); @Override public final Raster getRaster(int x, int y, int w, int h) { WritableRaster raster = getColorModel().createCompatibleWritableRaster(w, h); int[] data = new int[w * h * 4]; if (!isDataEmpty() || getBackground() != null) { for (int row = 0; row < h; row++) { for (int col = 0; col < w; col++) { Point p = new IntPoint(x + col, y + row); int value; Integer v = pixelTable.get(p); if (v != null) { value = v; } else { if (getBackground() == null) { continue; } value = getRgbBackground(); } int index = (row * w + col) * 4; data[index] = value & 255; value >>= 8; data[index + 1] = value & 255; value >>= 8; data[index + 2] = value & 255; data[index + 3] = 255; } } } raster.setPixels(0, 0, w, h, data); return raster; } }
for (ShadedTriangle tri : triangleList) { int degree = tri.getDeg(); if (degree == 2) { Line line = tri.getLine(); for (Point p : line.linePoints) { map.put(p, evalFunctionAndConvertToRGB(line.calcColor(p))); } } else { int[] boundary = tri.getBoundary(); boundary[0] = Math.max(boundary[0], deviceBounds.x); boundary[1] = Math.min(boundary[1], deviceBounds.x + deviceBounds.width); boundary[2] = Math.max(boundary[2], deviceBounds.y); boundary[3] = Math.min(boundary[3], deviceBounds.y + deviceBounds.height); for (int x = boundary[0]; x <= boundary[1]; x++) { for (int y = boundary[2]; y <= boundary[3]; y++) { Point p = new IntPoint(x, y); if (tri.contains(p)) { map.put(p, evalFunctionAndConvertToRGB(tri.calcColor(p))); } } } // "fatten" triangle by drawing the borders with Bresenham's line algorithm // Inspiration: Raph Levien in http://bugs.ghostscript.com/show_bug.cgi?id=219588 Point p0 = new IntPoint((int) Math.round(tri.corner[0].getX()), (int) Math.round(tri.corner[0].getY())); Point p1 = new IntPoint((int) Math.round(tri.corner[1].getX()), (int) Math.round(tri.corner[1].getY())); Point p2 = new IntPoint((int) Math.round(tri.corner[2].getX()), (int) Math.round(tri.corner[2].getY())); Line l1 = new Line(p0, p1, tri.color[0], tri.color[1]); Line l2 = new Line(p1, p2, tri.color[1], tri.color[2]); Line l3 = new Line(p2, p0, tri.color[2], tri.color[0]); for (Point p : l1.linePoints) { map.put(p, evalFunctionAndConvertToRGB(l1.calcColor(p))); } for (Point p : l2.linePoints) { map.put(p, evalFunctionAndConvertToRGB(l2.calcColor(p))); } for (Point p : l3.linePoints) { map.put(p, evalFunctionAndConvertToRGB(l3.calcColor(p))); } } }
882
733
1,615
<methods>public void <init>(org.apache.pdfbox.pdmodel.graphics.shading.PDShading, java.awt.image.ColorModel, java.awt.geom.AffineTransform, org.apache.pdfbox.util.Matrix) throws java.io.IOException,public void dispose() ,public java.awt.image.ColorModel getColorModel() <variables>private float[] background,private java.awt.image.ColorModel outputColorModel,private int rgbBackground,private final non-sealed org.apache.pdfbox.pdmodel.graphics.shading.PDShading shading,private org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace shadingColorSpace
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/Type1ShadingContext.java
Type1ShadingContext
getRaster
class Type1ShadingContext extends ShadingContext { private static final Logger LOG = LogManager.getLogger(Type1ShadingContext.class); private PDShadingType1 type1ShadingType; private AffineTransform rat; private final float[] domain; /** * Constructor creates an instance to be used for fill operations. * * @param shading the shading type to be used * @param colorModel the color model to be used * @param xform transformation for user to device space * @param matrix the pattern matrix concatenated with that of the parent content stream */ Type1ShadingContext(PDShadingType1 shading, ColorModel colorModel, AffineTransform xform, Matrix matrix) throws IOException { super(shading, colorModel, xform, matrix); this.type1ShadingType = shading; // (Optional) An array of four numbers [ xmin xmax ymin ymax ] // specifying the rectangular domain of coordinates over which the // color function(s) are defined. Default value: [ 0.0 1.0 0.0 1.0 ]. if (shading.getDomain() != null) { domain = shading.getDomain().toFloatArray(); } else { domain = new float[] { 0, 1, 0, 1 }; } try { // get inverse transform to be independent of // shading matrix and current user / device space // when handling actual pixels in getRaster() rat = shading.getMatrix().createAffineTransform().createInverse(); rat.concatenate(matrix.createAffineTransform().createInverse()); rat.concatenate(xform.createInverse()); } catch (NoninvertibleTransformException ex) { LOG.error("{}, matrix: {}", ex.getMessage(), matrix, ex); rat = new AffineTransform(); } } @Override public void dispose() { super.dispose(); type1ShadingType = null; } @Override public Raster getRaster(int x, int y, int w, int h) {<FILL_FUNCTION_BODY>} public float[] getDomain() { return domain; } }
WritableRaster raster = getColorModel().createCompatibleWritableRaster(w, h); int[] data = new int[w * h * 4]; float[] values = new float[2]; for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { int index = (j * w + i) * 4; boolean useBackground = false; values[0] = x + i; values[1] = y + j; rat.transform(values, 0, values, 0, 1); if (values[0] < domain[0] || values[0] > domain[1] || values[1] < domain[2] || values[1] > domain[3]) { if (getBackground() == null) { continue; } useBackground = true; } // evaluate function float[] tmpValues; // "values" can't be reused due to different length if (useBackground) { tmpValues = getBackground(); } else { try { tmpValues = type1ShadingType.evalFunction(values); } catch (IOException e) { LOG.error("error while processing a function", e); continue; } } // convert color values from shading color space to RGB PDColorSpace shadingColorSpace = getShadingColorSpace(); if (shadingColorSpace != null) { try { tmpValues = shadingColorSpace.toRGB(tmpValues); } catch (IOException e) { LOG.error("error processing color space", e); continue; } } data[index] = (int) (tmpValues[0] * 255); data[index + 1] = (int) (tmpValues[1] * 255); data[index + 2] = (int) (tmpValues[2] * 255); data[index + 3] = 255; } } raster.setPixels(0, 0, w, h, data); return raster;
598
569
1,167
<methods>public void <init>(org.apache.pdfbox.pdmodel.graphics.shading.PDShading, java.awt.image.ColorModel, java.awt.geom.AffineTransform, org.apache.pdfbox.util.Matrix) throws java.io.IOException,public void dispose() ,public java.awt.image.ColorModel getColorModel() <variables>private float[] background,private java.awt.image.ColorModel outputColorModel,private int rgbBackground,private final non-sealed org.apache.pdfbox.pdmodel.graphics.shading.PDShading shading,private org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace shadingColorSpace
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/Type1ShadingPaint.java
Type1ShadingPaint
createContext
class Type1ShadingPaint extends ShadingPaint<PDShadingType1> { private static final Logger LOG = LogManager.getLogger(Type1ShadingPaint.class); /** * Constructor. * * @param shading the shading resources * @param matrix the pattern matrix concatenated with that of the parent content stream */ Type1ShadingPaint(PDShadingType1 shading, Matrix matrix) { super(shading, matrix); } @Override public int getTransparency() { return 0; } @Override public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform xform, RenderingHints hints) {<FILL_FUNCTION_BODY>} }
try { return new Type1ShadingContext(shading, cm, xform, matrix); } catch (IOException e) { LOG.error("An error occurred while painting", e); return new Color(0, 0, 0, 0).createContext(cm, deviceBounds, userBounds, xform, hints); }
215
92
307
<methods>public org.apache.pdfbox.util.Matrix getMatrix() ,public org.apache.pdfbox.pdmodel.graphics.shading.PDShadingType1 getShading() <variables>protected final non-sealed org.apache.pdfbox.util.Matrix matrix,protected final non-sealed org.apache.pdfbox.pdmodel.graphics.shading.PDShadingType1 shading
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/Type4ShadingPaint.java
Type4ShadingPaint
createContext
class Type4ShadingPaint extends ShadingPaint<PDShadingType4> { private static final Logger LOG = LogManager.getLogger(Type4ShadingPaint.class); /** * Constructor. * * @param shading the shading resources * @param matrix the pattern matrix concatenated with that of the parent content stream */ Type4ShadingPaint(PDShadingType4 shading, Matrix matrix) { super(shading, matrix); } @Override public int getTransparency() { return 0; } @Override public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform xform, RenderingHints hints) {<FILL_FUNCTION_BODY>} }
try { return new Type4ShadingContext(shading, cm, xform, matrix, deviceBounds); } catch (IOException e) { LOG.error("An error occurred while painting", e); return new Color(0, 0, 0, 0).createContext(cm, deviceBounds, userBounds, xform, hints); }
215
95
310
<methods>public org.apache.pdfbox.util.Matrix getMatrix() ,public org.apache.pdfbox.pdmodel.graphics.shading.PDShadingType4 getShading() <variables>protected final non-sealed org.apache.pdfbox.util.Matrix matrix,protected final non-sealed org.apache.pdfbox.pdmodel.graphics.shading.PDShadingType4 shading
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/Type5ShadingPaint.java
Type5ShadingPaint
createContext
class Type5ShadingPaint extends ShadingPaint<PDShadingType5> { private static final Logger LOG = LogManager.getLogger(Type5ShadingPaint.class); /** * Constructor. * * @param shading the shading resources * @param matrix the pattern matrix concatenated with that of the parent content stream */ Type5ShadingPaint(PDShadingType5 shading, Matrix matrix) { super(shading, matrix); } @Override public int getTransparency() { return 0; } @Override public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform xform, RenderingHints hints) {<FILL_FUNCTION_BODY>} }
try { return new Type5ShadingContext(shading, cm, xform, matrix, deviceBounds); } catch (IOException e) { LOG.error("An error occurred while painting", e); return new Color(0, 0, 0, 0).createContext(cm, deviceBounds, userBounds, xform, hints); }
215
95
310
<methods>public org.apache.pdfbox.util.Matrix getMatrix() ,public org.apache.pdfbox.pdmodel.graphics.shading.PDShadingType5 getShading() <variables>protected final non-sealed org.apache.pdfbox.util.Matrix matrix,protected final non-sealed org.apache.pdfbox.pdmodel.graphics.shading.PDShadingType5 shading
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/Type6ShadingPaint.java
Type6ShadingPaint
createContext
class Type6ShadingPaint extends ShadingPaint<PDShadingType6> { private static final Logger LOG = LogManager.getLogger(Type6ShadingPaint.class); /** * Constructor. * * @param shading the shading resources * @param matrix the pattern matrix concatenated with that of the parent content stream */ Type6ShadingPaint(PDShadingType6 shading, Matrix matrix) { super(shading, matrix); } @Override public int getTransparency() { return 0; } @Override public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform xform, RenderingHints hints) {<FILL_FUNCTION_BODY>} }
try { return new Type6ShadingContext(shading, cm, xform, matrix, deviceBounds); } catch (IOException e) { LOG.error("An error occurred while painting", e); return new Color(0, 0, 0, 0).createContext(cm, deviceBounds, userBounds, xform, hints); }
215
95
310
<methods>public org.apache.pdfbox.util.Matrix getMatrix() ,public org.apache.pdfbox.pdmodel.graphics.shading.PDShadingType6 getShading() <variables>protected final non-sealed org.apache.pdfbox.util.Matrix matrix,protected final non-sealed org.apache.pdfbox.pdmodel.graphics.shading.PDShadingType6 shading
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/Type7ShadingPaint.java
Type7ShadingPaint
createContext
class Type7ShadingPaint extends ShadingPaint<PDShadingType7> { private static final Logger LOG = LogManager.getLogger(Type7ShadingPaint.class); /** * Constructor. * * @param shading the shading resources * @param matrix the pattern matrix concatenated with that of the parent content stream */ Type7ShadingPaint(PDShadingType7 shading, Matrix matrix) { super(shading, matrix); } @Override public int getTransparency() { return 0; } @Override public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform xform, RenderingHints hints) {<FILL_FUNCTION_BODY>} }
try { return new Type7ShadingContext(shading, cm, xform, matrix, deviceBounds); } catch (IOException e) { LOG.error("An error occurred while painting", e); return new Color(0, 0, 0, 0).createContext(cm, deviceBounds, userBounds, xform, hints); }
215
95
310
<methods>public org.apache.pdfbox.util.Matrix getMatrix() ,public org.apache.pdfbox.pdmodel.graphics.shading.PDShadingType7 getShading() <variables>protected final non-sealed org.apache.pdfbox.util.Matrix matrix,protected final non-sealed org.apache.pdfbox.pdmodel.graphics.shading.PDShadingType7 shading
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/shading/Vertex.java
Vertex
toString
class Vertex { final Point2D point; final float[] color; Vertex(Point2D p, float[] c) { point = p; color = c.clone(); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
StringBuilder sb = new StringBuilder(); for (float f : color) { if (sb.length() > 0) { sb.append(' '); } sb.append(String.format("%3.2f", f)); } return "Vertex{ " + point + ", colors=[" + sb + "] }";
85
91
176
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/state/PDSoftMask.java
PDSoftMask
create
class PDSoftMask implements COSObjectable { /** * Creates a new soft mask. * * @param dictionary SMask * * @return the newly created instance of PDSoftMask */ public static PDSoftMask create(COSBase dictionary) {<FILL_FUNCTION_BODY>} private static final Logger LOG = LogManager.getLogger(PDSoftMask.class); private final COSDictionary dictionary; private COSName subType = null; private PDTransparencyGroup group = null; private COSArray backdropColor = null; private PDFunction transferFunction = null; /** * To allow a soft mask to know the CTM at the time of activation of the ExtGState. */ private Matrix ctm; /** * Creates a new soft mask. * * @param dictionary The soft mask dictionary. */ public PDSoftMask(COSDictionary dictionary) { this.dictionary = dictionary; } @Override public COSDictionary getCOSObject() { return dictionary; } /** * Returns the subtype of the soft mask (Alpha, Luminosity) - S entry * * @return the subtype of the soft mask */ public COSName getSubType() { if (subType == null) { subType = getCOSObject().getCOSName(COSName.S); } return subType; } /** * Returns the G entry of the soft mask object * * @return form containing the transparency group * @throws IOException if the group could not be read */ public PDTransparencyGroup getGroup() throws IOException { if (group == null) { COSBase cosGroup = getCOSObject().getDictionaryObject(COSName.G); if (cosGroup != null) { PDXObject x = PDXObject.createXObject(cosGroup, null); if (x instanceof PDTransparencyGroup) { group = (PDTransparencyGroup) x; } } } return group; } /** * Returns the backdrop color. * * @return the backdrop color */ public COSArray getBackdropColor() { if (backdropColor == null) { backdropColor = (COSArray) getCOSObject().getDictionaryObject(COSName.BC); } return backdropColor; } /** * Returns the transfer function. * * @return the transfer function * @throws IOException If we are unable to create the PDFunction object. */ public PDFunction getTransferFunction() throws IOException { if (transferFunction == null) { COSBase cosTF = getCOSObject().getDictionaryObject(COSName.TR); if (cosTF != null) { transferFunction = PDFunction.create(cosTF); } } return transferFunction; } /** * Set the CTM that is valid at the time the ExtGState was activated. * * @param ctm the transformation matrix */ void setInitialTransformationMatrix(Matrix ctm) { this.ctm = ctm; } /** * Returns the CTM at the time the ExtGState was activated. * * @return the transformation matrix */ public Matrix getInitialTransformationMatrix() { return ctm; } }
if (dictionary instanceof COSName) { if (COSName.NONE.equals(dictionary)) { return null; } else { LOG.warn("Invalid SMask {}", dictionary); return null; } } else if (dictionary instanceof COSDictionary) { return new PDSoftMask((COSDictionary) dictionary); } else { LOG.warn("Invalid SMask {}", dictionary); return null; }
1,056
156
1,212
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/state/PDTextState.java
PDTextState
clone
class PDTextState implements Cloneable { private float characterSpacing = 0; private float wordSpacing = 0; private float horizontalScaling = 100; private float leading = 0; private PDFont font; private float fontSize; private RenderingMode renderingMode = RenderingMode.FILL; private float rise = 0; private boolean knockout = true; /** * Get the value of the characterSpacing. * * @return The current characterSpacing. */ public float getCharacterSpacing() { return characterSpacing; } /** * Set the value of the characterSpacing. * * @param value The characterSpacing. */ public void setCharacterSpacing(float value) { characterSpacing = value; } /** * Get the value of the wordSpacing. * * @return The wordSpacing. */ public float getWordSpacing() { return wordSpacing; } /** * Set the value of the wordSpacing. * * @param value The wordSpacing. */ public void setWordSpacing(float value) { wordSpacing = value; } /** * Get the value of the horizontalScaling. The default is 100. This value * is the percentage value 0-100 and not 0-1. So for mathematical operations * you will probably need to divide by 100 first. * * @return The horizontalScaling. */ public float getHorizontalScaling() { return horizontalScaling; } /** * Set the value of the horizontalScaling. * * @param value The horizontalScaling. */ public void setHorizontalScaling(float value) { horizontalScaling = value; } /** * Get the value of the leading. * * @return The leading. */ public float getLeading() { return leading; } /** * Set the value of the leading. * * @param value The leading. */ public void setLeading(float value) { leading = value; } /** * Get the value of the font. * * @return The font. */ public PDFont getFont() { return font; } /** * Set the value of the font. * * @param value The font. */ public void setFont(PDFont value) { font = value; } /** * Get the value of the fontSize. * * @return The fontSize. */ public float getFontSize() { return fontSize; } /** * Set the value of the fontSize. * * @param value The fontSize. */ public void setFontSize(float value) { fontSize = value; } /** * Get the value of the renderingMode. * * @return The renderingMode. */ public RenderingMode getRenderingMode() { return renderingMode; } /** * Set the value of the renderingMode. * * @param renderingMode The renderingMode. */ public void setRenderingMode(RenderingMode renderingMode) { this.renderingMode = renderingMode; } /** * Get the value of the rise. * * @return The rise. */ public float getRise() { return rise; } /** * Set the value of the rise. * * @param value The rise. */ public void setRise(float value) { rise = value; } /** * Get the value of the knockout. * * @return The knockout. */ public boolean getKnockoutFlag() { return knockout; } /** * Set the value of the knockout. * * @param value The knockout. */ public void setKnockoutFlag(boolean value) { knockout = value; } @Override public PDTextState clone() {<FILL_FUNCTION_BODY>} }
try { return (PDTextState)super.clone(); } catch (CloneNotSupportedException e) { // should not happen throw new RuntimeException(e); }
1,156
57
1,213
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/PlainText.java
Paragraph
getLines
class Paragraph { private final String textContent; Paragraph(String text) { textContent = text; } /** * Get the paragraph text. * * @return the text. */ String getText() { return textContent; } /** * Break the paragraph into individual lines. * * @param font the font used for rendering the text. * @param fontSize the fontSize used for rendering the text. * @param width the width of the box holding the content. * @return the individual lines. * @throws IOException */ public List<Line> getLines(PDFont font, float fontSize, float width) throws IOException {<FILL_FUNCTION_BODY>} }
BreakIterator iterator = BreakIterator.getLineInstance(); iterator.setText(textContent); final float scale = fontSize/FONTSCALE; int start = iterator.first(); int end = iterator.next(); float lineWidth = 0; List<Line> textLines = new ArrayList<>(); Line textLine = new Line(); while (end != BreakIterator.DONE) { String word = textContent.substring(start,end); float wordWidth = font.getStringWidth(word) * scale; boolean wordNeedsSplit = false; int splitOffset = end - start; lineWidth = lineWidth + wordWidth; // check if the last word would fit without the whitespace ending it if (lineWidth >= width && Character.isWhitespace(word.charAt(word.length()-1))) { float whitespaceWidth = font.getStringWidth(word.substring(word.length()-1)) * scale; lineWidth = lineWidth - whitespaceWidth; } if (lineWidth >= width && !textLine.getWords().isEmpty()) { textLine.setWidth(textLine.calculateWidth(font, fontSize)); textLines.add(textLine); textLine = new Line(); lineWidth = font.getStringWidth(word) * scale; } if (wordWidth > width && textLine.getWords().isEmpty()) { // single word does not fit into width wordNeedsSplit = true; while (true) { splitOffset--; String substring = word.substring(0, splitOffset); float substringWidth = font.getStringWidth(substring) * scale; if (substringWidth < width) { word = substring; wordWidth = font.getStringWidth(word) * scale; lineWidth = wordWidth; break; } } } AttributedString as = new AttributedString(word); as.addAttribute(TextAttribute.WIDTH, wordWidth); Word wordInstance = new Word(word); wordInstance.setAttributes(as); textLine.addWord(wordInstance); if (wordNeedsSplit) { start = start + splitOffset; } else { start = end; end = iterator.next(); } } textLine.setWidth(textLine.calculateWidth(font, fontSize)); textLines.add(textLine); return textLines;
203
645
848
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/PlainTextFormatter.java
Builder
processLines
class Builder { // required parameters private final PDAppearanceContentStream contents; // optional parameters private AppearanceStyle appearanceStyle; private boolean wrapLines = false; private float width = 0f; private PlainText textContent; private TextAlign textAlignment = TextAlign.LEFT; // initial offset from where to start the position of the first line private float horizontalOffset = 0f; private float verticalOffset = 0f; public Builder(PDAppearanceContentStream contents) { this.contents = contents; } public Builder style(AppearanceStyle appearanceStyle) { this.appearanceStyle = appearanceStyle; return this; } public Builder wrapLines(boolean wrapLines) { this.wrapLines = wrapLines; return this; } public Builder width(float width) { this.width = width; return this; } public Builder textAlign(int alignment) { this.textAlignment = TextAlign.valueOf(alignment); return this; } public Builder textAlign(TextAlign alignment) { this.textAlignment = alignment; return this; } public Builder text(PlainText textContent) { this.textContent = textContent; return this; } public Builder initialOffset(float horizontalOffset, float verticalOffset) { this.horizontalOffset = horizontalOffset; this.verticalOffset = verticalOffset; return this; } public PlainTextFormatter build() { return new PlainTextFormatter(this); } } private PlainTextFormatter(Builder builder) { appearanceStyle = builder.appearanceStyle; wrapLines = builder.wrapLines; width = builder.width; contents = builder.contents; textContent = builder.textContent; textAlignment = builder.textAlignment; horizontalOffset = builder.horizontalOffset; verticalOffset = builder.verticalOffset; } /** * Format the text block. * * @throws IOException if there is an error writing to the stream. */ public void format() throws IOException { if (textContent != null && !textContent.getParagraphs().isEmpty()) { boolean isFirstParagraph = true; for (Paragraph paragraph : textContent.getParagraphs()) { if (wrapLines) { List<Line> lines = paragraph.getLines( appearanceStyle.getFont(), appearanceStyle.getFontSize(), width ); processLines(lines, isFirstParagraph); isFirstParagraph = false; } else { float startOffset = 0f; float lineWidth = appearanceStyle.getFont().getStringWidth(paragraph.getText()) * appearanceStyle.getFontSize() / FONTSCALE; if (lineWidth < width) { switch (textAlignment) { case CENTER: startOffset = (width - lineWidth)/2; break; case RIGHT: startOffset = width - lineWidth; break; case JUSTIFY: default: startOffset = 0f; } } contents.newLineAtOffset(horizontalOffset + startOffset, verticalOffset); contents.showText(paragraph.getText()); } } } } /** * Process lines for output. * * Process lines for an individual paragraph and generate the * commands for the content stream to show the text. * * @param lines the lines to process. * @throws IOException if there is an error writing to the stream. */ private void processLines(List<Line> lines, boolean isFirstParagraph) throws IOException {<FILL_FUNCTION_BODY>
float wordWidth; float lastPos = 0f; float startOffset = 0f; float interWordSpacing = 0f; for (Line line : lines) { switch (textAlignment) { case CENTER: startOffset = (width - line.getWidth())/2; break; case RIGHT: startOffset = width - line.getWidth(); break; case JUSTIFY: if (lines.indexOf(line) != lines.size() -1) { interWordSpacing = line.getInterWordSpacing(width); } break; default: startOffset = 0f; } float offset = -lastPos + startOffset + horizontalOffset; if (lines.indexOf(line) == 0 && isFirstParagraph) { contents.newLineAtOffset(offset, verticalOffset); } else { // keep the last position verticalOffset = verticalOffset - appearanceStyle.getLeading(); contents.newLineAtOffset(offset, - appearanceStyle.getLeading()); } lastPos += offset; List<Word> words = line.getWords(); int wordIndex = 0; for (Word word : words) { contents.showText(word.getText()); wordWidth = (Float) word.getAttributes().getIterator().getAttribute(TextAttribute.WIDTH); if (wordIndex != words.size() -1) { contents.newLineAtOffset(wordWidth + interWordSpacing, 0f); lastPos = lastPos + wordWidth + interWordSpacing; } ++wordIndex; } } horizontalOffset = horizontalOffset - lastPos;
1,033
450
1,483
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/action/PDAction.java
PDAction
getNext
class PDAction implements PDDestinationOrAction { /** * The type of PDF object. */ public static final String TYPE = "Action"; /** * The action dictionary. */ protected final COSDictionary action; /** * Default constructor. */ public PDAction() { action = new COSDictionary(); setType( TYPE ); } /** * Constructor. * * @param a The action dictionary. */ public PDAction( COSDictionary a ) { action = a; } /** * Convert this standard java object to a COS object. * * @return The cos object that matches this Java object. */ @Override public COSDictionary getCOSObject() { return action; } /** * This will get the type of PDF object that the actions dictionary describes. * If present must be Action for an action dictionary. * * @return The Type of PDF object. */ public final String getType() { return action.getNameAsString( COSName.TYPE ); } /** * This will set the type of PDF object that the actions dictionary describes. * If present must be Action for an action dictionary. * * @param type The new Type for the PDF object. */ protected final void setType(String type) { action.setName(COSName.TYPE, type ); } /** * This will get the type of action that the actions dictionary describes. * * @return The S entry of actions dictionary. */ public final String getSubType() { return action.getNameAsString(COSName.S); } /** * This will set the type of action that the actions dictionary describes. * * @param s The new type of action. */ protected final void setSubType(String s) { action.setName(COSName.S, s); } /** * This will get the next action, or sequence of actions, to be performed after this one. * The value is either a single action dictionary or an array of action dictionaries * to be performed in order. * * @return The Next action or sequence of actions. */ public List<PDAction> getNext() {<FILL_FUNCTION_BODY>} /** * This will set the next action, or sequence of actions, to be performed after this one. * The value is either a single action dictionary or an array of action dictionaries * to be performed in order. * * @param next The Next action or sequence of actions. */ public void setNext(List<PDAction> next) { action.setItem(COSName.NEXT, new COSArray(next)); } }
List<PDAction> retval = null; COSBase next = action.getDictionaryObject(COSName.NEXT); if( next instanceof COSDictionary ) { PDAction pdAction = PDActionFactory.createAction( (COSDictionary) next ); retval = new COSArrayList<>(pdAction, next, action, COSName.NEXT); } else if( next instanceof COSArray ) { COSArray array = (COSArray)next; List<PDAction> actions = new ArrayList<>(array.size()); for( int i=0; i<array.size(); i++ ) { actions.add( PDActionFactory.createAction( (COSDictionary) array.getObject( i ))); } retval = new COSArrayList<>( actions, array ); } return retval;
738
221
959
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/action/PDActionEmbeddedGoTo.java
PDActionEmbeddedGoTo
setDestination
class PDActionEmbeddedGoTo extends PDAction { /** * This type of action this object represents. */ public static final String SUB_TYPE = "GoToE"; /** * Default constructor. */ public PDActionEmbeddedGoTo() { setSubType(SUB_TYPE); } /** * Constructor. * * @param a The action dictionary. */ public PDActionEmbeddedGoTo(COSDictionary a) { super(a); } /** * This will get the destination to jump to. * * @return The D entry of the specific go-to action dictionary. * * @throws IOException If there is an error creating the destination. */ public PDDestination getDestination() throws IOException { return PDDestination.create(getCOSObject().getDictionaryObject(COSName.D)); } /** * This will set the destination to jump to. * * @param d The destination. * * @throws IllegalArgumentException if the destination is not a page dictionary object. */ public void setDestination(PDDestination d) {<FILL_FUNCTION_BODY>} /** * This will get the file in which the destination is located. * * @return The F entry of the specific embedded go-to action dictionary. * * @throws IOException If there is an error creating the file spec. */ public PDFileSpecification getFile() throws IOException { return PDFileSpecification.createFS(getCOSObject().getDictionaryObject(COSName.F)); } /** * This will set the file in which the destination is located. * * @param fs The file specification. */ public void setFile(PDFileSpecification fs) { getCOSObject().setItem(COSName.F, fs); } /** * This will specify whether to open the destination document in a new window, in the same * window, or behave in accordance with the current user preference. * * @return A flag specifying how to open the destination document. */ public OpenMode getOpenInNewWindow() { if (getCOSObject().getDictionaryObject(COSName.NEW_WINDOW) instanceof COSBoolean) { COSBoolean b = (COSBoolean) getCOSObject().getDictionaryObject(COSName.NEW_WINDOW); return b.getValue() ? OpenMode.NEW_WINDOW : OpenMode.SAME_WINDOW; } return OpenMode.USER_PREFERENCE; } /** * This will specify whether to open the destination document in a new window. * * @param value The flag value. */ public void setOpenInNewWindow(OpenMode value) { if (null == value) { getCOSObject().removeItem(COSName.NEW_WINDOW); return; } switch (value) { case USER_PREFERENCE: getCOSObject().removeItem(COSName.NEW_WINDOW); break; case SAME_WINDOW: getCOSObject().setBoolean(COSName.NEW_WINDOW, false); break; case NEW_WINDOW: getCOSObject().setBoolean(COSName.NEW_WINDOW, true); break; default: // shouldn't happen unless the enum type is changed break; } } /** * Get the target directory. * * @return the target directory or null if there is none. */ public PDTargetDirectory getTargetDirectory() { COSDictionary targetDict = getCOSObject().getCOSDictionary(COSName.T); return targetDict != null ? new PDTargetDirectory(targetDict) : null; } /** * Sets the target directory. * * @param targetDirectory the target directory */ public void setTargetDirectory(PDTargetDirectory targetDirectory) { getCOSObject().setItem(COSName.T, targetDirectory); } }
if (d instanceof PDPageDestination) { PDPageDestination pageDest = (PDPageDestination) d; COSArray destArray = pageDest.getCOSObject(); if (!destArray.isEmpty()) { COSBase page = destArray.getObject(0); if (!(page instanceof COSInteger)) { throw new IllegalArgumentException( "Destination of a GoToE action must be an integer"); } } } getCOSObject().setItem(COSName.D, d);
1,094
143
1,237
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public org.apache.pdfbox.cos.COSDictionary getCOSObject() ,public List<org.apache.pdfbox.pdmodel.interactive.action.PDAction> getNext() ,public final java.lang.String getSubType() ,public final java.lang.String getType() ,public void setNext(List<org.apache.pdfbox.pdmodel.interactive.action.PDAction>) <variables>public static final java.lang.String TYPE,protected final non-sealed org.apache.pdfbox.cos.COSDictionary action
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/action/PDActionFactory.java
PDActionFactory
createAction
class PDActionFactory { /** * Utility Class. */ private PDActionFactory() { //utility class } /** * This will create the correct type of action based on the type specified * in the dictionary. * * @param action An action dictionary. * * @return An action of the correct type. */ public static PDAction createAction( COSDictionary action ) {<FILL_FUNCTION_BODY>} }
PDAction retval = null; if( action != null) { String type = action.getNameAsString(COSName.S); if (type != null) { switch (type) { case PDActionJavaScript.SUB_TYPE: retval = new PDActionJavaScript(action); break; case PDActionGoTo.SUB_TYPE: retval = new PDActionGoTo(action); break; case PDActionLaunch.SUB_TYPE: retval = new PDActionLaunch(action); break; case PDActionRemoteGoTo.SUB_TYPE: retval = new PDActionRemoteGoTo(action); break; case PDActionURI.SUB_TYPE: retval = new PDActionURI(action); break; case PDActionNamed.SUB_TYPE: retval = new PDActionNamed(action); break; case PDActionSound.SUB_TYPE: retval = new PDActionSound(action); break; case PDActionMovie.SUB_TYPE: retval = new PDActionMovie(action); break; case PDActionImportData.SUB_TYPE: retval = new PDActionImportData(action); break; case PDActionResetForm.SUB_TYPE: retval = new PDActionResetForm(action); break; case PDActionHide.SUB_TYPE: retval = new PDActionHide(action); break; case PDActionSubmitForm.SUB_TYPE: retval = new PDActionSubmitForm(action); break; case PDActionThread.SUB_TYPE: retval = new PDActionThread(action); break; case PDActionEmbeddedGoTo.SUB_TYPE: retval = new PDActionEmbeddedGoTo(action); break; default: break; } } } return retval;
131
524
655
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/action/PDActionGoTo.java
PDActionGoTo
setDestination
class PDActionGoTo extends PDAction { /** * This type of action this object represents. */ public static final String SUB_TYPE = "GoTo"; /** * Default constructor. */ public PDActionGoTo() { setSubType( SUB_TYPE ); } /** * Constructor. * * @param a The action dictionary. */ public PDActionGoTo( COSDictionary a ) { super( a ); } /** * This will get the destination to jump to. * * @return The D entry of the specific go-to action dictionary. * * @throws IOException If there is an error creating the destination. */ public PDDestination getDestination() throws IOException { return PDDestination.create(getCOSObject().getDictionaryObject(COSName.D)); } /** * This will set the destination to jump to. * * @param d The destination. * * @throws IllegalArgumentException if the destination is not a page dictionary object. */ public void setDestination( PDDestination d ) {<FILL_FUNCTION_BODY>} }
if (d instanceof PDPageDestination) { PDPageDestination pageDest = (PDPageDestination) d; COSArray destArray = pageDest.getCOSObject(); if (!destArray.isEmpty()) { COSBase page = destArray.getObject(0); if (!(page instanceof COSDictionary)) { throw new IllegalArgumentException( "Destination of a GoTo action must be a page dictionary object"); } } } getCOSObject().setItem(COSName.D, d);
320
144
464
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public org.apache.pdfbox.cos.COSDictionary getCOSObject() ,public List<org.apache.pdfbox.pdmodel.interactive.action.PDAction> getNext() ,public final java.lang.String getSubType() ,public final java.lang.String getType() ,public void setNext(List<org.apache.pdfbox.pdmodel.interactive.action.PDAction>) <variables>public static final java.lang.String TYPE,protected final non-sealed org.apache.pdfbox.cos.COSDictionary action
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/action/PDActionJavaScript.java
PDActionJavaScript
getAction
class PDActionJavaScript extends PDAction { /** * This type of action this object represents. */ public static final String SUB_TYPE = "JavaScript"; /** * Constructor #1. */ public PDActionJavaScript() { setSubType( SUB_TYPE ); } /** * Constructor. * * @param js Some javascript code. */ public PDActionJavaScript( String js ) { this(); setAction(js); } /** * Constructor #2. * * @param a The action dictionary. */ public PDActionJavaScript(COSDictionary a) { super(a); } /** * @param sAction The JavaScript. */ public final void setAction(String sAction) { action.setString(COSName.JS, sAction); } /** * @return The Javascript Code. */ public String getAction() {<FILL_FUNCTION_BODY>} }
COSBase base = action.getDictionaryObject( COSName.JS ); if (base instanceof COSString) { return ((COSString)base).getString(); } else if (base instanceof COSStream) { return ((COSStream)base).toTextString(); } else { return null; }
290
95
385
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public org.apache.pdfbox.cos.COSDictionary getCOSObject() ,public List<org.apache.pdfbox.pdmodel.interactive.action.PDAction> getNext() ,public final java.lang.String getSubType() ,public final java.lang.String getType() ,public void setNext(List<org.apache.pdfbox.pdmodel.interactive.action.PDAction>) <variables>public static final java.lang.String TYPE,protected final non-sealed org.apache.pdfbox.cos.COSDictionary action
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/action/PDActionLaunch.java
PDActionLaunch
setOpenInNewWindow
class PDActionLaunch extends PDAction { /** * This type of action this object represents. */ public static final String SUB_TYPE = "Launch"; /** * Default constructor. */ public PDActionLaunch() { setSubType( SUB_TYPE ); } /** * Constructor. * * @param a The action dictionary. */ public PDActionLaunch( COSDictionary a ) { super( a ); } /** * This will get the application to be launched or the document * to be opened or printed. It is required if none of the entries * Win, Mac or Unix is present. If this entry is absent and the * viewer application does not understand any of the alternative * entries it should do nothing. * * @return The F entry of the specific launch action dictionary. * * @throws IOException If there is an error creating the file spec. */ public PDFileSpecification getFile() throws IOException { return PDFileSpecification.createFS(getCOSObject().getDictionaryObject(COSName.F)); } /** * This will set the application to be launched or the document * to be opened or printed. It is required if none of the entries * Win, Mac or Unix is present. If this entry is absent and the * viewer application does not understand any of the alternative * entries it should do nothing. * * @param fs The file specification. */ public void setFile( PDFileSpecification fs ) { getCOSObject().setItem(COSName.F, fs); } /** * This will get a dictionary containing Windows-specific launch parameters. * * @return The Win entry of of the specific launch action dictionary. */ public PDWindowsLaunchParams getWinLaunchParams() { COSDictionary win = action.getCOSDictionary(COSName.WIN); return win != null ? new PDWindowsLaunchParams(win) : null; } /** * This will set a dictionary containing Windows-specific launch parameters. * * @param win The action to be performed. */ public void setWinLaunchParams( PDWindowsLaunchParams win ) { action.setItem(COSName.WIN, win); } /** * This will get the file name to be launched or the document to be opened * or printed, in standard Windows pathname format. If the name string includes * a backslash character (\), the backslash must itself be preceded by a backslash. * This value must be a single string; it is not a file specification. * * @return The F entry of the specific Windows launch parameter dictionary. */ public String getF() { return action.getString(COSName.F); } /** * This will set the file name to be launched or the document to be opened * or printed, in standard Windows pathname format. If the name string includes * a backslash character (\), the backslash must itself be preceded by a backslash. * This value must be a single string; it is not a file specification. * * @param f The file name to be launched. */ public void setF( String f ) { action.setString(COSName.F, f ); } /** * This will get the string specifying the default directory in standard DOS syntax. * * @return The D entry of the specific Windows launch parameter dictionary. */ public String getD() { return action.getString(COSName.D); } /** * This will set the string specifying the default directory in standard DOS syntax. * * @param d The default directory. */ public void setD( String d ) { action.setString(COSName.D, d ); } /** * This will get the string specifying the operation to perform: * open to open a document * print to print a document * If the F entry designates an application instead of a document, this entry * is ignored and the application is launched. Default value: open. * * @return The O entry of the specific Windows launch parameter dictionary. */ public String getO() { return action.getString(COSName.O); } /** * This will set the string specifying the operation to perform: * open to open a document * print to print a document * If the F entry designates an application instead of a document, this entry * is ignored and the application is launched. Default value: open. * * @param o The operation to perform. */ public void setO( String o ) { action.setString(COSName.O, o ); } /** * This will get a parameter string to be passed to the application designated by the F entry. * This entry should be omitted if F designates a document. * * @return The P entry of the specific Windows launch parameter dictionary. */ public String getP() { return action.getString(COSName.P); } /** * This will set a parameter string to be passed to the application designated by the F entry. * This entry should be omitted if F designates a document. * * @param p The parameter string. */ public void setP( String p ) { action.setString(COSName.P, p ); } /** * This will specify whether to open the destination document in a new window, in the same * window, or behave in accordance with the current user preference. * * @return A flag specifying how to open the destination document. */ public OpenMode getOpenInNewWindow() { if (getCOSObject().getDictionaryObject(COSName.NEW_WINDOW) instanceof COSBoolean) { COSBoolean b = (COSBoolean) getCOSObject().getDictionaryObject(COSName.NEW_WINDOW); return b.getValue() ? OpenMode.NEW_WINDOW : OpenMode.SAME_WINDOW; } return OpenMode.USER_PREFERENCE; } /** * This will specify whether to open the destination document in a new window. * * @param value The flag value. */ public void setOpenInNewWindow(OpenMode value) {<FILL_FUNCTION_BODY>} }
if (null == value) { getCOSObject().removeItem(COSName.NEW_WINDOW); return; } switch (value) { case USER_PREFERENCE: getCOSObject().removeItem(COSName.NEW_WINDOW); break; case SAME_WINDOW: getCOSObject().setBoolean(COSName.NEW_WINDOW, false); break; case NEW_WINDOW: getCOSObject().setBoolean(COSName.NEW_WINDOW, true); break; default: // shouldn't happen unless the enum type is changed break; }
1,667
180
1,847
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public org.apache.pdfbox.cos.COSDictionary getCOSObject() ,public List<org.apache.pdfbox.pdmodel.interactive.action.PDAction> getNext() ,public final java.lang.String getSubType() ,public final java.lang.String getType() ,public void setNext(List<org.apache.pdfbox.pdmodel.interactive.action.PDAction>) <variables>public static final java.lang.String TYPE,protected final non-sealed org.apache.pdfbox.cos.COSDictionary action
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/action/PDActionRemoteGoTo.java
PDActionRemoteGoTo
getOpenInNewWindow
class PDActionRemoteGoTo extends PDAction { /** * This type of action this object represents. */ public static final String SUB_TYPE = "GoToR"; /** * Default constructor. */ public PDActionRemoteGoTo() { setSubType( SUB_TYPE ); } /** * Constructor. * * @param a The action dictionary. */ public PDActionRemoteGoTo( COSDictionary a ) { super( a ); } /** * This will get the file in which the destination is located. * * @return The F entry of the specific remote go-to action dictionary. * * @throws IOException If there is an error creating the file spec. */ public PDFileSpecification getFile() throws IOException { return PDFileSpecification.createFS( action.getDictionaryObject( COSName.F ) ); } /** * This will set the file in which the destination is located. * * @param fs The file specification. */ public void setFile( PDFileSpecification fs ) { action.setItem( COSName.F, fs ); } /** * This will get the destination to jump to. * If the value is an array defining an explicit destination, * its first element must be a page number within the remote * document rather than an indirect reference to a page object * in the current document. The first page is numbered 0. * * @return The D entry of the specific remote go-to action dictionary. */ // Array or String. public COSBase getD() { return action.getDictionaryObject( COSName.D ); } /** * This will set the destination to jump to. * If the value is an array defining an explicit destination, * its first element must be a page number within the remote * document rather than an indirect reference to a page object * in the current document. The first page is numbered 0. * * @param d The destination. */ // In case the value is an array. public void setD( COSBase d ) { action.setItem( COSName.D, d ); } /** * This will specify whether to open the destination document in a new window, in the same * window, or behave in accordance with the current user preference. * * @return A flag specifying how to open the destination document. */ public OpenMode getOpenInNewWindow() {<FILL_FUNCTION_BODY>} /** * This will specify whether to open the destination document in a new window. * * @param value The flag value. */ public void setOpenInNewWindow(OpenMode value) { if (null == value) { getCOSObject().removeItem(COSName.NEW_WINDOW); return; } switch (value) { case USER_PREFERENCE: getCOSObject().removeItem(COSName.NEW_WINDOW); break; case SAME_WINDOW: getCOSObject().setBoolean(COSName.NEW_WINDOW, false); break; case NEW_WINDOW: getCOSObject().setBoolean(COSName.NEW_WINDOW, true); break; default: // shouldn't happen unless the enum type is changed break; } } }
if (getCOSObject().getDictionaryObject(COSName.NEW_WINDOW) instanceof COSBoolean) { COSBoolean b = (COSBoolean) getCOSObject().getDictionaryObject(COSName.NEW_WINDOW); return b.getValue() ? OpenMode.NEW_WINDOW : OpenMode.SAME_WINDOW; } return OpenMode.USER_PREFERENCE;
909
108
1,017
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public org.apache.pdfbox.cos.COSDictionary getCOSObject() ,public List<org.apache.pdfbox.pdmodel.interactive.action.PDAction> getNext() ,public final java.lang.String getSubType() ,public final java.lang.String getType() ,public void setNext(List<org.apache.pdfbox.pdmodel.interactive.action.PDAction>) <variables>public static final java.lang.String TYPE,protected final non-sealed org.apache.pdfbox.cos.COSDictionary action
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/action/PDActionURI.java
PDActionURI
getURI
class PDActionURI extends PDAction { /** * This type of action this object represents. */ public static final String SUB_TYPE = "URI"; /** * Default constructor. */ public PDActionURI() { setSubType(SUB_TYPE); } /** * Constructor. * * @param a The action dictionary. */ public PDActionURI(COSDictionary a) { super(a); } /** * This will get the uniform resource identifier to resolve. It should be encoded in 7-bit * ASCII, but UTF-8 and UTF-16 are supported too. * * @return The URI entry of the specific URI action dictionary or null if there isn't any. */ public String getURI() {<FILL_FUNCTION_BODY>} /** * This will set the uniform resource identifier to resolve, encoded in * 7-bit ASCII. * * @param uri The uniform resource identifier. */ public void setURI(String uri) { action.setString(COSName.URI, uri); } /** * This will specify whether to track the mouse position when the URI is * resolved. Default value: false. This entry applies only to actions * triggered by the user's clicking an annotation; it is ignored for actions * associated with outline items or with a document's OpenAction entry. * * @return A flag specifying whether to track the mouse position when the * URI is resolved. */ public boolean shouldTrackMousePosition() { return this.action.getBoolean("IsMap", false); } /** * This will specify whether to track the mouse position when the URI is * resolved. * * @param value The flag value. */ public void setTrackMousePosition(boolean value) { this.action.setBoolean("IsMap", value); } }
COSBase base = action.getDictionaryObject(COSName.URI); if (base instanceof COSString) { byte[] bytes = ((COSString) base).getBytes(); if (bytes.length >= 2) { // UTF-16 (BE) if ((bytes[0] & 0xFF) == 0xFE && (bytes[1] & 0xFF) == 0xFF) { return action.getString(COSName.URI); } // UTF-16 (LE) if ((bytes[0] & 0xFF) == 0xFF && (bytes[1] & 0xFF) == 0xFE) { return action.getString(COSName.URI); } } return new String(bytes, StandardCharsets.UTF_8); } return null;
512
221
733
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public org.apache.pdfbox.cos.COSDictionary getCOSObject() ,public List<org.apache.pdfbox.pdmodel.interactive.action.PDAction> getNext() ,public final java.lang.String getSubType() ,public final java.lang.String getType() ,public void setNext(List<org.apache.pdfbox.pdmodel.interactive.action.PDAction>) <variables>public static final java.lang.String TYPE,protected final non-sealed org.apache.pdfbox.cos.COSDictionary action
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/action/PDTargetDirectory.java
PDTargetDirectory
setPageNumber
class PDTargetDirectory implements COSObjectable { private final COSDictionary dict; /** * Default constructor, creates target directory. */ public PDTargetDirectory() { dict = new COSDictionary(); } /** * Create a target directory from an existing dictionary. * * @param dictionary The existing graphics state. */ public PDTargetDirectory(COSDictionary dictionary) { dict = dictionary; } /** * This will get the underlying dictionary that this class acts on. * * @return The underlying dictionary for this class. */ @Override public COSDictionary getCOSObject() { return dict; } /** * Get the relationship between the current document and the target (which may be an * intermediate target). * * @return the relationship as a name. Valid values are P (the target is the parent of the * current document) and C (the target is a child of the current document). Invalid values or * null are also returned. */ public COSName getRelationship() { return dict.getCOSName(COSName.R); } /** * Set the relationship between the current document and the target (which may be an * intermediate target). * * @param relationship Valid values are P (the target is the parent of the current document) and * C (the target is a child of the current document). * * throws IllegalArgumentException if the parameter is not P or C. */ public void setRelationship(COSName relationship) { if (!COSName.P.equals(relationship) && !COSName.C.equals(relationship)) { throw new IllegalArgumentException("The only valid are P or C, not " + relationship.getName()); } dict.setItem(COSName.R, relationship); } /** * Get the name of the file as found in the EmbeddedFiles name tree. This is only to be used if * the target is a child of the current document. * * @return a filename or null if there is none. */ public String getFilename() { return dict.getString(COSName.N); } /** * Sets the name of the file as found in the EmbeddedFiles name tree. This is only to be used if * the target is a child of the current document. * * @param filename a filename or null if the entry is to be deleted. */ public void setFilename(String filename) { dict.setString(COSName.N, filename); } /** * Get the target directory. If this entry is absent, the current document is the target file * containing the destination. * * @return the target directory or null if the current document is the target file containing * the destination. */ public PDTargetDirectory getTargetDirectory() { COSDictionary targetDict = dict.getCOSDictionary(COSName.T); return targetDict != null ? new PDTargetDirectory(targetDict) : null; } /** * Sets the target directory. * * @param targetDirectory the target directory or null if the current document is the target * file containing the destination. */ public void setTargetDirectory(PDTargetDirectory targetDirectory) { dict.setItem(COSName.T, targetDirectory); } /** * If the value in the /P entry is an integer, this will get the page number (zero-based) in the * current document containing the file attachment annotation. * * @return the zero based page number or -1 if the /P entry value is missing or not a number. */ public int getPageNumber() { return dict.getInt(COSName.P, -1); } /** * Set the page number (zero-based) in the current document containing the file attachment * annotation. * * @param pageNumber the zero based page number. If this is &lt; 0 then the entry is removed. */ public void setPageNumber(int pageNumber) {<FILL_FUNCTION_BODY>} /** * If the value in the /P entry is a string, this will get a named destination in the current * document that provides the page number of the file attachment annotation. * * @return a named destination or null if the /P entry value is missing or not a string. */ public PDNamedDestination getNamedDestination() { COSBase base = dict.getDictionaryObject(COSName.P); if (base instanceof COSString) { return new PDNamedDestination((COSString) base); } return null; } /** * This will set a named destination in the current document that provides the page number of * the file attachment annotation. * * @param dest a named destination or null if the entry is to be removed. */ public void setNamedDestination(PDNamedDestination dest) { if (dest == null) { dict.removeItem(COSName.P); } else { dict.setItem(COSName.P, dest); } } /** * If the value in the /A entry is an integer, this will get the index (zero-based) of the * annotation in the /Annots array of the page specified by the /P entry. * * @return the zero based page number or -1 if the /P entry value is missing or not a number. */ public int getAnnotationIndex() { return dict.getInt(COSName.A, -1); } /** * This will set the index (zero-based) of the annotation in the /Annots array of the page * specified by the /P entry. * * @param index the zero based index. If this is &lt; 0 then the entry is removed. */ public void setAnnotationIndex(int index) { if (index < 0) { dict.removeItem(COSName.A); } else { dict.setInt(COSName.A, index); } } /** * If the value in the /A entry is a string, this will get the value of the /NM entry in the * annotation dictionary. * * @return the /NM value of an annotation dictionary or null if the /A entry value is missing or * not a string. */ public String getAnnotationName() { return dict.getString(COSName.A); } /** * This will get the value of the /NM entry in the annotation dictionary. * * @param name the /NM value of an annotation dictionary or null if the entry is to be removed. */ public void setAnnotationName(String name) { dict.setString(COSName.A, name); } }
if (pageNumber < 0) { dict.removeItem(COSName.P); } else { dict.setInt(COSName.P, pageNumber); }
1,796
56
1,852
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationCaret.java
PDAnnotationCaret
setRectDifferences
class PDAnnotationCaret extends PDAnnotationMarkup { /** * The type of annotation. */ public static final String SUB_TYPE = "Caret"; private PDAppearanceHandler customAppearanceHandler; public PDAnnotationCaret() { getCOSObject().setName(COSName.SUBTYPE, SUB_TYPE); } /** * Creates a Caret annotation from a COSDictionary, expected to be a correct object definition. * * @param field the PDF object to represent as a field. */ public PDAnnotationCaret(COSDictionary field) { super(field); } /** * This will set the difference between the annotations "outer" rectangle defined by * /Rect and boundaries of the underlying. * * <p>This will set an equal difference for all sides</p> * * @param difference from the annotations /Rect entry */ public void setRectDifferences(float difference) { setRectDifferences(difference, difference, difference, difference); } /** * This will set the difference between the annotations "outer" rectangle defined by * /Rect and the border. * * @param differenceLeft left difference from the annotations /Rect entry * @param differenceTop top difference from the annotations /Rect entry * @param differenceRight right difference from the annotations /Rect entry * @param differenceBottom bottom difference from the annotations /Rect entry * */ public void setRectDifferences(float differenceLeft, float differenceTop, float differenceRight, float differenceBottom) {<FILL_FUNCTION_BODY>} /** * This will get the margin between the annotations "outer" rectangle defined by * /Rect and the boundaries of the underlying caret. * * @return the differences. If the entry hasn't been set am empty array is returned. */ public float[] getRectDifferences() { COSArray margin = getCOSObject().getCOSArray(COSName.RD); return margin != null ? margin.toFloatArray() : new float[] {}; } /** * Set a custom appearance handler for generating the annotations appearance streams. * * @param appearanceHandler custom appearance handler */ public void setCustomAppearanceHandler(PDAppearanceHandler appearanceHandler) { customAppearanceHandler = appearanceHandler; } @Override public void constructAppearances() { this.constructAppearances(null); } @Override public void constructAppearances(PDDocument document) { if (customAppearanceHandler == null) { PDCaretAppearanceHandler appearanceHandler = new PDCaretAppearanceHandler(this, document); appearanceHandler.generateAppearanceStreams(); } else { customAppearanceHandler.generateAppearanceStreams(); } } }
COSArray margins = new COSArray(); margins.add(new COSFloat(differenceLeft)); margins.add(new COSFloat(differenceTop)); margins.add(new COSFloat(differenceRight)); margins.add(new COSFloat(differenceBottom)); getCOSObject().setItem(COSName.RD, margins);
768
101
869
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary getBorderStyle() ,public float getConstantOpacity() ,public java.util.Calendar getCreationDate() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDExternalDataDictionary getExternalData() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation getInReplyTo() throws java.io.IOException,public java.lang.String getIntent() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationPopup getPopup() ,public java.lang.String getReplyType() ,public java.lang.String getRichContents() ,public java.lang.String getSubject() ,public java.lang.String getTitlePopup() ,public void setBorderStyle(org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary) ,public void setConstantOpacity(float) ,public void setCreationDate(java.util.Calendar) ,public void setExternalData(org.apache.pdfbox.pdmodel.interactive.annotation.PDExternalDataDictionary) ,public void setInReplyTo(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void setIntent(java.lang.String) ,public void setPopup(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationPopup) ,public void setReplyType(java.lang.String) ,public void setRichContents(java.lang.String) ,public void setSubject(java.lang.String) ,public void setTitlePopup(java.lang.String) <variables>public static final java.lang.String RT_GROUP,public static final java.lang.String RT_REPLY
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationCircle.java
PDAnnotationCircle
constructAppearances
class PDAnnotationCircle extends PDAnnotationSquareCircle { /** * The type of annotation. */ public static final String SUB_TYPE = "Circle"; private PDAppearanceHandler customAppearanceHandler; public PDAnnotationCircle() { super(SUB_TYPE); } /** * Creates a circle annotation from a COSDictionary, expected to be a correct object definition. * * @param field the PDF object to represent as a field. */ public PDAnnotationCircle(COSDictionary field) { super(field); } /** * Set a custom appearance handler for generating the annotations appearance streams. * * @param appearanceHandler custom appearance handler */ public void setCustomAppearanceHandler(PDAppearanceHandler appearanceHandler) { customAppearanceHandler = appearanceHandler; } @Override public void constructAppearances() { this.constructAppearances(null); } @Override public void constructAppearances(PDDocument document) {<FILL_FUNCTION_BODY>} }
if (customAppearanceHandler == null) { PDCircleAppearanceHandler appearanceHandler = new PDCircleAppearanceHandler(this, document); appearanceHandler.generateAppearanceStreams(); } else { customAppearanceHandler.generateAppearanceStreams(); }
302
84
386
<methods>public abstract void constructAppearances() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderEffectDictionary getBorderEffect() ,public org.apache.pdfbox.pdmodel.graphics.color.PDColor getInteriorColor() ,public org.apache.pdfbox.pdmodel.common.PDRectangle getRectDifference() ,public float[] getRectDifferences() ,public void setBorderEffect(org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderEffectDictionary) ,public void setInteriorColor(org.apache.pdfbox.pdmodel.graphics.color.PDColor) ,public void setRectDifference(org.apache.pdfbox.pdmodel.common.PDRectangle) ,public void setRectDifferences(float) ,public void setRectDifferences(float, float, float, float) <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationFileAttachment.java
PDAnnotationFileAttachment
constructAppearances
class PDAnnotationFileAttachment extends PDAnnotationMarkup { /** * See get/setAttachmentName. */ public static final String ATTACHMENT_NAME_PUSH_PIN = "PushPin"; /** * See get/setAttachmentName. */ public static final String ATTACHMENT_NAME_GRAPH = "Graph"; /** * See get/setAttachmentName. */ public static final String ATTACHMENT_NAME_PAPERCLIP = "Paperclip"; /** * See get/setAttachmentName. */ public static final String ATTACHMENT_NAME_TAG = "Tag"; /** * The type of annotation. */ public static final String SUB_TYPE = "FileAttachment"; private PDAppearanceHandler customAppearanceHandler; /** * Constructor. */ public PDAnnotationFileAttachment() { getCOSObject().setName(COSName.SUBTYPE, SUB_TYPE); } /** * Creates a Link annotation from a COSDictionary, expected to be a correct object definition. * * @param field the PDF object to represent as a field. */ public PDAnnotationFileAttachment(COSDictionary field) { super(field); } /** * Return the attached file. * * @return The attached file. * * @throws IOException If there is an error creating the file spec. */ public PDFileSpecification getFile() throws IOException { return PDFileSpecification.createFS(getCOSObject().getDictionaryObject(COSName.FS)); } /** * Set the attached file. * * @param file The file that is attached. */ public void setFile(PDFileSpecification file) { getCOSObject().setItem(COSName.FS, file); } /** * This is the name used to draw the type of attachment. See the ATTACHMENT_NAME_XXX constants. * * @return The name that describes the visual cue for the attachment. */ public String getAttachmentName() { return getCOSObject().getNameAsString(COSName.NAME, ATTACHMENT_NAME_PUSH_PIN); } /** * Set the name used to draw the attachment icon. See the ATTACHMENT_NAME_XXX constants. * * @param name The name of the visual icon to draw. */ public void setAttachmentName(String name) { getCOSObject().setName(COSName.NAME, name); } /** * Set a custom appearance handler for generating the annotations appearance streams. * * @param appearanceHandler custom appearance handler */ public void setCustomAppearanceHandler(PDAppearanceHandler appearanceHandler) { customAppearanceHandler = appearanceHandler; } @Override public void constructAppearances() { this.constructAppearances(null); } @Override public void constructAppearances(PDDocument document) {<FILL_FUNCTION_BODY>} }
if (customAppearanceHandler == null) { PDFileAttachmentAppearanceHandler appearanceHandler = new PDFileAttachmentAppearanceHandler(this, document); appearanceHandler.generateAppearanceStreams(); } else { customAppearanceHandler.generateAppearanceStreams(); }
834
86
920
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary getBorderStyle() ,public float getConstantOpacity() ,public java.util.Calendar getCreationDate() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDExternalDataDictionary getExternalData() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation getInReplyTo() throws java.io.IOException,public java.lang.String getIntent() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationPopup getPopup() ,public java.lang.String getReplyType() ,public java.lang.String getRichContents() ,public java.lang.String getSubject() ,public java.lang.String getTitlePopup() ,public void setBorderStyle(org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary) ,public void setConstantOpacity(float) ,public void setCreationDate(java.util.Calendar) ,public void setExternalData(org.apache.pdfbox.pdmodel.interactive.annotation.PDExternalDataDictionary) ,public void setInReplyTo(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void setIntent(java.lang.String) ,public void setPopup(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationPopup) ,public void setReplyType(java.lang.String) ,public void setRichContents(java.lang.String) ,public void setSubject(java.lang.String) ,public void setTitlePopup(java.lang.String) <variables>public static final java.lang.String RT_GROUP,public static final java.lang.String RT_REPLY
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationHighlight.java
PDAnnotationHighlight
constructAppearances
class PDAnnotationHighlight extends PDAnnotationTextMarkup { /** * The type of annotation. */ public static final String SUB_TYPE = "Highlight"; private PDAppearanceHandler customAppearanceHandler; /** * Constructor. */ public PDAnnotationHighlight() { super(SUB_TYPE); } /** * Constructor. * * @param dict The annotations dictionary. */ public PDAnnotationHighlight(COSDictionary dict) { super(dict); } /** * Set a custom appearance handler for generating the annotations appearance streams. * * @param appearanceHandler custom appearance handler */ public void setCustomAppearanceHandler(PDAppearanceHandler appearanceHandler) { customAppearanceHandler = appearanceHandler; } @Override public void constructAppearances() { this.constructAppearances(null); } @Override public void constructAppearances(PDDocument document) {<FILL_FUNCTION_BODY>} }
if (customAppearanceHandler == null) { PDHighlightAppearanceHandler appearanceHandler = new PDHighlightAppearanceHandler(this, document); appearanceHandler.generateAppearanceStreams(); } else { customAppearanceHandler.generateAppearanceStreams(); }
293
84
377
<methods>public float[] getQuadPoints() ,public final void setQuadPoints(float[]) <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationInk.java
PDAnnotationInk
getInkList
class PDAnnotationInk extends PDAnnotationMarkup { /** * The type of annotation. */ public static final String SUB_TYPE = "Ink"; private PDAppearanceHandler customAppearanceHandler; /** * Constructor. */ public PDAnnotationInk() { getCOSObject().setName(COSName.SUBTYPE, SUB_TYPE); } /** * Constructor. * * @param dict The annotations dictionary. */ public PDAnnotationInk(COSDictionary dict) { super(dict); } /** * Sets the paths that make this annotation. * * @param inkList An array of arrays, each representing a stroked path. Each array shall be a * series of alternating horizontal and vertical coordinates. If the parameter is null the entry * will be removed. */ public void setInkList(float[][] inkList) { if (inkList == null) { getCOSObject().removeItem(COSName.INKLIST); return; } COSArray array = new COSArray(); for (float[] path : inkList) { array.add(COSArray.of(path)); } getCOSObject().setItem(COSName.INKLIST, array); } /** * Get one or more disjoint paths that make this annotation. * * @return An array of arrays, each representing a stroked path. Each array shall be a series of * alternating horizontal and vertical coordinates. */ public float[][] getInkList() {<FILL_FUNCTION_BODY>} /** * Set a custom appearance handler for generating the annotations appearance streams. * * @param appearanceHandler custom appearance handler */ public void setCustomAppearanceHandler(PDAppearanceHandler appearanceHandler) { customAppearanceHandler = appearanceHandler; } @Override public void constructAppearances() { this.constructAppearances(null); } @Override public void constructAppearances(PDDocument document) { if (customAppearanceHandler == null) { PDInkAppearanceHandler appearanceHandler = new PDInkAppearanceHandler(this, document); appearanceHandler.generateAppearanceStreams(); } else { customAppearanceHandler.generateAppearanceStreams(); } } }
COSArray array = getCOSObject().getCOSArray(COSName.INKLIST); if (array != null) { float[][] inkList = new float[array.size()][]; for (int i = 0; i < array.size(); ++i) { COSBase base2 = array.getObject(i); if (base2 instanceof COSArray) { inkList[i] = ((COSArray) base2).toFloatArray(); } else { inkList[i] = new float[0]; } } return inkList; } return new float[0][0];
654
174
828
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary getBorderStyle() ,public float getConstantOpacity() ,public java.util.Calendar getCreationDate() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDExternalDataDictionary getExternalData() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation getInReplyTo() throws java.io.IOException,public java.lang.String getIntent() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationPopup getPopup() ,public java.lang.String getReplyType() ,public java.lang.String getRichContents() ,public java.lang.String getSubject() ,public java.lang.String getTitlePopup() ,public void setBorderStyle(org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary) ,public void setConstantOpacity(float) ,public void setCreationDate(java.util.Calendar) ,public void setExternalData(org.apache.pdfbox.pdmodel.interactive.annotation.PDExternalDataDictionary) ,public void setInReplyTo(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void setIntent(java.lang.String) ,public void setPopup(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationPopup) ,public void setReplyType(java.lang.String) ,public void setRichContents(java.lang.String) ,public void setSubject(java.lang.String) ,public void setTitlePopup(java.lang.String) <variables>public static final java.lang.String RT_GROUP,public static final java.lang.String RT_REPLY
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationPolyline.java
PDAnnotationPolyline
setStartPointEndingStyle
class PDAnnotationPolyline extends PDAnnotationMarkup { /** * The type of annotation. */ public static final String SUB_TYPE = "PolyLine"; private PDAppearanceHandler customAppearanceHandler; /** * Constructor. */ public PDAnnotationPolyline() { getCOSObject().setName(COSName.SUBTYPE, SUB_TYPE); } /** * Constructor. * * @param dict The annotations dictionary. */ public PDAnnotationPolyline(COSDictionary dict) { super(dict); } /** * This will set the line ending style for the start point, see the LE_ constants for the possible values. * * @param style The new style. */ public void setStartPointEndingStyle(String style) {<FILL_FUNCTION_BODY>} /** * This will retrieve the line ending style for the start point, possible values shown in the LE_ constants section. * * @return The ending style for the start point, LE_NONE if missing, never null. */ public String getStartPointEndingStyle() { COSArray array = getCOSObject().getCOSArray(COSName.LE); if (array != null && array.size() >= 2) { return array.getName(0, PDAnnotationLine.LE_NONE); } return PDAnnotationLine.LE_NONE; } /** * This will set the line ending style for the end point, see the LE_ constants for the possible values. * * @param style The new style. */ public void setEndPointEndingStyle(String style) { String actualStyle = style == null ? PDAnnotationLine.LE_NONE : style; COSArray array = getCOSObject().getCOSArray(COSName.LE); if (array == null || array.size() < 2) { array = new COSArray(); array.add(COSName.getPDFName(PDAnnotationLine.LE_NONE)); array.add(COSName.getPDFName(actualStyle)); getCOSObject().setItem(COSName.LE, array); } else { array.setName(1, actualStyle); } } /** * This will retrieve the line ending style for the end point, possible values shown in the LE_ constants section. * * @return The ending style for the end point, LE_NONE if missing, never null. */ public String getEndPointEndingStyle() { COSArray array = getCOSObject().getCOSArray(COSName.LE); if (array != null && array.size() >= 2) { return array.getName(1, PDAnnotationLine.LE_NONE); } return PDAnnotationLine.LE_NONE; } /** * This will set interior color of the line endings defined in the LE entry. * * @param ic color. */ public void setInteriorColor(PDColor ic) { getCOSObject().setItem(COSName.IC, ic.toCOSArray()); } /** * This will retrieve the interior color with which to fill the annotation’s line endings. * * @return object representing the color. */ public PDColor getInteriorColor() { return getColor(COSName.IC); } /** * This will retrieve the numbers that shall represent the alternating horizontal and vertical * coordinates. * * @return An array of floats representing the alternating horizontal and vertical coordinates. */ public float[] getVertices() { COSArray vertices = getCOSObject().getCOSArray(COSName.VERTICES); return vertices != null ? vertices.toFloatArray() : null; } /** * This will set the numbers that shall represent the alternating horizontal and vertical * coordinates. * * @param points an array with the numbers that shall represent the alternating horizontal and * vertical coordinates. */ public void setVertices(float[] points) { getCOSObject().setItem(COSName.VERTICES, COSArray.of(points)); } /** * Set a custom appearance handler for generating the annotations appearance streams. * * @param appearanceHandler custom appearance handler */ public void setCustomAppearanceHandler(PDAppearanceHandler appearanceHandler) { customAppearanceHandler = appearanceHandler; } @Override public void constructAppearances() { this.constructAppearances(null); } @Override public void constructAppearances(PDDocument document) { if (customAppearanceHandler == null) { PDPolylineAppearanceHandler appearanceHandler = new PDPolylineAppearanceHandler(this, document); appearanceHandler.generateAppearanceStreams(); } else { customAppearanceHandler.generateAppearanceStreams(); } } }
String actualStyle = style == null ? PDAnnotationLine.LE_NONE : style; COSArray array = getCOSObject().getCOSArray(COSName.LE); if (array == null || array.isEmpty()) { array = new COSArray(); array.add(COSName.getPDFName(actualStyle)); array.add(COSName.getPDFName(PDAnnotationLine.LE_NONE)); getCOSObject().setItem(COSName.LE, array); } else { array.setName(0, actualStyle); }
1,342
154
1,496
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary getBorderStyle() ,public float getConstantOpacity() ,public java.util.Calendar getCreationDate() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDExternalDataDictionary getExternalData() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation getInReplyTo() throws java.io.IOException,public java.lang.String getIntent() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationPopup getPopup() ,public java.lang.String getReplyType() ,public java.lang.String getRichContents() ,public java.lang.String getSubject() ,public java.lang.String getTitlePopup() ,public void setBorderStyle(org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary) ,public void setConstantOpacity(float) ,public void setCreationDate(java.util.Calendar) ,public void setExternalData(org.apache.pdfbox.pdmodel.interactive.annotation.PDExternalDataDictionary) ,public void setInReplyTo(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void setIntent(java.lang.String) ,public void setPopup(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationPopup) ,public void setReplyType(java.lang.String) ,public void setRichContents(java.lang.String) ,public void setSubject(java.lang.String) ,public void setTitlePopup(java.lang.String) <variables>public static final java.lang.String RT_GROUP,public static final java.lang.String RT_REPLY
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationPopup.java
PDAnnotationPopup
getParent
class PDAnnotationPopup extends PDAnnotation { private static final Logger LOG = LogManager.getLogger(PDAnnotationPopup.class); /** * The type of annotation. */ public static final String SUB_TYPE = "Popup"; /** * Constructor. */ public PDAnnotationPopup() { getCOSObject().setName(COSName.SUBTYPE, SUB_TYPE); } /** * Creates a popup annotation from a COSDictionary, expected to be a correct object definition. * * @param field the PDF object to represent as a field. */ public PDAnnotationPopup(COSDictionary field) { super(field); } /** * This will set the initial state of the annotation, open or closed. * * @param open Boolean value, true = open false = closed. */ public void setOpen(boolean open) { getCOSObject().setBoolean("Open", open); } /** * This will retrieve the initial state of the annotation, open Or closed (default closed). * * @return The initial state, true = open false = closed. */ public boolean getOpen() { return getCOSObject().getBoolean("Open", false); } /** * This will set the markup annotation which this popup relates to. * * @param annot the markup annotation. */ public void setParent(PDAnnotationMarkup annot) { getCOSObject().setItem(COSName.PARENT, annot.getCOSObject()); } /** * This will retrieve the markup annotation which this popup relates to. * * @return The parent markup annotation. */ public PDAnnotationMarkup getParent() {<FILL_FUNCTION_BODY>} }
try { PDAnnotation ann = PDAnnotation.createAnnotation(getCOSObject() .getDictionaryObject(COSName.PARENT, COSName.P)); if (!(ann instanceof PDAnnotationMarkup)) { LOG.error("parent annotation is of type {} but should be of type PDAnnotationMarkup", ann.getClass().getSimpleName()); return null; } return (PDAnnotationMarkup) ann; } catch (IOException ioe) { LOG.debug("An exception while trying to get the parent markup - ignoring", ioe); // Couldn't construct the annotation, so return null i.e. do nothing return null; }
484
183
667
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public void constructAppearances(org.apache.pdfbox.pdmodel.PDDocument) ,public void constructAppearances() ,public static org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation createAnnotation(org.apache.pdfbox.cos.COSBase) throws java.io.IOException,public boolean equals(java.lang.Object) ,public int getAnnotationFlags() ,public java.lang.String getAnnotationName() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary getAppearance() ,public org.apache.pdfbox.cos.COSName getAppearanceState() ,public org.apache.pdfbox.cos.COSArray getBorder() ,public org.apache.pdfbox.cos.COSDictionary getCOSObject() ,public org.apache.pdfbox.pdmodel.graphics.color.PDColor getColor() ,public java.lang.String getContents() ,public java.lang.String getModifiedDate() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream getNormalAppearanceStream() ,public org.apache.pdfbox.pdmodel.documentinterchange.markedcontent.PDPropertyList getOptionalContent() ,public org.apache.pdfbox.pdmodel.PDPage getPage() ,public org.apache.pdfbox.pdmodel.common.PDRectangle getRectangle() ,public int getStructParent() ,public final java.lang.String getSubtype() ,public int hashCode() ,public boolean isHidden() ,public boolean isInvisible() ,public boolean isLocked() ,public boolean isLockedContents() ,public boolean isNoRotate() ,public boolean isNoView() ,public boolean isNoZoom() ,public boolean isPrinted() ,public boolean isReadOnly() ,public boolean isToggleNoView() ,public void setAnnotationFlags(int) ,public void setAnnotationName(java.lang.String) ,public void setAppearance(org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary) ,public void setAppearanceState(java.lang.String) ,public void setBorder(org.apache.pdfbox.cos.COSArray) ,public void setColor(org.apache.pdfbox.pdmodel.graphics.color.PDColor) ,public void setContents(java.lang.String) ,public void setHidden(boolean) ,public void setInvisible(boolean) ,public void setLocked(boolean) ,public void setLockedContents(boolean) ,public void setModifiedDate(java.lang.String) ,public void setModifiedDate(java.util.Calendar) ,public void setNoRotate(boolean) ,public void setNoView(boolean) ,public void setNoZoom(boolean) ,public void setOptionalContent(org.apache.pdfbox.pdmodel.documentinterchange.markedcontent.PDPropertyList) ,public void setPage(org.apache.pdfbox.pdmodel.PDPage) ,public void setPrinted(boolean) ,public void setReadOnly(boolean) ,public void setRectangle(org.apache.pdfbox.pdmodel.common.PDRectangle) ,public void setStructParent(int) ,public void setToggleNoView(boolean) <variables>private static final int FLAG_HIDDEN,private static final int FLAG_INVISIBLE,private static final int FLAG_LOCKED,private static final int FLAG_LOCKED_CONTENTS,private static final int FLAG_NO_ROTATE,private static final int FLAG_NO_VIEW,private static final int FLAG_NO_ZOOM,private static final int FLAG_PRINTED,private static final int FLAG_READ_ONLY,private static final int FLAG_TOGGLE_NO_VIEW,private static final Logger LOG,private final non-sealed org.apache.pdfbox.cos.COSDictionary dictionary
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationSound.java
PDAnnotationSound
constructAppearances
class PDAnnotationSound extends PDAnnotationMarkup { /** * The type of annotation. */ public static final String SUB_TYPE = "Sound"; private PDAppearanceHandler customAppearanceHandler; public PDAnnotationSound() { getCOSObject().setName(COSName.SUBTYPE, SUB_TYPE); } /** * Creates a sound annotation from a COSDictionary, expected to be a correct object definition. * * @param field the PDF object to represent as a field. */ public PDAnnotationSound(COSDictionary field) { super(field); } /** * Set a custom appearance handler for generating the annotations appearance streams. * * @param appearanceHandler custom appearance handler */ public void setCustomAppearanceHandler(PDAppearanceHandler appearanceHandler) { customAppearanceHandler = appearanceHandler; } @Override public void constructAppearances() { this.constructAppearances(null); } @Override public void constructAppearances(PDDocument document) {<FILL_FUNCTION_BODY>} }
if (customAppearanceHandler == null) { PDSoundAppearanceHandler appearanceHandler = new PDSoundAppearanceHandler(this, document); appearanceHandler.generateAppearanceStreams(); } else { customAppearanceHandler.generateAppearanceStreams(); }
311
82
393
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary getBorderStyle() ,public float getConstantOpacity() ,public java.util.Calendar getCreationDate() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDExternalDataDictionary getExternalData() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation getInReplyTo() throws java.io.IOException,public java.lang.String getIntent() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationPopup getPopup() ,public java.lang.String getReplyType() ,public java.lang.String getRichContents() ,public java.lang.String getSubject() ,public java.lang.String getTitlePopup() ,public void setBorderStyle(org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary) ,public void setConstantOpacity(float) ,public void setCreationDate(java.util.Calendar) ,public void setExternalData(org.apache.pdfbox.pdmodel.interactive.annotation.PDExternalDataDictionary) ,public void setInReplyTo(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void setIntent(java.lang.String) ,public void setPopup(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationPopup) ,public void setReplyType(java.lang.String) ,public void setRichContents(java.lang.String) ,public void setSubject(java.lang.String) ,public void setTitlePopup(java.lang.String) <variables>public static final java.lang.String RT_GROUP,public static final java.lang.String RT_REPLY
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationSquare.java
PDAnnotationSquare
constructAppearances
class PDAnnotationSquare extends PDAnnotationSquareCircle { /** * The type of annotation. */ public static final String SUB_TYPE = "Square"; private PDAppearanceHandler customAppearanceHandler; public PDAnnotationSquare() { super(SUB_TYPE); } /** * Creates a square annotation from a COSDictionary, expected to be a correct object definition. * * @param field the PDF object to represent as a field. */ public PDAnnotationSquare(COSDictionary field) { super(field); } /** * Set a custom appearance handler for generating the annotations appearance streams. * * @param appearanceHandler custom appearance handler */ public void setCustomAppearanceHandler(PDAppearanceHandler appearanceHandler) { customAppearanceHandler = appearanceHandler; } @Override public void constructAppearances() { this.constructAppearances(null); } @Override public void constructAppearances(PDDocument document) {<FILL_FUNCTION_BODY>} }
if (customAppearanceHandler == null) { PDSquareAppearanceHandler appearanceHandler = new PDSquareAppearanceHandler(this, document); appearanceHandler.generateAppearanceStreams(); } else { customAppearanceHandler.generateAppearanceStreams(); }
303
82
385
<methods>public abstract void constructAppearances() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderEffectDictionary getBorderEffect() ,public org.apache.pdfbox.pdmodel.graphics.color.PDColor getInteriorColor() ,public org.apache.pdfbox.pdmodel.common.PDRectangle getRectDifference() ,public float[] getRectDifferences() ,public void setBorderEffect(org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderEffectDictionary) ,public void setInteriorColor(org.apache.pdfbox.pdmodel.graphics.color.PDColor) ,public void setRectDifference(org.apache.pdfbox.pdmodel.common.PDRectangle) ,public void setRectDifferences(float) ,public void setRectDifferences(float, float, float, float) <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationSquiggly.java
PDAnnotationSquiggly
constructAppearances
class PDAnnotationSquiggly extends PDAnnotationTextMarkup { /** * The type of annotation. */ public static final String SUB_TYPE = "Squiggly"; private PDAppearanceHandler customAppearanceHandler; /** * Constructor. */ public PDAnnotationSquiggly() { super(SUB_TYPE); } /** * Constructor. * * @param dict The annotations dictionary. */ public PDAnnotationSquiggly(COSDictionary dict) { super(dict); } /** * Set a custom appearance handler for generating the annotations appearance streams. * * @param appearanceHandler custom appearance handler */ public void setCustomAppearanceHandler(PDAppearanceHandler appearanceHandler) { customAppearanceHandler = appearanceHandler; } @Override public void constructAppearances() { this.constructAppearances(null); } @Override public void constructAppearances(PDDocument document) {<FILL_FUNCTION_BODY>} }
if (customAppearanceHandler == null) { PDSquigglyAppearanceHandler appearanceHandler = new PDSquigglyAppearanceHandler(this, document); appearanceHandler.generateAppearanceStreams(); } else { customAppearanceHandler.generateAppearanceStreams(); }
301
86
387
<methods>public float[] getQuadPoints() ,public final void setQuadPoints(float[]) <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationStrikeout.java
PDAnnotationStrikeout
constructAppearances
class PDAnnotationStrikeout extends PDAnnotationTextMarkup { /** * The type of annotation. */ public static final String SUB_TYPE = "StrikeOut"; private PDAppearanceHandler customAppearanceHandler; /** * Constructor. */ public PDAnnotationStrikeout() { super(SUB_TYPE); } /** * Constructor. * * @param dict The annotations dictionary. */ public PDAnnotationStrikeout(COSDictionary dict) { super(dict); } /** * Set a custom appearance handler for generating the annotations appearance streams. * * @param appearanceHandler custom appearance handler */ public void setCustomAppearanceHandler(PDAppearanceHandler appearanceHandler) { customAppearanceHandler = appearanceHandler; } @Override public void constructAppearances() { this.constructAppearances(null); } @Override public void constructAppearances(PDDocument document) {<FILL_FUNCTION_BODY>} }
if (customAppearanceHandler == null) { PDStrikeoutAppearanceHandler appearanceHandler = new PDStrikeoutAppearanceHandler(this, document); appearanceHandler.generateAppearanceStreams(); } else { customAppearanceHandler.generateAppearanceStreams(); }
301
88
389
<methods>public float[] getQuadPoints() ,public final void setQuadPoints(float[]) <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationText.java
PDAnnotationText
constructAppearances
class PDAnnotationText extends PDAnnotationMarkup { private PDAppearanceHandler customAppearanceHandler; /* * The various values of the Text as defined in the PDF 1.7 reference Table 172 */ /** * Constant for the name of a text annotation. */ public static final String NAME_COMMENT = "Comment"; /** * Constant for the name of a text annotation. */ public static final String NAME_KEY = "Key"; /** * Constant for the name of a text annotation. */ public static final String NAME_NOTE = "Note"; /** * Constant for the name of a text annotation. */ public static final String NAME_HELP = "Help"; /** * Constant for the name of a text annotation. */ public static final String NAME_NEW_PARAGRAPH = "NewParagraph"; /** * Constant for the name of a text annotation. */ public static final String NAME_PARAGRAPH = "Paragraph"; /** * Constant for the name of a text annotation. */ public static final String NAME_INSERT = "Insert"; /** * Constant for the name of a circle annotation. */ public static final String NAME_CIRCLE = "Circle"; /** * Constant for the name of a cross annotation. */ public static final String NAME_CROSS = "Cross"; /** * Constant for the name of a star annotation. */ public static final String NAME_STAR = "Star"; /** * Constant for the name of a check annotation. */ public static final String NAME_CHECK = "Check"; /** * Constant for the name of a right arrow annotation. */ public static final String NAME_RIGHT_ARROW = "RightArrow"; /** * Constant for the name of a right pointer annotation. */ public static final String NAME_RIGHT_POINTER = "RightPointer"; /** * Constant for the name of a crosshairs annotation. */ public static final String NAME_UP_ARROW = "UpArrow"; /** * Constant for the name of a crosshairs annotation. */ public static final String NAME_UP_LEFT_ARROW = "UpLeftArrow"; /** * Constant for the name of a crosshairs annotation. */ public static final String NAME_CROSS_HAIRS = "CrossHairs"; /** * The type of annotation. */ public static final String SUB_TYPE = "Text"; /** * Constructor. */ public PDAnnotationText() { getCOSObject().setName(COSName.SUBTYPE, SUB_TYPE); } /** * Creates a Text annotation from a COSDictionary, expected to be a correct object definition. * * @param field the PDF object to represent as a field. */ public PDAnnotationText(COSDictionary field) { super(field); } /** * This will set initial state of the annotation, open or closed. * * @param open Boolean value, true = open false = closed */ public void setOpen(boolean open) { getCOSObject().setBoolean(COSName.getPDFName("Open"), open); } /** * This will retrieve the initial state of the annotation, open Or closed (default closed). * * @return The initial state, true = open false = closed */ public boolean getOpen() { return getCOSObject().getBoolean(COSName.getPDFName("Open"), false); } /** * This will set the name (and hence appearance, AP taking precedence) For this annotation. See the NAME_XXX * constants for valid values. * * @param name The name of the annotation */ public void setName(String name) { getCOSObject().setName(COSName.NAME, name); } /** * This will retrieve the name (and hence appearance, AP taking precedence) For this annotation. The default is * NOTE. * * @return The name of this annotation, see the NAME_XXX constants. */ public String getName() { return getCOSObject().getNameAsString(COSName.NAME, NAME_NOTE); } /** * This will retrieve the annotation state. * * @return the annotation state */ public String getState() { return this.getCOSObject().getString(COSName.STATE); } /** * This will set the annotation state. * * @param state the annotation state */ public void setState(String state) { this.getCOSObject().setString(COSName.STATE, state); } /** * This will retrieve the annotation state model. * * @return the annotation state model */ public String getStateModel() { return this.getCOSObject().getString(COSName.STATE_MODEL); } /** * This will set the annotation state model. Allowed values are "Marked" and "Review" * * @param stateModel the annotation state model */ public void setStateModel(String stateModel) { this.getCOSObject().setString(COSName.STATE_MODEL, stateModel); } /** * Set a custom appearance handler for generating the annotations appearance streams. * * @param appearanceHandler custom appearance handler */ public void setCustomAppearanceHandler(PDAppearanceHandler appearanceHandler) { customAppearanceHandler = appearanceHandler; } @Override public void constructAppearances() { this.constructAppearances(null); } @Override public void constructAppearances(PDDocument document) {<FILL_FUNCTION_BODY>} }
if (customAppearanceHandler == null) { PDTextAppearanceHandler appearanceHandler = new PDTextAppearanceHandler(this, document); appearanceHandler.generateAppearanceStreams(); } else { customAppearanceHandler.generateAppearanceStreams(); }
1,557
82
1,639
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary getBorderStyle() ,public float getConstantOpacity() ,public java.util.Calendar getCreationDate() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDExternalDataDictionary getExternalData() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation getInReplyTo() throws java.io.IOException,public java.lang.String getIntent() ,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationPopup getPopup() ,public java.lang.String getReplyType() ,public java.lang.String getRichContents() ,public java.lang.String getSubject() ,public java.lang.String getTitlePopup() ,public void setBorderStyle(org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary) ,public void setConstantOpacity(float) ,public void setCreationDate(java.util.Calendar) ,public void setExternalData(org.apache.pdfbox.pdmodel.interactive.annotation.PDExternalDataDictionary) ,public void setInReplyTo(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void setIntent(java.lang.String) ,public void setPopup(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationPopup) ,public void setReplyType(java.lang.String) ,public void setRichContents(java.lang.String) ,public void setSubject(java.lang.String) ,public void setTitlePopup(java.lang.String) <variables>public static final java.lang.String RT_GROUP,public static final java.lang.String RT_REPLY
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationUnderline.java
PDAnnotationUnderline
constructAppearances
class PDAnnotationUnderline extends PDAnnotationTextMarkup { /** * The type of annotation. */ public static final String SUB_TYPE = "Underline"; private PDAppearanceHandler customAppearanceHandler; /** * Constructor. */ public PDAnnotationUnderline() { super(SUB_TYPE); } /** * Constructor. * * @param dict The annotations dictionary. */ public PDAnnotationUnderline(COSDictionary dict) { super(dict); } /** * Set a custom appearance handler for generating the annotations appearance streams. * * @param appearanceHandler custom appearance handler */ public void setCustomAppearanceHandler(PDAppearanceHandler appearanceHandler) { customAppearanceHandler = appearanceHandler; } @Override public void constructAppearances() { this.constructAppearances(null); } @Override public void constructAppearances(PDDocument document) {<FILL_FUNCTION_BODY>} }
if (customAppearanceHandler == null) { PDUnderlineAppearanceHandler appearanceHandler = new PDUnderlineAppearanceHandler(this, document); appearanceHandler.generateAppearanceStreams(); } else { customAppearanceHandler.generateAppearanceStreams(); }
293
84
377
<methods>public float[] getQuadPoints() ,public final void setQuadPoints(float[]) <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAppearanceCharacteristicsDictionary.java
PDAppearanceCharacteristicsDictionary
getColor
class PDAppearanceCharacteristicsDictionary implements COSObjectable { private final COSDictionary dictionary; /** * Constructor. * * @param dict dictionary */ public PDAppearanceCharacteristicsDictionary(COSDictionary dict) { this.dictionary = dict; } /** * returns the dictionary. * * @return the dictionary */ @Override public COSDictionary getCOSObject() { return this.dictionary; } /** * This will retrieve the rotation of the annotation widget. It must be a multiple of 90. Default is 0 * * @return the rotation */ public int getRotation() { return this.getCOSObject().getInt(COSName.R, 0); } /** * This will set the rotation. * * @param rotation the rotation as a multiple of 90 */ public void setRotation(int rotation) { this.getCOSObject().setInt(COSName.R, rotation); } /** * This will retrieve the border color. * * @return the border color. */ public PDColor getBorderColour() { return getColor(COSName.BC); } /** * This will set the border color. * * @param c the border color */ public void setBorderColour(PDColor c) { this.getCOSObject().setItem(COSName.BC, c.toCOSArray()); } /** * This will retrieve the background color. * * @return the background color. */ public PDColor getBackground() { return getColor(COSName.BG); } /** * This will set the background color. * * @param c the background color */ public void setBackground(PDColor c) { this.getCOSObject().setItem(COSName.BG, c.toCOSArray()); } /** * This will retrieve the normal caption. * * @return the normal caption. */ public String getNormalCaption() { return this.getCOSObject().getString(COSName.CA); } /** * This will set the normal caption. * * @param caption the normal caption */ public void setNormalCaption(String caption) { this.getCOSObject().setString(COSName.CA, caption); } /** * This will retrieve the rollover caption. * * @return the rollover caption. */ public String getRolloverCaption() { return this.getCOSObject().getString(COSName.RC); } /** * This will set the rollover caption. * * @param caption the rollover caption */ public void setRolloverCaption(String caption) { this.getCOSObject().setString(COSName.RC, caption); } /** * This will retrieve the alternate caption. * * @return the alternate caption. */ public String getAlternateCaption() { return this.getCOSObject().getString(COSName.AC); } /** * This will set the alternate caption. * * @param caption the alternate caption */ public void setAlternateCaption(String caption) { this.getCOSObject().setString(COSName.AC, caption); } /** * This will retrieve the normal icon. * * @return the normal icon. */ public PDFormXObject getNormalIcon() { COSStream stream = getCOSObject().getCOSStream(COSName.I); return stream != null ? new PDFormXObject(stream) : null; } /** * This will retrieve the rollover icon. * * @return the rollover icon */ public PDFormXObject getRolloverIcon() { COSStream stream = getCOSObject().getCOSStream(COSName.RI); return stream != null ? new PDFormXObject(stream) : null; } /** * This will retrieve the alternate icon. * * @return the alternate icon. */ public PDFormXObject getAlternateIcon() { COSStream stream = getCOSObject().getCOSStream(COSName.IX); return stream != null ? new PDFormXObject(stream) : null; } private PDColor getColor(COSName itemName) {<FILL_FUNCTION_BODY>} }
COSArray cs = getCOSObject().getCOSArray(itemName); if (cs != null) { PDColorSpace colorSpace; switch (cs.size()) { case 1: colorSpace = PDDeviceGray.INSTANCE; break; case 3: colorSpace = PDDeviceRGB.INSTANCE; break; case 4: colorSpace = PDDeviceCMYK.INSTANCE; break; default: return null; } return new PDColor(cs, colorSpace); } return null;
1,295
165
1,460
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAppearanceEntry.java
PDAppearanceEntry
getSubDictionary
class PDAppearanceEntry implements COSObjectable { private COSDictionary entry; private PDAppearanceEntry() { } /** * Constructor for reading. * * @param entry the dictionary of the appearance entry */ public PDAppearanceEntry(COSDictionary entry) { this.entry = entry; } @Override public COSDictionary getCOSObject() { return entry; } /** * Returns true if this entry is an appearance subdictionary. * * @return true if this entry is an appearance subdictionary */ public boolean isSubDictionary() { return !(this.entry instanceof COSStream); } /** * Returns true if this entry is an appearance stream. * * @return true if this entry is an appearance stream */ public boolean isStream() { return this.entry instanceof COSStream; } /** * Returns the entry as an appearance stream. * * @return the entry as an appearance stream * * @throws IllegalStateException if this entry is not an appearance stream */ public PDAppearanceStream getAppearanceStream() { if (!isStream()) { throw new IllegalStateException("This entry is not an appearance stream"); } return new PDAppearanceStream((COSStream) entry); } /** * Returns the entry as an appearance subdictionary. * * @return the entry as an appearance subdictionary * * @throws IllegalStateException if this entry is not an appearance subdictionary */ public Map<COSName, PDAppearanceStream> getSubDictionary() {<FILL_FUNCTION_BODY>} }
if (!isSubDictionary()) { throw new IllegalStateException("This entry is not an appearance subdictionary"); } COSDictionary dict = entry; Map<COSName, PDAppearanceStream> map = new HashMap<>(); for (COSName name : dict.keySet()) { COSStream stream = dict.getCOSStream(name); // the file from PDFBOX-1599 contains /null as its entry, so we skip non-stream entries if (stream != null) { map.put(name, new PDAppearanceStream(stream)); } } return new COSDictionaryMap<>(map, dict);
470
179
649
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDBorderStyleDictionary.java
PDBorderStyleDictionary
getWidth
class PDBorderStyleDictionary implements COSObjectable { /* * The various values of the style for the border as defined in the PDF 1.6 reference Table 8.13 */ /** * Constant for the name of a solid style. */ public static final String STYLE_SOLID = "S"; /** * Constant for the name of a dashed style. */ public static final String STYLE_DASHED = "D"; /** * Constant for the name of a beveled style. */ public static final String STYLE_BEVELED = "B"; /** * Constant for the name of a inset style. */ public static final String STYLE_INSET = "I"; /** * Constant for the name of a underline style. */ public static final String STYLE_UNDERLINE = "U"; private final COSDictionary dictionary; /** * Constructor. */ public PDBorderStyleDictionary() { dictionary = new COSDictionary(); } /** * Constructor. * * @param dict a border style dictionary. */ public PDBorderStyleDictionary(COSDictionary dict) { dictionary = dict; } /** * returns the dictionary. * * @return the dictionary */ @Override public COSDictionary getCOSObject() { return dictionary; } /** * This will set the border width in points, 0 = no border. * * There is a bug in Adobe Reader DC, float values are ignored for text field widgets. As a * workaround, floats that are integers (e.g. 2.0) are written as integer in the PDF. * <p> * In Adobe Acrobat DC, the values are shown as "0 = Invisible, 1 = Thin, 2 = Medium, 3 = Thick" * for widget and link annotations. * * @param w float the width in points */ public void setWidth(float w) { // PDFBOX-3929 workaround if (Float.compare(w, (int) w) == 0) { getCOSObject().setInt(COSName.W, (int) w); } else { getCOSObject().setFloat(COSName.W, w); } } /** * This will retrieve the border width in points, 0 = no border. * * @return The width of the border in points. */ public float getWidth() {<FILL_FUNCTION_BODY>} /** * This will set the border style, see the STYLE_* constants for valid values. * * @param s the border style to use */ public void setStyle(String s) { getCOSObject().setName(COSName.S, s); } /** * This will retrieve the border style, see the STYLE_* constants for valid values. * * @return the style of the border */ public String getStyle() { return getCOSObject().getNameAsString(COSName.S, STYLE_SOLID); } /** * This will set the dash style used for drawing the border. * * @param dashArray the dash style to use */ public void setDashStyle(COSArray dashArray) { getCOSObject().setItem(COSName.D, dashArray); } /** * This will retrieve the dash style used for drawing the border. * * @return the dash style of the border */ public PDLineDashPattern getDashStyle() { COSArray d = getCOSObject().getCOSArray(COSName.D); if (d == null) { d = new COSArray(); d.add(COSInteger.THREE); getCOSObject().setItem(COSName.D, d); } return new PDLineDashPattern(d, 0); } }
if (getCOSObject().getDictionaryObject(COSName.W) instanceof COSName) { // replicate Adobe behavior although it contradicts the specification // https://github.com/mozilla/pdf.js/issues/10385 return 0; } return getCOSObject().getFloat(COSName.W, 1);
1,080
95
1,175
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/AnnotationBorder.java
AnnotationBorder
getAnnotationBorder
class AnnotationBorder { float[] dashArray = null; boolean underline = false; float width = 0; // return border info. BorderStyle must be provided as parameter because // method is not available in the base class static AnnotationBorder getAnnotationBorder(PDAnnotation annotation, PDBorderStyleDictionary borderStyle) {<FILL_FUNCTION_BODY>} }
AnnotationBorder ab = new AnnotationBorder(); if (borderStyle == null) { COSArray border = annotation.getBorder(); if (border.size() >= 3 && border.getObject(2) instanceof COSNumber) { ab.width = ((COSNumber) border.getObject(2)).floatValue(); } if (border.size() > 3) { COSBase base3 = border.getObject(3); if (base3 instanceof COSArray) { ab.dashArray = ((COSArray) base3).toFloatArray(); } } } else { ab.width = borderStyle.getWidth(); if (borderStyle.getStyle().equals(PDBorderStyleDictionary.STYLE_DASHED)) { ab.dashArray = borderStyle.getDashStyle().getDashArray(); } if (borderStyle.getStyle().equals(PDBorderStyleDictionary.STYLE_UNDERLINE)) { ab.underline = true; } } if (ab.dashArray != null) { boolean allZero = true; for (float f : ab.dashArray) { if (Float.compare(f, 0) != 0) { allZero = false; break; } } if (allZero) { ab.dashArray = null; } } return ab;
100
378
478
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDCaretAppearanceHandler.java
PDCaretAppearanceHandler
generateNormalAppearance
class PDCaretAppearanceHandler extends PDAbstractAppearanceHandler { private static final Logger LOG = LogManager.getLogger(PDCaretAppearanceHandler.class); public PDCaretAppearanceHandler(PDAnnotation annotation) { super(annotation); } public PDCaretAppearanceHandler(PDAnnotation annotation, PDDocument document) { super(annotation, document); } @Override public void generateNormalAppearance() {<FILL_FUNCTION_BODY>} @Override public void generateRolloverAppearance() { // TODO to be implemented } @Override public void generateDownAppearance() { // TODO to be implemented } }
PDAnnotationCaret annotation = (PDAnnotationCaret) getAnnotation(); try (PDAppearanceContentStream contentStream = getNormalAppearanceAsContentStream()) { contentStream.setStrokingColor(getColor()); contentStream.setNonStrokingColor(getColor()); setOpacity(contentStream, annotation.getConstantOpacity()); PDRectangle rect = getRectangle(); PDRectangle bbox = new PDRectangle(rect.getWidth(), rect.getHeight()); PDAppearanceStream pdAppearanceStream = annotation.getNormalAppearanceStream(); if (!annotation.getCOSObject().containsKey(COSName.RD)) { // Adobe creates the /RD entry with a number that is decided // by dividing the height by 10, with a maximum result of 5. // That number is then used to enlarge the bbox and the rectangle and added to the // translation values in the matrix and also used for the line width // (not here because it has no effect, see comment near fill() ). // The curves are based on the original rectangle. float rd = Math.min(rect.getHeight() / 10, 5); annotation.setRectDifferences(rd); bbox = new PDRectangle(-rd, -rd, rect.getWidth() + 2 * rd, rect.getHeight() + 2 * rd); Matrix matrix = pdAppearanceStream.getMatrix(); pdAppearanceStream.setMatrix(matrix.createAffineTransform()); PDRectangle rect2 = new PDRectangle(rect.getLowerLeftX() - rd, rect.getLowerLeftY() - rd, rect.getWidth() + 2 * rd, rect.getHeight() + 2 * rd); annotation.setRectangle(rect2); } pdAppearanceStream.setBBox(bbox); float halfX = rect.getWidth() / 2; float halfY = rect.getHeight() / 2; contentStream.moveTo(0, 0); contentStream.curveTo(halfX, 0, halfX, halfY, halfX, rect.getHeight()); contentStream.curveTo(halfX, halfY, halfX, 0, rect.getWidth(), 0); contentStream.closePath(); contentStream.fill(); // Adobe has an additional stroke, but it has no effect // because fill "consumes" the path. } catch (IOException e) { LOG.error(e); }
197
657
854
<methods>public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation, org.apache.pdfbox.pdmodel.PDDocument) <variables>protected static final Set<java.lang.String> ANGLED_STYLES,static final double ARROW_ANGLE,protected static final Set<java.lang.String> INTERIOR_COLOR_STYLES,protected static final Set<java.lang.String> SHORT_STYLES,private final non-sealed org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation annotation,private org.apache.pdfbox.pdmodel.font.PDFont defaultFont,protected final non-sealed org.apache.pdfbox.pdmodel.PDDocument document
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDCircleAppearanceHandler.java
PDCircleAppearanceHandler
generateNormalAppearance
class PDCircleAppearanceHandler extends PDAbstractAppearanceHandler { private static final Logger LOG = LogManager.getLogger(PDCircleAppearanceHandler.class); public PDCircleAppearanceHandler(PDAnnotation annotation) { super(annotation); } public PDCircleAppearanceHandler(PDAnnotation annotation, PDDocument document) { super(annotation, document); } @Override public void generateNormalAppearance() {<FILL_FUNCTION_BODY>} @Override public void generateRolloverAppearance() { // TODO to be implemented } @Override public void generateDownAppearance() { // TODO to be implemented } /** * Get the line with of the border. * * Get the width of the line used to draw a border around the annotation. * This may either be specified by the annotation dictionaries Border * setting or by the W entry in the BS border style dictionary. If both are * missing the default width is 1. * * @return the line width */ // TODO: according to the PDF spec the use of the BS entry is annotation // specific // so we will leave that to be implemented by individual handlers. // If at the end all annotations support the BS entry this can be handled // here and removed from the individual handlers. float getLineWidth() { PDAnnotationMarkup annotation = (PDAnnotationMarkup) getAnnotation(); PDBorderStyleDictionary bs = annotation.getBorderStyle(); if (bs != null) { return bs.getWidth(); } COSArray borderCharacteristics = annotation.getBorder(); if (borderCharacteristics.size() >= 3) { COSBase base = borderCharacteristics.getObject(2); if (base instanceof COSNumber) { return ((COSNumber) base).floatValue(); } } return 1; } }
float lineWidth = getLineWidth(); PDAnnotationCircle annotation = (PDAnnotationCircle) getAnnotation(); try (PDAppearanceContentStream contentStream = getNormalAppearanceAsContentStream()) { boolean hasStroke = contentStream.setStrokingColorOnDemand(getColor()); boolean hasBackground = contentStream .setNonStrokingColorOnDemand(annotation.getInteriorColor()); setOpacity(contentStream, annotation.getConstantOpacity()); contentStream.setBorderLine(lineWidth, annotation.getBorderStyle(), annotation.getBorder()); PDBorderEffectDictionary borderEffect = annotation.getBorderEffect(); if (borderEffect != null && borderEffect.getStyle().equals(PDBorderEffectDictionary.STYLE_CLOUDY)) { CloudyBorder cloudyBorder = new CloudyBorder(contentStream, borderEffect.getIntensity(), lineWidth, getRectangle()); cloudyBorder.createCloudyEllipse(annotation.getRectDifference()); annotation.setRectangle(cloudyBorder.getRectangle()); annotation.setRectDifference(cloudyBorder.getRectDifference()); PDAppearanceStream appearanceStream = annotation.getNormalAppearanceStream(); appearanceStream.setBBox(cloudyBorder.getBBox()); appearanceStream.setMatrix(cloudyBorder.getMatrix()); } else { // Acrobat applies a padding to each side of the bbox so the line is completely within // the bbox. PDRectangle borderBox = handleBorderBox(annotation, lineWidth); // lower left corner float x0 = borderBox.getLowerLeftX(); float y0 = borderBox.getLowerLeftY(); // upper right corner float x1 = borderBox.getUpperRightX(); float y1 = borderBox.getUpperRightY(); // mid points float xm = x0 + borderBox.getWidth() / 2; float ym = y0 + borderBox.getHeight() / 2; // see http://spencermortensen.com/articles/bezier-circle/ // the below number was calculated from sampling content streams // generated using Adobe Reader float magic = 0.55555417f; // control point offsets float vOffset = borderBox.getHeight() / 2 * magic; float hOffset = borderBox.getWidth() / 2 * magic; contentStream.moveTo(xm, y1); contentStream.curveTo((xm + hOffset), y1, x1, (ym + vOffset), x1, ym); contentStream.curveTo(x1, (ym - vOffset), (xm + hOffset), y0, xm, y0); contentStream.curveTo((xm - hOffset), y0, x0, (ym - vOffset), x0, ym); contentStream.curveTo(x0, (ym + vOffset), (xm - hOffset), y1, xm, y1); contentStream.closePath(); } contentStream.drawShape(lineWidth, hasStroke, hasBackground); } catch (IOException e) { LOG.error(e); }
526
816
1,342
<methods>public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation, org.apache.pdfbox.pdmodel.PDDocument) <variables>protected static final Set<java.lang.String> ANGLED_STYLES,static final double ARROW_ANGLE,protected static final Set<java.lang.String> INTERIOR_COLOR_STYLES,protected static final Set<java.lang.String> SHORT_STYLES,private final non-sealed org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation annotation,private org.apache.pdfbox.pdmodel.font.PDFont defaultFont,protected final non-sealed org.apache.pdfbox.pdmodel.PDDocument document
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDFileAttachmentAppearanceHandler.java
PDFileAttachmentAppearanceHandler
generateNormalAppearance
class PDFileAttachmentAppearanceHandler extends PDAbstractAppearanceHandler { private static final Logger LOG = LogManager.getLogger(PDFileAttachmentAppearanceHandler.class); public PDFileAttachmentAppearanceHandler(PDAnnotation annotation) { super(annotation); } public PDFileAttachmentAppearanceHandler(PDAnnotation annotation, PDDocument document) { super(annotation, document); } @Override public void generateNormalAppearance() {<FILL_FUNCTION_BODY>} /** * Draw a paperclip. Shape is from * <a href="https://raw.githubusercontent.com/Iconscout/unicons/master/svg/line/paperclip.svg">Iconscout</a> * (Apache licensed). * * @param contentStream * @throws IOException */ private void drawPaperclip(final PDAppearanceContentStream contentStream) throws IOException { contentStream.moveTo(13.574f, 9.301f); contentStream.lineTo(8.926f, 13.949f); contentStream.curveTo(7.648f, 15.227f, 5.625f, 15.227f, 4.426f, 13.949f); contentStream.curveTo(3.148f, 12.676f, 3.148f, 10.648f, 4.426f, 9.449f); contentStream.lineTo(10.426f, 3.449f); contentStream.curveTo(11.176f, 2.773f, 12.301f, 2.773f, 13.051f, 3.449f); contentStream.curveTo(13.801f, 4.199f, 13.801f, 5.398f, 13.051f, 6.074f); contentStream.lineTo(7.875f, 11.25f); contentStream.curveTo(7.648f, 11.477f, 7.273f, 11.477f, 7.051f, 11.25f); contentStream.curveTo(6.824f, 11.023f, 6.824f, 10.648f, 7.051f, 10.426f); contentStream.lineTo(10.875f, 6.602f); contentStream.curveTo(11.176f, 6.301f, 11.176f, 5.852f, 10.875f, 5.551f); contentStream.curveTo(10.574f, 5.25f, 10.125f, 5.25f, 9.824f, 5.551f); contentStream.lineTo(6f, 9.449f); contentStream.curveTo(5.176f, 10.273f, 5.176f, 11.551f, 6f, 12.375f); contentStream.curveTo(6.824f, 13.125f, 8.102f, 13.125f, 8.926f, 12.375f); contentStream.lineTo(14.102f, 7.199f); contentStream.curveTo(15.449f, 5.852f, 15.449f, 3.75f, 14.102f, 2.398f); contentStream.curveTo(12.75f, 1.051f, 10.648f, 1.051f, 9.301f, 2.398f); contentStream.lineTo(3.301f, 8.398f); contentStream.curveTo(2.398f, 9.301f, 1.949f, 10.5f, 1.949f, 11.699f); contentStream.curveTo(1.949f, 14.324f, 4.051f, 16.352f, 6.676f, 16.352f); contentStream.curveTo(7.949f, 16.352f, 9.074f, 15.824f, 9.977f, 15f); contentStream.lineTo(14.625f, 10.352f); contentStream.curveTo(14.926f, 10.051f, 14.926f, 9.602f, 14.625f, 9.301f); contentStream.curveTo(14.324f, 9f, 13.875f, 9f, 13.574f, 9.301f); contentStream.closePath(); contentStream.fill(); } @Override public void generateRolloverAppearance() { // No rollover appearance generated } @Override public void generateDownAppearance() { // No down appearance generated } }
PDAnnotationFileAttachment annotation = (PDAnnotationFileAttachment) getAnnotation(); PDRectangle rect = getRectangle(); if (rect == null) { return; } try (PDAppearanceContentStream contentStream = getNormalAppearanceAsContentStream()) { setOpacity(contentStream, annotation.getConstantOpacity()); // minimum code of PDTextAppearanceHandler.adjustRectAndBBox() int size = 18; rect.setUpperRightX(rect.getLowerLeftX() + size); rect.setLowerLeftY(rect.getUpperRightY() - size); annotation.setRectangle(rect); annotation.getNormalAppearanceStream().setBBox(new PDRectangle(size, size)); //TODO support Graph, PushPin, Paperclip, Tag drawPaperclip(contentStream); } catch (IOException e) { LOG.error(e); }
1,523
251
1,774
<methods>public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation, org.apache.pdfbox.pdmodel.PDDocument) <variables>protected static final Set<java.lang.String> ANGLED_STYLES,static final double ARROW_ANGLE,protected static final Set<java.lang.String> INTERIOR_COLOR_STYLES,protected static final Set<java.lang.String> SHORT_STYLES,private final non-sealed org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation annotation,private org.apache.pdfbox.pdmodel.font.PDFont defaultFont,protected final non-sealed org.apache.pdfbox.pdmodel.PDDocument document
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDInkAppearanceHandler.java
PDInkAppearanceHandler
generateNormalAppearance
class PDInkAppearanceHandler extends PDAbstractAppearanceHandler { private static final Logger LOG = LogManager.getLogger(PDInkAppearanceHandler.class); public PDInkAppearanceHandler(PDAnnotation annotation) { super(annotation); } public PDInkAppearanceHandler(PDAnnotation annotation, PDDocument document) { super(annotation, document); } @Override public void generateNormalAppearance() {<FILL_FUNCTION_BODY>} @Override public void generateRolloverAppearance() { // No rollover appearance generated } @Override public void generateDownAppearance() { // No down appearance generated } }
PDAnnotationInk ink = (PDAnnotationInk) getAnnotation(); PDColor color = ink.getColor(); if (color == null || color.getComponents().length == 0) { return; } // PDF spec does not mention /Border for ink annotations, but it is used if /BS is not available AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(ink, ink.getBorderStyle()); if (Float.compare(ab.width, 0) == 0) { return; } // Adjust rectangle even if not empty // file from PDF.js issue 13447 //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 (float[] pathArray : ink.getInkList()) { int nPoints = pathArray.length / 2; for (int i = 0; i < nPoints; ++i) { float x = pathArray[i * 2]; float y = pathArray[i * 2 + 1]; minX = Math.min(minX, x); minY = Math.min(minY, y); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); } } PDRectangle rect = ink.getRectangle(); if (rect == null) { return; } rect.setLowerLeftX(Math.min(minX - ab.width * 2, rect.getLowerLeftX())); rect.setLowerLeftY(Math.min(minY - ab.width * 2, rect.getLowerLeftY())); rect.setUpperRightX(Math.max(maxX + ab.width * 2, rect.getUpperRightX())); rect.setUpperRightY(Math.max(maxY + ab.width * 2, rect.getUpperRightY())); ink.setRectangle(rect); try (PDAppearanceContentStream cs = getNormalAppearanceAsContentStream()) { setOpacity(cs, ink.getConstantOpacity()); cs.setStrokingColor(color); if (ab.dashArray != null) { cs.setLineDashPattern(ab.dashArray, 0); } cs.setLineWidth(ab.width); for (float[] pathArray : ink.getInkList()) { int nPoints = pathArray.length / 2; // "When drawn, the points shall be connected by straight lines or curves // in an implementation-dependent way" - we do lines. for (int i = 0; i < nPoints; ++i) { float x = pathArray[i * 2]; float y = pathArray[i * 2 + 1]; if (i == 0) { cs.moveTo(x, y); } else { cs.lineTo(x, y); } } cs.stroke(); } } catch (IOException ex) { LOG.error(ex); }
201
846
1,047
<methods>public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation, org.apache.pdfbox.pdmodel.PDDocument) <variables>protected static final Set<java.lang.String> ANGLED_STYLES,static final double ARROW_ANGLE,protected static final Set<java.lang.String> INTERIOR_COLOR_STYLES,protected static final Set<java.lang.String> SHORT_STYLES,private final non-sealed org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation annotation,private org.apache.pdfbox.pdmodel.font.PDFont defaultFont,protected final non-sealed org.apache.pdfbox.pdmodel.PDDocument document
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDLinkAppearanceHandler.java
PDLinkAppearanceHandler
generateNormalAppearance
class PDLinkAppearanceHandler extends PDAbstractAppearanceHandler { private static final Logger LOG = LogManager.getLogger(PDLinkAppearanceHandler.class); public PDLinkAppearanceHandler(PDAnnotation annotation) { super(annotation); } public PDLinkAppearanceHandler(PDAnnotation annotation, PDDocument document) { super(annotation, document); } @Override public void generateNormalAppearance() {<FILL_FUNCTION_BODY>} @Override public void generateRolloverAppearance() { // No rollover appearance generated for a link annotation } @Override public void generateDownAppearance() { // No down appearance generated for a link annotation } /** * Get the line with of the border. * * Get the width of the line used to draw a border around the annotation. * This may either be specified by the annotation dictionaries Border * setting or by the W entry in the BS border style dictionary. If both are * missing the default width is 1. * * @return the line width */ // TODO: according to the PDF spec the use of the BS entry is annotation // specific // so we will leave that to be implemented by individual handlers. // If at the end all annotations support the BS entry this can be handled // here and removed from the individual handlers. float getLineWidth() { PDAnnotationLink annotation = (PDAnnotationLink) getAnnotation(); PDBorderStyleDictionary bs = annotation.getBorderStyle(); if (bs != null) { return bs.getWidth(); } COSArray borderCharacteristics = annotation.getBorder(); if (borderCharacteristics.size() >= 3) { COSBase base = borderCharacteristics.getObject(2); if (base instanceof COSNumber) { return ((COSNumber) base).floatValue(); } } return 1; } }
PDAnnotationLink annotation = (PDAnnotationLink) getAnnotation(); PDRectangle rect = annotation.getRectangle(); if (rect == null) { // 660402-p1-AnnotationEmptyRect.pdf has /Rect entry with 0 elements return; } // Adobe doesn't generate an appearance for a link annotation float lineWidth = getLineWidth(); try (PDAppearanceContentStream contentStream = getNormalAppearanceAsContentStream()) { PDColor color = annotation.getColor(); if (color == null) { // spec is unclear, but black is what Adobe does color = new PDColor(new float[] { 0 }, PDDeviceGray.INSTANCE); } boolean hasStroke = contentStream.setStrokingColorOnDemand(color); contentStream.setBorderLine(lineWidth, annotation.getBorderStyle(), annotation.getBorder()); // Acrobat applies a padding to each side of the bbox so the line is completely within // the bbox. PDRectangle borderEdge = getPaddedRectangle(getRectangle(),lineWidth/2); float[] pathsArray = annotation.getQuadPoints(); if (pathsArray != null) { // QuadPoints shall be ignored if any coordinate in the array lies outside // the region specified by Rect. for (int i = 0; i < pathsArray.length / 2; ++i) { if (!rect.contains(pathsArray[i * 2], pathsArray[i * 2 + 1])) { LOG.warn( "At least one /QuadPoints entry ({};{}) is outside of rectangle, {}, /QuadPoints are ignored and /Rect is used instead", pathsArray[i * 2], pathsArray[i * 2 + 1], rect); pathsArray = null; break; } } } if (pathsArray == null) { // Convert rectangle coordinates as if it was a /QuadPoints entry pathsArray = new float[8]; pathsArray[0] = borderEdge.getLowerLeftX(); pathsArray[1] = borderEdge.getLowerLeftY(); pathsArray[2] = borderEdge.getUpperRightX(); pathsArray[3] = borderEdge.getLowerLeftY(); pathsArray[4] = borderEdge.getUpperRightX(); pathsArray[5] = borderEdge.getUpperRightY(); pathsArray[6] = borderEdge.getLowerLeftX(); pathsArray[7] = borderEdge.getUpperRightY(); } boolean underlined = false; if (pathsArray.length >= 8) { PDBorderStyleDictionary borderStyleDic = annotation.getBorderStyle(); if (borderStyleDic != null) { underlined = PDBorderStyleDictionary.STYLE_UNDERLINE.equals(borderStyleDic.getStyle()); } } int of = 0; while (of + 7 < pathsArray.length) { contentStream.moveTo(pathsArray[of], pathsArray[of + 1]); contentStream.lineTo(pathsArray[of + 2], pathsArray[of + 3]); if (!underlined) { contentStream.lineTo(pathsArray[of + 4], pathsArray[of + 5]); contentStream.lineTo(pathsArray[of + 6], pathsArray[of + 7]); contentStream.closePath(); } of += 8; } contentStream.drawShape(lineWidth, hasStroke, false); } catch (IOException e) { LOG.error(e); }
529
931
1,460
<methods>public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation, org.apache.pdfbox.pdmodel.PDDocument) <variables>protected static final Set<java.lang.String> ANGLED_STYLES,static final double ARROW_ANGLE,protected static final Set<java.lang.String> INTERIOR_COLOR_STYLES,protected static final Set<java.lang.String> SHORT_STYLES,private final non-sealed org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation annotation,private org.apache.pdfbox.pdmodel.font.PDFont defaultFont,protected final non-sealed org.apache.pdfbox.pdmodel.PDDocument document
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDPolygonAppearanceHandler.java
PDPolygonAppearanceHandler
generateNormalAppearance
class PDPolygonAppearanceHandler extends PDAbstractAppearanceHandler { private static final Logger LOG = LogManager.getLogger(PDPolygonAppearanceHandler.class); public PDPolygonAppearanceHandler(PDAnnotation annotation) { super(annotation); } public PDPolygonAppearanceHandler(PDAnnotation annotation, PDDocument document) { super(annotation, document); } @Override public void generateNormalAppearance() {<FILL_FUNCTION_BODY>} private float[][] getPathArray(PDAnnotationPolygon annotation) { // PDF 2.0: Path takes priority over Vertices float[][] pathArray = annotation.getPath(); if (pathArray == null) { // convert PDF 1.* array to PDF 2.0 array float[] verticesArray = annotation.getVertices(); if (verticesArray == null) { return null; } int points = verticesArray.length / 2; pathArray = new float[points][2]; for (int i = 0; i < points; ++i) { pathArray[i][0] = verticesArray[i * 2]; pathArray[i][1] = verticesArray[i * 2 + 1]; } } return pathArray; } @Override public void generateRolloverAppearance() { // No rollover appearance generated for a polygon annotation } @Override public void generateDownAppearance() { // No down appearance generated for a polygon annotation } /** * Get the line with of the border. * * Get the width of the line used to draw a border around the annotation. * This may either be specified by the annotation dictionaries Border * setting or by the W entry in the BS border style dictionary. If both are * missing the default width is 1. * * @return the line width */ // TODO: according to the PDF spec the use of the BS entry is annotation // specific // so we will leave that to be implemented by individual handlers. // If at the end all annotations support the BS entry this can be handled // here and removed from the individual handlers. float getLineWidth() { PDAnnotationMarkup annotation = (PDAnnotationMarkup) getAnnotation(); PDBorderStyleDictionary bs = annotation.getBorderStyle(); if (bs != null) { return bs.getWidth(); } COSArray borderCharacteristics = annotation.getBorder(); if (borderCharacteristics.size() >= 3) { COSBase base = borderCharacteristics.getObject(2); if (base instanceof COSNumber) { return ((COSNumber) base).floatValue(); } } return 1; } }
PDAnnotationPolygon annotation = (PDAnnotationPolygon) getAnnotation(); float lineWidth = getLineWidth(); PDRectangle rect = annotation.getRectangle(); if (rect == null) { return; } // Adjust rectangle even if not empty // CTAN-example-Annotations.pdf p2 float minX = Float.MAX_VALUE; float minY = Float.MAX_VALUE; float maxX = Float.MIN_VALUE; float maxY = Float.MIN_VALUE; float[][] pathArray = getPathArray(annotation); if (pathArray == null) { return; } for (int i = 0; i < pathArray.length; ++i) { for (int j = 0; j < pathArray[i].length / 2; ++j) { float x = pathArray[i][j * 2]; float y = pathArray[i][j * 2 + 1]; minX = Math.min(minX, x); minY = Math.min(minY, y); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); } } rect.setLowerLeftX(Math.min(minX - lineWidth, rect.getLowerLeftX())); rect.setLowerLeftY(Math.min(minY - lineWidth, rect.getLowerLeftY())); rect.setUpperRightX(Math.max(maxX + lineWidth, rect.getUpperRightX())); rect.setUpperRightY(Math.max(maxY + lineWidth, rect.getUpperRightY())); annotation.setRectangle(rect); try (PDAppearanceContentStream contentStream = getNormalAppearanceAsContentStream()) { boolean hasStroke = contentStream.setStrokingColorOnDemand(getColor()); boolean hasBackground = contentStream .setNonStrokingColorOnDemand(annotation.getInteriorColor()); setOpacity(contentStream, annotation.getConstantOpacity()); contentStream.setBorderLine(lineWidth, annotation.getBorderStyle(), annotation.getBorder()); PDBorderEffectDictionary borderEffect = annotation.getBorderEffect(); if (borderEffect != null && borderEffect.getStyle().equals(PDBorderEffectDictionary.STYLE_CLOUDY)) { CloudyBorder cloudyBorder = new CloudyBorder(contentStream, borderEffect.getIntensity(), lineWidth, getRectangle()); cloudyBorder.createCloudyPolygon(pathArray); annotation.setRectangle(cloudyBorder.getRectangle()); PDAppearanceStream appearanceStream = annotation.getNormalAppearanceStream(); appearanceStream.setBBox(cloudyBorder.getBBox()); appearanceStream.setMatrix(cloudyBorder.getMatrix()); } else { // Acrobat applies a padding to each side of the bbox so the line is // completely within the bbox. for (int i = 0; i < pathArray.length; i++) { float[] pointsArray = pathArray[i]; // first array shall be of size 2 and specify the moveto operator if (i == 0 && pointsArray.length == 2) { contentStream.moveTo(pointsArray[0], pointsArray[1]); } else { // entries of length 2 shall be treated as lineto operator if (pointsArray.length == 2) { contentStream.lineTo(pointsArray[0], pointsArray[1]); } else if (pointsArray.length == 6) { contentStream.curveTo(pointsArray[0], pointsArray[1], pointsArray[2], pointsArray[3], pointsArray[4], pointsArray[5]); } } } contentStream.closePath(); } contentStream.drawShape(lineWidth, hasStroke, hasBackground); } catch (IOException e) { LOG.error(e); }
741
1,029
1,770
<methods>public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation, org.apache.pdfbox.pdmodel.PDDocument) <variables>protected static final Set<java.lang.String> ANGLED_STYLES,static final double ARROW_ANGLE,protected static final Set<java.lang.String> INTERIOR_COLOR_STYLES,protected static final Set<java.lang.String> SHORT_STYLES,private final non-sealed org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation annotation,private org.apache.pdfbox.pdmodel.font.PDFont defaultFont,protected final non-sealed org.apache.pdfbox.pdmodel.PDDocument document
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDSquareAppearanceHandler.java
PDSquareAppearanceHandler
generateNormalAppearance
class PDSquareAppearanceHandler extends PDAbstractAppearanceHandler { private static final Logger LOG = LogManager.getLogger(PDSquareAppearanceHandler.class); public PDSquareAppearanceHandler(PDAnnotation annotation) { super(annotation); } public PDSquareAppearanceHandler(PDAnnotation annotation, PDDocument document) { super(annotation, document); } @Override public void generateNormalAppearance() {<FILL_FUNCTION_BODY>} @Override public void generateRolloverAppearance() { // TODO to be implemented } @Override public void generateDownAppearance() { // TODO to be implemented } /** * Get the line with of the border. * * Get the width of the line used to draw a border around the annotation. * This may either be specified by the annotation dictionaries Border * setting or by the W entry in the BS border style dictionary. If both are * missing the default width is 1. * * @return the line width */ // TODO: according to the PDF spec the use of the BS entry is annotation // specific // so we will leave that to be implemented by individual handlers. // If at the end all annotations support the BS entry this can be handled // here and removed from the individual handlers. float getLineWidth() { PDAnnotationMarkup annotation = (PDAnnotationMarkup) getAnnotation(); PDBorderStyleDictionary bs = annotation.getBorderStyle(); if (bs != null) { return bs.getWidth(); } COSArray borderCharacteristics = annotation.getBorder(); if (borderCharacteristics.size() >= 3) { COSBase base = borderCharacteristics.getObject(2); if (base instanceof COSNumber) { return ((COSNumber) base).floatValue(); } } return 1; } }
float lineWidth = getLineWidth(); PDAnnotationSquare annotation = (PDAnnotationSquare) getAnnotation(); try (PDAppearanceContentStream contentStream = getNormalAppearanceAsContentStream()) { boolean hasStroke = contentStream.setStrokingColorOnDemand(getColor()); boolean hasBackground = contentStream .setNonStrokingColorOnDemand(annotation.getInteriorColor()); setOpacity(contentStream, annotation.getConstantOpacity()); contentStream.setBorderLine(lineWidth, annotation.getBorderStyle(), annotation.getBorder()); PDBorderEffectDictionary borderEffect = annotation.getBorderEffect(); if (borderEffect != null && borderEffect.getStyle().equals(PDBorderEffectDictionary.STYLE_CLOUDY)) { CloudyBorder cloudyBorder = new CloudyBorder(contentStream, borderEffect.getIntensity(), lineWidth, 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 { PDRectangle borderBox = handleBorderBox(annotation, lineWidth); contentStream.addRect(borderBox.getLowerLeftX(), borderBox.getLowerLeftY(), borderBox.getWidth(), borderBox.getHeight()); } contentStream.drawShape(lineWidth, hasStroke, hasBackground); } catch (IOException e) { LOG.error(e); }
522
451
973
<methods>public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation, org.apache.pdfbox.pdmodel.PDDocument) <variables>protected static final Set<java.lang.String> ANGLED_STYLES,static final double ARROW_ANGLE,protected static final Set<java.lang.String> INTERIOR_COLOR_STYLES,protected static final Set<java.lang.String> SHORT_STYLES,private final non-sealed org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation annotation,private org.apache.pdfbox.pdmodel.font.PDFont defaultFont,protected final non-sealed org.apache.pdfbox.pdmodel.PDDocument document
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDSquigglyAppearanceHandler.java
PDSquigglyAppearanceHandler
generateNormalAppearance
class PDSquigglyAppearanceHandler extends PDAbstractAppearanceHandler { private static final Logger LOG = LogManager.getLogger(PDSquigglyAppearanceHandler.class); public PDSquigglyAppearanceHandler(PDAnnotation annotation) { super(annotation); } public PDSquigglyAppearanceHandler(PDAnnotation annotation, PDDocument document) { super(annotation, document); } @Override public void generateNormalAppearance() {<FILL_FUNCTION_BODY>} @Override public void generateRolloverAppearance() { // No rollover appearance generated } @Override public void generateDownAppearance() { // No down appearance generated } }
PDAnnotationSquiggly annotation = (PDAnnotationSquiggly) getAnnotation(); PDRectangle rect = annotation.getRectangle(); if (rect == null) { return; } 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; } if (Float.compare(ab.width, 0) == 0) { // value found in adobe reader ab.width = 1.5f; } // 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 // all coordinates (unlike painting) are used because I'm lazy 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); } rect.setLowerLeftX(Math.min(minX - ab.width / 2, rect.getLowerLeftX())); rect.setLowerLeftY(Math.min(minY - ab.width / 2, rect.getLowerLeftY())); rect.setUpperRightX(Math.max(maxX + ab.width / 2, rect.getUpperRightX())); rect.setUpperRightY(Math.max(maxY + ab.width / 2, rect.getUpperRightY())); annotation.setRectangle(rect); try (PDAppearanceContentStream cs = getNormalAppearanceAsContentStream()) { setOpacity(cs, annotation.getConstantOpacity()); cs.setStrokingColor(color); //TODO we ignore dash pattern and line width for now. Do they have any effect? // quadpoints spec is incorrect // https://stackoverflow.com/questions/9855814/pdf-spec-vs-acrobat-creation-quadpoints for (int i = 0; i < pathsArray.length / 8; ++i) { // Adobe uses a fixed pattern that assumes a height of 40, and it transforms to that height // horizontally and the same / 1.8 vertically. // translation apparently based on bottom left, but slightly different in Adobe //TODO what if the annotation is not horizontal? float height = pathsArray[i * 8 + 1] - pathsArray[i * 8 + 5]; cs.transform(new Matrix(height / 40f, 0, 0, height / 40f / 1.8f, pathsArray[i * 8 + 4], pathsArray[i * 8 + 5])); // Create form, BBox is mostly fixed, except for the horizontal size which is // horizontal size divided by the horizontal transform factor from above // (almost) PDFormXObject form = new PDFormXObject(createCOSStream()); form.setBBox(new PDRectangle(-0.5f, -0.5f, (pathsArray[i * 8 + 2] - pathsArray[i * 8]) / height * 40f + 0.5f, 13)); form.setResources(new PDResources()); form.setMatrix(AffineTransform.getTranslateInstance(0.5f, 0.5f)); cs.drawForm(form); try (PDFormContentStream formCS = new PDFormContentStream(form)) { PDTilingPattern pattern = new PDTilingPattern(); pattern.setBBox(new PDRectangle(0, 0, 10, 12)); pattern.setXStep(10); pattern.setYStep(13); pattern.setTilingType(PDTilingPattern.TILING_CONSTANT_SPACING_FASTER_TILING); pattern.setPaintType(PDTilingPattern.PAINT_UNCOLORED); try (PDPatternContentStream patternCS = new PDPatternContentStream(pattern)) { // from Adobe patternCS.setLineCapStyle(1); patternCS.setLineJoinStyle(1); patternCS.setLineWidth(1); patternCS.setMiterLimit(10); patternCS.moveTo(0, 1); patternCS.lineTo(5, 11); patternCS.lineTo(10, 1); patternCS.stroke(); } COSName patternName = form.getResources().add(pattern); PDColorSpace patternColorSpace = new PDPattern(null, PDDeviceRGB.INSTANCE); PDColor patternColor = new PDColor(color.getComponents(), patternName, patternColorSpace); formCS.setNonStrokingColor(patternColor); // With Adobe, the horizontal size is slightly different, don't know why formCS.addRect(0, 0, (pathsArray[i * 8 + 2] - pathsArray[i * 8]) / height * 40f, 12); formCS.fill(); } } } catch (IOException ex) { LOG.error(ex); }
206
1,492
1,698
<methods>public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation, org.apache.pdfbox.pdmodel.PDDocument) <variables>protected static final Set<java.lang.String> ANGLED_STYLES,static final double ARROW_ANGLE,protected static final Set<java.lang.String> INTERIOR_COLOR_STYLES,protected static final Set<java.lang.String> SHORT_STYLES,private final non-sealed org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation annotation,private org.apache.pdfbox.pdmodel.font.PDFont defaultFont,protected final non-sealed org.apache.pdfbox.pdmodel.PDDocument document
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDStrikeoutAppearanceHandler.java
PDStrikeoutAppearanceHandler
generateNormalAppearance
class PDStrikeoutAppearanceHandler extends PDAbstractAppearanceHandler { private static final Logger LOG = LogManager.getLogger(PDStrikeoutAppearanceHandler.class); public PDStrikeoutAppearanceHandler(PDAnnotation annotation) { super(annotation); } public PDStrikeoutAppearanceHandler(PDAnnotation annotation, PDDocument document) { super(annotation, document); } @Override public void generateNormalAppearance() {<FILL_FUNCTION_BODY>} @Override public void generateRolloverAppearance() { // No rollover appearance generated } @Override public void generateDownAppearance() { // No down appearance generated } }
PDAnnotationStrikeout annotation = (PDAnnotationStrikeout) getAnnotation(); PDRectangle rect = annotation.getRectangle(); if (rect == null) { return; } 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; } if (Float.compare(ab.width, 0) == 0) { // value found in adobe reader ab.width = 1.5f; } // 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 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); } rect.setLowerLeftX(Math.min(minX - ab.width / 2, rect.getLowerLeftX())); rect.setLowerLeftY(Math.min(minY - ab.width / 2, rect.getLowerLeftY())); rect.setUpperRightX(Math.max(maxX + ab.width / 2, rect.getUpperRightX())); rect.setUpperRightY(Math.max(maxY + ab.width / 2, rect.getUpperRightY())); annotation.setRectangle(rect); try (PDAppearanceContentStream cs = getNormalAppearanceAsContentStream()) { setOpacity(cs, annotation.getConstantOpacity()); cs.setStrokingColor(color); if (ab.dashArray != null) { cs.setLineDashPattern(ab.dashArray, 0); } cs.setLineWidth(ab.width); // spec is incorrect // https://stackoverflow.com/questions/9855814/pdf-spec-vs-acrobat-creation-quadpoints for (int i = 0; i < pathsArray.length / 8; ++i) { // get mid point between bounds, subtract the line width to approximate what Adobe is doing // See e.g. CTAN-example-Annotations.pdf and PLPDF.com-MarkupAnnotations.pdf // and https://bugs.ghostscript.com/show_bug.cgi?id=693664 // do the math for diagonal annotations with this weird old trick: // https://stackoverflow.com/questions/7740507/extend-a-line-segment-a-specific-distance float len0 = (float) (Math.sqrt(Math.pow(pathsArray[i * 8] - pathsArray[i * 8 + 4], 2) + Math.pow(pathsArray[i * 8 + 1] - pathsArray[i * 8 + 5], 2))); float x0 = pathsArray[i * 8 + 4]; float y0 = pathsArray[i * 8 + 5]; if (Float.compare(len0, 0) != 0) { // only if both coordinates are not identical to avoid divide by zero x0 += (pathsArray[i * 8] - pathsArray[i * 8 + 4]) / len0 * (len0 / 2 - ab.width); y0 += (pathsArray[i * 8 + 1] - pathsArray[i * 8 + 5]) / len0 * (len0 / 2 - ab.width); } float len1 = (float) (Math.sqrt(Math.pow(pathsArray[i * 8 + 2] - pathsArray[i * 8 + 6], 2) + Math.pow(pathsArray[i * 8 + 3] - pathsArray[i * 8 + 7], 2))); float x1 = pathsArray[i * 8 + 6]; float y1 = pathsArray[i * 8 + 7]; if (Float.compare(len1, 0) != 0) { // only if both coordinates are not identical to avoid divide by zero x1 += (pathsArray[i * 8 + 2] - pathsArray[i * 8 + 6]) / len1 * (len1 / 2 - ab.width); y1 += (pathsArray[i * 8 + 3] - pathsArray[i * 8 + 7]) / len1 * (len1 / 2 - ab.width); } cs.moveTo(x0, y0); cs.lineTo(x1, y1); } cs.stroke(); } catch (IOException ex) { LOG.error(ex); }
209
1,365
1,574
<methods>public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation, org.apache.pdfbox.pdmodel.PDDocument) <variables>protected static final Set<java.lang.String> ANGLED_STYLES,static final double ARROW_ANGLE,protected static final Set<java.lang.String> INTERIOR_COLOR_STYLES,protected static final Set<java.lang.String> SHORT_STYLES,private final non-sealed org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation annotation,private org.apache.pdfbox.pdmodel.font.PDFont defaultFont,protected final non-sealed org.apache.pdfbox.pdmodel.PDDocument document
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDUnderlineAppearanceHandler.java
PDUnderlineAppearanceHandler
generateNormalAppearance
class PDUnderlineAppearanceHandler extends PDAbstractAppearanceHandler { private static final Logger LOG = LogManager.getLogger(PDUnderlineAppearanceHandler.class); public PDUnderlineAppearanceHandler(PDAnnotation annotation) { super(annotation); } public PDUnderlineAppearanceHandler(PDAnnotation annotation, PDDocument document) { super(annotation, document); } @Override public void generateNormalAppearance() {<FILL_FUNCTION_BODY>} @Override public void generateRolloverAppearance() { // No rollover appearance generated } @Override public void generateDownAppearance() { // No down appearance generated } }
PDAnnotationUnderline annotation = (PDAnnotationUnderline) getAnnotation(); PDRectangle rect = annotation.getRectangle(); if (rect == null) { return; } 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; } if (Float.compare(ab.width, 0) == 0) { // value found in adobe reader ab.width = 1.5f; } // 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 // all coordinates (unlike painting) are used because I'm lazy 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); } rect.setLowerLeftX(Math.min(minX - ab.width / 2, rect.getLowerLeftX())); rect.setLowerLeftY(Math.min(minY - ab.width / 2, rect.getLowerLeftY())); rect.setUpperRightX(Math.max(maxX + ab.width / 2, rect.getUpperRightX())); rect.setUpperRightY(Math.max(maxY + ab.width / 2, rect.getUpperRightY())); annotation.setRectangle(rect); try (PDAppearanceContentStream cs = getNormalAppearanceAsContentStream()) { setOpacity(cs, annotation.getConstantOpacity()); cs.setStrokingColor(color); if (ab.dashArray != null) { cs.setLineDashPattern(ab.dashArray, 0); } cs.setLineWidth(ab.width); // spec is incorrect // https://stackoverflow.com/questions/9855814/pdf-spec-vs-acrobat-creation-quadpoints for (int i = 0; i < pathsArray.length / 8; ++i) { // Adobe doesn't use the lower coordinate for the line, it uses lower + delta / 7. // do the math for diagonal annotations with this weird old trick: // https://stackoverflow.com/questions/7740507/extend-a-line-segment-a-specific-distance float len0 = (float) (Math.sqrt(Math.pow(pathsArray[i * 8] - pathsArray[i * 8 + 4], 2) + Math.pow(pathsArray[i * 8 + 1] - pathsArray[i * 8 + 5], 2))); float x0 = pathsArray[i * 8 + 4]; float y0 = pathsArray[i * 8 + 5]; if (Float.compare(len0, 0) != 0) { // only if both coordinates are not identical to avoid divide by zero x0 += (pathsArray[i * 8] - pathsArray[i * 8 + 4]) / len0 * len0 / 7; y0 += (pathsArray[i * 8 + 1] - pathsArray[i * 8 + 5]) / len0 * (len0 / 7); } float len1 = (float) (Math.sqrt(Math.pow(pathsArray[i * 8 + 2] - pathsArray[i * 8 + 6], 2) + Math.pow(pathsArray[i * 8 + 3] - pathsArray[i * 8 + 7], 2))); float x1 = pathsArray[i * 8 + 6]; float y1 = pathsArray[i * 8 + 7]; if (Float.compare(len1, 0) != 0) { // only if both coordinates are not identical to avoid divide by zero x1 += (pathsArray[i * 8 + 2] - pathsArray[i * 8 + 6]) / len1 * len1 / 7; y1 += (pathsArray[i * 8 + 3] - pathsArray[i * 8 + 7]) / len1 * len1 / 7; } cs.moveTo(x0, y0); cs.lineTo(x1, y1); } cs.stroke(); } catch (IOException ex) { LOG.error(ex); }
201
1,303
1,504
<methods>public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public void <init>(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation, org.apache.pdfbox.pdmodel.PDDocument) <variables>protected static final Set<java.lang.String> ANGLED_STYLES,static final double ARROW_ANGLE,protected static final Set<java.lang.String> INTERIOR_COLOR_STYLES,protected static final Set<java.lang.String> SHORT_STYLES,private final non-sealed org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation annotation,private org.apache.pdfbox.pdmodel.font.PDFont defaultFont,protected final non-sealed org.apache.pdfbox.pdmodel.PDDocument document
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/digitalsignature/COSFilterInputStream.java
COSFilterInputStream
read
class COSFilterInputStream extends FilterInputStream { private int[][] ranges; private int range; private long position = 0; public COSFilterInputStream(InputStream in, int[] byteRange) { super(in); calculateRanges(byteRange); } public COSFilterInputStream(byte[] in, int[] byteRange) { this(new ByteArrayInputStream(in), byteRange); } @Override public int read() throws IOException {<FILL_FUNCTION_BODY>} @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { if ((this.range == -1 || getRemaining() <= 0) && !nextRange()) { return -1; // EOF } int bytesRead = super.read(b, off, (int) Math.min(len, getRemaining())); this.position += bytesRead; return bytesRead; } public byte[] toByteArray() throws IOException { return readAllBytes(); } private void calculateRanges(int[] byteRange) { this.ranges = new int[byteRange.length / 2][]; for (int i = 0; i < byteRange.length / 2; i++) { this.ranges[i] = new int[] { byteRange[i * 2], byteRange[i * 2] + byteRange[i * 2 + 1] }; } this.range = -1; } private long getRemaining() { return this.ranges[this.range][1] - this.position; } private boolean nextRange() throws IOException { if (this.range + 1 < this.ranges.length) { this.range++; while (this.position < this.ranges[this.range][0]) { long skipped = super.skip(this.ranges[this.range][0] - this.position); if (skipped == 0) { throw new IOException("FilterInputStream.skip() returns 0, range: " + Arrays.toString(this.ranges[this.range])); } this.position += skipped; } return true; } else { return false; } } }
if ((this.range == -1 || getRemaining() <= 0) && !nextRange()) { return -1; // EOF } int result = super.read(); this.position++; return result;
719
70
789
<methods>public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException<variables>protected volatile java.io.InputStream in
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/digitalsignature/PDPropBuild.java
PDPropBuild
getApp
class PDPropBuild implements COSObjectable { private final COSDictionary dictionary; /** * Default constructor. */ public PDPropBuild() { dictionary = new COSDictionary(); dictionary.setDirect(true); // the specification claim to use direct objects } /** * Constructor. * * @param dict The signature dictionary. */ public PDPropBuild(COSDictionary dict) { dictionary = dict; dictionary.setDirect(true); // the specification claim to use direct objects } /** * Convert this standard java object to a COS dictionary. * * @return The COS dictionary that matches this Java object. */ @Override public COSDictionary getCOSObject() { return dictionary; } /** * A build data dictionary for the signature handler that was * used to create the parent signature. * * @return the Filter as PDPropBuildFilter object */ public PDPropBuildDataDict getFilter() { PDPropBuildDataDict filter = null; COSDictionary filterDic = dictionary.getCOSDictionary(COSName.FILTER); if (filterDic != null) { filter = new PDPropBuildDataDict(filterDic); } return filter; } /** * Set the build data dictionary for the signature handler. * This entry is optional but is highly recommended for the signatures. * * @param filter is the PDPropBuildFilter */ public void setPDPropBuildFilter(PDPropBuildDataDict filter) { dictionary.setItem(COSName.FILTER, filter); } /** * A build data dictionary for the PubSec software module * that was used to create the parent signature. * * @return the PubSec as PDPropBuildPubSec object */ public PDPropBuildDataDict getPubSec() { PDPropBuildDataDict pubSec = null; COSDictionary pubSecDic = dictionary.getCOSDictionary(COSName.PUB_SEC); if (pubSecDic != null) { pubSec = new PDPropBuildDataDict(pubSecDic); } return pubSec; } /** * Set the build data dictionary for the PubSec Software module. * * @param pubSec is the PDPropBuildPubSec */ public void setPDPropBuildPubSec(PDPropBuildDataDict pubSec) { dictionary.setItem(COSName.PUB_SEC, pubSec); } /** * A build data dictionary for the viewing application software * module that was used to create the parent signature. * * @return the App as PDPropBuildApp object */ public PDPropBuildDataDict getApp() {<FILL_FUNCTION_BODY>} /** * Set the build data dictionary for the viewing application * software module. * * @param app is the PDPropBuildApp */ public void setPDPropBuildApp(PDPropBuildDataDict app) { dictionary.setItem(COSName.APP, app); } }
PDPropBuildDataDict app = null; COSDictionary appDic = dictionary.getCOSDictionary(COSName.APP); if (appDic != null) { app = new PDPropBuildDataDict(appDic); } return app;
842
77
919
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/digitalsignature/PDSeedValueMDP.java
PDSeedValueMDP
setP
class PDSeedValueMDP { private final COSDictionary dictionary; /** * Default constructor. */ public PDSeedValueMDP() { dictionary = new COSDictionary(); dictionary.setDirect(true); } /** * Constructor. * * @param dict The signature dictionary. */ public PDSeedValueMDP(COSDictionary dict) { dictionary = dict; dictionary.setDirect(true); } /** * Convert this standard java object to a COS dictionary. * * @return The COS dictionary that matches this Java object. */ public COSDictionary getCOSObject() { return dictionary; } /** * Return the P value. * * @return the P value */ public int getP() { return dictionary.getInt(COSName.P); } /** * Set the P value. * * @param p the value to be set as P */ public void setP(int p) {<FILL_FUNCTION_BODY>} }
if (p < 0 || p > 3) { throw new IllegalArgumentException("Only values between 0 and 3 nare allowed."); } dictionary.setInt(COSName.P, p);
305
55
360
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/digitalsignature/SignatureOptions.java
SignatureOptions
close
class SignatureOptions implements Closeable { private COSDocument visualSignature; private int preferredSignatureSize; private int pageNo; // the pdf to be read // this is done analog to PDDocument private RandomAccessRead pdfSource = null; public static final int DEFAULT_SIGNATURE_SIZE = 0x2500; /** * Creates the default signature options. */ public SignatureOptions() { pageNo = 0; } /** * Set the 0-based page number. * * @param pageNo the page number */ public void setPage(int pageNo) { this.pageNo = pageNo; } /** * Get the 0-based page number. * * @return the page number */ public int getPage() { return pageNo; } /** * Reads the visual signature from the given file. * * @param file the file containing the visual signature * @throws IOException when something went wrong during parsing */ public void setVisualSignature(File file) throws IOException { initFromRandomAccessRead(new RandomAccessReadBufferedFile(file)); } /** * Reads the visual signature from the given input stream. * * @param is the input stream containing the visual signature * @throws IOException when something went wrong during parsing */ public void setVisualSignature(InputStream is) throws IOException { initFromRandomAccessRead(new RandomAccessReadBuffer(is)); } private void initFromRandomAccessRead(RandomAccessRead rar) throws IOException { pdfSource = rar; PDFParser parser = new PDFParser(pdfSource); visualSignature = parser.parse().getDocument(); } /** * Reads the visual signature from the given visual signature properties * * @param visSignatureProperties the <code>PDVisibleSigProperties</code> object containing the * visual signature * * @throws IOException when something went wrong during parsing */ public void setVisualSignature(PDVisibleSigProperties visSignatureProperties) throws IOException { setVisualSignature(visSignatureProperties.getVisibleSignature()); } /** * Get the visual signature. * * @return the visual signature */ public COSDocument getVisualSignature() { return visualSignature; } /** * Get the preferred size of the signature. * * @return the preferred size of the signature in bytes. */ public int getPreferredSignatureSize() { return preferredSignatureSize; } /** * Set the preferred size of the signature. * * @param size the size of the signature in bytes. Only values above 0 will be considered. */ public void setPreferredSignatureSize(int size) { if (size > 0) { preferredSignatureSize = size; } } /** * Closes the visual signature COSDocument, if any. Do not call this before you're saved your * signed PDF document, or saving will fail because COSStream objects held both by the * COSDocument and by the signed document would no longer be available. * * @throws IOException if the document could not be closed */ @Override public void close() throws IOException {<FILL_FUNCTION_BODY>} }
try { if (visualSignature != null) { visualSignature.close(); } } finally { if (pdfSource != null) { pdfSource.close(); } }
874
68
942
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/digitalsignature/visible/PDFTemplateCreator.java
PDFTemplateCreator
buildPDF
class PDFTemplateCreator { private final PDFTemplateBuilder pdfBuilder; private static final Logger LOG = LogManager.getLogger(PDFTemplateCreator.class); /** * Constructor. * * @param templateBuilder the template builder */ public PDFTemplateCreator(PDFTemplateBuilder templateBuilder) { pdfBuilder = templateBuilder; } /** * Returns the PDFTemplateStructure object. * * @return the template for the structure */ public PDFTemplateStructure getPdfStructure() { return pdfBuilder.getStructure(); } /** * Build a PDF with a visible signature step by step, and return it as a stream. * * @param properties properties to be used for the creation * @return InputStream stream containing the pdf holding the visible signature * @throws IOException if the PDF could not be created */ public InputStream buildPDF(PDVisibleSignDesigner properties) throws IOException {<FILL_FUNCTION_BODY>} private InputStream getVisualSignatureAsStream(COSDocument visualSignature) throws IOException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { COSWriter writer = new COSWriter(baos); writer.write(visualSignature); return new ByteArrayInputStream(baos.toByteArray()); } } }
LOG.info("pdf building has been started"); PDFTemplateStructure pdfStructure = pdfBuilder.getStructure(); // we create array of [Text, ImageB, ImageC, ImageI] pdfBuilder.createProcSetArray(); //create page pdfBuilder.createPage(properties); PDPage page = pdfStructure.getPage(); //create template pdfBuilder.createTemplate(page); try (PDDocument template = pdfStructure.getTemplate()) { //create /AcroForm pdfBuilder.createAcroForm(template); PDAcroForm acroForm = pdfStructure.getAcroForm(); // AcroForm contains signature fields pdfBuilder.createSignatureField(acroForm); PDSignatureField pdSignatureField = pdfStructure.getSignatureField(); // create signature //TODO // The line below has no effect with the CreateVisibleSignature example. // The signature field is needed as a "holder" for the /AP tree, // but the /P and /V PDSignatureField entries are ignored by PDDocument.addSignature pdfBuilder.createSignature(pdSignatureField, page, ""); // that is /AcroForm/DR entry pdfBuilder.createAcroFormDictionary(acroForm, pdSignatureField); // create AffineTransform pdfBuilder.createAffineTransform(properties.getTransform()); AffineTransform transform = pdfStructure.getAffineTransform(); // rectangle, formatter, image. /AcroForm/DR/XObject contains that form pdfBuilder.createSignatureRectangle(pdSignatureField, properties); pdfBuilder.createFormatterRectangle(properties.getFormatterRectangleParameters()); PDRectangle bbox = pdfStructure.getFormatterRectangle(); pdfBuilder.createSignatureImage(template, properties.getImage()); // create form stream, form and resource. pdfBuilder.createHolderFormStream(template); PDStream holderFormStream = pdfStructure.getHolderFormStream(); pdfBuilder.createHolderFormResources(); PDResources holderFormResources = pdfStructure.getHolderFormResources(); pdfBuilder.createHolderForm(holderFormResources, holderFormStream, bbox); // that is /AP entry the appearance dictionary. pdfBuilder.createAppearanceDictionary(pdfStructure.getHolderForm(), pdSignatureField); // inner form stream, form and resource (holder form contains inner form) pdfBuilder.createInnerFormStream(template); pdfBuilder.createInnerFormResource(); PDResources innerFormResource = pdfStructure.getInnerFormResources(); pdfBuilder.createInnerForm(innerFormResource, pdfStructure.getInnerFormStream(), bbox); PDFormXObject innerForm = pdfStructure.getInnerForm(); // inner form must be in the holder form as we wrote pdfBuilder.insertInnerFormToHolderResources(innerForm, holderFormResources); // Image form is in this structure: /AcroForm/DR/FRM/Resources/XObject/n2 pdfBuilder.createImageFormStream(template); PDStream imageFormStream = pdfStructure.getImageFormStream(); pdfBuilder.createImageFormResources(); PDResources imageFormResources = pdfStructure.getImageFormResources(); pdfBuilder.createImageForm(imageFormResources, innerFormResource, imageFormStream, bbox, transform, pdfStructure.getImage()); pdfBuilder.createBackgroundLayerForm(innerFormResource, bbox); // now inject procSetArray pdfBuilder.injectProcSetArray(innerForm, page, innerFormResource, imageFormResources, holderFormResources, pdfStructure.getProcSet()); COSName imageFormName = pdfStructure.getImageFormName(); COSName imageName = pdfStructure.getImageName(); COSName innerFormName = pdfStructure.getInnerFormName(); // now create Streams of AP pdfBuilder.injectAppearanceStreams(holderFormStream, imageFormStream, imageFormStream, imageFormName, imageName, innerFormName, properties); pdfBuilder.createVisualSignature(template); pdfBuilder.createWidgetDictionary(pdSignatureField, holderFormResources); InputStream in = getVisualSignatureAsStream(pdfStructure.getVisualSignature()); LOG.info("stream returning started, size= {}", in.available()); // return result of the stream return in; }
350
1,092
1,442
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/digitalsignature/visible/PDVisibleSigProperties.java
PDVisibleSigProperties
buildSignature
class PDVisibleSigProperties { private String signerName; private String signerLocation; private String signatureReason; private boolean visualSignEnabled; private int page; private int preferredSize; private InputStream visibleSignature; private PDVisibleSignDesigner pdVisibleSignature; /** * start building of visible signature * * @throws IOException if the output could not be written */ public void buildSignature() throws IOException {<FILL_FUNCTION_BODY>} /** * * @return - signer name */ public String getSignerName() { return signerName; } /** * Sets signer name * * @param signerName the signer name * @return the visible signature properties. */ public PDVisibleSigProperties signerName(String signerName) { this.signerName = signerName; return this; } /** * Gets signer location * * @return - location */ public String getSignerLocation() { return signerLocation; } /** * Sets location * * @param signerLocation the new signer location * @return the visible signature properties. */ public PDVisibleSigProperties signerLocation(String signerLocation) { this.signerLocation = signerLocation; return this; } /** * gets reason of signing * @return the signing reason. */ public String getSignatureReason() { return signatureReason; } /** * sets reason of signing * * @param signatureReason the reason of signing * @return the visible signature properties. */ public PDVisibleSigProperties signatureReason(String signatureReason) { this.signatureReason = signatureReason; return this; } /** * returns your page * @return the page number (1-based). */ public int getPage() { return page; } /** * sets page number * @param page page the signature should be placed on (1-based) * @return the visible signature properties. */ public PDVisibleSigProperties page(int page) { this.page = page; return this; } /** * Gets the preferred signature size in bytes. * * @return the signature's preferred size. A return value of 0 means to use default. */ public int getPreferredSize() { return preferredSize; } /** * Sets the preferred signature size in bytes. * * @param preferredSize The preferred signature size in bytes, or 0 to use default. * @return the visible signature properties. */ public PDVisibleSigProperties preferredSize(int preferredSize) { this.preferredSize = preferredSize; return this; } /** * checks if we need to add visible signature * @return state if visible signature is needed. */ public boolean isVisualSignEnabled() { return visualSignEnabled; } /** * sets visible signature to be added or not * * @param visualSignEnabled if true the visible signature is added * @return the visible signature properties. */ public PDVisibleSigProperties visualSignEnabled(boolean visualSignEnabled) { this.visualSignEnabled = visualSignEnabled; return this; } /** * this method gets visible signature configuration object * @return the visible signature configuration. */ public PDVisibleSignDesigner getPdVisibleSignature() { return pdVisibleSignature; } /** * Sets visible signature configuration Object * * @param pdVisibleSignature the new visible signature configuration * @return the visible signature properties. */ public PDVisibleSigProperties setPdVisibleSignature(PDVisibleSignDesigner pdVisibleSignature) { this.pdVisibleSignature = pdVisibleSignature; return this; } /** * returns visible signature configuration object * @return the input stream representing the visible signature. */ public InputStream getVisibleSignature() { return visibleSignature; } /** * sets configuration object of visible signature * * @param visibleSignature the stream of the visible signature */ public void setVisibleSignature(InputStream visibleSignature) { this.visibleSignature = visibleSignature; } }
PDFTemplateBuilder builder = new PDVisibleSigBuilder(); PDFTemplateCreator creator = new PDFTemplateCreator(builder); setVisibleSignature(creator.buildPDF(getPdVisibleSignature()));
1,178
53
1,231
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDDestination.java
PDDestination
create
class PDDestination implements PDDestinationOrAction { /** * This will create a new destination depending on the type of COSBase * that is passed in. * * @param base The base level object. * * @return A new destination. * * @throws IOException If the base cannot be converted to a Destination. */ public static PDDestination create( COSBase base ) throws IOException {<FILL_FUNCTION_BODY>} }
PDDestination retval = null; if( base == null ) { //this is ok, just return null. } else if (base instanceof COSArray && ((COSArray) base).size() > 1 && ((COSArray) base).getObject(1) instanceof COSName) { COSArray array = (COSArray) base; COSName type = (COSName) array.getObject(1); String typeString = type.getName(); switch (typeString) { case PDPageFitDestination.TYPE: case PDPageFitDestination.TYPE_BOUNDED: retval = new PDPageFitDestination(array); break; case PDPageFitHeightDestination.TYPE: case PDPageFitHeightDestination.TYPE_BOUNDED: retval = new PDPageFitHeightDestination(array); break; case PDPageFitRectangleDestination.TYPE: retval = new PDPageFitRectangleDestination(array); break; case PDPageFitWidthDestination.TYPE: case PDPageFitWidthDestination.TYPE_BOUNDED: retval = new PDPageFitWidthDestination(array); break; case PDPageXYZDestination.TYPE: retval = new PDPageXYZDestination(array); break; default: throw new IOException("Unknown destination type: " + type.getName()); } } else if( base instanceof COSString ) { retval = new PDNamedDestination( (COSString)base ); } else if( base instanceof COSName ) { retval = new PDNamedDestination( (COSName)base ); } else { throw new IOException( "Error: can't convert to Destination " + base ); } return retval;
128
500
628
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDNamedDestination.java
PDNamedDestination
getNamedDestination
class PDNamedDestination extends PDDestination { private COSBase namedDestination; /** * Constructor. * * @param dest The named destination. */ public PDNamedDestination( COSString dest ) { namedDestination = dest; } /** * Constructor. * * @param dest The named destination. */ public PDNamedDestination( COSName dest ) { namedDestination = dest; } /** * Default constructor. */ public PDNamedDestination() { //default, so do nothing } /** * Default constructor. * * @param dest The named destination. */ public PDNamedDestination( String dest ) { namedDestination = new COSString( dest ); } /** * Convert this standard java object to a COS object. * * @return The cos object that matches this Java object. */ @Override public COSBase getCOSObject() { return namedDestination; } /** * This will get the name of the destination. * * @return The name of the destination. */ public String getNamedDestination() {<FILL_FUNCTION_BODY>} /** * Set the named destination. * * @param dest The new named destination. * * @throws IOException If there is an error setting the named destination. */ public void setNamedDestination( String dest ) throws IOException { if (dest == null) { namedDestination = null; } else { namedDestination = new COSString( dest ); } } }
String retval = null; if( namedDestination instanceof COSString ) { retval = ((COSString)namedDestination).getString(); } else if( namedDestination instanceof COSName ) { retval = ((COSName)namedDestination).getName(); } return retval;
462
87
549
<methods>public non-sealed void <init>() ,public static org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDDestination create(org.apache.pdfbox.cos.COSBase) throws java.io.IOException<variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDPageDestination.java
PDPageDestination
getPage
class PDPageDestination extends PDDestination { /** * Storage for the page destination. */ protected final COSArray array; /** * Constructor to create empty page destination. * */ protected PDPageDestination() { array = new COSArray(); } /** * Constructor to create empty page destination. * * @param arr A page destination array. */ protected PDPageDestination( COSArray arr ) { array = arr; } /** * This will get the page for this destination. A page destination can either reference a page * (for a local destination) or a page number (when doing a remote destination to another PDF). * If this object is referencing by page number then this method will return null and * {@link #getPageNumber()} should be used. * * @return The page for this destination. */ public PDPage getPage() {<FILL_FUNCTION_BODY>} /** * Set the page for a local destination. For an external destination, call {@link #setPageNumber(int) setPageNumber(int pageNumber)}. * * @param page The page for a local destination. */ public void setPage( PDPage page ) { array.set( 0, page ); } /** * This will get the page number for this destination. A page destination can either reference a * page (for a local destination) or a page number (when doing a remote destination to another * PDF). If this object is referencing by page number then this method will return that number, * otherwise -1 will be returned. * * @return The zero-based page number for this destination. */ public int getPageNumber() { int retval = -1; if( !array.isEmpty() ) { COSBase page = array.getObject( 0 ); if( page instanceof COSNumber ) { retval = ((COSNumber)page).intValue(); } } return retval; } /** * Returns the page number for this destination, regardless of whether this is a page number or * a reference to a page. * * @see org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem * @return the 0-based page number, or -1 if the destination type is unknown. */ public int retrievePageNumber() { int retval = -1; if (!array.isEmpty()) { COSBase page = array.getObject(0); if (page instanceof COSNumber) { retval = ((COSNumber) page).intValue(); } else if (page instanceof COSDictionary) { return indexOfPageTree((COSDictionary) page); } } return retval; } // climb up the page tree up to the top to be able to call PageTree.indexOf for a page dictionary private int indexOfPageTree(COSDictionary pageDict) { COSDictionary parent = pageDict; while (true) { COSDictionary prevParent = parent.getCOSDictionary(COSName.PARENT, COSName.P); if (prevParent == null) { break; } parent = prevParent; } if (parent.containsKey(COSName.KIDS) && COSName.PAGES.equals(parent.getCOSName(COSName.TYPE))) { // now parent is the highest pages node PDPageTree pages = new PDPageTree(parent); return pages.indexOf(new PDPage(pageDict)); } return -1; } /** * Set the page number for a remote destination. For an internal destination, call * {@link #setPage(PDPage) setPage(PDPage page)}. * * @param pageNumber The page for a remote destination. */ public void setPageNumber( int pageNumber ) { array.set( 0, pageNumber ); } /** * Convert this standard java object to a COS object. * * @return The cos object that matches this Java object. */ @Override public COSArray getCOSObject() { return array; } }
PDPage retval = null; if (!array.isEmpty()) { COSBase page = array.getObject( 0 ); if( page instanceof COSDictionary ) { retval = new PDPage( (COSDictionary)page ); } } return retval;
1,128
81
1,209
<methods>public non-sealed void <init>() ,public static org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDDestination create(org.apache.pdfbox.cos.COSBase) throws java.io.IOException<variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDPageFitDestination.java
PDPageFitDestination
setFitBoundingBox
class PDPageFitDestination extends PDPageDestination { /** * The type of this destination. */ protected static final String TYPE = "Fit"; /** * The type of this destination. */ protected static final String TYPE_BOUNDED = "FitB"; /** * Default constructor. * */ public PDPageFitDestination() { array.growToSize(2); array.setName( 1, TYPE ); } /** * Constructor from an existing destination array. * * @param arr The destination array. */ public PDPageFitDestination( COSArray arr ) { super( arr ); } /** * A flag indicating if this page destination should just fit bounding box of the PDF. * * @return true If the destination should fit just the bounding box. */ public boolean fitBoundingBox() { return TYPE_BOUNDED.equals( array.getName( 1 ) ); } /** * Set if this page destination should just fit the bounding box. The default is false. * * @param fitBoundingBox A flag indicating if this should fit the bounding box. */ public void setFitBoundingBox( boolean fitBoundingBox ) {<FILL_FUNCTION_BODY>} }
array.growToSize( 2 ); if( fitBoundingBox ) { array.setName( 1, TYPE_BOUNDED ); } else { array.setName( 1, TYPE ); }
359
66
425
<methods>public org.apache.pdfbox.cos.COSArray getCOSObject() ,public org.apache.pdfbox.pdmodel.PDPage getPage() ,public int getPageNumber() ,public int retrievePageNumber() ,public void setPage(org.apache.pdfbox.pdmodel.PDPage) ,public void setPageNumber(int) <variables>protected final non-sealed org.apache.pdfbox.cos.COSArray array
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDPageFitHeightDestination.java
PDPageFitHeightDestination
setLeft
class PDPageFitHeightDestination extends PDPageDestination { /** * The type of this destination. */ protected static final String TYPE = "FitV"; /** * The type of this destination. */ protected static final String TYPE_BOUNDED = "FitBV"; /** * Default constructor. * */ public PDPageFitHeightDestination() { array.growToSize(3); array.setName( 1, TYPE ); } /** * Constructor from an existing destination array. * * @param arr The destination array. */ public PDPageFitHeightDestination( COSArray arr ) { super( arr ); } /** * Get the left x coordinate. A return value of -1 implies that the current x-coordinate * will be used. * * @return The left x coordinate. */ public int getLeft() { return array.getInt( 2 ); } /** * Set the left x-coordinate, a value of -1 implies that the current x-coordinate * will be used. * @param x The left x coordinate. */ public void setLeft( int x ) {<FILL_FUNCTION_BODY>} /** * A flag indicating if this page destination should just fit bounding box of the PDF. * * @return true If the destination should fit just the bounding box. */ public boolean fitBoundingBox() { return TYPE_BOUNDED.equals( array.getName( 1 ) ); } /** * Set if this page destination should just fit the bounding box. The default is false. * * @param fitBoundingBox A flag indicating if this should fit the bounding box. */ public void setFitBoundingBox( boolean fitBoundingBox ) { array.growToSize(3); if( fitBoundingBox ) { array.setName( 1, TYPE_BOUNDED ); } else { array.setName( 1, TYPE ); } } }
array.growToSize( 3 ); if( x == -1 ) { array.set(2, null); } else { array.setInt( 2, x ); }
566
60
626
<methods>public org.apache.pdfbox.cos.COSArray getCOSObject() ,public org.apache.pdfbox.pdmodel.PDPage getPage() ,public int getPageNumber() ,public int retrievePageNumber() ,public void setPage(org.apache.pdfbox.pdmodel.PDPage) ,public void setPageNumber(int) <variables>protected final non-sealed org.apache.pdfbox.cos.COSArray array
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDPageFitRectangleDestination.java
PDPageFitRectangleDestination
setRight
class PDPageFitRectangleDestination extends PDPageDestination { /** * The type of this destination. */ protected static final String TYPE = "FitR"; /** * Default constructor. * */ public PDPageFitRectangleDestination() { array.growToSize(6); array.setName( 1, TYPE ); } /** * Constructor from an existing destination array. * * @param arr The destination array. */ public PDPageFitRectangleDestination( COSArray arr ) { super( arr ); } /** * Get the left x coordinate. A return value of -1 implies that the current x-coordinate * will be used. * * @return The left x coordinate. */ public int getLeft() { return array.getInt( 2 ); } /** * Set the left x-coordinate, a value of -1 implies that the current x-coordinate * will be used. * @param x The left x coordinate. */ public void setLeft( int x ) { array.growToSize(6); if( x == -1 ) { array.set(2, null); } else { array.setInt( 2, x ); } } /** * Get the bottom y coordinate. A return value of -1 implies that the current y-coordinate * will be used. * * @return The bottom y coordinate. */ public int getBottom() { return array.getInt( 3 ); } /** * Set the bottom y-coordinate, a value of -1 implies that the current y-coordinate * will be used. * @param y The bottom y coordinate. */ public void setBottom( int y ) { array.growToSize( 6 ); if( y == -1 ) { array.set(3, null); } else { array.setInt( 3, y ); } } /** * Get the right x coordinate. A return value of -1 implies that the current x-coordinate * will be used. * * @return The right x coordinate. */ public int getRight() { return array.getInt( 4 ); } /** * Set the right x-coordinate, a value of -1 implies that the current x-coordinate * will be used. * @param x The right x coordinate. */ public void setRight( int x ) {<FILL_FUNCTION_BODY>} /** * Get the top y coordinate. A return value of -1 implies that the current y-coordinate * will be used. * * @return The top y coordinate. */ public int getTop() { return array.getInt( 5 ); } /** * Set the top y-coordinate, a value of -1 implies that the current y-coordinate * will be used. * @param y The top ycoordinate. */ public void setTop( int y ) { array.growToSize( 6 ); if( y == -1 ) { array.set(5, null); } else { array.setInt( 5, y ); } } }
array.growToSize( 6 ); if( x == -1 ) { array.set(4, null); } else { array.setInt( 4, x ); }
909
60
969
<methods>public org.apache.pdfbox.cos.COSArray getCOSObject() ,public org.apache.pdfbox.pdmodel.PDPage getPage() ,public int getPageNumber() ,public int retrievePageNumber() ,public void setPage(org.apache.pdfbox.pdmodel.PDPage) ,public void setPageNumber(int) <variables>protected final non-sealed org.apache.pdfbox.cos.COSArray array
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDPageFitWidthDestination.java
PDPageFitWidthDestination
setFitBoundingBox
class PDPageFitWidthDestination extends PDPageDestination { /** * The type of this destination. */ protected static final String TYPE = "FitH"; /** * The type of this destination. */ protected static final String TYPE_BOUNDED = "FitBH"; /** * Default constructor. * */ public PDPageFitWidthDestination() { array.growToSize(3); array.setName( 1, TYPE ); } /** * Constructor from an existing destination array. * * @param arr The destination array. */ public PDPageFitWidthDestination( COSArray arr ) { super( arr ); } /** * Get the top y coordinate. A return value of -1 implies that the current y-coordinate * will be used. * * @return The top y coordinate. */ public int getTop() { return array.getInt( 2 ); } /** * Set the top y-coordinate, a value of -1 implies that the current y-coordinate * will be used. * @param y The top ycoordinate. */ public void setTop( int y ) { array.growToSize( 3 ); if( y == -1 ) { array.set(2, null); } else { array.setInt( 2, y ); } } /** * A flag indicating if this page destination should just fit bounding box of the PDF. * * @return true If the destination should fit just the bounding box. */ public boolean fitBoundingBox() { return TYPE_BOUNDED.equals( array.getName( 1 ) ); } /** * Set if this page destination should just fit the bounding box. The default is false. * * @param fitBoundingBox A flag indicating if this should fit the bounding box. */ public void setFitBoundingBox( boolean fitBoundingBox ) {<FILL_FUNCTION_BODY>} }
array.growToSize(3); if( fitBoundingBox ) { array.setName( 1, TYPE_BOUNDED ); } else { array.setName( 1, TYPE ); }
563
65
628
<methods>public org.apache.pdfbox.cos.COSArray getCOSObject() ,public org.apache.pdfbox.pdmodel.PDPage getPage() ,public int getPageNumber() ,public int retrievePageNumber() ,public void setPage(org.apache.pdfbox.pdmodel.PDPage) ,public void setPageNumber(int) <variables>protected final non-sealed org.apache.pdfbox.cos.COSArray array
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDPageXYZDestination.java
PDPageXYZDestination
setLeft
class PDPageXYZDestination extends PDPageDestination { /** * The type of this destination. */ protected static final String TYPE = "XYZ"; /** * Default constructor. * */ public PDPageXYZDestination() { array.growToSize(5); array.setName( 1, TYPE ); } /** * Constructor from an existing destination array. * * @param arr The destination array. */ public PDPageXYZDestination( COSArray arr ) { super( arr ); } /** * Get the left x coordinate. Return values of 0 or -1 imply that the current x-coordinate * will be used. * * @return The left x coordinate. */ public int getLeft() { return array.getInt( 2 ); } /** * Set the left x-coordinate, values 0 or -1 imply that the current x-coordinate * will be used. * @param x The left x coordinate. */ public void setLeft( int x ) {<FILL_FUNCTION_BODY>} /** * Get the top y coordinate. Return values of 0 or -1 imply that the current y-coordinate * will be used. * * @return The top y coordinate. */ public int getTop() { return array.getInt( 3 ); } /** * Set the top y-coordinate, values 0 or -1 imply that the current y-coordinate * will be used. * @param y The top ycoordinate. */ public void setTop( int y ) { array.growToSize(5); if( y == -1 ) { array.set(3, null); } else { array.setInt( 3, y ); } } /** * Get the zoom value. Return values of 0 or -1 imply that the current zoom * will be used. * * @return The zoom value for the page. */ public float getZoom() { COSBase obj = array.getObject(4); if (obj instanceof COSNumber) { return ((COSNumber) obj).floatValue(); } return -1; } /** * Set the zoom value for the page, values 0 or -1 imply that the current zoom * will be used. * @param zoom The zoom value. */ public void setZoom( float zoom ) { array.growToSize( 5 ); if( Float.compare(zoom, -1) == 0) { array.set(4, null); } else { array.set( 4, new COSFloat(zoom) ); } } }
array.growToSize( 5 ); if( x == -1 ) { array.set(2, null); } else { array.setInt( 2, x ); }
759
60
819
<methods>public org.apache.pdfbox.cos.COSArray getCOSObject() ,public org.apache.pdfbox.pdmodel.PDPage getPage() ,public int getPageNumber() ,public int retrievePageNumber() ,public void setPage(org.apache.pdfbox.pdmodel.PDPage) ,public void setPageNumber(int) <variables>protected final non-sealed org.apache.pdfbox.cos.COSArray array
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/outline/PDDocumentOutline.java
PDDocumentOutline
closeNode
class PDDocumentOutline extends PDOutlineNode { /** * Default Constructor. */ public PDDocumentOutline() { getCOSObject().setName(COSName.TYPE, COSName.OUTLINES.getName()); } /** * Constructor for an existing document outline. * * @param dic The storage dictionary. */ public PDDocumentOutline( COSDictionary dic ) { super( dic ); getCOSObject().setName(COSName.TYPE, COSName.OUTLINES.getName()); } @Override public boolean isNodeOpen() { return true; } @Override public void openNode() { // The root of the outline hierarchy is not an OutlineItem and cannot be opened or closed } @Override public void closeNode() {<FILL_FUNCTION_BODY>} }
// The root of the outline hierarchy is not an OutlineItem and cannot be opened or closed
245
24
269
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public void addFirst(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem) ,public void addLast(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem) ,public Iterable<org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem> children() ,public void closeNode() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem getFirstChild() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem getLastChild() ,public int getOpenCount() ,public boolean hasChildren() ,public boolean isNodeOpen() ,public void openNode() <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/outline/PDOutlineItemIterator.java
PDOutlineItemIterator
next
class PDOutlineItemIterator implements Iterator<PDOutlineItem> { private PDOutlineItem currentItem; private final PDOutlineItem startingItem; PDOutlineItemIterator(PDOutlineItem startingItem) { this.startingItem = startingItem; } @Override public boolean hasNext() { if (startingItem == null) { return false; } if (currentItem == null) { return true; } PDOutlineItem sibling = currentItem.getNextSibling(); return sibling != null && !startingItem.equals(sibling); } @Override public PDOutlineItem next() {<FILL_FUNCTION_BODY>} @Override public void remove() { throw new UnsupportedOperationException(); } }
if (!hasNext()) { throw new NoSuchElementException(); } if (currentItem == null) { currentItem = startingItem; } else { currentItem = currentItem.getNextSibling(); } return currentItem;
232
77
309
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/FieldUtils.java
KeyValue
getPairableItems
class KeyValue { private final String key; private final String value; KeyValue(final String theKey, final String theValue) { this.key = theKey; this.value = theValue; } public String getKey() { return this.key; } public String getValue() { return this.value; } @Override public String toString() { return "(" + this.key + ", " + this.value + ")"; } } /** * Constructor. */ private FieldUtils() { } /** * Return two related lists as a single list with key value pairs. * * @param key the key elements * @param value the value elements * @return a sorted list of KeyValue elements. */ static List<KeyValue> toKeyValueList(List<String> key, List<String> value) { List<KeyValue> list = new ArrayList<>(key.size()); for(int i =0; i<key.size(); i++) { list.add(new FieldUtils.KeyValue(key.get(i),value.get(i))); } return list; } /** * Sort two related lists simultaneously by the elements in the key parameter. * * @param pairs a list of KeyValue elements */ static void sortByValue(List<KeyValue> pairs) { pairs.sort(BY_VALUE_COMPARATOR); } /** * Sort two related lists simultaneously by the elements in the value parameter. * * @param pairs a list of KeyValue elements */ static void sortByKey(List<KeyValue> pairs) { pairs.sort(BY_KEY_COMPARATOR); } /** * Return either one of a list which can have two-element arrays entries. * <p> * Some entries in a dictionary can either be an array of elements * or an array of two-element arrays. This method will either return * the elements in the array or in case of two-element arrays, the element * designated by the pair index * </p> * <p> * An {@link IllegalArgumentException} will be thrown if the items contain * two-element arrays and the index is not 0 or 1. * </p> * * @param items the array of elements or two-element arrays * @param pairIdx the index into the two-element array * @return a List of single elements */ static List<String> getPairableItems(COSBase items, int pairIdx) {<FILL_FUNCTION_BODY>
if (pairIdx < 0 || pairIdx > 1) { throw new IllegalArgumentException("Only 0 and 1 are allowed as an index into two-element arrays"); } if (items instanceof COSString) { List<String> array = new ArrayList<>(1); array.add(((COSString) items).getString()); return array; } else if (items instanceof COSArray) { List<String> entryList = new ArrayList<>(); for (COSBase entry : (COSArray) items) { if (entry instanceof COSString) { entryList.add(((COSString) entry).getString()); } else if (entry instanceof COSArray) { COSArray cosArray = (COSArray) entry; if (cosArray.size() >= pairIdx +1 && cosArray.get(pairIdx) instanceof COSString) { entryList.add(((COSString) cosArray.get(pairIdx)).getString()); } } } return entryList; } return Collections.emptyList();
708
293
1,001
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDCheckBox.java
PDCheckBox
getOnValue
class PDCheckBox extends PDButton { /** * @see PDField#PDField(PDAcroForm) * * @param acroForm The acroform. */ public PDCheckBox(PDAcroForm acroForm) { super(acroForm); } /** * Constructor. * * @param acroForm The form that this field is part of. * @param field the PDF object to represent as a field. * @param parent the parent node of the node */ PDCheckBox(PDAcroForm acroForm, COSDictionary field, PDNonTerminalField parent) { super(acroForm, field, parent); } /** * This will tell if this radio button is currently checked or not. * This is equivalent to calling {@link #getValue()}. * * @return true If this field is checked. */ public boolean isChecked() { return getValue().compareTo(getOnValue()) == 0; } /** * Checks the check box. * * @throws IOException if the appearance couldn't be generated. */ public void check() throws IOException { setValue(getOnValue()); } /** * Unchecks the check box. * * @throws IOException if the appearance couldn't be generated. */ public void unCheck() throws IOException { setValue(COSName.Off.getName()); } /** * Get the value which sets the check box to the On state. * * <p>The On value should be 'Yes' but other values are possible * so we need to look for that. On the other hand the Off value shall * always be 'Off'. If not set or not part of the normal appearance keys * 'Off' is the default</p> * * @return the value setting the check box to the On state. * If an empty string is returned there is no appearance definition. */ public String getOnValue() {<FILL_FUNCTION_BODY>} }
PDAnnotationWidget widget = this.getWidgets().get(0); PDAppearanceDictionary apDictionary = widget.getAppearance(); if (apDictionary != null) { PDAppearanceEntry normalAppearance = apDictionary.getNormalAppearance(); if (normalAppearance != null) { Set<COSName> entries = normalAppearance.getSubDictionary().keySet(); for (COSName entry : entries) { if (COSName.Off.compareTo(entry) != 0) { return entry.getName(); } } } } return "";
554
173
727
<methods>public java.lang.String getDefaultValue() ,public List<java.lang.String> getExportValues() ,public Set<java.lang.String> getOnValues() ,public java.lang.String getValue() ,public java.lang.String getValueAsString() ,public boolean isPushButton() ,public boolean isRadioButton() ,public void setDefaultValue(java.lang.String) ,public void setExportValues(List<java.lang.String>) ,public void setValue(java.lang.String) throws java.io.IOException,public void setValue(int) throws java.io.IOException<variables>static final int FLAG_PUSHBUTTON,static final int FLAG_RADIO,static final int FLAG_RADIOS_IN_UNISON
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDComboBox.java
PDComboBox
constructAppearances
class PDComboBox extends PDChoice { private static final int FLAG_EDIT = 1 << 18; /** * @see PDField#PDField(PDAcroForm) * * @param acroForm The acroform. */ public PDComboBox(PDAcroForm acroForm) { super(acroForm); setCombo(true); } /** * Constructor. * * @param acroForm The form that this field is part of. * @param field the PDF object to represent as a field. * @param parent the parent node of the node */ PDComboBox(PDAcroForm acroForm, COSDictionary field, PDNonTerminalField parent) { super(acroForm, field, parent); } /** * Determines if Edit is set. * * @return true if the combo box shall include an editable text box as well as a drop-down list. */ public boolean isEdit() { return getCOSObject().getFlag(COSName.FF, FLAG_EDIT); } /** * Set the Edit bit. * * @param edit The value for Edit. */ public void setEdit(boolean edit) { getCOSObject().setFlag(COSName.FF, FLAG_EDIT, edit); } @Override void constructAppearances() throws IOException {<FILL_FUNCTION_BODY>} }
AppearanceGeneratorHelper apHelper; apHelper = new AppearanceGeneratorHelper(this); List<String> values = getValue(); if (!values.isEmpty()) { apHelper.setAppearanceValue(values.get(0)); } else { apHelper.setAppearanceValue(""); }
409
90
499
<methods>public void <init>(org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm) ,public List<java.lang.String> getDefaultValue() ,public List<java.lang.String> getOptions() ,public List<java.lang.String> getOptionsDisplayValues() ,public List<java.lang.String> getOptionsExportValues() ,public List<java.lang.Integer> getSelectedOptionsIndex() ,public List<java.lang.String> getValue() ,public java.lang.String getValueAsString() ,public boolean isCombo() ,public boolean isCommitOnSelChange() ,public boolean isDoNotSpellCheck() ,public boolean isMultiSelect() ,public boolean isSort() ,public void setCombo(boolean) ,public void setCommitOnSelChange(boolean) ,public void setDefaultValue(java.lang.String) ,public void setDoNotSpellCheck(boolean) ,public void setMultiSelect(boolean) ,public void setOptions(List<java.lang.String>) ,public void setOptions(List<java.lang.String>, List<java.lang.String>) ,public void setSelectedOptionsIndex(List<java.lang.Integer>) ,public void setSort(boolean) ,public void setValue(java.lang.String) throws java.io.IOException,public void setValue(List<java.lang.String>) throws java.io.IOException<variables>static final int FLAG_COMBO,private static final int FLAG_COMMIT_ON_SEL_CHANGE,private static final int FLAG_DO_NOT_SPELL_CHECK,private static final int FLAG_MULTI_SELECT,private static final int FLAG_SORT
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDFieldFactory.java
PDFieldFactory
findFieldType
class PDFieldFactory { private static final String FIELD_TYPE_TEXT = "Tx"; private static final String FIELD_TYPE_BUTTON = "Btn"; private static final String FIELD_TYPE_CHOICE = "Ch"; private static final String FIELD_TYPE_SIGNATURE = "Sig"; private PDFieldFactory() { } /** * Creates a COSField subclass from the given field. * * @param form the form that the field is part of * @param field the dictionary representing a field element * @param parent the parent node of the node to be created * @return the corresponding PDField instance */ public static PDField createField(PDAcroForm form, COSDictionary field, PDNonTerminalField parent) { // Test if we have a non terminal field first as it might have // properties which do apply to other fields // A non terminal fields has Kids entries which do have // a field name (other than annotations) if (field.containsKey(COSName.KIDS)) { COSArray kids = field.getCOSArray(COSName.KIDS); if (kids != null && !kids.isEmpty()) { for (int i = 0; i < kids.size(); i++) { COSBase kid = kids.getObject(i); if (kid instanceof COSDictionary && ((COSDictionary) kid).getString(COSName.T) != null) { return new PDNonTerminalField(form, field, parent); } } } } String fieldType = findFieldType(field); if (FIELD_TYPE_CHOICE.equals(fieldType)) { return createChoiceSubType(form, field, parent); } else if (FIELD_TYPE_TEXT.equals(fieldType)) { return new PDTextField(form, field, parent); } else if (FIELD_TYPE_SIGNATURE.equals(fieldType)) { return new PDSignatureField(form, field, parent); } else if (FIELD_TYPE_BUTTON.equals(fieldType)) { return createButtonSubType(form, field, parent); } else { // an erroneous non-field object, see PDFBOX-2885 return null; } } private static PDField createChoiceSubType(PDAcroForm form, COSDictionary field, PDNonTerminalField parent) { int flags = field.getInt(COSName.FF, 0); if ((flags & PDChoice.FLAG_COMBO) != 0) { return new PDComboBox(form, field, parent); } else { return new PDListBox(form, field, parent); } } private static PDField createButtonSubType(PDAcroForm form, COSDictionary field, PDNonTerminalField parent) { int flags = field.getInt(COSName.FF, 0); // BJL: I have found that the radio flag bit is not always set // and that sometimes there is just a kids dictionary. // so, if there is a kids dictionary then it must be a radio button group. if ((flags & PDButton.FLAG_RADIO) != 0) { return new PDRadioButton(form, field, parent); } else if ((flags & PDButton.FLAG_PUSHBUTTON) != 0) { return new PDPushButton(form, field, parent); } else { return new PDCheckBox(form, field, parent); } } private static String findFieldType(COSDictionary dic) {<FILL_FUNCTION_BODY>} }
String retval = dic.getNameAsString(COSName.FT); if (retval == null) { COSDictionary base = dic.getCOSDictionary(COSName.PARENT, COSName.P); return base != null ? findFieldType(base):null; } return retval;
1,006
86
1,092
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDFieldTree.java
FieldIterator
enqueueKids
class FieldIterator implements Iterator<PDField> { private final Queue<PDField> queue = new ArrayDeque<>(); // PDFBOX-5044: to prevent recursion // must be COSDictionary and not PDField, because PDField is newly created each time private final Set<COSDictionary> set = Collections.newSetFromMap(new IdentityHashMap<>()); private FieldIterator(PDAcroForm form) { List<PDField> fields = form.getFields(); for (PDField field : fields) { enqueueKids(field); } } @Override public boolean hasNext() { return !queue.isEmpty(); } @Override public PDField next() { if(!hasNext()) { throw new NoSuchElementException(); } return queue.poll(); } @Override public void remove() { throw new UnsupportedOperationException(); } private void enqueueKids(PDField node) {<FILL_FUNCTION_BODY>} }
queue.add(node); set.add(node.getCOSObject()); if (node instanceof PDNonTerminalField) { List<PDField> kids = ((PDNonTerminalField) node).getChildren(); for (PDField kid : kids) { if (set.contains(kid.getCOSObject())) { LOG.error( "Child of field '{}' already exists elsewhere, ignored to avoid recursion", node.getFullyQualifiedName()); } else { enqueueKids(kid); } } }
298
158
456
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDListBox.java
PDListBox
setTopIndex
class PDListBox extends PDChoice { /** * @see PDField#PDField(PDAcroForm) * * @param acroForm The acroform. */ public PDListBox(PDAcroForm acroForm) { super(acroForm); } /** * Constructor. * * @param acroForm The form that this field is part of. * @param field the PDF object to represent as a field. * @param parent the parent node of the node */ PDListBox(PDAcroForm acroForm, COSDictionary field, PDNonTerminalField parent) { super(acroForm, field, parent); } /** * This will get the top index "TI" value. * * @return the top index, default value 0. */ public int getTopIndex() { return getCOSObject().getInt(COSName.TI, 0); } /** * This will set top index "TI" value. * * @param topIndex the value for the top index, null will remove the value. */ public void setTopIndex(Integer topIndex) {<FILL_FUNCTION_BODY>} @Override void constructAppearances() throws IOException { AppearanceGeneratorHelper apHelper; apHelper = new AppearanceGeneratorHelper(this); apHelper.setAppearanceValue(""); } }
if (topIndex != null) { getCOSObject().setInt(COSName.TI, topIndex); } else { getCOSObject().removeItem(COSName.TI); }
394
63
457
<methods>public void <init>(org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm) ,public List<java.lang.String> getDefaultValue() ,public List<java.lang.String> getOptions() ,public List<java.lang.String> getOptionsDisplayValues() ,public List<java.lang.String> getOptionsExportValues() ,public List<java.lang.Integer> getSelectedOptionsIndex() ,public List<java.lang.String> getValue() ,public java.lang.String getValueAsString() ,public boolean isCombo() ,public boolean isCommitOnSelChange() ,public boolean isDoNotSpellCheck() ,public boolean isMultiSelect() ,public boolean isSort() ,public void setCombo(boolean) ,public void setCommitOnSelChange(boolean) ,public void setDefaultValue(java.lang.String) ,public void setDoNotSpellCheck(boolean) ,public void setMultiSelect(boolean) ,public void setOptions(List<java.lang.String>) ,public void setOptions(List<java.lang.String>, List<java.lang.String>) ,public void setSelectedOptionsIndex(List<java.lang.Integer>) ,public void setSort(boolean) ,public void setValue(java.lang.String) throws java.io.IOException,public void setValue(List<java.lang.String>) throws java.io.IOException<variables>static final int FLAG_COMBO,private static final int FLAG_COMMIT_ON_SEL_CHANGE,private static final int FLAG_DO_NOT_SPELL_CHECK,private static final int FLAG_MULTI_SELECT,private static final int FLAG_SORT
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDPushButton.java
PDPushButton
setExportValues
class PDPushButton extends PDButton { /** * @see PDField#PDField(PDAcroForm) * * @param acroForm The acroform. */ public PDPushButton(PDAcroForm acroForm) { super(acroForm); getCOSObject().setFlag(COSName.FF, FLAG_PUSHBUTTON, true); } /** * Constructor. * * @param acroForm The form that this field is part of. * @param field the PDF object to represent as a field. * @param parent the parent node of the node */ PDPushButton(PDAcroForm acroForm, COSDictionary field, PDNonTerminalField parent) { super(acroForm, field, parent); } @Override public List<String> getExportValues() { return Collections.emptyList(); } @Override public void setExportValues(List<String> values) {<FILL_FUNCTION_BODY>} @Override public String getValue() { return ""; } @Override public String getDefaultValue() { return ""; } @Override public String getValueAsString() { return getValue(); } @Override public Set<String> getOnValues() { return Collections.emptySet(); } @Override void constructAppearances() throws IOException { // TODO: add appearance handler to generate/update appearance } }
if (values != null && !values.isEmpty()) { throw new IllegalArgumentException("A PDPushButton shall not use the Opt entry in the field dictionary"); }
428
46
474
<methods>public java.lang.String getDefaultValue() ,public List<java.lang.String> getExportValues() ,public Set<java.lang.String> getOnValues() ,public java.lang.String getValue() ,public java.lang.String getValueAsString() ,public boolean isPushButton() ,public boolean isRadioButton() ,public void setDefaultValue(java.lang.String) ,public void setExportValues(List<java.lang.String>) ,public void setValue(java.lang.String) throws java.io.IOException,public void setValue(int) throws java.io.IOException<variables>static final int FLAG_PUSHBUTTON,static final int FLAG_RADIO,static final int FLAG_RADIOS_IN_UNISON
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDRadioButton.java
PDRadioButton
getSelectedExportValues
class PDRadioButton extends PDButton { /** * A Ff flag. */ private static final int FLAG_NO_TOGGLE_TO_OFF = 1 << 14; /** * @see PDField#PDField(PDAcroForm) * * @param acroForm The acroform. */ public PDRadioButton(PDAcroForm acroForm) { super(acroForm); getCOSObject().setFlag(COSName.FF, FLAG_RADIO, true); } /** * Constructor. * * @param acroForm The form that this field is part of. * @param field the PDF object to represent as a field. * @param parent the parent node of the node */ PDRadioButton(PDAcroForm acroForm, COSDictionary field, PDNonTerminalField parent) { super(acroForm, field, parent); } /** * From the PDF Spec <br> * If set, a group of radio buttons within a radio button field that use the same value for the on state will turn * on and off in unison; that is if one is checked, they are all checked. If clear, the buttons are mutually * exclusive (the same behavior as HTML radio buttons). * * @param radiosInUnison The new flag for radiosInUnison. */ public void setRadiosInUnison(boolean radiosInUnison) { getCOSObject().setFlag(COSName.FF, FLAG_RADIOS_IN_UNISON, radiosInUnison); } /** * * @return true If the flag is set for radios in unison. */ public boolean isRadiosInUnison() { return getCOSObject().getFlag(COSName.FF, FLAG_RADIOS_IN_UNISON); } /** * This will get the selected index. * <p> * A RadioButton might have multiple same value options which are not selected jointly if * they are not set in unison {@link #isRadiosInUnison()}.</p> * * <p> * The method will return the first selected index or -1 if no option is selected.</p> * * @return the first selected index or -1. */ public int getSelectedIndex() { int idx = 0; for (PDAnnotationWidget widget : getWidgets()) { if (!COSName.Off.equals(widget.getAppearanceState())) { return idx; } idx ++; } return -1; } /** * This will get the selected export values. * <p> * A RadioButton might have an export value to allow field values * which can not be encoded as PDFDocEncoding or for the same export value * being assigned to multiple RadioButtons in a group.<br> * To define an export value the RadioButton must define options {@link #setExportValues(List)} * which correspond to the individual items within the RadioButton.</p> * <p> * The method will either return the corresponding values from the options entry or in case there * is no such entry the fields value</p> * * @return the export value of the field. */ public List<String> getSelectedExportValues() {<FILL_FUNCTION_BODY>} }
List<String> exportValues = getExportValues(); List<String> selectedExportValues = new ArrayList<>(); if (exportValues.isEmpty()) { selectedExportValues.add(getValue()); return selectedExportValues; } else { String fieldValue = getValue(); int idx = 0; for (String onValue : getOnValues()) { if (onValue.compareTo(fieldValue) == 0) { selectedExportValues.add(exportValues.get(idx)); } ++idx; } return selectedExportValues; }
908
154
1,062
<methods>public java.lang.String getDefaultValue() ,public List<java.lang.String> getExportValues() ,public Set<java.lang.String> getOnValues() ,public java.lang.String getValue() ,public java.lang.String getValueAsString() ,public boolean isPushButton() ,public boolean isRadioButton() ,public void setDefaultValue(java.lang.String) ,public void setExportValues(List<java.lang.String>) ,public void setValue(java.lang.String) throws java.io.IOException,public void setValue(int) throws java.io.IOException<variables>static final int FLAG_PUSHBUTTON,static final int FLAG_RADIO,static final int FLAG_RADIOS_IN_UNISON
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDSignatureField.java
PDSignatureField
generatePartialName
class PDSignatureField extends PDTerminalField { private static final Logger LOG = LogManager.getLogger(PDSignatureField.class); /** * @see PDTerminalField#PDTerminalField(PDAcroForm) * * @param acroForm The acroForm for this field. */ public PDSignatureField(PDAcroForm acroForm) { super(acroForm); getCOSObject().setItem(COSName.FT, COSName.SIG); PDAnnotationWidget firstWidget = getWidgets().get(0); firstWidget.setLocked(true); firstWidget.setPrinted(true); setPartialName(generatePartialName()); } /** * Constructor. * * @param acroForm The form that this field is part of. * @param field the PDF object to represent as a field. * @param parent the parent node of the node to be created */ PDSignatureField(PDAcroForm acroForm, COSDictionary field, PDNonTerminalField parent) { super(acroForm, field, parent); } /** * Generate a unique name for the signature. * * @return the signature's unique name */ private String generatePartialName() {<FILL_FUNCTION_BODY>} /** * Get the signature dictionary. * * @return the signature dictionary * */ public PDSignature getSignature() { return getValue(); } /** * Sets the value of this field to be the given signature. * * @param value is the PDSignatureField * * @throws IOException if the new value could not be applied */ public void setValue(PDSignature value) throws IOException { getCOSObject().setItem(COSName.V, value); applyChange(); } /** * <b>This will throw an UnsupportedOperationException if used as the signature fields * value can't be set using a String</b> * * @param value the plain text value. * * @throws UnsupportedOperationException in all cases! */ @Override public void setValue(String value) { throw new UnsupportedOperationException("Signature fields don't support setting the value as String " + "- use setValue(PDSignature value) instead"); } /** * Sets the default value of this field to be the given signature. * * @param value is the PDSignatureField */ public void setDefaultValue(PDSignature value) { getCOSObject().setItem(COSName.DV, value); } /** * Returns the signature contained in this field. * * @return A signature dictionary. */ public PDSignature getValue() { COSDictionary value = getCOSObject().getCOSDictionary(COSName.V); return value != null ? new PDSignature(value) : null; } /** * Returns the default value, if any. * * @return A signature dictionary. */ public PDSignature getDefaultValue() { COSDictionary value = getCOSObject().getCOSDictionary(COSName.DV); return value != null ? new PDSignature(value) : null; } @Override public String getValueAsString() { PDSignature signature = getValue(); return signature != null ? signature.toString() : ""; } /** * <p>(Optional; PDF 1.5) A seed value dictionary containing information * that constrains the properties of a signature that is applied to the * field.</p> * * @return the seed value dictionary as PDSeedValue */ public PDSeedValue getSeedValue() { COSDictionary dict = getCOSObject().getCOSDictionary(COSName.SV); return dict != null ? new PDSeedValue(dict) : null; } /** * <p>(Optional; PDF 1.) A seed value dictionary containing information * that constrains the properties of a signature that is applied to the * field.</p> * * @param sv is the seed value dictionary as PDSeedValue */ public void setSeedValue(PDSeedValue sv) { if (sv != null) { getCOSObject().setItem(COSName.SV, sv); } } @Override void constructAppearances() throws IOException { PDAnnotationWidget widget = this.getWidgets().get(0); if (widget != null) { // check if the signature is visible if (widget.getRectangle() == null || Float.compare(widget.getRectangle().getHeight(), 0) == 0 && Float.compare(widget.getRectangle().getWidth(), 0) == 0 || widget.isNoView() || widget.isHidden()) { return; } // TODO: implement appearance generation for signatures (PDFBOX-3524) LOG.warn("Appearance generation for signature fields not implemented here. " + "You need to generate/update that manually, see the " + "CreateVisibleSignature*.java files in the examples subproject " + "of the source code download"); } } }
String fieldName = "Signature"; Set<String> nameSet = new HashSet<>(); getAcroForm().getFieldTree().forEach(field -> nameSet.add(field.getPartialName())); int i = 1; while (nameSet.contains(fieldName + i)) { ++i; } return fieldName+i;
1,446
94
1,540
<methods>public int getFieldFlags() ,public java.lang.String getFieldType() ,public List<org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget> getWidgets() ,public void importFDF(org.apache.pdfbox.pdmodel.fdf.FDFField) throws java.io.IOException,public void setActions(org.apache.pdfbox.pdmodel.interactive.action.PDFormFieldAdditionalActions) ,public void setWidgets(List<org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget>) <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDTerminalField.java
PDTerminalField
getFieldFlags
class PDTerminalField extends PDField { /** * Constructor. * * @param acroForm The form that this field is part of. */ protected PDTerminalField(PDAcroForm acroForm) { super(acroForm); } /** * Constructor. * * @param acroForm The form that this field is part of. * @param field the PDF object to represent as a field. * @param parent the parent node of the node */ PDTerminalField(PDAcroForm acroForm, COSDictionary field, PDNonTerminalField parent) { super(acroForm, field, parent); } /** * Set the actions of the field. * * @param actions The field actions. */ public void setActions(PDFormFieldAdditionalActions actions) { getCOSObject().setItem(COSName.AA, actions); } @Override public int getFieldFlags() {<FILL_FUNCTION_BODY>} @Override public String getFieldType() { String fieldType = getCOSObject().getNameAsString(COSName.FT); if (fieldType == null && getParent() != null) { fieldType = getParent().getFieldType(); } return fieldType; } @Override public void importFDF(FDFField fdfField) throws IOException { super.importFDF(fdfField); Integer f = fdfField.getWidgetFieldFlags(); for (PDAnnotationWidget widget : getWidgets()) { if (f != null) { widget.setAnnotationFlags(f); } else { // these are supposed to be ignored if the F is set. Integer setF = fdfField.getSetWidgetFieldFlags(); int annotFlags = widget.getAnnotationFlags(); if (setF != null) { annotFlags = annotFlags | setF; widget.setAnnotationFlags(annotFlags); } Integer clrF = fdfField.getClearWidgetFieldFlags(); if (clrF != null) { // we have to clear the bits of the document fields for every bit that is // set in this field. // // Example: // docF = 1011 // clrF = 1101 // clrFValue = 0010; // newValue = 1011 & 0010 which is 0010 int clrFValue = clrF; clrFValue ^= 0xFFFFFFFFL; annotFlags = annotFlags & clrFValue; widget.setAnnotationFlags(annotFlags); } } } } @Override FDFField exportFDF() throws IOException { FDFField fdfField = new FDFField(); fdfField.setPartialFieldName(getPartialName()); fdfField.setValue(getCOSObject().getDictionaryObject(COSName.V)); // fixme: the old code which was here assumed that Kids were PDField instances, // which is never true. They're annotation widgets. return fdfField; } /** * Returns the widget annotations associated with this field. * * @return The list of widget annotations. Be aware that this list is <i>not</i> backed by the * actual widget collection of the field, so adding or deleting has no effect on the PDF * document until you call {@link #setWidgets(java.util.List) setWidgets()} with the modified * list. */ @Override public List<PDAnnotationWidget> getWidgets() { List<PDAnnotationWidget> widgets = new ArrayList<>(); COSArray kids = getCOSObject().getCOSArray(COSName.KIDS); if (kids == null) { // the field itself is a widget widgets.add(new PDAnnotationWidget(getCOSObject())); } else if (!kids.isEmpty()) { // there are multiple widgets for (int i = 0; i < kids.size(); i++) { COSBase kid = kids.getObject(i); if (kid instanceof COSDictionary) { widgets.add(new PDAnnotationWidget((COSDictionary)kid)); } } } return widgets; } /** * Sets the field's widget annotations. * * @param children The list of widget annotations. */ public void setWidgets(List<PDAnnotationWidget> children) { COSArray kidsArray = new COSArray(children); getCOSObject().setItem(COSName.KIDS, kidsArray); for (PDAnnotationWidget widget : children) { widget.getCOSObject().setItem(COSName.PARENT, this); } } /** * Applies a value change to the field. Generates appearances if required and raises events. * * @throws IOException if the appearance couldn't be generated */ protected final void applyChange() throws IOException { constructAppearances(); // if we supported JavaScript we would raise a field changed event here } /** * Constructs appearance streams and appearance dictionaries for all widget annotations. * Subclasses should not call this method directly but via {@link #applyChange()}. * * @throws IOException if the appearance couldn't be generated */ abstract void constructAppearances() throws IOException; }
int retval = 0; COSInteger ff = (COSInteger) getCOSObject().getDictionaryObject(COSName.FF); if (ff != null) { retval = ff.intValue(); } else if (getParent() != null) { retval = getParent().getFieldFlags(); } return retval;
1,470
99
1,569
<methods>public org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm getAcroForm() ,public org.apache.pdfbox.pdmodel.interactive.action.PDFormFieldAdditionalActions getActions() ,public java.lang.String getAlternateFieldName() ,public org.apache.pdfbox.cos.COSDictionary getCOSObject() ,public abstract int getFieldFlags() ,public abstract java.lang.String getFieldType() ,public java.lang.String getFullyQualifiedName() ,public java.lang.String getMappingName() ,public org.apache.pdfbox.pdmodel.interactive.form.PDNonTerminalField getParent() ,public java.lang.String getPartialName() ,public abstract java.lang.String getValueAsString() ,public abstract List<org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget> getWidgets() ,public boolean isNoExport() ,public boolean isReadOnly() ,public boolean isRequired() ,public void setAlternateFieldName(java.lang.String) ,public void setFieldFlags(int) ,public void setMappingName(java.lang.String) ,public void setNoExport(boolean) ,public void setPartialName(java.lang.String) ,public void setReadOnly(boolean) ,public void setRequired(boolean) ,public abstract void setValue(java.lang.String) throws java.io.IOException,public java.lang.String toString() <variables>private static final int FLAG_NO_EXPORT,private static final int FLAG_READ_ONLY,private static final int FLAG_REQUIRED,private final non-sealed org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm acroForm,private final non-sealed org.apache.pdfbox.cos.COSDictionary dictionary,private final non-sealed org.apache.pdfbox.pdmodel.interactive.form.PDNonTerminalField parent
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDVariableText.java
PDVariableText
setDefaultStyleString
class PDVariableText extends PDTerminalField { public static final int QUADDING_LEFT = 0; public static final int QUADDING_CENTERED = 1; public static final int QUADDING_RIGHT = 2; /** * @see PDTerminalField#PDTerminalField(PDAcroForm) * * @param acroForm The acroform. */ PDVariableText(PDAcroForm acroForm) { super(acroForm); } /** * Constructor. * * @param acroForm The form that this field is part of. * @param field the PDF object to represent as a field. * @param parent the parent node of the node */ PDVariableText(PDAcroForm acroForm, COSDictionary field, PDNonTerminalField parent) { super(acroForm, field, parent); } /** * Get the default appearance. * * This is an inheritable attribute. * * The default appearance contains a set of default graphics and text operators * to define the field’s text size and color. * * @return the DA element of the dictionary object */ public String getDefaultAppearance() { COSBase base = getInheritableAttribute(COSName.DA); COSString defaultAppearance; if (!(base instanceof COSString)) { return null; } defaultAppearance = (COSString) base; return defaultAppearance.getString(); } /** * Get the default appearance. * * This is an inheritable attribute. * * The default appearance contains a set of default graphics and text operators * to define the field’s text size and color. * * @return the DA element of the dictionary object */ PDDefaultAppearanceString getDefaultAppearanceString() throws IOException { COSBase base = getInheritableAttribute(COSName.DA); COSString da = null; if (base instanceof COSString) { da = (COSString) base; } PDResources dr = getAcroForm().getDefaultResources(); return new PDDefaultAppearanceString(da, dr); } /** * Set the default appearance. * * This will set the local default appearance for the variable text field only, not * affecting a default appearance in the parent hierarchy. * * Providing null as the value will remove the local default appearance. * <p> * This method can also be used to change the font of a field, by replacing the font name from * this string with another font name found in the AcroForm default resources <u>before</u> * calling {@link #setValue(java.lang.String) setValue(String)}, see also * <a href="https://stackoverflow.com/questions/47995062/pdfbox-api-how-to-handle-cyrillic-values">this * stackoverflow answer</a>. For example, "/Helv 10 Tf 0 g" can be replaced with "/F1 10 Tf 0 * g". Performance may go down (see * <a href="https://issues.apache.org/jira/browse/PDFBOX-4508">PDFBOX-4508)</a> if this is done * for many fields and with a very large font (e.g. ArialUni); to avoid this, save and reload * the file after changing all fields. * * @param daValue a string describing the default appearance */ public void setDefaultAppearance(String daValue) { getCOSObject().setString(COSName.DA, daValue); } /** * Get the default style string. * * The default style string defines the default style for * rich text fields. * * @return the DS element of the dictionary object */ public String getDefaultStyleString() { return getCOSObject().getString(COSName.DS); } /** * Set the default style string. * * Providing null as the value will remove the default style string. * * @param defaultStyleString a string describing the default style. */ public void setDefaultStyleString(String defaultStyleString) {<FILL_FUNCTION_BODY>} /** * This will get the 'quadding' or justification of the text to be displayed. * * This is an inheritable attribute. * <br> * 0 - Left (default)<br> * 1 - Centered<br> * 2 - Right<br> * Please see the QUADDING_CONSTANTS. * * @return The justification of the text strings. */ public int getQ() { int retval = 0; COSNumber number = (COSNumber)getInheritableAttribute(COSName.Q); if (number != null) { retval = number.intValue(); } return retval; } /** * This will set the quadding/justification of the text. See QUADDING constants. * * @param q The new text justification. */ public void setQ(int q) { getCOSObject().setInt(COSName.Q, q); } /** * Get the fields rich text value. * * @return the rich text value string */ public String getRichTextValue() { return getStringOrStream(getInheritableAttribute(COSName.RV)); } /** * Set the fields rich text value. * * <p> * Setting the rich text value will not generate the appearance * for the field. * <br> * You can set {@link PDAcroForm#setNeedAppearances(Boolean)} to * signal a conforming reader to generate the appearance stream. * </p> * * Providing null as the value will remove the default style string. * * @param richTextValue a rich text string */ public void setRichTextValue(String richTextValue) { if (richTextValue != null) { getCOSObject().setItem(COSName.RV, new COSString(richTextValue)); } else { getCOSObject().removeItem(COSName.RV); } } /** * Get a text as text stream. * * Some dictionary entries allow either a text or a text stream. * * @param base the potential text or text stream * @return the text stream */ protected final String getStringOrStream(COSBase base) { if (base instanceof COSString) { return ((COSString)base).getString(); } else if (base instanceof COSStream) { return ((COSStream)base).toTextString(); } return ""; } }
if (defaultStyleString != null) { getCOSObject().setItem(COSName.DS, new COSString(defaultStyleString)); } else { getCOSObject().removeItem(COSName.DS); }
1,871
70
1,941
<methods>public int getFieldFlags() ,public java.lang.String getFieldType() ,public List<org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget> getWidgets() ,public void importFDF(org.apache.pdfbox.pdmodel.fdf.FDFField) throws java.io.IOException,public void setActions(org.apache.pdfbox.pdmodel.interactive.action.PDFormFieldAdditionalActions) ,public void setWidgets(List<org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget>) <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDXFAResource.java
PDXFAResource
getBytesFromPacket
class PDXFAResource implements COSObjectable { private final COSBase xfa; /** * Constructor. * * @param xfaBase The xfa resource. */ public PDXFAResource(COSBase xfaBase) { xfa = xfaBase; } /** * {@inheritDoc} */ @Override public COSBase getCOSObject() { return xfa; } /** * Get the XFA content as byte array. * * The XFA is either a stream containing the entire XFA resource or an array specifying individual packets that * together make up the XFA resource. * * A packet is a pair of a string and stream. The string contains the name of the XML element and the stream * contains the complete text of this XML element. Each packet represents a complete XML element, with the exception * of the first and last packet, which specify begin and end tags for the xdp:xdp element. [IS0 32000-1:2008: * 12.7.8] * * @return the XFA content * @throws IOException if the XFA content could not be created */ public byte[] getBytes() throws IOException { // handle the case if the XFA is split into individual parts if (this.getCOSObject() instanceof COSArray) { return getBytesFromPacket((COSArray) this.getCOSObject()); } else if (xfa.getCOSObject() instanceof COSStream) { return getBytesFromStream((COSStream) this.getCOSObject()); } return new byte[0]; } /* * Read all bytes from a packet */ private static byte[] getBytesFromPacket(final COSArray cosArray) throws IOException {<FILL_FUNCTION_BODY>} /* * Read all bytes from a COSStream */ private static byte[] getBytesFromStream(final COSStream stream) throws IOException { try (final InputStream is = stream.createInputStream()) { return is.readAllBytes(); } } /** * Get the XFA content as W3C document. * * @see #getBytes() * * @return the XFA content * * @throws IOException if something went wrong when reading the XFA content. * */ public Document getDocument() throws IOException { return org.apache.pdfbox.util.XMLUtil // .parse(new ByteArrayInputStream(this.getBytes()), true); } }
try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { for (int i = 1; i < cosArray.size(); i += 2) { COSBase cosObj = cosArray.getObject(i); if (cosObj instanceof COSStream) { baos.write(getBytesFromStream((COSStream) cosObj.getCOSObject())); } } return baos.toByteArray(); }
703
120
823
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/pagenavigation/PDThreadBead.java
PDThreadBead
appendBead
class PDThreadBead implements COSObjectable { private final COSDictionary bead; /** * Constructor that is used for a preexisting dictionary. * * @param b The underlying dictionary. */ public PDThreadBead( COSDictionary b ) { bead = b; } /** * Default constructor. * */ public PDThreadBead() { bead = new COSDictionary(); bead.setItem(COSName.TYPE, COSName.BEAD); setNextBead( this ); setPreviousBead( this ); } /** * This will get the underlying dictionary that this object wraps. * * @return The underlying info dictionary. */ @Override public COSDictionary getCOSObject() { return bead; } /** * This will get the thread that this bead is part of. This is only required * for the first bead in a thread, so other beads 'may' return null. * * @return The thread that this bead is part of. */ public PDThread getThread() { COSDictionary dic = bead.getCOSDictionary(COSName.T); return dic != null ? new PDThread(dic) : null; } /** * Set the thread that this bead is part of. This is only required for the * first bead in a thread. Note: This property is set for you by the PDThread.setFirstBead() method. * * @param thread The thread that this bead is part of. */ public void setThread( PDThread thread ) { bead.setItem(COSName.T, thread); } /** * This will get the next bead. If this bead is the last bead in the list then this * will return the first bead. * * @return The next bead in the list or the first bead if this is the last bead. */ public PDThreadBead getNextBead() { return new PDThreadBead(bead.getCOSDictionary(COSName.N)); } /** * Set the next bead in the thread. * * @param next The next bead. */ protected final void setNextBead( PDThreadBead next ) { bead.setItem(COSName.N, next); } /** * This will get the previous bead. If this bead is the first bead in the list then this * will return the last bead. * * @return The previous bead in the list or the last bead if this is the first bead. */ public PDThreadBead getPreviousBead() { return new PDThreadBead(bead.getCOSDictionary(COSName.V)); } /** * Set the previous bead in the thread. * * @param previous The previous bead. */ protected final void setPreviousBead( PDThreadBead previous ) { bead.setItem(COSName.V, previous); } /** * Append a bead after this bead. This will correctly set the next/previous beads in the * linked list. * * @param append The bead to insert. */ public void appendBead( PDThreadBead append ) {<FILL_FUNCTION_BODY>} /** * Get the page that this bead is part of. * * @return The page that this bead is part of. */ public PDPage getPage() { COSDictionary dic = bead.getCOSDictionary(COSName.P); return dic != null ? new PDPage(dic) : null; } /** * Set the page that this bead is part of. This is a required property and must be * set when creating a new bead. The PDPage object also has a list of beads in the natural * reading order. It is recommended that you add this object to that list as well. * * @param page The page that this bead is on. */ public void setPage( PDPage page ) { bead.setItem(COSName.P, page); } /** * The rectangle on the page that this bead is part of. * * @return The part of the page that this bead covers. */ public PDRectangle getRectangle() { COSArray array = bead.getCOSArray(COSName.R); return array != null ? new PDRectangle(array) : null; } /** * Set the rectangle on the page that this bead covers. * * @param rect The portion of the page that this bead covers. */ public void setRectangle( PDRectangle rect ) { bead.setItem( COSName.R, rect ); } }
PDThreadBead nextBead = getNextBead(); nextBead.setPreviousBead( append ); append.setNextBead( nextBead ); setNextBead( append ); append.setPreviousBead( this );
1,324
65
1,389
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/pagenavigation/PDTransition.java
PDTransition
getDirection
class PDTransition extends PDDictionaryWrapper { /** * creates a new transition with default "replace" style {@link PDTransitionStyle#R} */ public PDTransition() { this(PDTransitionStyle.R); } /** * creates a new transition with the given style. * * @param style the style to be used to create the new transition */ public PDTransition(PDTransitionStyle style) { super(); getCOSObject().setName(COSName.TYPE, COSName.TRANS.getName()); getCOSObject().setName(COSName.S, style.name()); } /** * creates a new transition for an existing dictionary * * @param dictionary the dictionary to be used for the new transition */ public PDTransition(COSDictionary dictionary) { super(dictionary); } /** * @return the style for this transition * @see PDTransitionStyle#valueOf(String) */ public String getStyle() { return getCOSObject().getNameAsString(COSName.S, PDTransitionStyle.R.name()); } /** * @return The dimension in which the specified transition effect shall occur or the default * {@link PDTransitionDimension#H} if no dimension is found. * @see PDTransitionDimension */ public String getDimension() { return getCOSObject().getNameAsString(COSName.DM, PDTransitionDimension.H.name()); } /** * Sets the dimension in which the specified transition effect shall occur. Only for {@link PDTransitionStyle#Split} * and {@link PDTransitionStyle#Blinds}. * * @param dimension the dimension in which the specified transition effect shall occur */ public void setDimension(PDTransitionDimension dimension) { getCOSObject().setName(COSName.DM, dimension.name()); } /** * @return The direction of motion for the specified transition effect or the default {@link PDTransitionMotion#I} * if no motion is found. * @see PDTransitionMotion */ public String getMotion() { return getCOSObject().getNameAsString(COSName.M, PDTransitionMotion.I.name()); } /** * Sets the direction of motion for the specified transition effect. Only for {@link PDTransitionStyle#Split}, * {@link PDTransitionStyle#Blinds} and {@link PDTransitionStyle#Fly}. * * @param motion the direction of motion for the specified transition effect */ public void setMotion(PDTransitionMotion motion) { getCOSObject().setName(COSName.M, motion.name()); } /** * @return the direction in which the specified transition effect shall move. It can be either a {@link COSInteger} * or {@link COSName#NONE}. Default to {@link COSInteger#ZERO} * @see PDTransitionDirection */ public COSBase getDirection() {<FILL_FUNCTION_BODY>} /** * Sets the direction in which the specified transition effect shall move. Only for {@link PDTransitionStyle#Wipe}, * {@link PDTransitionStyle#Glitter}, {@link PDTransitionStyle#Fly}, {@link PDTransitionStyle#Cover}, * {@link PDTransitionStyle#Uncover} and {@link PDTransitionStyle#Push}. * * @param direction the direction in which the specified transition effect shall move */ public void setDirection(PDTransitionDirection direction) { getCOSObject().setItem(COSName.DI, direction.getCOSBase()); } /** * @return The duration in seconds of the transition effect or the default 1 if no duration is found. */ public float getDuration() { return getCOSObject().getFloat(COSName.D, 1); } /** * @param duration The duration of the transition effect, in seconds. */ public void setDuration(float duration) { getCOSObject().setItem(COSName.D, new COSFloat(duration)); } /** * @return The starting or ending scale at which the changes shall be drawn or the default 1 if no scale is found. * Only for {@link PDTransitionStyle#Fly}. */ public float getFlyScale() { return getCOSObject().getFloat(COSName.SS, 1); } /** * @param scale The starting or ending scale at which the changes shall be drawn. Only for * {@link PDTransitionStyle#Fly}. */ public void setFlyScale(float scale) { getCOSObject().setItem(COSName.SS, new COSFloat(scale)); } /** * @return true if the area that shall be flown in is rectangular and opaque. Default is false. Only for * {@link PDTransitionStyle#Fly}. */ public boolean isFlyAreaOpaque() { return getCOSObject().getBoolean(COSName.B, false); } /** * @param opaque If true, the area that shall be flown in is rectangular and opaque. Only for * {@link PDTransitionStyle#Fly}. */ public void setFlyAreaOpaque(boolean opaque) { getCOSObject().setItem(COSName.B, COSBoolean.getBoolean(opaque)); } }
COSBase item = getCOSObject().getItem(COSName.DI); if (item == null) { return COSInteger.ZERO; } return item;
1,474
54
1,528
<methods>public void <init>() ,public void <init>(org.apache.pdfbox.cos.COSDictionary) ,public boolean equals(java.lang.Object) ,public org.apache.pdfbox.cos.COSDictionary getCOSObject() ,public int hashCode() <variables>private final non-sealed org.apache.pdfbox.cos.COSDictionary dictionary
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/printing/PDFPageable.java
PDFPageable
getPageFormat
class PDFPageable extends Book { private final PDDocument document; private final int numberOfPages; private final boolean showPageBorder; private final float dpi; private final Orientation orientation; private boolean subsamplingAllowed = false; private RenderingHints renderingHints = null; /** * Creates a new PDFPageable. * * @param document the document to print */ public PDFPageable(PDDocument document) { this(document, Orientation.AUTO, false, 0); } /** * Creates a new PDFPageable with the given page orientation. * * @param document the document to print * @param orientation page orientation policy */ public PDFPageable(PDDocument document, Orientation orientation) { this(document, orientation, false, 0); } /** * Creates a new PDFPageable with the given page orientation and with optional page borders * shown. The image will be rasterized at the given DPI before being sent to the printer. * * @param document the document to print * @param orientation page orientation policy * @param showPageBorder true if page borders are to be printed */ public PDFPageable(PDDocument document, Orientation orientation, boolean showPageBorder) { this(document, orientation, showPageBorder, 0); } /** * Creates a new PDFPageable with the given page orientation and with optional page borders * shown. The image will be rasterized at the given DPI before being sent to the printer. * * @param document the document to print * @param orientation page orientation policy * @param showPageBorder true if page borders are to be printed * @param dpi if non-zero then the image will be rasterized at the given DPI */ public PDFPageable(PDDocument document, Orientation orientation, boolean showPageBorder, float dpi) { this.document = document; this.orientation = orientation; this.showPageBorder = showPageBorder; this.dpi = dpi; numberOfPages = document.getNumberOfPages(); } /** * Get the rendering hints. * * @return the rendering hints or null if none are set. */ public RenderingHints getRenderingHints() { return renderingHints; } /** * Set the rendering hints. Use this to influence rendering quality and speed. If you don't set them yourself or * pass null, PDFBox will decide <b><u>at runtime</u></b> depending on the destination. * * @param renderingHints rendering hints to be used to influence rendering quality and speed */ public void setRenderingHints(RenderingHints renderingHints) { this.renderingHints = renderingHints; } /** * Value indicating if the renderer is allowed to subsample images before drawing, according to * image dimensions and requested scale. * * Subsampling may be faster and less memory-intensive in some cases, but it may also lead to * loss of quality, especially in images with high spatial frequency. * * @return true if subsampling of images is allowed, false otherwise. */ public boolean isSubsamplingAllowed() { return subsamplingAllowed; } /** * Sets a value instructing the renderer whether it is allowed to subsample images before * drawing. The subsampling frequency is determined according to image size and requested scale. * * Subsampling may be faster and less memory-intensive in some cases, but it may also lead to * loss of quality, especially in images with high spatial frequency. * * @param subsamplingAllowed The new value indicating if subsampling is allowed. */ public void setSubsamplingAllowed(boolean subsamplingAllowed) { this.subsamplingAllowed = subsamplingAllowed; } @Override public int getNumberOfPages() { return numberOfPages; } /** * {@inheritDoc} * * Returns the actual physical size of the pages in the PDF file. May not fit the local printer. */ @Override public PageFormat getPageFormat(int pageIndex) {<FILL_FUNCTION_BODY>} @Override public Printable getPrintable(int i) { if (i >= numberOfPages) { throw new IndexOutOfBoundsException(i + " >= " + numberOfPages); } PDFPrintable printable = new PDFPrintable(document, Scaling.ACTUAL_SIZE, showPageBorder, dpi); printable.setSubsamplingAllowed(subsamplingAllowed); printable.setRenderingHints(renderingHints); return printable; } }
PDPage page = document.getPage(pageIndex); PDRectangle mediaBox = PDFPrintable.getRotatedMediaBox(page); PDRectangle cropBox = PDFPrintable.getRotatedCropBox(page); // Java does not seem to understand landscape paper sizes, i.e. where width > height, it // always crops the imageable area as if the page were in portrait. I suspect that this is // a JDK bug but it might be by design, see PDFBOX-2922. // // As a workaround, we normalise all Page(s) to be portrait, then flag them as landscape in // the PageFormat. Paper paper; boolean isLandscape; if (mediaBox.getWidth() > mediaBox.getHeight()) { // rotate paper = new Paper(); paper.setSize(mediaBox.getHeight(), mediaBox.getWidth()); paper.setImageableArea(cropBox.getLowerLeftY(), cropBox.getLowerLeftX(), cropBox.getHeight(), cropBox.getWidth()); isLandscape = true; } else { paper = new Paper(); paper.setSize(mediaBox.getWidth(), mediaBox.getHeight()); paper.setImageableArea(cropBox.getLowerLeftX(), cropBox.getLowerLeftY(), cropBox.getWidth(), cropBox.getHeight()); isLandscape = false; } PageFormat format = new PageFormat(); format.setPaper(paper); // auto portrait/landscape switch (orientation) { case AUTO: format.setOrientation(isLandscape ? PageFormat.LANDSCAPE : PageFormat.PORTRAIT); break; case LANDSCAPE: format.setOrientation(PageFormat.LANDSCAPE); break; case PORTRAIT: format.setOrientation(PageFormat.PORTRAIT); break; default: break; } return format;
1,251
522
1,773
<methods>public void <init>() ,public void append(java.awt.print.Printable, java.awt.print.PageFormat) ,public void append(java.awt.print.Printable, java.awt.print.PageFormat, int) ,public int getNumberOfPages() ,public java.awt.print.PageFormat getPageFormat(int) throws java.lang.IndexOutOfBoundsException,public java.awt.print.Printable getPrintable(int) throws java.lang.IndexOutOfBoundsException,public void setPage(int, java.awt.print.Printable, java.awt.print.PageFormat) throws java.lang.IndexOutOfBoundsException<variables>private Vector<java.awt.print.Book.BookPage> mPages
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/rendering/GlyphCache.java
GlyphCache
getPathForCharacterCode
class GlyphCache { private static final Logger LOG = LogManager.getLogger(GlyphCache.class); private final PDVectorFont font; private final Map<Integer, GeneralPath> cache = new HashMap<>(); GlyphCache(PDVectorFont font) { this.font = font; } public GeneralPath getPathForCharacterCode(int code) {<FILL_FUNCTION_BODY>} }
GeneralPath path = cache.get(code); if (path != null) { return path; } try { if (!font.hasGlyph(code)) { String fontName = ((PDFontLike) font).getName(); if (font instanceof PDType0Font) { int cid = ((PDType0Font) font).codeToCID(code); String cidHex = String.format("%04x", cid); LOG.warn("No glyph for code {} (CID {}) in font {}", code, cidHex, fontName); } else if (font instanceof PDSimpleFont) { PDSimpleFont simpleFont = (PDSimpleFont) font; LOG.warn("No glyph for code {} in {} {} (embedded or system font used: {})", code, font.getClass().getSimpleName(), fontName, simpleFont.getFontBoxFont().getName()); if (code == 10 && simpleFont.isStandard14()) { // PDFBOX-4001 return empty path for line feed on std14 path = new GeneralPath(); cache.put(code, path); return path; } } else { LOG.warn("No glyph for code {} in font {}", code, fontName); } } path = font.getNormalizedPath(code); cache.put(code, path); return path; } catch (IOException e) { // todo: escalate this error? String fontName = ((PDFontLike) font).getName(); LOG.error("Glyph rendering failed for code {} in font {}", code, fontName, e); return new GeneralPath(); }
117
450
567
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/rendering/SoftMask.java
SoftPaintContext
getRaster
class SoftPaintContext implements PaintContext { private final PaintContext context; SoftPaintContext(PaintContext context) { this.context = context; } @Override public ColorModel getColorModel() { return ARGB_COLOR_MODEL; } @Override public Raster getRaster(int x1, int y1, int w, int h) {<FILL_FUNCTION_BODY>} @Override public void dispose() { context.dispose(); } }
Raster raster = context.getRaster(x1, y1, w, h); ColorModel rasterCM = context.getColorModel(); float[] input = null; Float[] map = null; if (transferFunction != null) { map = new Float[256]; input = new float[1]; } // buffer WritableRaster output = getColorModel().createCompatibleWritableRaster(w, h); // the soft mask has its own bbox x1 = x1 - (int)bboxDevice.getX(); y1 = y1 - (int)bboxDevice.getY(); int[] gray = new int[4]; Object pixelInput = null; int[] pixelOutput = new int[4]; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { pixelInput = raster.getDataElements(x, y, pixelInput); pixelOutput[0] = rasterCM.getRed(pixelInput); pixelOutput[1] = rasterCM.getGreen(pixelInput); pixelOutput[2] = rasterCM.getBlue(pixelInput); pixelOutput[3] = rasterCM.getAlpha(pixelInput); // get the alpha value from the gray mask, if within mask bounds gray[0] = 0; if (x1 + x >= 0 && y1 + y >= 0 && x1 + x < mask.getWidth() && y1 + y < mask.getHeight()) { mask.getRaster().getPixel(x1 + x, y1 + y, gray); int g = gray[0]; if (transferFunction != null) { // apply transfer function try { if (map[g] != null) { // was calculated before pixelOutput[3] = Math.round(pixelOutput[3] * map[g]); } else { // calculate and store in map input[0] = g / 255f; float f = transferFunction.eval(input)[0]; map[g] = f; pixelOutput[3] = Math.round(pixelOutput[3] * f); } } catch (IOException ex) { // ignore exception, treat as outside LOG.debug("Couldn't apply transferFunction - treating as outside", ex); pixelOutput[3] = Math.round(pixelOutput[3] * (bc / 255f)); } } else { pixelOutput[3] = Math.round(pixelOutput[3] * (g / 255f)); } } else { pixelOutput[3] = Math.round(pixelOutput[3] * (bc / 255f)); } output.setPixel(x, y, pixelOutput); } } return output;
151
766
917
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/rendering/TilingPaintFactory.java
TilingPaintParameter
equals
class TilingPaintParameter { private final Matrix matrix; private final COSDictionary patternDict; private final PDColorSpace colorSpace; private final PDColor color; private final AffineTransform xform; private TilingPaintParameter(Matrix matrix, COSDictionary patternDict, PDColorSpace colorSpace, PDColor color, AffineTransform xform) { this.matrix = matrix.clone(); this.patternDict = patternDict; this.colorSpace = colorSpace; this.color = color; this.xform = xform; } // this may not catch all equals, but at least those related to one resource dictionary. // it isn't needed to investigate further because matrix or transform would be different anyway. @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int hash = 7; hash = 23 * hash + (this.matrix != null ? this.matrix.hashCode() : 0); hash = 23 * hash + (this.patternDict != null ? this.patternDict.hashCode() : 0); hash = 23 * hash + (this.colorSpace != null ? this.colorSpace.hashCode() : 0); hash = 23 * hash + (this.color != null ? this.color.hashCode() : 0); hash = 23 * hash + (this.xform != null ? this.xform.hashCode() : 0); return hash; } @Override public String toString() { return "TilingPaintParameter{" + "matrix=" + matrix + ", pattern=" + patternDict + ", colorSpace=" + colorSpace + ", color=" + color + ", xform=" + xform + '}'; } }
if (this == obj) { return true; } if (!(obj instanceof TilingPaintParameter)) { return false; } final TilingPaintParameter other = (TilingPaintParameter) obj; if (!Objects.equals(this.matrix, other.matrix)) { return false; } if (!Objects.equals(this.patternDict, other.patternDict)) { return false; } if (!Objects.equals(this.colorSpace, other.colorSpace)) { return false; } if (this.color == null && other.color != null) { return false; } if (this.color != null && other.color == null) { return false; } if (this.color != null && this.color.getColorSpace() != other.color.getColorSpace()) { return false; } try { if (this.color != null && other.color != null && this.color != other.color && this.color.toRGB() != other.color.toRGB()) { return false; } } catch (IOException ex) { LOG.debug("Couldn't convert color to RGB - treating as not equal", ex); return false; } return Objects.equals(this.xform, other.xform);
479
373
852
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/text/PDFMarkedContentExtractor.java
PDFMarkedContentExtractor
within
class PDFMarkedContentExtractor extends LegacyPDFStreamEngine { private boolean suppressDuplicateOverlappingText = true; private final List<PDMarkedContent> markedContents = new ArrayList<>(); private final Deque<PDMarkedContent> currentMarkedContents = new ArrayDeque<>(); private final Map<String, List<TextPosition>> characterListMapping = new HashMap<>(); /** * Instantiate a new PDFTextStripper object. */ public PDFMarkedContentExtractor() { this(null); } /** * Constructor. Will apply encoding-specific conversions to the output text. * * @param encoding The encoding that the output will be written in. */ public PDFMarkedContentExtractor(String encoding) { addOperator(new BeginMarkedContentSequenceWithProperties(this)); addOperator(new BeginMarkedContentSequence(this)); addOperator(new EndMarkedContentSequence(this)); addOperator(new DrawObject(this)); // todo: DP - Marked Content Point // todo: MP - Marked Content Point with Properties } /** * @return the suppressDuplicateOverlappingText setting. */ public boolean isSuppressDuplicateOverlappingText() { return suppressDuplicateOverlappingText; } /** * By default the class will attempt to remove text that overlaps each other. Word paints the * same character several times in order to make it look bold. By setting this to false all text * will be extracted, which means that certain sections will be duplicated, but better * performance will be noticed. * * @param suppressDuplicateOverlappingText The suppressDuplicateOverlappingText setting to set. */ public void setSuppressDuplicateOverlappingText(boolean suppressDuplicateOverlappingText) { this.suppressDuplicateOverlappingText = suppressDuplicateOverlappingText; } /** * This will determine of two floating point numbers are within a specified variance. * * @param first The first number to compare to. * @param second The second number to compare to. * @param variance The allowed variance. */ private boolean within( float first, float second, float variance ) {<FILL_FUNCTION_BODY>} @Override public void beginMarkedContentSequence(COSName tag, COSDictionary properties) { PDMarkedContent markedContent = PDMarkedContent.create(tag, properties); if (this.currentMarkedContents.isEmpty()) { this.markedContents.add(markedContent); } else { PDMarkedContent currentMarkedContent = this.currentMarkedContents.peek(); if (currentMarkedContent != null) { currentMarkedContent.addMarkedContent(markedContent); } } this.currentMarkedContents.push(markedContent); } @Override public void endMarkedContentSequence() { if (!this.currentMarkedContents.isEmpty()) { this.currentMarkedContents.pop(); } } public void xobject(PDXObject xobject) { if (!this.currentMarkedContents.isEmpty()) { this.currentMarkedContents.peek().addXObject(xobject); } } /** * This will process a TextPosition object and add the * text to the list of characters on a page. It takes care of * overlapping text. * * @param text The text to process. */ @Override protected void processTextPosition( TextPosition text ) { boolean showCharacter = true; if( this.suppressDuplicateOverlappingText ) { showCharacter = false; String textCharacter = text.getUnicode(); float textX = text.getX(); float textY = text.getY(); List<TextPosition> sameTextCharacters = this.characterListMapping.computeIfAbsent(textCharacter, k -> new ArrayList<>()); // RDD - Here we compute the value that represents the end of the rendered // text. This value is used to determine whether subsequent text rendered // on the same line overwrites the current text. // // We subtract any positive padding to handle cases where extreme amounts // of padding are applied, then backed off (not sure why this is done, but there // are cases where the padding is on the order of 10x the character width, and // the TJ just backs up to compensate after each character). Also, we subtract // an amount to allow for kerning (a percentage of the width of the last // character). // boolean suppressCharacter = false; float tolerance = (text.getWidth()/textCharacter.length())/3.0f; for (TextPosition sameTextCharacter : sameTextCharacters) { String charCharacter = sameTextCharacter.getUnicode(); float charX = sameTextCharacter.getX(); float charY = sameTextCharacter.getY(); //only want to suppress if( charCharacter != null && //charCharacter.equals( textCharacter ) && within( charX, textX, tolerance ) && within( charY, textY, tolerance ) ) { suppressCharacter = true; break; } } if( !suppressCharacter ) { sameTextCharacters.add( text ); showCharacter = true; } } if( showCharacter ) { List<TextPosition> textList = new ArrayList<>(); /* In the wild, some PDF encoded documents put diacritics (accents on * top of characters) into a separate Tj element. When displaying them * graphically, the two chunks get overlaid. With text output though, * we need to do the overlay. This code recombines the diacritic with * its associated character if the two are consecutive. */ if(textList.isEmpty()) { textList.add(text); } else { /* test if we overlap the previous entry. * Note that we are making an assumption that we need to only look back * one TextPosition to find what we are overlapping. * This may not always be true. */ TextPosition previousTextPosition = textList.get(textList.size()-1); if(text.isDiacritic() && previousTextPosition.contains(text)) { previousTextPosition.mergeDiacritic(text); } /* If the previous TextPosition was the diacritic, merge it into this * one and remove it from the list. */ else if(previousTextPosition.isDiacritic() && text.contains(previousTextPosition)) { text.mergeDiacritic(previousTextPosition); textList.remove(textList.size()-1); textList.add(text); } else { textList.add(text); } } if (!this.currentMarkedContents.isEmpty()) { this.currentMarkedContents.peek().addText(text); } } } public List<PDMarkedContent> getMarkedContents() { return this.markedContents; } }
return second > first - variance && second < first + variance;
1,865
18
1,883
<methods>public void processPage(org.apache.pdfbox.pdmodel.PDPage) throws java.io.IOException<variables>private static final non-sealed org.apache.pdfbox.pdmodel.font.encoding.GlyphList GLYPHLIST,private static final Logger LOG,private final Map<org.apache.pdfbox.cos.COSDictionary,java.lang.Float> fontHeightMap,private int pageRotation,private org.apache.pdfbox.pdmodel.common.PDRectangle pageSize,private org.apache.pdfbox.util.Matrix translateMatrix
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/text/PDFTextStripperByArea.java
PDFTextStripperByArea
extractRegions
class PDFTextStripperByArea extends PDFTextStripper { private final List<String> regions = new ArrayList<>(); private final Map<String, Rectangle2D> regionArea = new HashMap<>(); private final Map<String, ArrayList<List<TextPosition>>> regionCharacterList = new HashMap<>(); private final Map<String, StringWriter> regionText = new HashMap<>(); /** * Constructor. * @throws IOException If there is an error loading properties. */ public PDFTextStripperByArea() throws IOException { super.setShouldSeparateByBeads(false); } /** * This method does nothing in this derived class, because beads and regions are incompatible. Beads are * ignored when stripping by area. * * @param aShouldSeparateByBeads The new grouping of beads. */ @Override public final void setShouldSeparateByBeads(boolean aShouldSeparateByBeads) { } /** * Add a new region to group text by. * * @param regionName The name of the region. * @param rect The rectangle area to retrieve the text from. The y-coordinates are java * coordinates (y == 0 is top), not PDF coordinates (y == 0 is bottom). */ public void addRegion( String regionName, Rectangle2D rect ) { regions.add( regionName ); regionArea.put( regionName, rect ); } /** * Delete a region to group text by. If the region does not exist, this method does nothing. * * @param regionName The name of the region to delete. */ public void removeRegion(String regionName) { regions.remove(regionName); regionArea.remove(regionName); } /** * Get the list of regions that have been setup. * * @return A list of java.lang.String objects to identify the region names. */ public List<String> getRegions() { return regions; } /** * Get the text for the region, this should be called after extractRegions(). * * @param regionName The name of the region to get the text from. * @return The text that was identified in that region. */ public String getTextForRegion( String regionName ) { StringWriter text = regionText.get( regionName ); return text.toString(); } /** * Process the page to extract the region text. * * @param page The page to extract the regions from. * @throws IOException If there is an error while extracting text. */ public void extractRegions( PDPage page ) throws IOException {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} */ @Override protected void processTextPosition(TextPosition text) { regionArea.forEach((key, rect) -> { if (rect.contains(text.getX(), text.getY())) { charactersByArticle = regionCharacterList.get(key); super.processTextPosition(text); } }); } /** * This will print the processed page text to the output stream. * * @throws IOException If there is an error writing the text. */ @Override protected void writePage() throws IOException { for (String region : regionArea.keySet()) { charactersByArticle = regionCharacterList.get( region ); output = regionText.get( region ); super.writePage(); } } }
for (String regionName : regions) { setStartPage(getCurrentPageNo()); setEndPage(getCurrentPageNo()); // reset the stored text for the region so this class can be reused. ArrayList<List<TextPosition>> regionCharactersByArticle = new ArrayList<>(); regionCharactersByArticle.add(new ArrayList<>()); regionCharacterList.put( regionName, regionCharactersByArticle ); regionText.put( regionName, new StringWriter() ); } if( page.hasContents() ) { processPage( page ); }
936
152
1,088
<methods>public void <init>() ,public boolean getAddMoreFormatting() ,public java.lang.String getArticleEnd() ,public java.lang.String getArticleStart() ,public float getAverageCharTolerance() ,public float getDropThreshold() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem getEndBookmark() ,public int getEndPage() ,public float getIndentThreshold() ,public java.lang.String getLineSeparator() ,public java.lang.String getPageEnd() ,public java.lang.String getPageStart() ,public java.lang.String getParagraphEnd() ,public java.lang.String getParagraphStart() ,public boolean getSeparateByBeads() ,public boolean getSortByPosition() ,public float getSpacingTolerance() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem getStartBookmark() ,public int getStartPage() ,public boolean getSuppressDuplicateOverlappingText() ,public java.lang.String getText(org.apache.pdfbox.pdmodel.PDDocument) throws java.io.IOException,public java.lang.String getWordSeparator() ,public void processPage(org.apache.pdfbox.pdmodel.PDPage) throws java.io.IOException,public void setAddMoreFormatting(boolean) ,public void setArticleEnd(java.lang.String) ,public void setArticleStart(java.lang.String) ,public void setAverageCharTolerance(float) ,public void setDropThreshold(float) ,public void setEndBookmark(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem) ,public void setEndPage(int) ,public void setIndentThreshold(float) ,public void setLineSeparator(java.lang.String) ,public void setPageEnd(java.lang.String) ,public void setPageStart(java.lang.String) ,public void setParagraphEnd(java.lang.String) ,public void setParagraphStart(java.lang.String) ,public void setShouldSeparateByBeads(boolean) ,public void setSortByPosition(boolean) ,public void setSpacingTolerance(float) ,public void setStartBookmark(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem) ,public void setStartPage(int) ,public void setSuppressDuplicateOverlappingText(boolean) ,public void setWordSeparator(java.lang.String) ,public void writeText(org.apache.pdfbox.pdmodel.PDDocument, java.io.Writer) throws java.io.IOException<variables>private static final float END_OF_LAST_TEXT_X_RESET_VALUE,private static final float EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE,private static final float LAST_WORD_SPACING_RESET_VALUE,protected static final java.lang.String LINE_SEPARATOR,private static final java.lang.String[] LIST_ITEM_EXPRESSIONS,private static final Logger LOG,private static final float MAX_HEIGHT_FOR_LINE_RESET_VALUE,private static final float MAX_Y_FOR_LINE_RESET_VALUE,private static final float MIN_Y_TOP_FOR_LINE_RESET_VALUE,private static final Map<java.lang.Character,java.lang.Character> MIRRORING_CHAR_MAP,private boolean addMoreFormatting,private java.lang.String articleEnd,private java.lang.String articleStart,private float averageCharTolerance,private List<org.apache.pdfbox.pdmodel.common.PDRectangle> beadRectangles,private final Map<java.lang.String,TreeMap<java.lang.Float,TreeSet<java.lang.Float>>> characterListMapping,protected ArrayList<List<org.apache.pdfbox.text.TextPosition>> charactersByArticle,private int currentPageNo,private static float defaultDropThreshold,private static float defaultIndentThreshold,protected org.apache.pdfbox.pdmodel.PDDocument document,private float dropThreshold,private org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem endBookmark,private int endBookmarkPageNumber,private int endPage,private boolean inParagraph,private float indentThreshold,private java.lang.String lineSeparator,private List<java.util.regex.Pattern> listOfPatterns,protected java.io.Writer output,private java.lang.String pageEnd,private java.lang.String pageStart,private java.lang.String paragraphEnd,private java.lang.String paragraphStart,private boolean shouldSeparateByBeads,private boolean sortByPosition,private float spacingTolerance,private org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem startBookmark,private int startBookmarkPageNumber,private int startPage,private boolean suppressDuplicateOverlappingText,private java.lang.String wordSeparator
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/text/TextPositionComparator.java
TextPositionComparator
compare
class TextPositionComparator implements Comparator<TextPosition> { @Override public int compare(TextPosition pos1, TextPosition pos2) {<FILL_FUNCTION_BODY>} }
// only compare text that is in the same direction int cmp1 = Float.compare(pos1.getDir(), pos2.getDir()); if (cmp1 != 0) { return cmp1; } // get the text direction adjusted coordinates float x1 = pos1.getXDirAdj(); float x2 = pos2.getXDirAdj(); float pos1YBottom = pos1.getYDirAdj(); float pos2YBottom = pos2.getYDirAdj(); // note that the coordinates have been adjusted so 0,0 is in upper left float pos1YTop = pos1YBottom - pos1.getHeightDir(); float pos2YTop = pos2YBottom - pos2.getHeightDir(); float yDifference = Math.abs(pos1YBottom - pos2YBottom); // we will do a simple tolerance comparison if (yDifference < .1 || pos2YBottom >= pos1YTop && pos2YBottom <= pos1YBottom || pos1YBottom >= pos2YTop && pos1YBottom <= pos2YBottom) { return Float.compare(x1, x2); } else if (pos1YBottom < pos2YBottom) { return -1; } else { return 1; }
54
350
404
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/util/IterativeMergeSort.java
IterativeMergeSort
sort
class IterativeMergeSort { private IterativeMergeSort() { // utility class } /** * Sorts this list according to the order induced by the specified * {@link Comparator}. * * @param <T> the class of the objects in the list * @param list the list to be sorted. * @param cmp the comparator to determine the order of the list. * */ @SuppressWarnings({ "unchecked", "rawtypes"}) public static <T> void sort(List<T> list, Comparator<? super T> cmp) {<FILL_FUNCTION_BODY>} /** * Sorts the array using iterative (bottom-up) merge sort. * * @param <T> the class of the objects in the list * @param arr the array of objects to be sorted. * @param cmp the comparator to determine the order of the list. */ private static <T> void iterativeMergeSort(T[] arr, Comparator<? super T> cmp) { T[] aux = arr.clone(); for (int blockSize = 1; blockSize < arr.length; blockSize = (blockSize << 1)) { for (int start = 0; start < arr.length; start += (blockSize << 1)) { merge(arr, aux, start, start + blockSize, start + (blockSize << 1), cmp); } } } /** * Merges two sorted subarrays arr and aux into the order specified by cmp and places the * ordered result back into into arr array. * * @param <T> * @param arr Array containing source data to be sorted and target for destination data * @param aux Array containing copy of source data to be sorted * @param from Start index of left data run so that Left run is arr[from : mid-1]. * @param mid End index of left data run and start index of right run data so that Left run is * arr[from : mid-1] and Right run is arr[mid : to] * @param to End index of right run data so that Right run is arr[mid : to] * @param cmp the comparator to determine the order of the list. */ private static <T> void merge(T[] arr, T[] aux, int from, int mid, int to, Comparator<? super T> cmp) { if (mid >= arr.length) { return; } if (to > arr.length) { to = arr.length; } int i = from; int j = mid; for (int k = from; k < to; k++) { if (i == mid) { aux[k] = arr[j++]; } else if (j == to) { aux[k] = arr[i++]; } else if (cmp.compare(arr[j], arr[i]) < 0) { aux[k] = arr[j++]; } else { aux[k] = arr[i++]; } } System.arraycopy(aux, from, arr, from, to - from); } }
if (list.size() < 2) { return; } Object[] arr = list.toArray(); iterativeMergeSort(arr, (Comparator) cmp); ListIterator<T> i = list.listIterator(); for (Object e : arr) { i.next(); i.set((T) e); }
842
100
942
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/util/NumberFormatUtil.java
NumberFormatUtil
formatFloatFast
class NumberFormatUtil { /** * Maximum number of fraction digits supported by the format methods */ private static final int MAX_FRACTION_DIGITS = 5; /** * Contains the power of ten values for fast lookup in the format methods */ private static final long[] POWER_OF_TENS; private static final int[] POWER_OF_TENS_INT; static { POWER_OF_TENS = new long[19]; POWER_OF_TENS[0] = 1; for (int exp = 1; exp < POWER_OF_TENS.length; exp++) { POWER_OF_TENS[exp] = POWER_OF_TENS[exp - 1] * 10; } POWER_OF_TENS_INT = new int[10]; POWER_OF_TENS_INT[0] = 1; for (int exp = 1; exp < POWER_OF_TENS_INT.length; exp++) { POWER_OF_TENS_INT[exp] = POWER_OF_TENS_INT[exp - 1] * 10; } } private NumberFormatUtil() { } /** * Fast variant to format a floating point value to a ASCII-string. The format will fail if the * value is greater than {@link Long#MAX_VALUE}, smaller or equal to {@link Long#MIN_VALUE}, is * {@link Float#NaN}, infinite or the number of requested fraction digits is greater than * {@link #MAX_FRACTION_DIGITS}. * * When the number contains more fractional digits than {@code maxFractionDigits} the value will * be rounded. Rounding is done to the nearest possible value, with the tie breaking rule of * rounding away from zero. * * @param value The float value to format * @param maxFractionDigits The maximum number of fraction digits used * @param asciiBuffer The output buffer to write the formatted value to * * @return The number of bytes used in the buffer or {@code -1} if formatting failed */ public static int formatFloatFast(float value, int maxFractionDigits, byte[] asciiBuffer) {<FILL_FUNCTION_BODY>} /** * Formats a positive integer number starting with the digit at {@code 10^exp}. * * @param number The number to format * @param exp The start digit * @param omitTrailingZeros Whether the formatting should stop if only trailing zeros are left. * This is needed e.g. when formatting fractions of a number. * @param asciiBuffer The buffer to write the ASCII digits to * @param startOffset The start offset into the buffer to start writing * * @return The offset into the buffer which contains the first byte that was not filled by the * method */ private static int formatPositiveNumber(long number, int exp, boolean omitTrailingZeros, byte[] asciiBuffer, int startOffset) { int offset = startOffset; long remaining = number; while (remaining > Integer.MAX_VALUE && (!omitTrailingZeros || remaining > 0)) { long digit = remaining / POWER_OF_TENS[exp]; remaining -= (digit * POWER_OF_TENS[exp]); asciiBuffer[offset++] = (byte) ('0' + digit); exp--; } //If the remaining fits into an integer, use int arithmetic as it is faster int remainingInt = (int) remaining; while (exp >= 0 && (!omitTrailingZeros || remainingInt > 0)) { int digit = remainingInt / POWER_OF_TENS_INT[exp]; remainingInt -= (digit * POWER_OF_TENS_INT[exp]); asciiBuffer[offset++] = (byte) ('0' + digit); exp--; } return offset; } /** * Returns the highest exponent of 10 where {@code 10^exp < number} for numbers > 0 */ private static int getExponent(long number) { for (int exp = 0; exp < (POWER_OF_TENS.length - 1); exp++) { if (number < POWER_OF_TENS[exp + 1]) { return exp; } } return POWER_OF_TENS.length - 1; } }
if (Float.isNaN(value) || Float.isInfinite(value) || value > Long.MAX_VALUE || value <= Long.MIN_VALUE || maxFractionDigits > MAX_FRACTION_DIGITS) { return -1; } int offset = 0; long integerPart = (long) value; //handle sign if (value < 0) { asciiBuffer[offset++] = '-'; integerPart = -integerPart; } //extract fraction part long fractionPart = (long) ((Math.abs((double)value) - integerPart) * POWER_OF_TENS[maxFractionDigits] + 0.5d); //Check for rounding to next integer if (fractionPart >= POWER_OF_TENS[maxFractionDigits]) { integerPart++; fractionPart -= POWER_OF_TENS[maxFractionDigits]; } //format integer part offset = formatPositiveNumber(integerPart, getExponent(integerPart), false, asciiBuffer, offset); if (fractionPart > 0 && maxFractionDigits > 0) { asciiBuffer[offset++] = '.'; offset = formatPositiveNumber(fractionPart, maxFractionDigits - 1, true, asciiBuffer, offset); } return offset;
1,193
371
1,564
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/util/Vector.java
Vector
toString
class Vector { private final float x, y; public Vector(float x, float y) { this.x = x; this.y = y; } /** * Returns the x magnitude. * * @return the x magnitude */ public float getX() { return x; } /** * Returns the y magnitude. * * @return the y magnitude */ public float getY() { return y; } /** * Returns a new vector scaled by both x and y. * * @param sxy x and y scale * @return a new vector scaled by both x and y */ public Vector scale(float sxy) { return new Vector(x * sxy, y * sxy); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "(" + x + ", " + y + ")";
248
18
266
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/util/Version.java
Version
getVersion
class Version { private static final Logger LOG = LogManager.getLogger(Version.class); private static final String PDFBOX_VERSION_PROPERTIES = "/org/apache/pdfbox/resources/version.properties"; private Version() { // static helper } /** * Returns the version of PDFBox. * * @return the version of PDFBox */ public static String getVersion() {<FILL_FUNCTION_BODY>} }
try (InputStream resourceAsStream = Version.class.getResourceAsStream(PDFBOX_VERSION_PROPERTIES); InputStream is = new BufferedInputStream(resourceAsStream)) { Properties properties = new Properties(); properties.load(is); return properties.getProperty("pdfbox.version", null); } catch (IOException io) { LOG.debug("Unable to read version from properties - returning null", io); return null; }
149
133
282
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/util/XMLUtil.java
XMLUtil
getNodeValue
class XMLUtil { /** * Utility class, should not be instantiated. * */ private XMLUtil() { } /** * This will parse an XML stream and create a DOM document. * * @param is The stream to get the XML from. * @return The DOM document. * @throws IOException It there is an error creating the dom. */ public static Document parse(InputStream is) throws IOException { return parse(is, false); } /** * This will parse an XML stream and create a DOM document. * * @param is The stream to get the XML from. * @param nsAware activates namespace awareness of the parser * @return The DOM document. * @throws IOException It there is an error creating the dom. */ public static Document parse(InputStream is, boolean nsAware) throws IOException { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); builderFactory.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); builderFactory.setXIncludeAware(false); builderFactory.setExpandEntityReferences(false); builderFactory.setNamespaceAware(nsAware); DocumentBuilder builder = builderFactory.newDocumentBuilder(); return builder.parse(is); } catch (FactoryConfigurationError | ParserConfigurationException | SAXException e) { throw new IOException(e.getMessage(), e); } } /** * This will get the text value of an element. * * @param node The node to get the text value for. * @return The text of the node. */ public static String getNodeValue(Element node) {<FILL_FUNCTION_BODY>} }
StringBuilder sb = new StringBuilder(); NodeList children = node.getChildNodes(); int numNodes = children.getLength(); for (int i = 0; i < numNodes; i++) { Node next = children.item(i); if (next instanceof Text) { sb.append(next.getNodeValue()); } } return sb.toString();
556
103
659
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/util/filetypedetector/ByteTrie.java
ByteTrieNode
addPath
class ByteTrieNode<T> { private final Map<Byte, ByteTrieNode<T>> children = new HashMap<>(); private T value = null; public void setValue(T value) { if (this.value != null) { throw new IllegalStateException("Value already set for this trie node"); } this.value = value; } public T getValue() { return value; } } private final ByteTrieNode<T> root = new ByteTrieNode<>(); private int maxDepth; /** * Return the most specific value stored for this byte sequence. If not found, returns * <code>null</code> or a default values as specified by calling * {@link ByteTrie#setDefaultValue}. * @param bytes * @return */ public T find(byte[] bytes) { ByteTrieNode<T> node = root; T val = node.getValue(); for (byte b : bytes) { ByteTrieNode<T> child = node.children.get(b); if (child == null) { break; } node = child; if (node.getValue() != null) { val = node.getValue(); } } return val; } /** * Store the given value at the specified path. * @param value * @param parts */ public void addPath(T value, byte[]... parts) {<FILL_FUNCTION_BODY>
int depth = 0; ByteTrieNode<T> node = root; for (byte[] part : parts) { for (byte b : part) { ByteTrieNode<T> child = node.children.get(b); if (child == null) { child = new ByteTrieNode<>(); node.children.put(b, child); } node = child; depth++; } } node.setValue(value); maxDepth = Math.max(maxDepth, depth);
408
144
552
<no_super_class>