proj_name
stringclasses 132
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
49
| masked_class
stringlengths 68
9.82k
| func_body
stringlengths 46
9.09k
| len_input
int64 27
2.01k
| len_output
int64 14
1.87k
| total
int64 55
2.05k
| generated_code
stringlengths 3
9.76k
| compiler_feedback
stringlengths 9
23.5k
|
---|---|---|---|---|---|---|---|---|---|---|
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 |
getCOSObject().setItem(COSName.D, d);
| <success> |
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 |
if ( action == null )
{
return null;
}
COSName type = (COSName) action.getDictionaryObject( COSName.TYPE );
if ( type == null )
{
return null;
}
if ( type.equals( COSName.URI ) )
{
return new PDURIAction( action );
}
else if ( type.equals( COSName.LAUNCH ) )
{
return new PDLaunchAction( action );
}
else if ( type.equals( COSName.RENDITION ) )
{
return new PDRenditionAction( action );
}
else if ( type.equals( COSName.NAVIGATE ) )
{
return new PDNavigateAction( action );
}
else if ( type.equals( COSName.SUBMIT_FORM ) )
{
return new PDSubmitFormAction( action );
}
else if ( type.equals( COSName.SUBMIT_DOC ) )
{
return new PDSubmitDocAction( action );
}
else if ( type.equals( COSName.HIDE ) )
{
return new PDHideAction( action );
}
else if ( type.equals( COSName.NAMED ) )
{
return new PDNamedAction( action );
}
else if ( type.equals( COSName.RENDITION_VOID ) )
{
return new PDRenditionVoidAction( action );
}
else | <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/action/PDActionFactory.java<line>96<col>13<err>illegal start of statement |
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 |
if (d instanceof PDPageDestination) {
getCOSObject().setItem(COSName.D, ((PDPageDestination) d).getCOSObject());
} else {
throw new IllegalArgumentException("Destination must be a page dictionary object.");
}
| <success> |
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 |
return action.getString(COSName.JS);
| <success> |
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 |
if (value == OpenMode.USER_PREFERENCE)
{
getCOSObject().removeItem(COSName.NEW_WINDOW);
}
else
{
getCOSObject().setItem(COSName.NEW_WINDOW, new COSBoolean(value == OpenMode.NEW_WINDOW));
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/action/PDActionLaunch.java<line>235<col>56<err>COSBoolean(boolean) has private access in org.apache.pdfbox.cos.COSBoolean |
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 |
COSBoolean cb = (COSBoolean) action.getDictionaryObject( COSName.NEW_WINDOW );
if (null == cb)
{
return OpenMode.USER_PREFERENCE;
}
return cb.booleanValue() ? OpenMode.NEW_WINDOW : OpenMode.SAME_WINDOW;
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/action/PDActionRemoteGoTo.java<line>126<col>18<err>cannot find symbol |
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 |
return action.getString(COSName.URI);
| <success> |
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 < 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 < 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 |
if (pageNumber < 0)
{
dict.removeItem(COSName.P);
}
else
{
dict.setInt(COSName.P, pageNumber);
}
| <success> |
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 |
COSArray margin = new COSArray();
margin.add(differenceLeft);
margin.add(differenceTop);
margin.add(differenceRight);
margin.add(differenceBottom);
getCOSObject().setItem(COSName.RD, margin);
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationCaret.java<line>80<col>15<err>no suitable method found for add(float)
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationCaret.java<line>82<col>15<err>no suitable method found for add(float)
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationCaret.java<line>81<col>15<err>no suitable method found for add(float)
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationCaret.java<line>79<col>15<err>no suitable method found for add(float) |
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 |
if (customAppearanceHandler != null)
{
customAppearanceHandler.constructAppearances(this, document);
}
else
{
super.constructAppearances(document);
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationCircle.java<line>72<col>36<err>cannot find symbol |
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 |
if (customAppearanceHandler != null)
{
customAppearanceHandler.constructAppearances(this, document);
}
else
{
super.constructAppearances(document);
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationFileAttachment.java<line>140<col>36<err>cannot find symbol |
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 |
if (customAppearanceHandler != null)
{
customAppearanceHandler.constructAppearances(this);
}
else
{
super.constructAppearances(document);
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationHighlight.java<line>76<col>36<err>cannot find symbol |
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 |
COSArray array = (COSArray) getCOSObject().getDictionaryObject(COSName.INKLIST);
if (array == null)
{
return null;
}
float[][] inkList = new float[array.size()][];
for (int i = 0; i < array.size(); i++)
{
COSArray path = (COSArray) array.getObject(i);
inkList[i] = new float[path.size()];
for (int j = 0; j < path.size(); j++)
{
inkList[i][j] = ((COSFloat) path.getObject(j)).floatValue();
}
}
return inkList;
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationInk.java<line>100<col>35<err>cannot find symbol |
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 |
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(actualStyle));
array.add(COSName.getPDFName(PDAnnotationLine.LE_NONE));
getCOSObject().setItem(COSName.LE, array);
}
else
{
array.setName(0, actualStyle);
}
| <success> |
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 |
COSDictionary parent = getCOSObject().getDictionary(COSName.PARENT);
if (parent == null)
{
return null;
}
return new PDAnnotationMarkup(parent);
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationPopup.java<line>96<col>46<err>cannot find symbol |
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 |
if (customAppearanceHandler != null)
{
customAppearanceHandler.constructAppearances(this, document);
}
else
{
super.constructAppearances(document);
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationSound.java<line>73<col>36<err>cannot find symbol |
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 |
if (customAppearanceHandler != null)
{
customAppearanceHandler.constructAppearances(this, document);
}
else
{
super.constructAppearances(document);
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationSquare.java<line>73<col>36<err>cannot find symbol |
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 |
if (customAppearanceHandler != null)
{
customAppearanceHandler.constructAppearances(this);
}
else
{
super.constructAppearances(document);
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationSquiggly.java<line>76<col>36<err>cannot find symbol |
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 |
if (customAppearanceHandler != null)
{
customAppearanceHandler.constructAppearances(this);
}
else
{
super.constructAppearances(document);
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationStrikeout.java<line>76<col>36<err>cannot find symbol |
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 |
if (customAppearanceHandler != null)
{
customAppearanceHandler.constructAppearances(this, document);
}
else
{
super.constructAppearances(document);
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationText.java<line>244<col>36<err>cannot find symbol |
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 |
if (customAppearanceHandler != null)
{
customAppearanceHandler.constructAppearances(this);
}
else
{
super.constructAppearances(document);
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationUnderline.java<line>76<col>36<err>cannot find symbol |
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 |
COSArray array = this.getCOSObject().getCOSArray(itemName);
if (array == null)
{
return null;
}
return new PDColor(array);
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAppearanceCharacteristicsDictionary.java<line>221<col>16<err>no suitable constructor found for PDColor(org.apache.pdfbox.cos.COSArray) |
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 |
if (isStream())
{
throw new IllegalStateException("This entry is not an appearance subdictionary");
}
Map<COSName, PDAppearanceStream> map = new HashMap<COSName, PDAppearanceStream>();
for (Map.Entry<COSName, COSObject> entry : this.entry.entrySet())
{
if (entry.getValue() instanceof COSStream)
{
map.put(entry.getKey(), new PDAppearanceStream((COSStream) entry.getValue()));
}
}
return map;
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAppearanceEntry.java<line>107<col>33<err>cannot find symbol |
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 |
return getCOSObject().getFloat(COSName.W, 0);
| <success> |
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 |
AnnotationBorder border = new AnnotationBorder();
PDBorderStyle borderStyleObj = borderStyle.getBorderStyle(annotation.getBorderStyle());
if (borderStyleObj != null)
{
border.width = borderStyleObj.getWidth();
border.dashArray = borderStyleObj.getDashArray();
border.underline = borderStyleObj.isUnderline();
}
return border;
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/AnnotationBorder.java<line>42<col>77<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/AnnotationBorder.java<line>42<col>9<err>cannot find symbol |
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 |
// TODO to be implemented
| <success> |
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 |
PDAnnotationMarkup annotation = (PDAnnotationMarkup) getAnnotation();
PDAppearanceStream appearanceStream = annotation.getAppearanceStream();
if (appearanceStream == null)
{
appearanceStream = new PDAppearanceStream(getDocument());
annotation.setAppearanceStream(appearanceStream);
}
PDAppearanceDictionary appearance = appearanceStream.getNormalAppearance();
if (appearance == null)
{
appearance = new PDAppearanceDictionary(getDocument());
appearanceStream.setNormalAppearance(appearance);
}
PDAppearanceStreamContentGenerator contentGenerator = new PDAppearanceStreamContentGenerator(appearanceStream);
PDAppearanceDictionary appearanceDict = new PDAppearanceDictionary(getDocument());
appearance.setNormalAppearance(appearanceDict);
PDAppearanceStreamContentGenerator.PDAppearanceStreamContentGeneratorState state = contentGenerator.beginAppearance(appearanceDict);
PDAppearanceStreamContentGenerator.PDAppearanceStreamContentGeneratorState state2 = contentGenerator.beginLayer(state, 0);
PDAppearanceStreamContentGenerator.PDAppearanceStreamContentGeneratorState state3 = contentGenerator.beginLayer(state2, 1);
PDAppearanceStreamContentGenerator.PDAppearanceStreamContentGeneratorState state4 = contentGenerator.beginLayer(state3, 2);
PDAppearanceStreamContentGenerator.PDAppearanceStreamContentGeneratorState state5 = contentGenerator.beginLayer(state4, 3);
PDAppearanceStreamContentGenerator | <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDCircleAppearanceHandler.java<line>88<col>43<err>';' expected
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDCircleAppearanceHandler.java<line>88<col>9<err>not a statement |
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 |
try
{
PDAppearanceStream appearanceStream = getAppearanceStream();
if (appearanceStream == null)
{
return;
}
PDAppearanceContentStream contentStream = new PDAppearanceContentStream(appearanceStream, getDocument());
contentStream.beginMarkedContentSequence(PDAppearanceStream.MARKED_CONTENT_TYPE_DRAWING);
contentStream.setNonStrokingColor(0, 0, 0);
drawPaperclip(contentStream);
contentStream.endMarkedContentSequence();
contentStream.close();
}
catch (IOException e)
{
LOG.warn("Error generating appearance stream for file attachment annotation", e);
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDFileAttachmentAppearanceHandler.java<line>52<col>13<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDFileAttachmentAppearanceHandler.java<line>58<col>103<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDFileAttachmentAppearanceHandler.java<line>59<col>54<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDFileAttachmentAppearanceHandler.java<line>52<col>51<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDFileAttachmentAppearanceHandler.java<line>62<col>26<err>cannot find symbol |
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 |
// No normal appearance generated
| <success> |
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 |
PDAnnotationLink annotation = (PDAnnotationLink) getAnnotation();
PDAppearanceStream appearanceStream = new PDAppearanceStream(getDocument(), annotation.getRectangle());
PDAppearanceDictionary appearanceDictionary = new PDAppearanceDictionary();
appearanceDictionary.setNormalAppearance(appearanceStream);
PDAppearanceStream normalAppearanceStream = appearanceDictionary.getNormalAppearance();
PDAnnotationLinkAppearanceStream appearanceStreamHandler = new PDAnnotationLinkAppearanceStream(normalAppearanceStream, annotation);
appearanceStreamHandler.generateNormalAppearance();
annotation.setAppearance(appearanceDictionary);
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDLinkAppearanceHandler.java<line>59<col>9<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDLinkAppearanceHandler.java<line>61<col>59<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDLinkAppearanceHandler.java<line>61<col>9<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDLinkAppearanceHandler.java<line>66<col>9<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDLinkAppearanceHandler.java<line>66<col>72<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDLinkAppearanceHandler.java<line>64<col>9<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDLinkAppearanceHandler.java<line>59<col>51<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDLinkAppearanceHandler.java<line>59<col>70<err>cannot find symbol |
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 |
PDAnnotationPolygon annotation = (PDAnnotationPolygon) getAnnotation();
float[][] pathArray = getPathArray(annotation);
if (pathArray == null)
{
return;
}
PDAppearanceStream appearanceStream = getAppearanceStream();
if (appearanceStream == null)
{
return;
}
PDAppearanceDictionary appearanceDictionary = appearanceStream.getNormalAppearance();
if (appearanceDictionary == null)
{
return;
}
PDAppearanceStreamContentGenerator contentGenerator = new PDAppearanceStreamContentGenerator(appearanceStream);
PDAppearanceDictionary borderAppearance = appearanceDictionary.getBorderAppearance();
if (borderAppearance != null)
{
contentGenerator.setBorderAppearance(borderAppearance);
}
PDAppearanceDictionary interiorAppearance = appearanceDictionary.getInteriorAppearance();
if (interiorAppearance != null)
{
contentGenerator.setInteriorAppearance(interiorAppearance);
}
contentGenerator.setLineWidth(getLineWidth());
contentGenerator.setPath(pathArray);
contentGenerator.close();
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDPolygonAppearanceHandler.java<line>66<col>47<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDPolygonAppearanceHandler.java<line>80<col>9<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDPolygonAppearanceHandler.java<line>78<col>67<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDPolygonAppearanceHandler.java<line>72<col>71<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDPolygonAppearanceHandler.java<line>86<col>9<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDPolygonAppearanceHandler.java<line>72<col>9<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDPolygonAppearanceHandler.java<line>78<col>9<err>cannot find symbol |
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 |
PDAnnotationMarkup annotation = (PDAnnotationMarkup) getAnnotation();
PDAppearanceStream appearanceStream = annotation.getAppearanceStream();
if (appearanceStream == null)
{
appearanceStream = new PDAppearanceStream(getDocument());
annotation.setAppearanceStream(appearanceStream);
}
PDAppearanceDictionary appearance = appearanceStream.getNormalAppearance();
if (appearance == null)
{
appearance = new PDAppearanceDictionary(getDocument());
appearanceStream.setNormalAppearance(appearance);
}
PDAppearanceStreamContentGenerator contentGenerator = new PDAppearanceStreamContentGenerator(appearanceStream);
PDAppearanceDictionary appearanceDict = new PDAppearanceDictionary(getDocument());
appearance.setNormalAppearance(appearanceDict);
PDAppearanceStreamContentGenerator.PDAppearanceStreamContentGeneratorState state = contentGenerator.beginAppearance(appearanceDict);
PDAppearanceStreamContentGenerator.PDAppearanceStreamContentGeneratorState state2 = contentGenerator.beginLayer(state, 0);
PDAppearanceStreamContentGenerator.PDAppearanceStreamContentGeneratorState state3 = contentGenerator.beginLayer(state2, 1);
PDAppearanceStreamContentGenerator.PDAppearanceStreamContentGeneratorState state4 = contentGenerator.beginLayer(state3, 2);
PDAppearanceStreamContentGenerator.PDAppearanceStreamContentGeneratorState state5 = contentGenerator.beginLayer(state4, 3);
PDAppearanceStreamContentGenerator | <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDSquareAppearanceHandler.java<line>89<col>43<err>';' expected
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDSquareAppearanceHandler.java<line>89<col>9<err>not a statement |
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 |
// No normal appearance generated
| <success> |
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 |
PDAnnotationWidget widget = getAnnotationWidget();
if (widget == null)
{
LOG.warn("No widget for strikeout annotation");
return;
}
PDAppearanceStream appearanceStream = widget.getAppearanceStream();
if (appearanceStream == null)
{
LOG.warn("No appearance stream for strikeout annotation");
return;
}
PDAppearanceDictionary appearanceDict = appearanceStream.getAppearanceDictionary();
if (appearanceDict == null)
{
LOG.warn("No appearance dictionary for strikeout annotation");
return;
}
PDStrikeout strikeout = new PDStrikeout();
strikeout.setStrikeout(true);
appearanceDict.setStrikeout(strikeout);
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDStrikeoutAppearanceHandler.java<line>49<col>9<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDStrikeoutAppearanceHandler.java<line>70<col>37<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDStrikeoutAppearanceHandler.java<line>49<col>37<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDStrikeoutAppearanceHandler.java<line>70<col>9<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDStrikeoutAppearanceHandler.java<line>56<col>9<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDStrikeoutAppearanceHandler.java<line>63<col>9<err>cannot find symbol |
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 |
PDAnnotationAppearanceStream appearanceStream = getAnnotation().getAppearanceStream();
if (appearanceStream == null)
{
LOG.warn("No appearance stream found for underline annotation");
return;
}
PDAnnotationAppearanceStreamWriter writer = new PDAnnotationAppearanceStreamWriter(appearanceStream);
writer.setLineWidth(1);
writer.setLineColor(new PDColor(0, 0, 0));
writer.setLineStyle(PDLineStyle.SOLID);
writer.setLineEndStyle(PDLineEndStyle.BUTT);
writer.setLineJoinStyle(PDLineJoinStyle.MITER);
writer.setMiterLimit(10);
writer.setLineDashArray(new float[] { 1, 1 });
writer.setLineDashPhase(0);
writer.setLineCapStyle(PDLineCapStyle.BUTT);
writer.setLineAlignment(PDLineAlignment.CENTER);
writer.setLineInset(0);
writer.setLineIndent(0);
writer.setLineLeading(0);
writer.setLineStartOffset(0);
writer.setLineEndOffset(0);
writer.setLineStartWidth(0);
writer.setLineEndWidth(0);
writer.setLineStartType(PDLineStartType.NONE);
writer.setLineEndType(PDLineEndType.NONE);
writer.setLineStartLength(0);
writer.setLineEndLength(0);
writer.setLineStartAngle(0);
writer.setLineEndAng | <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDUnderlineAppearanceHandler.java<line>79<col>29<err>';' expected
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDUnderlineAppearanceHandler.java<line>79<col>15<err>not a statement |
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 |
if ((this.range == -1 || getRemaining() <= 0) && !nextRange())
{
return -1; // EOF
}
int b = super.read();
if (b != -1)
{
this.position++;
}
return b;
| <success> |
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 |
PDPropBuildDataDict app = null;
COSDictionary appDic = dictionary.getCOSDictionary(COSName.APP);
if (appDic != null)
{
app = new PDPropBuildDataDict(appDic);
}
return app;
| <success> |
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 |
dictionary.setInt(COSName.P, p);
| <success> |
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 |
if (visualSignature != null)
{
visualSignature.close();
}
| <success> |
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 |
try (ByteArrayOutputStream baos = new ByteArrayOutputStream())
{
COSDocument visualSignature = pdfBuilder.buildPDF(properties);
COSWriter writer = new COSWriter(baos);
writer.write(visualSignature);
return new ByteArrayInputStream(baos.toByteArray());
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/digitalsignature/visible/PDFTemplateCreator.java<line>80<col>53<err>cannot find symbol |
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 |
if (visualSignEnabled)
{
pdVisibleSignature.buildSignature(visibleSignature);
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/digitalsignature/visible/PDVisibleSigProperties.java<line>48<col>31<err>cannot find symbol |
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 |
if( base instanceof COSString )
{
return new PDStringDestination( (COSString) base );
}
else if( base instanceof COSName )
{
return new PDNameDestination( (COSName) base );
}
else if( base instanceof COSDictionary )
{
return new PDDictionaryDestination( (COSDictionary) base );
}
else
{
throw new IOException( "Invalid destination type: " + base.getClass().getName() );
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDDestination.java<line>50<col>24<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDDestination.java<line>54<col>24<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDDestination.java<line>56<col>34<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDDestination.java<line>58<col>24<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDDestination.java<line>58<col>50<err>cannot find symbol |
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 |
if (namedDestination == null)
{
return null;
}
else if (namedDestination instanceof COSString)
{
return ((COSString) namedDestination).getS();
}
else if (namedDestination instanceof COSName)
{
return ((COSName) namedDestination).getName();
}
else
{
throw new IllegalStateException( "Named destination is not a string or name" );
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDNamedDestination.java<line>96<col>50<err>cannot find symbol |
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 |
PDPage retval = null;
if( !array.isEmpty() )
{
COSBase page = array.getObject( 0 );
if( page instanceof PDPage )
{
retval = (PDPage)page;
}
}
return retval;
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDPageDestination.java<line>72<col>17<err>incompatible types: org.apache.pdfbox.cos.COSBase cannot be converted to org.apache.pdfbox.pdmodel.PDPage
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDPageDestination.java<line>74<col>34<err>incompatible types: org.apache.pdfbox.cos.COSBase cannot be converted to org.apache.pdfbox.pdmodel.PDPage |
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 |
array.setName( 1, fitBoundingBox ? TYPE_BOUNDED : TYPE );
| <success> |
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 |
array.growToSize(3);
array.setInt( 2, x );
| <success> |
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 |
array.growToSize( 6 );
if( x == -1 )
{
array.set(4, null);
}
else
{
array.setInt( 4, x );
}
| <success> |
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 |
array.growToSize( 3 );
array.setName( 1, fitBoundingBox ? TYPE_BOUNDED : TYPE );
| <success> |
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 |
array.growToSize(5);
if( x == -1 )
{
array.set(2, null);
}
else
{
array.setInt( 2, x );
}
| <success> |
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 |
// The root of the outline hierarchy is not an OutlineItem and cannot be opened or closed
| <success> |
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 |
if (currentItem == null)
{
currentItem = startingItem;
}
else
{
currentItem = currentItem.getNextSibling();
}
return currentItem;
| <success> |
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 |
List<String> list = new ArrayList<>();
if (items instanceof COSArray)
{
COSArray array = (COSArray) items;
for (int i = 0; i < array.size(); i++)
{
COSBase base = array.getObject(i);
if (base instanceof COSArray)
{
COSArray pair = (COSArray) base;
if (pair.size() != 2)
{
throw new IllegalArgumentException("Array of two-element arrays must have two elements");
}
list.add(pair.getString(pairIdx));
}
else
{
list.add(base.toString());
}
}
}
else
{
list.add(items.toString());
}
return list;
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/FieldUtils.java<line>168<col>5<err>illegal start of expression |
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 |
COSDictionary appearance = getAppearance();
if (appearance == null)
{
return "";
}
COSDictionary normal = appearance.getDictionaryObject(COSName.N);
if (normal == null)
{
return "";
}
COSDictionary on = normal.getDictionaryObject(COSName.ON);
if (on == null)
{
return "";
}
COSName onValue = on.getCOSName(COSName.V);
if (onValue == null)
{
return "";
}
return onValue.getName();
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDCheckBox.java<line>107<col>62<err>incompatible types: org.apache.pdfbox.cos.COSBase cannot be converted to org.apache.pdfbox.cos.COSDictionary
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDCheckBox.java<line>102<col>36<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDCheckBox.java<line>112<col>54<err>incompatible types: org.apache.pdfbox.cos.COSBase cannot be converted to org.apache.pdfbox.cos.COSDictionary |
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 |
super.constructAppearances();
if (isEdit())
{
getAppearance().setAppearance(COSName.N, getAppearance().getAppearance(COSName.N));
}
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDComboBox.java<line>84<col>54<err>cannot find symbol
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDComboBox.java<line>81<col>14<err>abstract method constructAppearances() in org.apache.pdfbox.pdmodel.interactive.form.PDChoice cannot be accessed directly
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDComboBox.java<line>84<col>13<err>cannot find symbol |
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 |
String fieldType = dic.getString(COSName.FT);
if (fieldType == null)
{
fieldType = dic.getString(COSName.FTI);
}
return fieldType;
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDFieldFactory.java<line>135<col>46<err>cannot find symbol |
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 |
if (set.add(node.getCOSObject()))
{
queue.add(node);
if (node instanceof PDButtonField)
{
PDButtonField button = (PDButtonField) node;
enqueueKids(button.getKids());
}
else if (node instanceof PDCheckBox)
{
PDCheckBox checkBox = (PDCheckBox) node;
enqueueKids(checkBox.getKids());
}
else if (node instanceof PDRadioButton)
{
PDRadioButton radioButton = (PDRadioButton) node;
enqueueKids(radioButton.getKids());
}
else if (node instanceof PDListBox)
{
PDListBox listBox = (PDListBox) node;
enqueueKids(listBox.getKids());
}
else if (node instanceof PDComboBox)
{
PDComboBox comboBox = (PDComboBox) node;
enqueueKids(comboBox.getKids());
}
else if (node instanceof PDMultiLineTextBox)
{
PDMultiLineTextBox multiLineTextBox = (PDMultiLineTextBox) node;
enqueueKids(multiLineTextBox.getKids());
}
else if (node instanceof PDMultiSelectListBox)
{
PDMultiSelectListBox multiSelectListBox = (PDMultiSelectListBox) node;
enqueueKids(multiSelectListBox.getKids());
}
else if (node instanceof PDMultiSelectCombo | <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDFieldTree.java<line>150<col>2<err>reached end of file while parsing
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDFieldTree.java<line>148<col>60<err>')' expected |
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 |
if (topIndex == null)
{
getCOSObject().removeItem(COSName.TI);
}
else
{
getCOSObject().setInt(COSName.TI, topIndex);
}
| <success> |
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 |
// no-op
| <success> |
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 |
List<String> exportValues = new ArrayList<String>();
int idx = 0;
for (PDAnnotationWidget widget : getWidgets())
{
if (!COSName.Off.equals(widget.getAppearanceState()))
{
exportValues.add(getExportValues().get(idx));
}
idx ++;
}
return exportValues;
| <success> |
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 |
return "Signature" + getAcroForm().getFields().size();
| <success> |
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 |
return getCOSObject().getInt(COSName.FF, 0);
| <success> |
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 |
if (defaultStyleString != null)
{
getCOSObject().setString(COSName.DS, defaultStyleString);
}
else
{
getCOSObject().removeItem(COSName.DS);
}
| <success> |
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 |
final int size = cosArray.size();
final byte[] result = new byte[size];
for (int i = 0; i < size; i++)
{
final COSBase cosBase = cosArray.getObject(i);
if (cosBase instanceof COSStream)
{
result[i] = getBytesFromStream((COSStream) cosBase)[0];
}
}
return result;
| <success> |
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 |
append.setPreviousBead( this );
append.setNextBead( getNextBead() );
setNextBead( append );
append.getNextBead().setPreviousBead( append );
| <success> |
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 |
return getCOSObject().getItem(COSName.DI);
| <success> |
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 |
PDPage page = document.getPage(pageIndex);
PDRectangle mediaBox = page.getMediaBox();
float width = mediaBox.getWidth();
float height = mediaBox.getHeight();
PageFormat pageFormat = new PageFormat();
pageFormat.setOrientation(orientation);
pageFormat.setPaper(new Paper(width, height));
return pageFormat;
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/printing/PDFPageable.java<line>166<col>29<err>constructor Paper in class java.awt.print.Paper cannot be applied to given types;
<file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/printing/PDFPageable.java<line>165<col>35<err>incompatible types: org.apache.pdfbox.printing.Orientation cannot be converted to int |
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 |
GeneralPath path = cache.get(code);
if (path == null)
{
path = font.getPathForCharacterCode(code);
if (path != null)
{
cache.put(code, path);
}
}
return path;
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/rendering/GlyphCache.java<line>52<col>24<err>cannot find symbol |
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 |
return context.getRaster(x1, y1, w, h);
| <success> |
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 |
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final TilingPaintParameter other = (TilingPaintParameter)obj;
if (this.matrix != other.matrix && (this.matrix == null || !this.matrix.equals(other.matrix)))
{
return false;
}
if (this.patternDict != other.patternDict && (this.patternDict == null || !this.patternDict.equals(other.patternDict)))
{
return false;
}
if (this.colorSpace != other.colorSpace && (this.colorSpace == null || !this.colorSpace.equals(other.colorSpace)))
{
return false;
}
if (this.color != other.color && (this.color == null || !this.color.equals(other.color)))
{
return false;
}
if (this.xform != other.xform && (this.xform == null || !this.xform.equals(other.xform)))
{
return false;
}
return true;
| <success> |
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 |
return Math.abs(first - second) <= variance;
| <success> |
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 |
super.extractRegions( page );
regionArea.forEach((key, rect) ->
{
charactersByArticle = regionCharacterList.get(key);
output = regionText.get(key);
super.writePage();
});
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/text/PDFTextStripperByArea.java<line>115<col>14<err>cannot find symbol |
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 |
return pos1.compareTo(pos2);
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/text/TextPositionComparator.java<line>34<col>20<err>cannot find symbol |
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 |
if (list.size() < 2)
{
return;
}
T[] arr = (T[]) list.toArray();
iterativeMergeSort(arr, cmp);
list.clear();
for (T t : arr)
{
list.add(t);
}
| <success> |
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 |
if (maxFractionDigits > MAX_FRACTION_DIGITS)
{
return -1;
}
if (Float.isNaN(value) || Float.isInfinite(value))
{
return -1;
}
int offset = 0;
if (value < 0)
{
asciiBuffer[offset++] = '-';
value = -value;
}
long longValue = (long) value;
int exp = getExponent(longValue);
if (exp < 0)
{
asciiBuffer[offset++] = '0';
}
else
{
offset = formatPositiveNumber(longValue, exp, false, asciiBuffer, offset);
}
if (maxFractionDigits > 0)
{
asciiBuffer[offset++] = '.';
long fraction = (long) ((value - longValue) * POWER_OF_TENS[maxFractionDigits]);
offset = formatPositiveNumber(fraction, maxFractionDigits - 1, true, asciiBuffer, offset);
}
return offset;
| <success> |
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 |
return "Vector{" +
"x=" + x +
", y=" + y +
'}';
| <success> |
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 |
try
{
Properties properties = new Properties();
properties.load(Version.class.getResourceAsStream(PDFBOX_VERSION_PROPERTIES));
return properties.getProperty("version");
}
catch (IOException e)
{
LOG.warn("Could not load version.properties", e);
return "unknown";
}
| <success> |
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 |
if (node == null)
{
return null;
}
return node.getTextContent();
| <success> |
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 |
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;
}
}
node.setValue(value);
maxDepth = Math.max(maxDepth, parts.length);
}
/**
* Return the maximum depth of the trie.
* @return
*/
public int getMaxDepth()
{
return maxDepth;
| <file>apache_pdfbox/pdfbox/pdfbox/src/main/java/org/apache/pdfbox/util/filetypedetector/ByteTrie.java<line>125<col>5<err>illegal start of expression |
apache_pdfbox | pdfbox/pdfbox/src/main/java/org/apache/pdfbox/util/filetypedetector/FileTypeDetector.java | FileTypeDetector | detectFileType | class FileTypeDetector
{
private static final ByteTrie<FileType> root;
static
{
root = new ByteTrie<>();
root.setDefaultValue(FileType.UNKNOWN);
// https://en.wikipedia.org/wiki/List_of_file_signatures
root.addPath(FileType.JPEG, new byte[]{(byte)0xff, (byte)0xd8});
root.addPath(FileType.TIFF, "II".getBytes(StandardCharsets.ISO_8859_1), new byte[]{0x2a, 0x00});
root.addPath(FileType.TIFF, "MM".getBytes(StandardCharsets.ISO_8859_1), new byte[]{0x00, 0x2a});
root.addPath(FileType.PSD, "8BPS".getBytes(StandardCharsets.ISO_8859_1));
root.addPath(FileType.PNG, new byte[]{(byte)0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52});
// TODO technically there are other very rare magic numbers for OS/2 BMP files...
root.addPath(FileType.BMP, "BM".getBytes(StandardCharsets.ISO_8859_1));
root.addPath(FileType.GIF, "GIF87a".getBytes(StandardCharsets.ISO_8859_1));
root.addPath(FileType.GIF, "GIF89a".getBytes(StandardCharsets.ISO_8859_1));
root.addPath(FileType.ICO, new byte[]{0x00, 0x00, 0x01, 0x00});
// multiple PCX versions, explicitly listed
root.addPath(FileType.PCX, new byte[]{0x0A, 0x00, 0x01});
root.addPath(FileType.PCX, new byte[]{0x0A, 0x02, 0x01});
root.addPath(FileType.PCX, new byte[]{0x0A, 0x03, 0x01});
root.addPath(FileType.PCX, new byte[]{0x0A, 0x05, 0x01});
root.addPath(FileType.RIFF, "RIFF".getBytes(StandardCharsets.ISO_8859_1));
// https://github.com/drewnoakes/metadata-extractor/issues/217
// root.addPath(FileType.ARW, "II".getBytes(StandardCharsets.ISO_8859_1), new byte[]{0x2a, 0x00, 0x08, 0x00})
root.addPath(FileType.CRW, "II".getBytes(StandardCharsets.ISO_8859_1), new byte[]{0x1a, 0x00, 0x00, 0x00}, "HEAPCCDR".getBytes(StandardCharsets.ISO_8859_1));
root.addPath(FileType.CR2, "II".getBytes(StandardCharsets.ISO_8859_1), new byte[]{0x2a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x43, 0x52});
root.addPath(FileType.NEF, "MM".getBytes(StandardCharsets.ISO_8859_1), new byte[]{0x00, 0x2a, 0x00, 0x00, 0x00, (byte)0x80, 0x00});
root.addPath(FileType.ORF, "IIRO".getBytes(StandardCharsets.ISO_8859_1), new byte[]{(byte)0x08, 0x00});
root.addPath(FileType.ORF, "IIRS".getBytes(StandardCharsets.ISO_8859_1), new byte[]{(byte)0x08, 0x00});
root.addPath(FileType.RAF, "FUJIFILMCCD-RAW".getBytes(StandardCharsets.ISO_8859_1));
root.addPath(FileType.RW2, "II".getBytes(StandardCharsets.ISO_8859_1), new byte[]{0x55, 0x00});
}
private FileTypeDetector()
{
}
/**
* Examines the a file's first bytes and estimates the file's type.
* <p>
* Requires a {@link BufferedInputStream} in order to mark and reset the stream to the position
* at which it was provided to this method once completed.
* <p>
* Requires the stream to contain at least eight bytes.
*
* @param inputStream a buffered input stream of the file to examine.
* @return the file type.
* @throws IOException if an IO error occurred or the input stream ended unexpectedly.
*/
public static FileType detectFileType(final BufferedInputStream inputStream) throws IOException
{<FILL_FUNCTION_BODY>}
public static FileType detectFileType(final byte[] fileBytes)
{
return root.find(fileBytes);
}
} |
if (!inputStream.markSupported())
{
throw new IOException("Stream must support mark/reset");
}
int maxByteCount = root.getMaxDepth();
inputStream.mark(maxByteCount);
byte[] bytes = new byte[maxByteCount];
int bytesRead = inputStream.read(bytes);
if (bytesRead == -1)
{
throw new IOException("Stream ended before file's magic number could be determined.");
}
inputStream.reset();
//noinspection ConstantConditions
return root.find(bytes);
| 1,431 | 148 | 1,579 |
try
{
inputStream.mark(8);
final byte[] fileBytes = new byte[8];
final int bytesRead = inputStream.read(fileBytes);
if (bytesRead != 8)
{
throw new IOException("File too short");
}
inputStream.reset();
return root.find(fileBytes);
}
finally
{
inputStream.close();
}
| <success> |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/DecompressObjectstreams.java | DecompressObjectstreams | main | class DecompressObjectstreams implements Callable<Integer>
{
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSERR;
@Option(names = {"-h", "--help"}, usageHelp = true, description = "display this help message")
boolean usageHelpRequested;
@Option(names = {"-i", "--input"}, description = "the PDF file to decompress", required = true)
private File infile;
@Option(names = {"-o", "--output"}, description = "the decompressed PDF file. If omitted the original file is overwritten.")
private File outfile;
/**
* Constructor.
*/
public DecompressObjectstreams()
{
SYSERR = System.err;
}
/**
* This is the entry point for the application.
*
* @param args The command-line arguments.
*/
public static void main(String[] args)
{<FILL_FUNCTION_BODY>}
public Integer call()
{
try (PDDocument doc = Loader.loadPDF(infile))
{
// overwrite inputfile if no outputfile was specified
if (outfile == null) {
outfile = infile;
}
doc.save(outfile, CompressParameters.NO_COMPRESSION);
}
catch (IOException ioe)
{
SYSERR.println("Error processing file [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage());
return 4;
}
return 0;
}
} |
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new DecompressObjectstreams()).execute(args);
System.exit(exitCode);
| 430 | 63 | 493 |
DecompressObjectstreams app = new DecompressObjectstreams();
CommandLine.run(app, args);
| <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/DecompressObjectstreams.java<line>71<col>20<err>no suitable method found for run(org.apache.pdfbox.tools.DecompressObjectstreams,java.lang.String[]) |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Decrypt.java | Decrypt | call | class Decrypt implements Callable<Integer>
{
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSERR;
@Option(names = "-alias", description = "the alias to the certificate in the keystore.")
private String alias;
@Option(names = "-keyStore", description = "the path to the keystore that holds the certificate to decrypt the document. " +
"This is only required if the document is encrypted with a certificate, otherwise only the password is required.")
private String keyStore;
@Option(names = "-password", arity="0..1", interactive = true, description = "the password for the PDF or certificate in keystore.")
private String password;
@Option(names = {"-i", "--input"}, description = "the PDF file to decrypt", required = true)
private File infile;
@Option(names = {"-o", "--output"}, description = "the decrypted PDF file. If omitted the original file is overwritten.")
private File outfile;
/**
* Constructor.
*/
public Decrypt()
{
SYSERR = System.err;
}
/**
* This is the entry point for the application.
*
* @param args The command-line arguments.
*
*/
public static void main(String[] args)
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new Decrypt()).execute(args);
System.exit(exitCode);
}
public Integer call()
{<FILL_FUNCTION_BODY>}
} |
try (InputStream keyStoreStream = keyStore == null ? null : new FileInputStream(keyStore);
PDDocument document = Loader.loadPDF(infile, password, keyStoreStream, alias))
{
// overwrite inputfile if no outputfile was specified
if (outfile == null) {
outfile = infile;
}
if (document.isEncrypted())
{
AccessPermission ap = document.getCurrentAccessPermission();
if(ap.isOwnerPermission())
{
document.setAllSecurityToBeRemoved(true);
document.save( outfile );
}
else
{
SYSERR.println( "Error: You are only allowed to decrypt a document with the owner password.");
return 1;
}
}
else
{
SYSERR.println( "Error: Document is not encrypted.");
return 1;
}
}
catch (IOException ioe)
{
SYSERR.println( "Error decrypting document [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage());
return 4;
}
return 0;
| 447 | 294 | 741 |
try
{
if (outfile == null)
{
outfile = infile;
}
PDDocument doc = PDDocument.load(infile);
if (keyStore != null)
{
PDAcroForm form = doc.getDocumentCatalog().getAcroForm();
if (form == null)
{
SYSERR.println("Document is not an AcroForm");
return 1;
}
PDSecurityDictionary security = form.getDocumentSecurity();
if (security == null)
{
SYSERR.println("Document is not encrypted");
return 1;
}
PDKeyStore keyStore = new PDKeyStore(new File(this.keyStore), password);
PDKey key = keyStore.getKey(alias, password);
if (key == null)
{
SYSERR.println("Key not found");
return 1;
}
PDSecurityDictionary.setCurrentSecurity(security);
PDSecurityDictionary.setCurrentKey(key);
PDSecurityDictionary.setCurrentKeyStore(keyStore);
PDSecurityDictionary.decrypt(doc);
}
else
{
doc.decrypt(password);
}
doc.save(outfile);
doc.close();
}
catch (Exception e)
{
SYSERR.println(e.getMessage());
return 1;
}
return 0;
| <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Decrypt.java<line>120<col>17<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Decrypt.java<line>102<col>40<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Decrypt.java<line>132<col>17<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Decrypt.java<line>128<col>17<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Decrypt.java<line>120<col>43<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Decrypt.java<line>130<col>17<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Decrypt.java<line>121<col>17<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Decrypt.java<line>113<col>17<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Decrypt.java<line>129<col>17<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Decrypt.java<line>136<col>20<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Decrypt.java<line>106<col>17<err>cannot find symbol |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Encrypt.java | Encrypt | call | class Encrypt implements Callable<Integer>
{
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSERR;
@Option(names = "-O", description = "set the owner password (ignored if certFile is set)", arity = "0..1", interactive = true)
private String ownerPassword;
@Option(names = "-U", description = "set the user password (ignored if certFile is set)", arity = "0..1", interactive = true)
private String userPassword;
@Option(names = "-certFile", paramLabel="certFile", description = "Path to X.509 certificate (repeat both if needed)")
private List<File> certFileList = new ArrayList<>();
@Option(names = "-canAssemble", description = "set the assemble permission (default: ${DEFAULT-VALUE})")
private boolean canAssembleDocument = true;
@Option(names = "-canExtractContent", description = "set the extraction permission (default: ${DEFAULT-VALUE})")
private boolean canExtractContent = true;
@Option(names = "-canExtractForAccessibility", description = "set the extraction permission (default: ${DEFAULT-VALUE})")
private boolean canExtractForAccessibility = true;
@Option(names = "-canFillInForm", description = "set the form fill in permission (default: ${DEFAULT-VALUE})")
private boolean canFillInForm = true;
@Option(names = "-canModify", description = "set the modify permission (default: ${DEFAULT-VALUE})")
private boolean canModify = true;
@Option(names = "-canModifyAnnotations", description = "set the modify annots permission (default: ${DEFAULT-VALUE})")
private boolean canModifyAnnotations = true;
@Option(names = "-canPrint", description = "set the print permission (default: ${DEFAULT-VALUE})")
private boolean canPrint = true;
@Option(names = "-canPrintFaithful", description = "set the print faithful permission (default: ${DEFAULT-VALUE})")
private boolean canPrintFaithful = true;
@Option(names = "-keyLength", description = "Key length in bits (valid values: 40, 128 or 256) (default: ${DEFAULT-VALUE})")
private int keyLength = 256;
@Option(names = {"-i", "--input"}, description = "the PDF file to encrypt", required = true)
private File infile;
@Option(names = {"-o", "--output"}, description = "the encrypted PDF file. If omitted the original file is overwritten.")
private File outfile;
/**
* Constructor.
*/
public Encrypt()
{
SYSERR = System.err;
}
/**
* This is the entry point for the application.
*
* @param args The command-line arguments.
*/
public static void main( String[] args )
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new Encrypt()).execute(args);
System.exit(exitCode);
}
public Integer call()
{<FILL_FUNCTION_BODY>}
} |
AccessPermission ap = new AccessPermission();
ap.setCanAssembleDocument(canAssembleDocument);
ap.setCanExtractContent(canExtractContent);
ap.setCanExtractForAccessibility(canExtractForAccessibility);
ap.setCanFillInForm(canFillInForm);
ap.setCanModify(canModify);
ap.setCanModifyAnnotations(canModifyAnnotations);
ap.setCanPrint(canPrint);
ap.setCanPrintFaithful(canPrintFaithful);
if (outfile == null)
{
outfile = infile;
}
try (PDDocument document = Loader.loadPDF(infile))
{
if( !document.isEncrypted() )
{
if (!document.getSignatureDictionaries().isEmpty())
{
SYSERR.println( "Warning: Document contains signatures which will be invalidated by encryption." );
}
if (!certFileList.isEmpty())
{
PublicKeyProtectionPolicy ppp = new PublicKeyProtectionPolicy();
PublicKeyRecipient recip = new PublicKeyRecipient();
recip.setPermission(ap);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
for (File certFile : certFileList)
{
try (InputStream inStream = new FileInputStream(certFile))
{
X509Certificate certificate = (X509Certificate) cf.generateCertificate(inStream);
recip.setX509(certificate);
}
ppp.addRecipient(recip);
}
ppp.setEncryptionKeyLength(keyLength);
document.protect(ppp);
}
else
{
StandardProtectionPolicy spp =
new StandardProtectionPolicy(ownerPassword, userPassword, ap);
spp.setEncryptionKeyLength(keyLength);
document.protect(spp);
}
document.save( outfile );
}
else
{
SYSERR.println( "Error: Document is already encrypted." );
}
}
catch (IOException | CertificateException ex)
{
SYSERR.println( "Error encrypting PDF [" + ex.getClass().getSimpleName() + "]: " + ex.getMessage());
return 4;
}
return 0;
| 848 | 602 | 1,450 |
if (certFileList.size() == 0)
{
SYSERR.println("No certificate file specified");
return 1;
}
if (certFileList.size() > 2)
{
SYSERR.println("Only two certificate files are allowed");
return 1;
}
try
{
PDDocument doc = PDDocument.load(infile);
if (certFileList.size() == 1)
{
PDKey key = new PDKey(certFileList.get(0), ownerPassword, userPassword);
doc.getDocumentCatalog().setOpenTo(key);
}
else
{
PDKey key = new PDKey(certFileList.get(0), certFileList.get(1), ownerPassword, userPassword);
doc.getDocumentCatalog().setOpenTo(key);
}
PDSecurity security = doc.getDocumentCatalog().getAcroForm().getSecurity();
security.setCanAssembleDocument(canAssembleDocument);
security.setCanExtractContent(canExtractContent);
security.setCanExtractForAccessibility(canExtractForAccessibility);
security.setCanFillInForm(canFillInForm);
security.setCanModify(canModify);
security.setCanModifyAnnotations(canModifyAnnotations);
security.setCanPrint(canPrint);
security.setCanPrintFaithful(canPrintFaithful);
security.setKeyLength(keyLength);
if (outfile == null)
{
outfile = infile; | <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Encrypt.java<line>171<col>2<err>reached end of file while parsing
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Encrypt.java<line>142<col>9<err>'try' without 'catch', 'finally' or resource declarations |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExportFDF.java | ExportFDF | call | class ExportFDF implements Callable<Integer>
{
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSERR;
@Option(names = {"-i", "--input"}, description = "the PDF file to export", required = true)
private File infile;
@Option(names = {"-o", "--output"}, description = "the FDF data file", required = true)
private File outfile;
/**
* Constructor.
*/
public ExportFDF()
{
SYSERR = System.err;
}
/**
* This is the entry point for the application.
*
* @param args The command-line arguments.
*
*/
public static void main(String[] args)
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new ExportFDF()).execute(args);
System.exit(exitCode);
}
public Integer call()
{<FILL_FUNCTION_BODY>}
} |
try (PDDocument pdf = Loader.loadPDF(infile))
{
PDAcroForm form = pdf.getDocumentCatalog().getAcroForm();
if( form == null )
{
SYSERR.println( "Error: This PDF does not contain a form." );
return 1;
}
else
{
if (outfile == null)
{
String outPath = FilenameUtils.removeExtension(infile.getAbsolutePath()) + ".fdf";
outfile = new File(outPath);
}
try (FDFDocument fdf = form.exportFDF())
{
fdf.save( outfile );
}
}
}
catch (IOException ioe)
{
SYSERR.println( "Error exporting FDF data [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage());
return 4;
}
return 0;
| 306 | 244 | 550 |
try
{
PDDocument doc = PDDocument.load(infile);
FDFSerializer serializer = new FDFSerializer(doc);
serializer.serialize(outfile);
doc.close();
}
catch (IOException e)
{
SYSERR.println("Error: " + e.getMessage());
return 1;
}
return 0;
| <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExportFDF.java<line>79<col>40<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExportFDF.java<line>80<col>13<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExportFDF.java<line>80<col>44<err>cannot find symbol |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExportXFDF.java | ExportXFDF | call | class ExportXFDF implements Callable<Integer>
{
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSERR;
@Option(names = {"-i", "--input"}, description = "the PDF file to export", required = true)
private File infile;
@Option(names = {"-o", "--output"}, description = "the XFDF data file", required = true)
private File outfile;
/**
* Constructor.
*/
public ExportXFDF()
{
SYSERR = System.err;
}
/**
* This is the entry point for the application.
*
* @param args The command-line arguments.
*
*/
public static void main(String[] args)
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new ExportXFDF()).execute(args);
System.exit(exitCode);
}
public Integer call()
{<FILL_FUNCTION_BODY>}
} |
try (PDDocument pdf = Loader.loadPDF(infile))
{
PDAcroForm form = pdf.getDocumentCatalog().getAcroForm();
if( form == null )
{
SYSERR.println( "Error: This PDF does not contain a form." );
}
else
{
if (outfile == null)
{
String outPath = FilenameUtils.removeExtension(infile.getAbsolutePath()) + ".xfdf";
outfile = new File(outPath);
}
try (FDFDocument fdf = form.exportFDF())
{
fdf.saveXFDF(outfile);
}
}
}
catch (IOException ioe)
{
SYSERR.println( "Error exporting XFDF data [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage());
return 4;
}
return 0;
| 310 | 244 | 554 |
try
{
PDDocument doc = PDDocument.load(infile);
XFDFExporter exporter = new XFDFExporter();
exporter.setDocument(doc);
exporter.export(outfile);
doc.close();
}
catch (IOException e)
{
SYSERR.println("Error: " + e.getMessage());
return 1;
}
return 0;
| <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExportXFDF.java<line>81<col>41<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExportXFDF.java<line>81<col>13<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExportXFDF.java<line>80<col>40<err>cannot find symbol |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExtractXMP.java | ExtractXMP | call | class ExtractXMP implements Callable<Integer>
{
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSOUT;
@SuppressWarnings("squid:S106")
private final PrintStream SYSERR;
@CommandLine.Option(names = "-page", description = "extract the XMP information from a specific page (1 based)")
private int page = 0;
@CommandLine.Option(names = "-password", description = "the password for the PDF or certificate in keystore.", arity = "0..1", interactive = true)
private String password = "";
@CommandLine.Option(names = "-console", description = "Send text to console instead of file")
private boolean toConsole = false;
@CommandLine.Option(names = {"-i", "--input"}, description = "the PDF file", required = true)
private File infile;
@CommandLine.Option(names = {"-o", "--output"}, description = "the exported text file")
private File outfile;
/**
* Constructor.
*/
public ExtractXMP()
{
SYSOUT = System.out;
SYSERR = System.err;
}
/**
* Infamous main method.
*
* @param args Command line arguments, should be one and a reference to a file.
*/
public static void main(String[] args)
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new ExtractXMP()).execute(args);
System.exit(exitCode);
}
/**
* Starts the xmp extraction.
*/
@Override
public Integer call()
{<FILL_FUNCTION_BODY>}
} |
if (outfile == null)
{
String outPath = FilenameUtils.removeExtension(infile.getAbsolutePath()) + ".xml";
outfile = new File(outPath);
}
try (PDDocument document = Loader.loadPDF(infile, password))
{
PDDocumentCatalog catalog = document.getDocumentCatalog();
PDMetadata meta;
if (page == 0)
{
meta = catalog.getMetadata();
}
else
{
if (page > document.getNumberOfPages())
{
SYSERR.println("Page " + page + " doesn't exist");
return 1;
}
meta = document.getPage(page - 1).getMetadata();
}
if (meta == null)
{
SYSERR.println("No XMP metadata available");
return 1;
}
try (PrintStream ps = toConsole ? SYSOUT : new PrintStream(outfile))
{
ps.write(meta.toByteArray());
}
}
catch (IOException ioe)
{
SYSERR.println( "Error extracting text for document [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage());
return 4;
}
return 0;
| 487 | 336 | 823 |
try
{
PDDocument doc = PDDocument.load(infile);
if (page > 0)
{
doc.getDocumentCatalog().getAllPages().removeIf(p -> p.getPageNumber() != page);
}
if (password != null && !password.isEmpty())
{
doc.decrypt(password);
}
String xmp = doc.getDocumentInformation().getXmpMetadata();
if (xmp == null)
{
SYSERR.println("No XMP metadata found");
return 1;
}
if (toConsole)
{
SYSOUT.println(xmp);
}
else
{
if (outfile == null)
{
outfile = new File(infile.getAbsolutePath() + ".xmp");
}
try (FileOutputStream fos = new FileOutputStream(outfile))
{
fos.write(xmp.getBytes());
}
}
doc.close();
return 0;
}
catch (IOException e)
{
SYSERR.println("Error: " + e.getMessage());
return 1;
}
| <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExtractXMP.java<line>101<col>20<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExtractXMP.java<line>119<col>49<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExtractXMP.java<line>97<col>41<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExtractXMP.java<line>103<col>54<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExtractXMP.java<line>94<col>40<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExtractXMP.java<line>119<col>22<err>cannot find symbol |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ImageToPDF.java | ImageToPDF | createRectangle | class ImageToPDF implements Callable<Integer>
{
private PDRectangle mediaBox = PDRectangle.LETTER;
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSERR;
@Option(names = "-autoOrientation", description = "set orientation depending of image proportion")
private boolean autoOrientation = false;
@Option(names = "-landscape", description = "set orientation to landscape")
private boolean landscape = false;
@Option(names = "-pageSize", description = "the page size to use: Letter, Legal, A0, A1, A2, A3, A4, A5, A6 (default: ${DEFAULT-VALUE})")
private String pageSize = "Letter";
@Option(names = "-resize", description = "resize to page size")
private boolean resize = false;
@Option(names = {"-i", "--input"}, description = "the image files to convert", paramLabel="image-file", required = true)
private File[] infiles;
@Option(names = {"-o", "--output"}, description = "the generated PDF file", required = true)
private File outfile;
/**
* Constructor.
*/
public ImageToPDF()
{
SYSERR = System.err;
}
public static void main(String[] args)
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new ImageToPDF()).execute(args);
System.exit(exitCode);
}
public Integer call()
{
setMediaBox(createRectangle(pageSize));
try (PDDocument doc = new PDDocument())
{
for (File imageFile : infiles)
{
PDImageXObject pdImage = PDImageXObject.createFromFile(imageFile.getAbsolutePath(), doc);
PDRectangle actualMediaBox = mediaBox;
if ((autoOrientation && pdImage.getWidth() > pdImage.getHeight()) || landscape)
{
actualMediaBox = new PDRectangle(mediaBox.getHeight(), mediaBox.getWidth());
}
PDPage page = new PDPage(actualMediaBox);
doc.addPage(page);
try (PDPageContentStream contents = new PDPageContentStream(doc, page))
{
if (resize)
{
contents.drawImage(pdImage, 0, 0, actualMediaBox.getWidth(), actualMediaBox.getHeight());
}
else
{
contents.drawImage(pdImage, 0, 0, pdImage.getWidth(), pdImage.getHeight());
}
}
}
doc.save(outfile);
}
catch (IOException ioe)
{
SYSERR.println( "Error converting image to PDF [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage());
return 4;
}
return 0;
}
private static PDRectangle createRectangle(String paperSize)
{<FILL_FUNCTION_BODY>}
/**
* Sets page size of produced PDF.
*
* @return returns the page size (media box)
*/
public PDRectangle getMediaBox()
{
return mediaBox;
}
/**
* Sets page size of produced PDF.
*
* @param mediaBox the media box of the PDF document.
*/
public void setMediaBox(PDRectangle mediaBox)
{
this.mediaBox = mediaBox;
}
/**
* Tells the paper orientation.
*
* @return true for landscape orientation
*/
public boolean isLandscape()
{
return landscape;
}
/**
* Sets paper orientation.
*
* @param landscape use landscape orientation.
*/
public void setLandscape(boolean landscape)
{
this.landscape = landscape;
}
/**
* Gets whether page orientation (portrait / landscape) should be decided automatically for each
* page depending on image proportion.
*
* @return true if auto, false if not.
*/
public boolean isAutoOrientation()
{
return autoOrientation;
}
/**
* Sets whether page orientation (portrait / landscape) should be decided automatically for each
* page depending on image proportion.
*
* @param autoOrientation true if auto, false if not.
*/
public void setAutoOrientation(boolean autoOrientation)
{
this.autoOrientation = autoOrientation;
}
} |
if ("letter".equalsIgnoreCase(paperSize))
{
return PDRectangle.LETTER;
}
else if ("legal".equalsIgnoreCase(paperSize))
{
return PDRectangle.LEGAL;
}
else if ("A0".equalsIgnoreCase(paperSize))
{
return PDRectangle.A0;
}
else if ("A1".equalsIgnoreCase(paperSize))
{
return PDRectangle.A1;
}
else if ("A2".equalsIgnoreCase(paperSize))
{
return PDRectangle.A2;
}
else if ("A3".equalsIgnoreCase(paperSize))
{
return PDRectangle.A3;
}
else if ("A4".equalsIgnoreCase(paperSize))
{
return PDRectangle.A4;
}
else if ("A5".equalsIgnoreCase(paperSize))
{
return PDRectangle.A5;
}
else if ("A6".equalsIgnoreCase(paperSize))
{
return PDRectangle.A6;
}
else
{
// return default if wron size was specified
return PDRectangle.LETTER;
}
| 1,208 | 320 | 1,528 |
switch (paperSize)
{
case "Letter":
return PDRectangle.LETTER;
case "Legal":
return PDRectangle.LEGAL;
case "A0":
return PDRectangle.A0;
case "A1":
return PDRectangle.A1;
case "A2":
return PDRectangle.A2;
case "A3":
return PDRectangle.A3;
case "A4":
return PDRectangle.A4;
case "A5":
return PDRectangle.A5;
case "A6":
return PDRectangle.A6;
default:
throw new IllegalArgumentException("Unknown paper size: " + paperSize);
}
| <success> |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ImportFDF.java | ImportFDF | call | class ImportFDF implements Callable<Integer>
{
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSERR;
@Option(names = {"-i", "--input"}, description = "the PDF file to import to", required = true)
private File infile;
@Option(names = {"-o", "--output"}, description = "the PDF file to save to. If omitted the original file will be used")
private File outfile;
@Option(names = {"--data"}, description = "the FDF data file to import from", required = true)
private File fdffile;
/**
* This will takes the values from the fdf document and import them into the
* PDF document.
*
* @param pdfDocument The document to put the fdf data into.
* @param fdfDocument The FDF document to get the data from.
*
* @throws IOException If there is an error setting the data in the field.
*/
public void importFDF( PDDocument pdfDocument, FDFDocument fdfDocument ) throws IOException
{
PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();
if (acroForm == null)
{
return;
}
acroForm.setCacheFields( true );
acroForm.importFDF( fdfDocument );
//TODO this can be removed when we create appearance streams
acroForm.setNeedAppearances(true);
}
/**
* Constructor.
*/
public ImportFDF()
{
SYSERR = System.err;
}
/**
* This will import an fdf document and write out another pdf. <br>
* see usage() for commandline
*
* @param args command line arguments
*/
public static void main(String[] args)
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new ImportFDF()).execute(args);
System.exit(exitCode);
}
public Integer call()
{<FILL_FUNCTION_BODY>}
} |
ImportFDF importer = new ImportFDF();
try (PDDocument pdf = Loader.loadPDF(infile);
FDFDocument fdf = Loader.loadFDF(fdffile))
{
importer.importFDF( pdf, fdf );
if (outfile == null)
{
outfile = infile;
}
pdf.save(outfile);
}
catch (IOException ioe)
{
SYSERR.println( "Error importing FDF data [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage());
return 4;
}
return 0;
| 591 | 171 | 762 |
try (PDDocument pdfDocument = PDDocument.load(infile))
{
FDFDocument fdfDocument = FDFDocument.load(fdffile);
importFDF(pdfDocument, fdfDocument);
if (outfile == null)
{
outfile = infile;
}
pdfDocument.save(outfile);
}
catch (IOException e)
{
SYSERR.println("Error: " + e.getMessage());
return 1;
}
return 0;
| <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ImportFDF.java<line>106<col>50<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ImportFDF.java<line>104<col>49<err>cannot find symbol |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ImportXFDF.java | ImportXFDF | call | class ImportXFDF implements Callable<Integer>
{
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSERR;
@Option(names = {"-i", "--input"}, description = "the PDF file to import to", required = true)
private File infile;
@Option(names = {"-o", "--output"}, description = "the PDF file to save to. If omitted the original file will be used")
private File outfile;
@Option(names = {"--data"}, description = "the XFDF data file to import from", required = true)
private File xfdffile;
/**
* This will takes the values from the fdf document and import them into the
* PDF document.
*
* @param pdfDocument The document to put the fdf data into.
* @param fdfDocument The FDF document to get the data from.
*
* @throws IOException If there is an error setting the data in the field.
*/
public void importFDF( PDDocument pdfDocument, FDFDocument fdfDocument ) throws IOException
{
PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();
acroForm.setCacheFields( true );
acroForm.importFDF( fdfDocument );
}
/**
* Constructor.
*/
public ImportXFDF()
{
SYSERR = System.err;
}
/**
* This will import an fdf document and write out another pdf. <br>
* see usage() for commandline
*
* @param args command line arguments
*/
public static void main(String[] args)
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new ImportXFDF()).execute(args);
System.exit(exitCode);
}
public Integer call()
{<FILL_FUNCTION_BODY>}
} |
ImportXFDF importer = new ImportXFDF();
try (PDDocument pdf = Loader.loadPDF(infile);
FDFDocument fdf = Loader.loadXFDF(xfdffile))
{
importer.importFDF( pdf, fdf );
if (outfile == null)
{
outfile = infile;
}
pdf.save(outfile);
}
catch (IOException ioe)
{
SYSERR.println( "Error importing XFDF data [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage());
return 4;
}
return 0;
| 544 | 175 | 719 |
try (PDDocument pdfDocument = PDDocument.load(infile))
{
FDFDocument fdfDocument = FDFDocument.load(xfdffile);
importFDF(pdfDocument, fdfDocument);
if (outfile == null)
{
outfile = infile;
}
pdfDocument.save(outfile);
}
catch (IOException e)
{
SYSERR.println("Error: " + e.getMessage());
return 1;
}
return 0;
| <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ImportXFDF.java<line>101<col>50<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ImportXFDF.java<line>99<col>49<err>cannot find symbol |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/OverlayPDF.java | OverlayPDF | call | class OverlayPDF implements Callable<Integer>
{
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSERR;
@Option(names = "-odd", description = "overlay file used for odd pages")
private File oddPageOverlay;
@Option(names = "-even", description = "overlay file used for even pages")
private File evenPageOverlay;
@Option(names = "-first", description = "overlay file used for the first page")
private File firstPageOverlay;
@Option(names = "-last", description = "overlay file used for the last page")
private File lastPageOverlay;
@Option(names = "-useAllPages", description = "overlay file used for overlay, all pages are used by simply repeating them")
private File useAllPages;
@Option(names = "-page", description = "overlay file used for the given page number, may occur more than once")
Map<Integer, String> specificPageOverlayFile = new HashMap<>();
@Option(names = {"-default"}, description = "the default overlay file")
private File defaultOverlay;
@Option(names = "-position", description = "where to put the overlay file: foreground or background (default: ${DEFAULT-VALUE})")
private Position position = Position.BACKGROUND;
@Option(names = {"-i", "--input"}, description = "the PDF input file", required = true)
private File infile;
@Option(names = {"-o", "--output"}, description = "the PDF output file", required = true)
private File outfile;
/**
* Constructor.
*/
public OverlayPDF()
{
SYSERR = System.err;
}
/**
* This will overlay a document and write out the results.
*
* @param args command line arguments
*/
public static void main(final String[] args)
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new OverlayPDF()).execute(args);
System.exit(exitCode);
}
@Override
public Integer call()
{<FILL_FUNCTION_BODY>}
} |
int retcode = 0;
Overlay overlayer = new Overlay();
overlayer.setOverlayPosition(position);
if (firstPageOverlay != null)
{
overlayer.setFirstPageOverlayFile(firstPageOverlay.getAbsolutePath());
}
if (lastPageOverlay != null)
{
overlayer.setLastPageOverlayFile(lastPageOverlay.getAbsolutePath());
}
if (oddPageOverlay != null)
{
overlayer.setOddPageOverlayFile(oddPageOverlay.getAbsolutePath());
}
if (evenPageOverlay != null)
{
overlayer.setEvenPageOverlayFile(evenPageOverlay.getAbsolutePath());
}
if (useAllPages != null)
{
overlayer.setAllPagesOverlayFile(useAllPages.getAbsolutePath());
}
if (defaultOverlay != null)
{
overlayer.setDefaultOverlayFile(defaultOverlay.getAbsolutePath());
}
if (infile != null)
{
overlayer.setInputFile(infile.getAbsolutePath());
}
try (PDDocument result = overlayer.overlay(specificPageOverlayFile))
{
result.save(outfile);
}
catch (IOException ioe)
{
SYSERR.println( "Error adding overlay(s) to PDF [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage());
return 4;
}
finally
{
// close the input files AFTER saving the resulting file as some
// streams are shared among the input and the output files
try
{
overlayer.close();
}
catch (IOException ioe)
{
SYSERR.println( "Error adding overlay(s) to PDF [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage());
retcode = 4;
}
}
return retcode;
| 599 | 531 | 1,130 |
try
{
PDDocument doc = PDDocument.load(infile);
PDPageTree pages = doc.getDocumentCatalog().getPages();
if (useAllPages != null)
{
PDPage page = (PDPage) pages.get(0);
PDResources resources = page.getResources();
PDXObjectImage image = (PDXObjectImage) resources.getXObject(useAllPages);
PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);
contentStream.drawImage(image, 0, 0);
contentStream.close();
}
for (int i = 0; i < pages.getCount(); i++)
{
PDPage page = (PDPage) pages.get(i);
PDResources resources = page.getResources();
PDXObjectImage image = null;
if (i % 2 == 0)
{
if (evenPageOverlay != null)
{
image = (PDXObjectImage) resources.getXObject(evenPageOverlay);
}
else if (defaultOverlay != null)
{
image = (PDXObjectImage) resources.getXObject(defaultOverlay);
}
}
else
{
if (oddPageOverlay != null)
{
image = (PDXObjectImage) resources.getXObject(oddPageOverlay);
}
else if (defaultOverlay != null)
{
image = (PDXObjectImage) | <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/OverlayPDF.java<line>104<col>9<err>'try' without 'catch', 'finally' or resource declarations
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/OverlayPDF.java<line>145<col>2<err>reached end of file while parsing
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/OverlayPDF.java<line>144<col>49<err>';' expected |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFBox.java | PDFBox | main | class PDFBox implements Runnable
{
@Spec CommandLine.Model.CommandSpec spec;
/**
* Main method.
*
* @param args command line arguments
*/
public static void main(String[] args)
{<FILL_FUNCTION_BODY>}
@Override
public void run()
{
throw new ParameterException(spec.commandLine(), "Error: Subcommand required");
}
} |
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
CommandLine commandLine = new CommandLine(new PDFBox()).setSubcommandsCaseInsensitive(true);
if (!GraphicsEnvironment.isHeadless())
{
commandLine.addSubcommand("debug", PDFDebugger.class);
}
commandLine.addSubcommand("decrypt", Decrypt.class);
commandLine.addSubcommand("encrypt", Encrypt.class);
commandLine.addSubcommand("decode", WriteDecodedDoc.class);
commandLine.addSubcommand("export:images", ExtractImages.class);
commandLine.addSubcommand("export:xmp", ExtractXMP.class);
commandLine.addSubcommand("export:text", ExtractText.class);
commandLine.addSubcommand("export:fdf", ExportFDF.class);
commandLine.addSubcommand("export:xfdf", ExportXFDF.class);
commandLine.addSubcommand("import:fdf", ImportFDF.class);
commandLine.addSubcommand("import:xfdf", ImportXFDF.class);
commandLine.addSubcommand("overlay", OverlayPDF.class);
commandLine.addSubcommand("print", PrintPDF.class);
commandLine.addSubcommand("render", PDFToImage.class);
commandLine.addSubcommand("merge", PDFMerger.class);
commandLine.addSubcommand("split", PDFSplit.class);
commandLine.addSubcommand("fromimage", ImageToPDF.class);
commandLine.addSubcommand("fromtext", TextToPDF.class);
commandLine.addSubcommand("version", Version.class);
commandLine.addSubcommand("help", CommandLine.HelpCommand.class);
commandLine.execute(args);
| 114 | 452 | 566 |
CommandLine.run(PDFBox.class, args);
| <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFBox.java<line>48<col>20<err>no suitable method found for run(java.lang.Class<org.apache.pdfbox.tools.PDFBox>,java.lang.String[]) |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFMerger.java | PDFMerger | main | class PDFMerger implements Callable<Integer>
{
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSERR;
@Option(names = {"-i", "--input"}, description = "the PDF files to merge.", paramLabel = "<infile>", required = true)
private File[] infiles;
@Option(names = {"-o", "--output"}, description = "the merged PDF file.", required = true)
private File outfile;
/**
* Constructor.
*/
public PDFMerger()
{
SYSERR = System.err;
}
/**
* Infamous main method.
*
* @param args Command line arguments, should be at least 3.
*/
public static void main( String[] args )
{<FILL_FUNCTION_BODY>}
public Integer call()
{
PDFMergerUtility merger = new PDFMergerUtility();
try
{
for (File infile : infiles)
{
merger.addSource(infile);
}
merger.setDestinationFileName(outfile.getAbsolutePath());
merger.mergeDocuments(IOUtils.createMemoryOnlyStreamCache());
}
catch (IOException ioe)
{
SYSERR.println( "Error merging documents [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage());
return 4;
}
return 0;
}
} |
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new PDFMerger()).execute(args);
System.exit(exitCode);
| 410 | 61 | 471 |
PDFMerger merger = new PDFMerger();
CommandLine.populateCommand(merger, args);
int exitCode = merger.call();
System.exit(exitCode);
| <success> |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFSplit.java | PDFSplit | call | class PDFSplit implements Callable<Integer>
{
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSERR;
@Option(names = "-password", description = "the password to decrypt the document.", arity = "0..1", interactive = true)
private String password;
@Option(names = "-split", description = "split after this many pages (default 1, if startPage and endPage are unset).")
private int split = -1;
@Option(names = "-startPage", description = "start page.")
private int startPage = -1;
@Option(names = "-endPage", description = "end page.")
private int endPage = -1;
@Option(names = "-outputPrefix", description = "the filename prefix for split files.")
private String outputPrefix;
@Option(names = {"-i", "--input"}, description = "the PDF file to split", required = true)
private File infile;
/**
* Constructor.
*/
public PDFSplit()
{
SYSERR = System.err;
}
/**
* Infamous main method.
*
* @param args Command line arguments, should be one and a reference to a file.
*/
public static void main( String[] args )
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new PDFSplit()).execute(args);
System.exit(exitCode);
}
public Integer call()
{<FILL_FUNCTION_BODY>}
} |
Splitter splitter = new Splitter();
if (outputPrefix == null)
{
outputPrefix = FilenameUtils.removeExtension(infile.getAbsolutePath());
}
List<PDDocument> documents = null;
try (PDDocument document = Loader.loadPDF(infile, password))
{
boolean startEndPageSet = false;
if (startPage != -1)
{
splitter.setStartPage(startPage);
startEndPageSet = true;
if (split == -1)
{
int numberOfPages = document.getNumberOfPages();
splitter.setSplitAtPage(numberOfPages);
}
}
if (endPage != -1)
{
splitter.setEndPage(endPage);
startEndPageSet = true;
if (split == -1)
{
splitter.setSplitAtPage(endPage);
}
}
if (split != -1)
{
splitter.setSplitAtPage(split);
}
else
{
if (!startEndPageSet)
{
splitter.setSplitAtPage(1);
}
}
documents = splitter.split( document );
for( int i=0; i<documents.size(); i++ )
{
try (PDDocument doc = documents.get(i))
{
doc.save(outputPrefix + "-" + (i + 1) + ".pdf");
}
}
}
catch (IOException ioe)
{
SYSERR.println( "Error splitting document [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage());
return 4;
}
finally
{
if (documents != null)
{
documents.forEach(IOUtils::closeQuietly);
}
}
return 0;
| 438 | 493 | 931 |
if (infile == null)
{
SYSERR.println("No input file specified");
return 1;
}
if (split < 1 && startPage < 1 && endPage < 1)
{
SYSERR.println("No split specified");
return 1;
}
if (split < 1)
{
if (startPage < 1)
{
SYSERR.println("No start page specified");
return 1;
}
if (endPage < 1)
{
SYSERR.println("No end page specified");
return 1;
}
if (startPage > endPage)
{
SYSERR.println("Start page must be less than end page");
return 1;
}
split = endPage - startPage + 1;
}
try
{
PDDocument doc = PDDocument.load(infile);
if (password != null)
{
doc.decrypt(password);
}
int pageCount = doc.getNumberOfPages();
if (startPage < 1)
{
startPage = 1;
}
if (endPage < 1)
{
endPage = pageCount;
}
if (startPage > endPage)
{
SYSERR.println("Start page must be less than end page");
return 1;
}
if (startPage > pageCount)
{
SYSERR.println("Start page must be less than or equal to the number of pages in the document");
return 1; | <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFSplit.java<line>122<col>9<err>'try' without 'catch', 'finally' or resource declarations
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFSplit.java<line>148<col>2<err>reached end of file while parsing |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFText2HTML.java | FontState | closeUntil | class FontState
{
private final List<String> stateList = new ArrayList<>();
private final Set<String> stateSet = new HashSet<>();
/**
* Pushes new {@link TextPosition TextPositions} into the font state. The state is only
* preserved correctly for each letter if the number of letters in <code>text</code> matches
* the number of {@link TextPosition} objects. Otherwise, it's done once for the complete
* array (just by looking at its first entry).
*
* @return A string that contains the text including tag changes caused by its font state.
*/
public String push(String text, List<TextPosition> textPositions)
{
StringBuilder buffer = new StringBuilder();
if (text.length() == textPositions.size())
{
// There is a 1:1 mapping, and we can use the TextPositions directly
for (int i = 0; i < text.length(); i++)
{
push(buffer, text.charAt(i), textPositions.get(i));
}
}
else if (!text.isEmpty())
{
// The normalized text does not match the number of TextPositions, so we'll just
// have a look at its first entry.
// TODO change PDFTextStripper.normalize() such that it maintains the 1:1 relation
if (textPositions.isEmpty())
{
return text;
}
push(buffer, text.charAt(0), textPositions.get(0));
buffer.append(escape(text.substring(1)));
}
return buffer.toString();
}
/**
* Closes all open states.
* @return A string that contains the closing tags of all currently open states.
*/
public String clear()
{
StringBuilder buffer = new StringBuilder();
closeUntil(buffer, null);
stateList.clear();
stateSet.clear();
return buffer.toString();
}
protected String push(StringBuilder buffer, char character, TextPosition textPosition)
{
boolean bold = false;
boolean italics = false;
PDFontDescriptor descriptor = textPosition.getFont().getFontDescriptor();
if (descriptor != null)
{
bold = isBold(descriptor);
italics = isItalic(descriptor);
}
buffer.append(bold ? open("b") : close("b"));
buffer.append(italics ? open("i") : close("i"));
appendEscaped(buffer, character);
return buffer.toString();
}
private String open(String tag)
{
if (stateSet.contains(tag))
{
return "";
}
stateList.add(tag);
stateSet.add(tag);
return openTag(tag);
}
private String close(String tag)
{
if (!stateSet.contains(tag))
{
return "";
}
// Close all tags until (but including) the one we should close
StringBuilder tagsBuilder = new StringBuilder();
int index = closeUntil(tagsBuilder, tag);
// Remove from state
stateList.remove(index);
stateSet.remove(tag);
// Now open the states that were closed but should remain open again
for (; index < stateList.size(); index++)
{
tagsBuilder.append(openTag(stateList.get(index)));
}
return tagsBuilder.toString();
}
private int closeUntil(StringBuilder tagsBuilder, String endTag)
{<FILL_FUNCTION_BODY>}
private String openTag(String tag)
{
return "<" + tag + ">";
}
private String closeTag(String tag)
{
return "</" + tag + ">";
}
private boolean isBold(PDFontDescriptor descriptor)
{
if (descriptor.isForceBold())
{
return true;
}
return descriptor.getFontName().contains("Bold");
}
private boolean isItalic(PDFontDescriptor descriptor)
{
if (descriptor.isItalic())
{
return true;
}
return descriptor.getFontName().contains("Italic");
}
} |
for (int i = stateList.size(); i-- > 0;)
{
String tag = stateList.get(i);
tagsBuilder.append(closeTag(tag));
if (endTag != null && tag.equals(endTag))
{
return i;
}
}
return -1;
| 1,082 | 84 | 1,166 |
int index = 0;
for (String tag : stateList)
{
if (tag.equals(endTag))
{
break;
}
tagsBuilder.append(closeTag(tag));
index++;
}
return index;
| <success> |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFText2Markdown.java | FontState | isItalic | class FontState
{
private final List<String> stateList = new ArrayList<>();
private final Set<String> stateSet = new HashSet<>();
/**
* Pushes new {@link TextPosition TextPositions} into the font state. The state is only
* preserved correctly for each letter if the number of letters in <code>text</code> matches
* the number of {@link TextPosition} objects. Otherwise, it's done once for the complete
* array (just by looking at its first entry).
*
* @return A string that contains the text including tag changes caused by its font state.
*/
public String push(String text, List<TextPosition> textPositions)
{
StringBuilder buffer = new StringBuilder();
if (text.length() == textPositions.size())
{
// There is a 1:1 mapping, and we can use the TextPositions directly
for (int i = 0; i < text.length(); i++)
{
push(buffer, text.charAt(i), textPositions.get(i));
}
}
else if (!text.isEmpty())
{
// The normalized text does not match the number of TextPositions, so we'll just
// have a look at its first entry.
// TODO change PDFTextStripper.normalize() such that it maintains the 1:1 relation
if (textPositions.isEmpty())
{
return text;
}
push(buffer, text.charAt(0), textPositions.get(0));
buffer.append(escape(text.substring(1)));
}
return buffer.toString();
}
/**
* Closes all open Markdown formatting.
*
* @return A string that contains the closing tags of all currently open Markdown
* formatting.
*/
public String clear()
{
StringBuilder buffer = new StringBuilder();
closeUntil(buffer, null);
stateList.clear();
stateSet.clear();
return buffer.toString();
}
protected String push(StringBuilder buffer, char character, TextPosition textPosition)
{
boolean bold = false;
boolean italics = false;
PDFontDescriptor descriptor = textPosition.getFont().getFontDescriptor();
if (descriptor != null)
{
bold = isBold(descriptor);
italics = isItalic(descriptor);
}
buffer.append(bold ? open("**") : close("**"));
buffer.append(italics ? open("*") : close("*"));
appendEscaped(buffer, character);
return buffer.toString();
}
private String open(String tag)
{
if (stateSet.contains(tag))
{
return "";
}
stateList.add(tag);
stateSet.add(tag);
return openTag(tag);
}
private String close(String tag)
{
if (!stateSet.contains(tag))
{
return "";
}
// Close all tags until (but including) the one we should close
StringBuilder tagsBuilder = new StringBuilder();
int index = closeUntil(tagsBuilder, tag);
// Remove from state
stateList.remove(index);
stateSet.remove(tag);
// Now open the states that were closed but should remain open again
for (; index < stateList.size(); index++)
{
tagsBuilder.append(openTag(stateList.get(index)));
}
return tagsBuilder.toString();
}
private int closeUntil(StringBuilder tagsBuilder, String endTag)
{
for (int i = stateList.size(); i-- > 0;)
{
String tag = stateList.get(i);
tagsBuilder.append(closeTag(tag));
if (endTag != null && tag.equals(endTag))
{
return i;
}
}
return -1;
}
private String openTag(String tag)
{
return tag;
}
private String closeTag(String tag)
{
return tag;
}
private boolean isBold(PDFontDescriptor descriptor)
{
if (descriptor.isForceBold())
{
return true;
}
return descriptor.getFontName().toLowerCase().contains("bold");
}
private boolean isItalic(PDFontDescriptor descriptor)
{<FILL_FUNCTION_BODY>}
} |
if (descriptor.isItalic())
{
return true;
}
String fontName = descriptor.getFontName().toLowerCase();
return fontName.contains("italic") || fontName.contains("oblique");
| 1,126 | 63 | 1,189 |
if (descriptor.isForceItalic())
{
return true;
}
return descriptor.getFontName().toLowerCase().contains("italic");
| <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFText2Markdown.java<line>310<col>27<err>cannot find symbol |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFToImage.java | PDFToImage | call | class PDFToImage implements Callable<Integer>
{
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSERR;
@Option(names = "-password", description = "the password to decrypt the document", arity = "0..1", interactive = true)
private String password;
@Option(names = {"-format"}, description = "the image file format (default: ${DEFAULT-VALUE})")
private String imageFormat = "jpg";
@Option(names = {"-prefix", "-outputPrefix"}, description = "the filename prefix for image files")
private String outputPrefix;
@Option(names = "-page", description = "the only page to extract (1-based)")
private int page = -1;
@Option(names = "-startPage", description = "the first page to start extraction (1-based)")
private int startPage = 1;
@Option(names = "-endPage", description = "the last page to extract (inclusive)")
private int endPage = Integer.MAX_VALUE;
@Option(names = "-color", description = "the color depth (valid: ${COMPLETION-CANDIDATES}) (default: ${DEFAULT-VALUE})")
private ImageType imageType = ImageType.RGB;
@Option(names = {"-dpi", "-resolution"}, description = "the DPI of the output image, default: screen resolution or 96 if unknown")
private int dpi;
@Option(names = "-quality", description = "the quality to be used when compressing the image (0 <= quality <= 1) " +
"(default: 0 for PNG and 1 for the other formats)")
private float quality = -1;
@Option(names = "-cropbox", arity="4", description = "the page area to export")
private int[] cropbox;
@Option(names = "-time", description = "print timing information to stdout")
private boolean showTime;
@Option(names = "-subsampling", description = "activate subsampling (for PDFs with huge images)")
private boolean subsampling;
@Option(names = {"-i", "--input"}, description = "the PDF files to convert.", required = true)
private File infile;
/**
* Constructor.
*/
public PDFToImage()
{
SYSERR = System.err;
}
/**
* Infamous main method.
*
* @param args Command line arguments, should be one and a reference to a file.
*
*/
public static void main( String[] args )
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new PDFToImage()).execute(args);
System.exit(exitCode);
}
public Integer call()
{<FILL_FUNCTION_BODY>}
private static void changeCropBox(PDDocument document, float a, float b, float c, float d)
{
for (PDPage page : document.getPages())
{
PDRectangle rectangle = new PDRectangle();
rectangle.setLowerLeftX(a);
rectangle.setLowerLeftY(b);
rectangle.setUpperRightX(c);
rectangle.setUpperRightY(d);
page.setCropBox(rectangle);
}
}
} |
if (outputPrefix == null)
{
outputPrefix = FilenameUtils.removeExtension(infile.getAbsolutePath());
}
if (!List.of(ImageIO.getWriterFormatNames()).contains(imageFormat))
{
SYSERR.println("Error: Invalid image format " + imageFormat + " - supported formats: " +
String.join(", ", ImageIO.getWriterFormatNames()));
return 2;
}
if (quality < 0)
{
quality = "png".equals(imageFormat) ? 0f : 1f;
}
if (dpi == 0)
{
try
{
dpi = Toolkit.getDefaultToolkit().getScreenResolution();
}
catch (HeadlessException e)
{
dpi = 96;
}
}
try (PDDocument document = Loader.loadPDF(infile, password))
{
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
if (acroForm != null && acroForm.getNeedAppearances())
{
acroForm.refreshAppearances();
}
if (cropbox != null)
{
changeCropBox(document, cropbox[0], cropbox[1], cropbox[2], cropbox[3]);
}
long startTime = System.nanoTime();
// render the pages
boolean success = true;
endPage = Math.min(endPage, document.getNumberOfPages());
PDFRenderer renderer = new PDFRenderer(document);
renderer.setSubsamplingAllowed(subsampling);
for (int i = startPage - 1; i < endPage; i++)
{
BufferedImage image = renderer.renderImageWithDPI(i, dpi, imageType);
String fileName = outputPrefix + "-" + (i + 1) + "." + imageFormat;
success &= ImageIOUtil.writeImage(image, fileName, dpi, quality);
}
// performance stats
long endTime = System.nanoTime();
long duration = endTime - startTime;
int count = 1 + endPage - startPage;
if (showTime)
{
SYSERR.printf("Rendered %d page%s in %dms%n", count, count == 1 ? "" : "s",
duration / 1000000);
}
if (!success)
{
SYSERR.println( "Error: no writer found for image format '" + imageFormat + "'" );
return 1;
}
}
catch (IOException ioe)
{
SYSERR.println( "Error converting document [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage());
return 4;
}
return 0;
| 885 | 730 | 1,615 |
if (infile == null)
{
SYSERR.println("No input file specified");
return 1;
}
if (outputPrefix == null)
{
outputPrefix = infile.getName();
}
if (dpi == 0)
{
dpi = Toolkit.getDefaultToolkit().getScreenResolution();
}
if (dpi == 0)
{
dpi = 96;
}
if (cropbox != null && cropbox.length == 4)
{
changeCropBox(infile, cropbox[0], cropbox[1], cropbox[2], cropbox[3]);
}
try (PDDocument document = PDDocument.load(infile))
{
if (password != null)
{
document.decrypt(password);
}
if (page > 0)
{
document.setAllPages(page);
}
if (startPage > 0)
{
document.setStartPage(startPage);
}
if (endPage > 0)
{
document.setEndPage(endPage);
}
if (subsampling)
{
document.setSubsampling(true);
}
if (showTime)
{
long start = System.currentTimeMillis();
document.save(outputPrefix, imageFormat, imageType, dpi, quality);
long end = System.currentTimeMillis();
System.out.println("Time: " + (end - start) + " ms"); | <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFToImage.java<line>180<col>5<err>illegal start of expression |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Version.java | Version | main | class Version implements Callable<Integer>, IVersionProvider
{
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSOUT;
@Spec CommandSpec spec;
/**
* Get the version of PDFBox or unknown if it is not known.
*
* @return The version of pdfbox that is being used.
*/
public String[] getVersion()
{
String version = org.apache.pdfbox.util.Version.getVersion();
if (version != null)
{
return new String[] { spec.qualifiedName() + " [" + version + "]" };
}
else
{
return new String[] { "unknown" };
}
}
/**
* Constructor.
*/
public Version()
{
SYSOUT = System.out;
}
/**
* This will print out the version of PDF to System.out.
*
* @param args Command line arguments.
*/
public static void main(String[] args)
{<FILL_FUNCTION_BODY>}
public Integer call()
{
SYSOUT.println(getVersion()[0]);
return 0;
}
} |
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new Version()).execute(args);
System.exit(exitCode);
| 333 | 59 | 392 |
Version version = new Version();
version.SYSOUT = System.out;
version.call();
| <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Version.java<line>76<col>16<err>cannot assign a value to final variable SYSOUT |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java | WriteDecodedDoc | processObject | class WriteDecodedDoc implements Callable<Integer>
{
// Expected for CLI app to write to System.out/System.err
@SuppressWarnings("squid:S106")
private final PrintStream SYSERR;
@Option(names = "-password", description = "the password to decrypt the document", arity = "0..1", interactive = true)
private String password;
@Option(names = "-skipImages", description = "don't uncompress images")
private boolean skipImages;
@Parameters(paramLabel = "inputfile", index="0", description = "the PDF document to be decompressed")
private File infile;
@Parameters(paramLabel = "outputfile", arity = "0..1", description = "the PDF file to save to.")
private File outfile;
/**
* Constructor.
*/
public WriteDecodedDoc()
{
SYSERR = System.err;
}
/**
* This will perform the document reading, decoding and writing.
*
* @param in The filename used for input.
* @param out The filename used for output.
* @param password The password to open the document.
* @param skipImages Whether to skip decoding images.
*
* @throws IOException if the output could not be written
*/
public void doIt(String in, String out, String password, boolean skipImages)
throws IOException
{
try (PDDocument doc = Loader.loadPDF(new File(in), password))
{
doc.setAllSecurityToBeRemoved(true);
COSDocument cosDocument = doc.getDocument();
cosDocument.getXrefTable().keySet().stream()
.forEach(o -> processObject(cosDocument.getObjectFromPool(o), skipImages));
doc.getDocumentCatalog();
doc.getDocument().setIsXRefStream(false);
doc.save(out, CompressParameters.NO_COMPRESSION);
}
}
private void processObject(COSObject cosObject, boolean skipImages)
{<FILL_FUNCTION_BODY>}
/**
* This will write a PDF document with completely decoded streams.
* <br>
* see usage() for commandline
*
* @param args command line arguments
*/
public static void main(String[] args)
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new WriteDecodedDoc()).execute(args);
System.exit(exitCode);
}
public Integer call()
{
String outputFilename;
if (outfile == null)
{
outputFilename = calculateOutputFilename(infile.getAbsolutePath());
}
else
{
outputFilename = outfile.getAbsolutePath();
}
try {
doIt(infile.getAbsolutePath(), outputFilename, password, skipImages);
}
catch (IOException ioe)
{
SYSERR.println( "Error writing decoded PDF [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage());
return 4;
}
return 0;
}
private static String calculateOutputFilename(String filename)
{
String outputFilename;
if (filename.toLowerCase().endsWith(".pdf"))
{
outputFilename = filename.substring(0,filename.length()-4);
}
else
{
outputFilename = filename;
}
outputFilename += "_unc.pdf";
return outputFilename;
}
} |
COSBase base = cosObject.getObject();
if (base instanceof COSStream)
{
COSStream stream = (COSStream) base;
if (skipImages && COSName.XOBJECT.equals(stream.getItem(COSName.TYPE))
&& COSName.IMAGE.equals(stream.getItem(COSName.SUBTYPE)))
{
return;
}
try
{
byte[] bytes = new PDStream(stream).toByteArray();
stream.removeItem(COSName.FILTER);
try (OutputStream streamOut = stream.createOutputStream())
{
streamOut.write(bytes);
}
}
catch (IOException ex)
{
SYSERR.println("skip " + cosObject.getKey() + " obj: " + ex.getMessage());
}
}
| 931 | 218 | 1,149 |
if (cosObject == null)
{
return;
}
if (cosObject.getObjectType() == COSObjectType.STREAM)
{
COSStream cosStream = (COSStream) cosObject;
if (cosStream.getFilter() != null)
{
if (skipImages && cosStream.getFilter().equals(COSName.FLATE_DECODE))
{
cosStream.setFilter(null);
}
else
{
cosStream.setFilter(null);
}
}
}
else if (cosObject.getObjectType() == COSObjectType.ARRAY)
{
COSArray cosArray = (COSArray) cosObject;
for (int i = 0; i < cosArray.size(); i++)
{
processObject(cosArray.getObject(i), skipImages);
}
}
else if (cosObject.getObjectType() == COSObjectType.DICTIONARY)
{
COSDictionary cosDictionary = (COSDictionary) cosObject;
for (Map.Entry<String, COSObject> entry : cosDictionary.entrySet())
{
processObject(entry.getValue(), skipImages);
}
}
| <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>108<col>44<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>120<col>34<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>106<col>26<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>103<col>22<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>118<col>47<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>118<col>27<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>120<col>13<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>128<col>44<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>114<col>30<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>103<col>42<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>126<col>27<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>128<col>13<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>129<col>21<err>package Map does not exist
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>105<col>47<err>incompatible types: org.apache.pdfbox.cos.COSObject cannot be converted to org.apache.pdfbox.cos.COSStream
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>126<col>47<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java<line>110<col>30<err>cannot find symbol |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/JPEGUtil.java | JPEGUtil | updateMetadata | class JPEGUtil
{
private JPEGUtil()
{
}
/**
* Set dpi in a JPEG file
*
* @param metadata the meta data
* @param dpi the dpi
*
* @throws IIOInvalidTreeException if something goes wrong
*/
static void updateMetadata(IIOMetadata metadata, int dpi) throws IIOInvalidTreeException
{<FILL_FUNCTION_BODY>}
} |
MetaUtil.debugLogMetadata(metadata, MetaUtil.JPEG_NATIVE_FORMAT);
// https://svn.apache.org/viewvc/xmlgraphics/commons/trunk/src/java/org/apache/xmlgraphics/image/writer/imageio/ImageIOJPEGImageWriter.java
// http://docs.oracle.com/javase/6/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html
Element root = (Element) metadata.getAsTree(MetaUtil.JPEG_NATIVE_FORMAT);
NodeList jvarNodeList = root.getElementsByTagName("JPEGvariety");
Element jvarChild;
if (jvarNodeList.getLength() == 0)
{
jvarChild = new IIOMetadataNode("JPEGvariety");
root.appendChild(jvarChild);
}
else
{
jvarChild = (Element) jvarNodeList.item(0);
}
NodeList jfifNodeList = jvarChild.getElementsByTagName("app0JFIF");
Element jfifChild;
if (jfifNodeList.getLength() == 0)
{
jfifChild = new IIOMetadataNode("app0JFIF");
jvarChild.appendChild(jfifChild);
}
else
{
jfifChild = (Element) jfifNodeList.item(0);
}
if (jfifChild.getAttribute("majorVersion").isEmpty())
{
jfifChild.setAttribute("majorVersion", "1");
}
if (jfifChild.getAttribute("minorVersion").isEmpty())
{
jfifChild.setAttribute("minorVersion", "2");
}
jfifChild.setAttribute("resUnits", "1"); // inch
jfifChild.setAttribute("Xdensity", Integer.toString(dpi));
jfifChild.setAttribute("Ydensity", Integer.toString(dpi));
if (jfifChild.getAttribute("thumbWidth").isEmpty())
{
jfifChild.setAttribute("thumbWidth", "0");
}
if (jfifChild.getAttribute("thumbHeight").isEmpty())
{
jfifChild.setAttribute("thumbHeight", "0");
}
// mergeTree doesn't work for ARGB
metadata.setFromTree(MetaUtil.JPEG_NATIVE_FORMAT, root);
| 121 | 628 | 749 |
IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(JPEGDirectory.TAG_JPEG);
if (root == null)
{
root = new IIOMetadataNode(JPEGDirectory.TAG_JPEG);
metadata.mergeTree(JPEGDirectory.TAG_JPEG, root);
}
IIOMetadataNode node = new IIOMetadataNode(JPEGDirectory.TAG_RESOLUTION);
node.setAttribute(JPEGDirectory.TAG_RESOLUTION_X_RESOLUTION, String.valueOf(dpi));
node.setAttribute(JPEGDirectory.TAG_RESOLUTION_Y_RESOLUTION, String.valueOf(dpi));
node.setAttribute(JPEGDirectory.TAG_RESOLUTION_RESOLUTION_UNIT, "in");
root.appendChild(node);
| <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/JPEGUtil.java<line>50<col>52<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/JPEGUtil.java<line>47<col>40<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/JPEGUtil.java<line>51<col>27<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/JPEGUtil.java<line>48<col>32<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/JPEGUtil.java<line>52<col>27<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/JPEGUtil.java<line>44<col>69<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/JPEGUtil.java<line>53<col>27<err>cannot find symbol |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/MetaUtil.java | MetaUtil | debugLogMetadata | class MetaUtil
{
private static final Logger LOG = LogManager.getLogger(MetaUtil.class);
static final String SUN_TIFF_FORMAT = "com_sun_media_imageio_plugins_tiff_image_1.0";
static final String JPEG_NATIVE_FORMAT = "javax_imageio_jpeg_image_1.0";
static final String STANDARD_METADATA_FORMAT = "javax_imageio_1.0";
private MetaUtil()
{
}
// logs metadata as an XML tree if debug is enabled
static void debugLogMetadata(IIOMetadata metadata, String format)
{<FILL_FUNCTION_BODY>}
} |
if (!LOG.isDebugEnabled())
{
return;
}
// see http://docs.oracle.com/javase/7/docs/api/javax/imageio/
// metadata/doc-files/standard_metadata.html
IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(format);
try
{
StringWriter xmlStringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(xmlStringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = transformerFactory.newTransformer();
// see http://stackoverflow.com/a/1264872/535646
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource domSource = new DOMSource(root);
transformer.transform(domSource, streamResult);
LOG.debug("\n{}", xmlStringWriter);
}
catch (IllegalArgumentException | TransformerException ex)
{
LOG.error(ex, ex);
}
| 185 | 366 | 551 |
if (LOG.isDebugEnabled())
{
try
{
StringWriter sw = new StringWriter();
metadata.writeTo(sw);
LOG.debug("Metadata for format " + format + ":\n" + sw.toString());
}
catch (IOException e)
{
LOG.warn("Error writing metadata to string", e);
}
}
| <file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/MetaUtil.java<line>59<col>20<err>cannot find symbol
<file>apache_pdfbox/pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/MetaUtil.java<line>56<col>25<err>cannot find symbol |
apache_pdfbox | pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/TIFFUtil.java | TIFFUtil | createRationalField | class TIFFUtil
{
private static final Logger LOG = LogManager.getLogger(TIFFUtil.class);
private TIFFUtil()
{
}
/**
* Sets the ImageIO parameter compression type based on the given image.
* @param image buffered image used to decide compression type
* @param param ImageIO write parameter to update
*/
public static void setCompressionType(ImageWriteParam param, BufferedImage image)
{
// avoid error: first compression type is RLE, not optimal and incorrect for color images
// TODO expose this choice to the user?
if (image.getType() == BufferedImage.TYPE_BYTE_BINARY &&
image.getColorModel().getPixelSize() == 1)
{
param.setCompressionType("CCITT T.6");
}
else
{
param.setCompressionType("LZW");
}
}
/**
* Updates the given ImageIO metadata with Sun's custom TIFF tags, as described in
* the <a href="https://svn.apache.org/repos/asf/xmlgraphics/commons/tags/commons-1_3_1/src/java/org/apache/xmlgraphics/image/writer/imageio/ImageIOTIFFImageWriter.java">org.apache.xmlgraphics.image.writer.imageio.ImageIOTIFFImageWriter
* sources</a>,
* the <a href="http://download.java.net/media/jai-imageio/javadoc/1.0_01/com/sun/media/imageio/plugins/tiff/package-summary.html">com.sun.media.imageio.plugins.tiff
* package javadoc</a>
* and the <a href="http://partners.adobe.com/public/developer/tiff/index.html">TIFF
* specification</a>.
*
* @param image buffered image which will be written
* @param metadata ImageIO metadata
* @param dpi image dots per inch
* @throws IIOInvalidTreeException if something goes wrong
*/
static void updateMetadata(IIOMetadata metadata, BufferedImage image, int dpi)
throws IIOInvalidTreeException
{
String metaDataFormat = metadata.getNativeMetadataFormatName();
if (metaDataFormat == null)
{
LOG.debug("TIFF image writer doesn't support any data format");
return;
}
debugLogMetadata(metadata, metaDataFormat);
IIOMetadataNode root = new IIOMetadataNode(metaDataFormat);
IIOMetadataNode ifd;
NodeList nodeListTIFFIFD = root.getElementsByTagName("TIFFIFD");
if (nodeListTIFFIFD.getLength() == 0)
{
ifd = new IIOMetadataNode("TIFFIFD");
root.appendChild(ifd);
}
else
{
ifd = (IIOMetadataNode) nodeListTIFFIFD.item(0);
}
// standard metadata does not work, so we set the DPI manually
ifd.appendChild(createRationalField(282, "XResolution", dpi, 1));
ifd.appendChild(createRationalField(283, "YResolution", dpi, 1));
ifd.appendChild(createShortField(296, "ResolutionUnit", 2)); // Inch
ifd.appendChild(createLongField(278, "RowsPerStrip", image.getHeight()));
ifd.appendChild(createAsciiField(305, "Software", "PDFBOX"));
if (image.getType() == BufferedImage.TYPE_BYTE_BINARY &&
image.getColorModel().getPixelSize() == 1)
{
// set PhotometricInterpretation WhiteIsZero
// because of bug in Windows XP preview
ifd.appendChild(createShortField(262, "PhotometricInterpretation", 0));
}
metadata.mergeTree(metaDataFormat, root);
debugLogMetadata(metadata, metaDataFormat);
}
private static IIOMetadataNode createShortField(int tiffTagNumber, String name, int val)
{
IIOMetadataNode field, arrayNode, valueNode;
field = new IIOMetadataNode("TIFFField");
field.setAttribute("number", Integer.toString(tiffTagNumber));
field.setAttribute("name", name);
arrayNode = new IIOMetadataNode("TIFFShorts");
field.appendChild(arrayNode);
valueNode = new IIOMetadataNode("TIFFShort");
arrayNode.appendChild(valueNode);
valueNode.setAttribute("value", Integer.toString(val));
return field;
}
private static IIOMetadataNode createAsciiField(int number, String name, String val)
{
IIOMetadataNode field, arrayNode, valueNode;
field = new IIOMetadataNode("TIFFField");
field.setAttribute("number", Integer.toString(number));
field.setAttribute("name", name);
arrayNode = new IIOMetadataNode("TIFFAsciis");
field.appendChild(arrayNode);
valueNode = new IIOMetadataNode("TIFFAscii");
arrayNode.appendChild(valueNode);
valueNode.setAttribute("value", val);
return field;
}
private static IIOMetadataNode createLongField(int number, String name, long val)
{
IIOMetadataNode field, arrayNode, valueNode;
field = new IIOMetadataNode("TIFFField");
field.setAttribute("number", Integer.toString(number));
field.setAttribute("name", name);
arrayNode = new IIOMetadataNode("TIFFLongs");
field.appendChild(arrayNode);
valueNode = new IIOMetadataNode("TIFFLong");
arrayNode.appendChild(valueNode);
valueNode.setAttribute("value", Long.toString(val));
return field;
}
private static IIOMetadataNode createRationalField(int number, String name, int numerator,
int denominator)
{<FILL_FUNCTION_BODY>}
} |
IIOMetadataNode field, arrayNode, valueNode;
field = new IIOMetadataNode("TIFFField");
field.setAttribute("number", Integer.toString(number));
field.setAttribute("name", name);
arrayNode = new IIOMetadataNode("TIFFRationals");
field.appendChild(arrayNode);
valueNode = new IIOMetadataNode("TIFFRational");
arrayNode.appendChild(valueNode);
valueNode.setAttribute("value", numerator + "/" + denominator);
return field;
| 1,593 | 139 | 1,732 |
IIOMetadataNode field, arrayNode, valueNode;
field = new IIOMetadataNode("TIFFField");
field.setAttribute("number", Integer.toString(number));
field.setAttribute("name", name);
arrayNode = new IIOMetadataNode("TIFFRationals");
field.appendChild(arrayNode);
valueNode = new IIOMetadataNode("TIFFRational");
arrayNode.appendChild(valueNode);
valueNode.setAttribute("value", Integer.toString(numerator) + "/" +
Integer.toString(denominator));
return field;
| <success> |