proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PRIndirectReference.java
|
PRIndirectReference
|
toPdf
|
class PRIndirectReference extends PdfIndirectReference {
protected PdfReader reader;
// membervariables
// constructors
/**
* Constructs a <CODE>PdfIndirectReference</CODE>.
*
* @param reader a <CODE>PdfReader</CODE>
* @param number the object number.
* @param generation the generation number.
*/
public PRIndirectReference(PdfReader reader, int number, int generation) {
type = INDIRECT;
this.number = number;
this.generation = generation;
this.reader = reader;
}
/**
* Constructs a <CODE>PdfIndirectReference</CODE>.
*
* @param reader a <CODE>PdfReader</CODE>
* @param number the object number.
*/
public PRIndirectReference(PdfReader reader, int number) {
this(reader, number, 0);
}
// methods
public void toPdf(PdfWriter writer, OutputStream os) throws IOException {<FILL_FUNCTION_BODY>}
public PdfReader getReader() {
return reader;
}
public void setNumber(int number, int generation) {
this.number = number;
this.generation = generation;
}
}
|
int n = writer.getNewObjectNumber(reader, number, generation);
os.write(PdfEncodings.convertToBytes(new StringBuffer().append(n).append(" 0 R").toString(), null));
| 341
| 55
| 396
|
<methods>public int getGeneration() ,public int getNumber() ,public java.lang.String toString() <variables>protected int generation,protected int number
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PRStream.java
|
PRStream
|
setData
|
class PRStream extends PdfStream {
protected PdfReader reader;
protected int offset;
protected int length;
//added by ujihara for decryption
protected int objNum = 0;
protected int objGen = 0;
public PRStream(PRStream stream, PdfDictionary newDic) {
reader = stream.reader;
offset = stream.offset;
length = stream.length;
compressed = stream.compressed;
compressionLevel = stream.compressionLevel;
streamBytes = stream.streamBytes;
bytes = stream.bytes;
objNum = stream.objNum;
objGen = stream.objGen;
if (newDic != null) {
putAll(newDic);
} else {
hashMap.putAll(stream.hashMap);
}
}
public PRStream(PRStream stream, PdfDictionary newDic, PdfReader reader) {
this(stream, newDic);
this.reader = reader;
}
public PRStream(PdfReader reader, int offset) {
this.reader = reader;
this.offset = offset;
}
public PRStream(PdfReader reader, byte[] conts) {
this(reader, conts, DEFAULT_COMPRESSION);
}
/**
* Creates a new PDF stream object that will replace a stream in a existing PDF file.
*
* @param reader the reader that holds the existing PDF
* @param conts the new content
* @param compressionLevel the compression level for the content
* @since 2.1.3 (replacing the existing constructor without param compressionLevel)
*/
public PRStream(PdfReader reader, byte[] conts, int compressionLevel) {
this.reader = reader;
this.offset = -1;
if (Document.compress) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Deflater deflater = new Deflater(compressionLevel);
DeflaterOutputStream zip = new DeflaterOutputStream(stream, deflater);
zip.write(conts);
zip.close();
deflater.end();
bytes = stream.toByteArray();
} catch (IOException ioe) {
throw new ExceptionConverter(ioe);
}
put(PdfName.FILTER, PdfName.FLATEDECODE);
} else {
bytes = conts;
}
setLength(bytes.length);
}
/**
* Sets the data associated with the stream, either compressed or uncompressed. Note that the data will never be
* compressed if Document.compress is set to false.
*
* @param data raw data, decrypted and uncompressed.
* @param compress true if you want the stream to be compressed.
* @since iText 2.1.1
*/
public void setData(byte[] data, boolean compress) {
setData(data, compress, DEFAULT_COMPRESSION);
}
/**
* Sets the data associated with the stream, either compressed or uncompressed. Note that the data will never be
* compressed if Document.compress is set to false.
*
* @param data raw data, decrypted and uncompressed.
* @param compress true if you want the stream to be compressed.
* @param compressionLevel a value between -1 and 9 (ignored if compress == false)
* @since iText 2.1.3
*/
public void setData(byte[] data, boolean compress, int compressionLevel) {<FILL_FUNCTION_BODY>}
/**
* Sets the data associated with the stream
*
* @param data raw data, decrypted and uncompressed.
*/
public void setData(byte[] data) {
setData(data, true);
}
public int getOffset() {
return offset;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
put(PdfName.LENGTH, new PdfNumber(length));
}
public PdfReader getReader() {
return reader;
}
public byte[] getBytes() {
return bytes;
}
public void setObjNum(int objNum, int objGen) {
this.objNum = objNum;
this.objGen = objGen;
}
int getObjNum() {
return objNum;
}
int getObjGen() {
return objGen;
}
public void toPdf(PdfWriter writer, OutputStream os) throws IOException {
byte[] b = PdfReader.getStreamBytesRaw(this);
PdfEncryption crypto = null;
if (writer != null) {
crypto = writer.getEncryption();
}
PdfObject objLen = get(PdfName.LENGTH);
int nn = b.length;
if (crypto != null) {
nn = crypto.calculateStreamSize(nn);
}
put(PdfName.LENGTH, new PdfNumber(nn));
superToPdf(writer, os);
put(PdfName.LENGTH, objLen);
os.write(STARTSTREAM);
if (length > 0) {
if (crypto != null && !crypto.isEmbeddedFilesOnly()) {
b = crypto.encryptByteArray(b);
}
os.write(b);
}
os.write(ENDSTREAM);
}
}
|
remove(PdfName.FILTER);
this.offset = -1;
if (Document.compress && compress) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Deflater deflater = new Deflater(compressionLevel);
DeflaterOutputStream zip = new DeflaterOutputStream(stream, deflater);
zip.write(data);
zip.close();
deflater.end();
bytes = stream.toByteArray();
this.compressionLevel = compressionLevel;
} catch (IOException ioe) {
throw new ExceptionConverter(ioe);
}
put(PdfName.FILTER, PdfName.FLATEDECODE);
} else {
bytes = data;
}
setLength(bytes.length);
| 1,400
| 193
| 1,593
|
<methods>public void <init>(byte[]) ,public void <init>(java.io.InputStream, com.lowagie.text.pdf.PdfWriter) ,public void flateCompress() ,public void flateCompress(int) ,public long getRawLength() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() ,public void writeContent(java.io.OutputStream) throws java.io.IOException,public void writeLength() throws java.io.IOException<variables>public static final int BEST_COMPRESSION,public static final int BEST_SPEED,public static final int DEFAULT_COMPRESSION,static final byte[] ENDSTREAM,public static final int NO_COMPRESSION,static final int SIZESTREAM,static final byte[] STARTSTREAM,protected boolean compressed,protected int compressionLevel,protected java.io.InputStream inputStream,protected long inputStreamLength,protected long rawLength,protected com.lowagie.text.pdf.PdfIndirectReference ref,protected java.io.ByteArrayOutputStream streamBytes,protected com.lowagie.text.pdf.PdfWriter writer
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PageResources.java
|
PageResources
|
setOriginalResources
|
class PageResources {
protected PdfDictionary fontDictionary = new PdfDictionary();
protected PdfDictionary xObjectDictionary = new PdfDictionary();
protected PdfDictionary colorDictionary = new PdfDictionary();
protected PdfDictionary patternDictionary = new PdfDictionary();
protected PdfDictionary shadingDictionary = new PdfDictionary();
protected PdfDictionary extGStateDictionary = new PdfDictionary();
protected PdfDictionary propertyDictionary = new PdfDictionary();
protected HashMap<PdfName, ?> forbiddenNames;
protected PdfDictionary originalResources;
protected int[] namePtr = {0};
protected HashMap<PdfName, PdfName> usedNames;
PageResources() {
}
void setOriginalResources(PdfDictionary resources, int[] newNamePtr) {<FILL_FUNCTION_BODY>}
PdfName translateName(PdfName name) {
PdfName translated = name;
if (forbiddenNames != null) {
translated = usedNames.get(name);
if (translated == null) {
do {
translated = new PdfName("Xi" + (namePtr[0]++));
} while (forbiddenNames.containsKey(translated));
usedNames.put(name, translated);
}
}
return translated;
}
PdfName addFont(PdfName name, PdfIndirectReference reference) {
name = translateName(name);
fontDictionary.put(name, reference);
return name;
}
PdfName addXObject(PdfName name, PdfIndirectReference reference) {
name = translateName(name);
xObjectDictionary.put(name, reference);
return name;
}
PdfName addColor(PdfName name, PdfIndirectReference reference) {
name = translateName(name);
colorDictionary.put(name, reference);
return name;
}
void addDefaultColor(PdfName name, PdfObject obj) {
if (obj == null || obj.isNull()) {
colorDictionary.remove(name);
} else {
colorDictionary.put(name, obj);
}
}
void addDefaultColor(PdfDictionary dic) {
colorDictionary.merge(dic);
}
void addDefaultColorDiff(PdfDictionary dic) {
colorDictionary.mergeDifferent(dic);
}
PdfName addShading(PdfName name, PdfIndirectReference reference) {
name = translateName(name);
shadingDictionary.put(name, reference);
return name;
}
PdfName addPattern(PdfName name, PdfIndirectReference reference) {
name = translateName(name);
patternDictionary.put(name, reference);
return name;
}
PdfName addExtGState(PdfName name, PdfIndirectReference reference) {
name = translateName(name);
extGStateDictionary.put(name, reference);
return name;
}
PdfName addProperty(PdfName name, PdfIndirectReference reference) {
name = translateName(name);
propertyDictionary.put(name, reference);
return name;
}
PdfDictionary getResources() {
PdfResources resources = new PdfResources();
if (originalResources != null) {
resources.putAll(originalResources);
}
//resources.put(PdfName.PROCSET, new PdfLiteral("[/PDF /Text /ImageB /ImageC /ImageI]"));
resources.add(PdfName.FONT, fontDictionary);
resources.add(PdfName.XOBJECT, xObjectDictionary);
resources.add(PdfName.COLORSPACE, colorDictionary);
resources.add(PdfName.PATTERN, patternDictionary);
resources.add(PdfName.SHADING, shadingDictionary);
resources.add(PdfName.EXTGSTATE, extGStateDictionary);
resources.add(PdfName.PROPERTIES, propertyDictionary);
return resources;
}
boolean hasResources() {
return (fontDictionary.size() > 0
|| xObjectDictionary.size() > 0
|| colorDictionary.size() > 0
|| patternDictionary.size() > 0
|| shadingDictionary.size() > 0
|| extGStateDictionary.size() > 0
|| propertyDictionary.size() > 0);
}
}
|
if (newNamePtr != null) {
namePtr = newNamePtr;
}
forbiddenNames = new HashMap<>();
usedNames = new HashMap<>();
if (resources == null) {
return;
}
originalResources = new PdfDictionary();
originalResources.merge(resources);
for (PdfName key : resources.getKeys()) {
PdfObject sub = PdfReader.getPdfObject(resources.get(key));
if (sub != null && sub.isDictionary()) {
PdfDictionary dic = (PdfDictionary) sub;
for (PdfName pdfName : dic.getKeys()) {
forbiddenNames.put(pdfName, null);
}
PdfDictionary dic2 = new PdfDictionary();
dic2.merge(dic);
originalResources.put(key, dic2);
}
}
| 1,102
| 221
| 1,323
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfAnnotation.java
|
PdfImportedLink
|
getDestinationPage
|
class PdfImportedLink {
float llx, lly, urx, ury;
HashMap<PdfName, PdfObject> parameters = new HashMap<>();
PdfArray destination;
int newPage = 0;
PdfImportedLink(PdfDictionary annotation) {
parameters.putAll(annotation.hashMap);
try {
destination = (PdfArray) parameters.remove(PdfName.DEST);
} catch (ClassCastException ex) {
throw new IllegalArgumentException(
MessageLocalization.getComposedMessage(
"you.have.to.consolidate.the.named.destinations.of.your.reader"));
}
if (destination != null) {
destination = new PdfArray(destination);
}
PdfArray rc = (PdfArray) parameters.remove(PdfName.RECT);
llx = rc.getAsNumber(0).floatValue();
lly = rc.getAsNumber(1).floatValue();
urx = rc.getAsNumber(2).floatValue();
ury = rc.getAsNumber(3).floatValue();
}
public boolean isInternal() {
return destination != null;
}
public int getDestinationPage() {<FILL_FUNCTION_BODY>}
public void setDestinationPage(int newPage) {
if (!isInternal()) {
throw new IllegalArgumentException(
MessageLocalization.getComposedMessage("cannot.change.destination.of.external.link"));
}
this.newPage = newPage;
}
public void transformDestination(float a, float b, float c, float d, float e, float f) {
if (!isInternal()) {
throw new IllegalArgumentException(
MessageLocalization.getComposedMessage("cannot.change.destination.of.external.link"));
}
if (destination.getAsName(1).equals(PdfName.XYZ)) {
float x = destination.getAsNumber(2).floatValue();
float y = destination.getAsNumber(3).floatValue();
float xx = x * a + y * c + e;
float yy = x * b + y * d + f;
destination.set(2, new PdfNumber(xx));
destination.set(3, new PdfNumber(yy));
}
}
public void transformRect(float a, float b, float c, float d, float e, float f) {
float x = llx * a + lly * c + e;
float y = llx * b + lly * d + f;
llx = x;
lly = y;
x = urx * a + ury * c + e;
y = urx * b + ury * d + f;
urx = x;
ury = y;
}
public PdfAnnotation createAnnotation(PdfWriter writer) {
PdfAnnotation annotation = new PdfAnnotation(writer, new Rectangle(llx, lly, urx, ury));
if (newPage != 0) {
PdfIndirectReference ref = writer.getPageReference(newPage);
destination.set(0, ref);
}
if (destination != null) {
annotation.put(PdfName.DEST, destination);
}
annotation.hashMap.putAll(parameters);
return annotation;
}
/**
* Returns a String representation of the link.
*
* @return a String representation of the imported link
* @since 2.1.6
*/
public String toString() {
StringBuilder buf = new StringBuilder("Imported link: location [");
buf.append(llx);
buf.append(' ');
buf.append(lly);
buf.append(' ');
buf.append(urx);
buf.append(' ');
buf.append(ury);
buf.append("] destination ");
buf.append(destination);
buf.append(" parameters ");
buf.append(parameters);
return buf.toString();
}
}
|
if (!isInternal()) {
return 0;
}
// here destination is something like
// [132 0 R, /XYZ, 29.3898, 731.864502, null]
PdfIndirectReference ref = destination.getAsIndirectObject(0);
PRIndirectReference pr = (PRIndirectReference) ref;
PdfReader r = pr.getReader();
for (int i = 1; i <= r.getNumberOfPages(); i++) {
PRIndirectReference pp = r.getPageOrigRef(i);
if (pp.getGeneration() == pr.getGeneration() && pp.getNumber() == pr.getNumber()) {
return i;
}
}
throw new IllegalArgumentException(MessageLocalization.getComposedMessage("page.not.found"));
| 1,030
| 217
| 1,247
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.PdfName) ,public void clear() ,public boolean contains(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject get(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfArray getAsArray(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfBoolean getAsBoolean(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfDictionary getAsDict(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfIndirectReference getAsIndirectObject(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfName getAsName(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfNumber getAsNumber(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfStream getAsStream(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfString getAsString(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject getDirectObject(com.lowagie.text.pdf.PdfName) ,public Set<com.lowagie.text.pdf.PdfName> getKeys() ,public Set<Entry<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject>> getKeysAndValues() ,public boolean isCatalog() ,public boolean isFont() ,public boolean isOutlineTree() ,public boolean isPage() ,public boolean isPages() ,public void merge(com.lowagie.text.pdf.PdfDictionary) ,public void mergeDifferent(com.lowagie.text.pdf.PdfDictionary) ,public void put(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void putAll(com.lowagie.text.pdf.PdfDictionary) ,public void putEx(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void remove(com.lowagie.text.pdf.PdfName) ,public int size() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() <variables>public static final com.lowagie.text.pdf.PdfName CATALOG,public static final com.lowagie.text.pdf.PdfName FONT,public static final com.lowagie.text.pdf.PdfName OUTLINES,public static final com.lowagie.text.pdf.PdfName PAGE,public static final com.lowagie.text.pdf.PdfName PAGES,private com.lowagie.text.pdf.PdfName dictionaryType,protected Map<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject> hashMap
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfAppearance.java
|
PdfAppearance
|
setFontAndSize
|
class PdfAppearance extends PdfTemplate {
public static final Map<String, PdfName> stdFieldFontNames = new HashMap<>();
static {
stdFieldFontNames.put("Courier-BoldOblique", new PdfName("CoBO"));
stdFieldFontNames.put("Courier-Bold", new PdfName("CoBo"));
stdFieldFontNames.put("Courier-Oblique", new PdfName("CoOb"));
stdFieldFontNames.put("Courier", new PdfName("Cour"));
stdFieldFontNames.put("Helvetica-BoldOblique", new PdfName("HeBO"));
stdFieldFontNames.put("Helvetica-Bold", new PdfName("HeBo"));
stdFieldFontNames.put("Helvetica-Oblique", new PdfName("HeOb"));
stdFieldFontNames.put("Helvetica", PdfName.HELV);
stdFieldFontNames.put("Symbol", new PdfName("Symb"));
stdFieldFontNames.put("Times-BoldItalic", new PdfName("TiBI"));
stdFieldFontNames.put("Times-Bold", new PdfName("TiBo"));
stdFieldFontNames.put("Times-Italic", new PdfName("TiIt"));
stdFieldFontNames.put("Times-Roman", new PdfName("TiRo"));
stdFieldFontNames.put("ZapfDingbats", PdfName.ZADB);
stdFieldFontNames.put("HYSMyeongJo-Medium", new PdfName("HySm"));
stdFieldFontNames.put("HYGoThic-Medium", new PdfName("HyGo"));
stdFieldFontNames.put("HeiseiKakuGo-W5", new PdfName("KaGo"));
stdFieldFontNames.put("HeiseiMin-W3", new PdfName("KaMi"));
stdFieldFontNames.put("MHei-Medium", new PdfName("MHei"));
stdFieldFontNames.put("MSung-Light", new PdfName("MSun"));
stdFieldFontNames.put("STSong-Light", new PdfName("STSo"));
stdFieldFontNames.put("MSungStd-Light", new PdfName("MSun"));
stdFieldFontNames.put("STSongStd-Light", new PdfName("STSo"));
stdFieldFontNames.put("HYSMyeongJoStd-Medium", new PdfName("HySm"));
stdFieldFontNames.put("KozMinPro-Regular", new PdfName("KaMi"));
}
/**
* Creates a <CODE>PdfAppearance</CODE>.
*/
PdfAppearance() {
super();
separator = ' ';
}
PdfAppearance(PdfIndirectReference iref) {
thisReference = iref;
}
/**
* Creates new PdfTemplate
*
* @param wr the <CODE>PdfWriter</CODE>
*/
PdfAppearance(PdfWriter wr) {
super(wr);
separator = ' ';
}
/**
* Creates a new appearance to be used with form fields.
*
* @param writer the PdfWriter to use
* @param width the bounding box width
* @param height the bounding box height
* @return the appearance created
*/
public static PdfAppearance createAppearance(PdfWriter writer, float width, float height) {
return createAppearance(writer, width, height, (PdfName) null);
}
private static PdfAppearance createAppearance(PdfWriter writer, float width, float height, PdfName forcedName) {
PdfAppearance template = new PdfAppearance(writer);
template.setWidth(width);
template.setHeight(height);
writer.addDirectTemplateSimple(template, forcedName);
return template;
}
/**
* Creates a new appearance to be used with existing form fields. (Create an empty signature appearance with an
* existing reference).
*
* @param writer the PdfWriter to use
* @param width the bounding box width
* @param height the bounding box height
* @param ref to be overwritten
* @return the created appearance
*/
public static PdfAppearance createAppearance(PdfWriter writer, float width, float height,
PdfIndirectReference ref) {
PdfAppearance template = new PdfAppearance(ref);
template.setWidth(width);
template.setHeight(height);
writer.addDirectTemplateSimple(template, null);
return template;
}
/**
* Set the font and the size for the subsequent text writing.
*
* @param bf the font
* @param size the font size in points
*/
public void setFontAndSize(BaseFont bf, float size) {<FILL_FUNCTION_BODY>}
public PdfContentByte getDuplicate() {
PdfAppearance tpl = new PdfAppearance();
tpl.writer = writer;
tpl.pdf = pdf;
tpl.thisReference = thisReference;
tpl.pageResources = pageResources;
tpl.bBox = new Rectangle(bBox);
tpl.group = group;
tpl.layer = layer;
if (matrix != null) {
tpl.matrix = new PdfArray(matrix);
}
tpl.separator = separator;
return tpl;
}
}
|
checkWriter();
state.size = size;
if (bf.getFontType() == BaseFont.FONT_TYPE_DOCUMENT) {
state.fontDetails = new FontDetails(null, ((DocumentFont) bf).getIndirectReference(), bf);
} else {
state.fontDetails = writer.addSimple(bf);
}
PdfName psn = stdFieldFontNames.get(bf.getPostscriptFontName());
if (psn == null) {
if (bf.isSubset() && bf.getFontType() == BaseFont.FONT_TYPE_TTUNI) {
psn = state.fontDetails.getFontName();
} else {
psn = new PdfName(bf.getPostscriptFontName());
state.fontDetails.setSubset(false);
}
}
PageResources prs = getPageResources();
// PdfName name = state.fontDetails.getFontName();
prs.addFont(psn, state.fontDetails.getIndirectReference());
content.append(psn.getBytes()).append(' ').append(size).append(" Tf").append_i(separator);
| 1,432
| 291
| 1,723
|
<methods>public void beginVariableText() ,public static com.lowagie.text.pdf.PdfTemplate createTemplate(com.lowagie.text.pdf.PdfWriter, float, float) ,public void endVariableText() ,public com.lowagie.text.Rectangle getBoundingBox() ,public com.lowagie.text.pdf.PdfContentByte getDuplicate() ,public com.lowagie.text.pdf.PdfTransparencyGroup getGroup() ,public float getHeight() ,public com.lowagie.text.pdf.PdfIndirectReference getIndirectReference() ,public com.lowagie.text.pdf.PdfOCG getLayer() ,public int getType() ,public float getWidth() ,public void setBoundingBox(com.lowagie.text.Rectangle) ,public void setGroup(com.lowagie.text.pdf.PdfTransparencyGroup) ,public void setHeight(float) ,public void setLayer(com.lowagie.text.pdf.PdfOCG) ,public void setMatrix(float, float, float, float, float, float) ,public void setWidth(float) <variables>public static final int TYPE_IMPORTED,public static final int TYPE_PATTERN,public static final int TYPE_TEMPLATE,protected com.lowagie.text.Rectangle bBox,protected com.lowagie.text.pdf.PdfTransparencyGroup group,protected com.lowagie.text.pdf.PdfOCG layer,protected com.lowagie.text.pdf.PdfArray matrix,protected com.lowagie.text.pdf.PageResources pageResources,protected com.lowagie.text.pdf.PdfIndirectReference thisReference,protected int type
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfContentParser.java
|
PdfContentParser
|
readDictionary
|
class PdfContentParser {
/**
* Commands have this type.
*/
public static final int COMMAND_TYPE = 200;
/**
* Holds value of property tokeniser.
*/
private PRTokeniser tokeniser;
/**
* Creates a new instance of PdfContentParser
*
* @param tokeniser the tokeniser with the content
*/
public PdfContentParser(PRTokeniser tokeniser) {
this.tokeniser = tokeniser;
}
/**
* Parses a single command from the content. Each command is output as an array of arguments having the command
* itself as the last element. The returned array will be empty if the end of content was reached.
*
* @param ls an <CODE>ArrayList</CODE> to use. It will be cleared before using. If it's
* <CODE>null</CODE> will create a new <CODE>ArrayList</CODE>
* @return the same <CODE>ArrayList</CODE> given as argument or a new one
* @throws IOException on error
*/
public List<PdfObject> parse(List<PdfObject> ls) throws IOException {
if (ls == null) {
ls = new ArrayList<>();
} else {
ls.clear();
}
PdfObject ob;
while ((ob = readPRObject()) != null) {
ls.add(ob);
if (ob.type() == COMMAND_TYPE) {
break;
}
}
return ls;
}
/**
* Gets the tokeniser.
*
* @return the tokeniser.
*/
public PRTokeniser getTokeniser() {
return this.tokeniser;
}
/**
* Sets the tokeniser.
*
* @param tokeniser the tokeniser
*/
public void setTokeniser(PRTokeniser tokeniser) {
this.tokeniser = tokeniser;
}
/**
* Reads a dictionary. The tokeniser must be positioned past the "<<" token.
*
* @return the dictionary
* @throws IOException on error
*/
public PdfDictionary readDictionary() throws IOException {<FILL_FUNCTION_BODY>}
/**
* Reads an array. The tokeniser must be positioned past the "[" token.
*
* @return an array
* @throws IOException on error
*/
public PdfArray readArray() throws IOException {
PdfArray array = new PdfArray();
while (true) {
PdfObject obj = readPRObject();
int type = obj.type();
if (-type == PRTokeniser.TK_END_ARRAY) {
break;
}
if (-type == PRTokeniser.TK_END_DIC) {
throw new IOException(MessageLocalization.getComposedMessage("unexpected.gt.gt"));
}
array.add(obj);
}
return array;
}
/**
* Reads a pdf object.
*
* @return the pdf object
* @throws IOException on error
*/
public PdfObject readPRObject() throws IOException {
if (!nextValidToken()) {
return null;
}
int type = tokeniser.getTokenType();
switch (type) {
case PRTokeniser.TK_START_DIC: {
PdfDictionary dic = readDictionary();
return dic;
}
case PRTokeniser.TK_START_ARRAY:
return readArray();
case PRTokeniser.TK_STRING:
PdfString str = new PdfString(tokeniser.getStringValue(), null).setHexWriting(tokeniser.isHexString());
return str;
case PRTokeniser.TK_NAME:
return new PdfName(tokeniser.getStringValue(), false);
case PRTokeniser.TK_NUMBER:
return new PdfNumber(tokeniser.getStringValue());
case PRTokeniser.TK_OTHER:
return new PdfLiteral(COMMAND_TYPE, tokeniser.getStringValue());
default:
return new PdfLiteral(-type, tokeniser.getStringValue());
}
}
/**
* Reads the next token skipping over the comments.
*
* @return <CODE>true</CODE> if a token was read, <CODE>false</CODE> if the end of content was reached
* @throws IOException on error
*/
public boolean nextValidToken() throws IOException {
while (tokeniser.nextToken()) {
if (tokeniser.getTokenType() == PRTokeniser.TK_COMMENT) {
continue;
}
return true;
}
return false;
}
}
|
PdfDictionary dic = new PdfDictionary();
while (true) {
if (!nextValidToken()) {
throw new IOException(MessageLocalization.getComposedMessage("unexpected.end.of.file"));
}
if (tokeniser.getTokenType() == PRTokeniser.TK_END_DIC) {
break;
}
if (tokeniser.getTokenType() != PRTokeniser.TK_NAME) {
throw new IOException(MessageLocalization.getComposedMessage("dictionary.key.is.not.a.name"));
}
PdfName name = new PdfName(tokeniser.getStringValue(), false);
PdfObject obj = readPRObject();
int type = obj.type();
if (-type == PRTokeniser.TK_END_DIC) {
throw new IOException(MessageLocalization.getComposedMessage("unexpected.gt.gt"));
}
if (-type == PRTokeniser.TK_END_ARRAY) {
throw new IOException(MessageLocalization.getComposedMessage("unexpected.close.bracket"));
}
dic.put(name, obj);
}
return dic;
| 1,194
| 292
| 1,486
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfCopyFormsImp.java
|
PdfCopyFormsImp
|
copyDocumentFields
|
class PdfCopyFormsImp extends PdfCopyFieldsImp {
/**
* This sets up the output document
*
* @param os The Outputstream pointing to the output document
* @throws DocumentException
*/
PdfCopyFormsImp(OutputStream os) throws DocumentException {
super(os);
}
/**
* This method feeds in the source document
*
* @param reader The PDF reader containing the source document
* @throws DocumentException
*/
public void copyDocumentFields(PdfReader reader) throws DocumentException {<FILL_FUNCTION_BODY>}
/**
* This merge fields is slightly different from the mergeFields method of PdfCopyFields.
*/
void mergeFields() {
for (AcroFields field : fields) {
mergeWithMaster(field.getAllFields());
}
}
}
|
if (!reader.isOpenedWithFullPermissions()) {
throw new IllegalArgumentException(
MessageLocalization.getComposedMessage("pdfreader.not.opened.with.owner.password"));
}
if (readers2intrefs.containsKey(reader)) {
reader = new PdfReader(reader);
} else {
if (reader.isTampered()) {
throw new DocumentException(MessageLocalization.getComposedMessage("the.document.was.reused"));
}
reader.consolidateNamedDestinations();
reader.setTampered(true);
}
reader.shuffleSubsetNames();
readers2intrefs.put(reader, new IntHashtable());
fields.add(reader.getAcroFields());
updateCalculationOrder(reader);
| 218
| 201
| 419
|
<methods>public void close() ,public com.lowagie.text.pdf.PdfIndirectReference getPageReference(int) ,public void openDoc() <variables>private final List<java.lang.Object> calculationOrder,private List<java.lang.Object> calculationOrderRefs,boolean closing,protected static final Map<com.lowagie.text.pdf.PdfName,java.lang.Integer> fieldKeys,Map<java.lang.String,java.lang.Object> fieldTree,List<com.lowagie.text.pdf.AcroFields> fields,com.lowagie.text.pdf.RandomAccessFileOrArray file,com.lowagie.text.pdf.PdfDictionary form,private boolean hasSignature,private static final com.lowagie.text.pdf.PdfName iTextTag,com.lowagie.text.Document nd,List<com.lowagie.text.pdf.PdfDictionary> pageDics,List<com.lowagie.text.pdf.PdfIndirectReference> pageRefs,private final Map<com.lowagie.text.pdf.PdfReader,com.lowagie.text.pdf.IntHashtable> pages2intrefs,private final List<com.lowagie.text.pdf.PdfReader> readers,Map<com.lowagie.text.pdf.PdfReader,com.lowagie.text.pdf.IntHashtable> readers2intrefs,com.lowagie.text.pdf.PdfDictionary resources,private Map<com.lowagie.text.pdf.PdfArray,List<java.lang.Integer>> tabOrder,private final Map<com.lowagie.text.pdf.PdfReader,com.lowagie.text.pdf.IntHashtable> visited,protected static final Map<com.lowagie.text.pdf.PdfName,java.lang.Integer> widgetKeys,private static final java.lang.Integer zero
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfDashPattern.java
|
PdfDashPattern
|
toPdf
|
class PdfDashPattern extends PdfArray {
// membervariables
/**
* This is the length of a dash.
*/
private float dash = -1;
/**
* This is the length of a gap.
*/
private float gap = -1;
/**
* This is the phase.
*/
private float phase = -1;
// constructors
/**
* Constructs a new <CODE>PdfDashPattern</CODE>.
*/
public PdfDashPattern() {
super();
}
/**
* Constructs a new <CODE>PdfDashPattern</CODE>.
*
* @param dash {@link PdfDashPattern#dash}
*/
public PdfDashPattern(float dash) {
super(new PdfNumber(dash));
this.dash = dash;
}
/**
* Constructs a new <CODE>PdfDashPattern</CODE>.
*
* @param dash {@link PdfDashPattern#dash}
* @param gap {@link PdfDashPattern#gap}
*/
public PdfDashPattern(float dash, float gap) {
super(new PdfNumber(dash));
add(new PdfNumber(gap));
this.dash = dash;
this.gap = gap;
}
/**
* Constructs a new <CODE>PdfDashPattern</CODE>.
*
* @param dash {@link PdfDashPattern#dash}
* @param gap {@link PdfDashPattern#gap}
* @param phase {@link PdfDashPattern#phase}
*/
public PdfDashPattern(float dash, float gap, float phase) {
super(new PdfNumber(dash));
add(new PdfNumber(gap));
this.dash = dash;
this.gap = gap;
this.phase = phase;
}
public void add(float n) {
add(new PdfNumber(n));
}
/**
* Returns the PDF representation of this <CODE>PdfArray</CODE>.
*/
public void toPdf(PdfWriter writer, OutputStream os) throws IOException {<FILL_FUNCTION_BODY>}
}
|
os.write('[');
if (dash >= 0) {
new PdfNumber(dash).toPdf(writer, os);
if (gap >= 0) {
os.write(' ');
new PdfNumber(gap).toPdf(writer, os);
}
}
os.write(']');
if (phase >= 0) {
os.write(' ');
new PdfNumber(phase).toPdf(writer, os);
}
| 584
| 123
| 707
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.PdfObject) ,public void <init>(float[]) ,public void <init>(int[]) ,public void <init>(List<? extends com.lowagie.text.pdf.PdfObject>) ,public void <init>(com.lowagie.text.pdf.PdfArray) ,public boolean add(com.lowagie.text.pdf.PdfObject) ,public boolean add(float[]) ,public boolean add(int[]) ,public void add(int, com.lowagie.text.pdf.PdfObject) ,public void addFirst(com.lowagie.text.pdf.PdfObject) ,public boolean contains(com.lowagie.text.pdf.PdfObject) ,public com.lowagie.text.pdf.PdfArray getAsArray(int) ,public com.lowagie.text.pdf.PdfBoolean getAsBoolean(int) ,public com.lowagie.text.pdf.PdfDictionary getAsDict(int) ,public com.lowagie.text.pdf.PdfIndirectReference getAsIndirectObject(int) ,public com.lowagie.text.pdf.PdfName getAsName(int) ,public com.lowagie.text.pdf.PdfNumber getAsNumber(int) ,public com.lowagie.text.pdf.PdfStream getAsStream(int) ,public com.lowagie.text.pdf.PdfString getAsString(int) ,public com.lowagie.text.pdf.PdfObject getDirectObject(int) ,public List<com.lowagie.text.pdf.PdfObject> getElements() ,public com.lowagie.text.pdf.PdfObject getPdfObject(int) ,public boolean isEmpty() ,public ListIterator<com.lowagie.text.pdf.PdfObject> listIterator() ,public com.lowagie.text.pdf.PdfObject remove(int) ,public boolean remove(com.lowagie.text.pdf.PdfObject) ,public com.lowagie.text.pdf.PdfObject set(int, com.lowagie.text.pdf.PdfObject) ,public int size() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() <variables>protected List<com.lowagie.text.pdf.PdfObject> arrayList
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfDestination.java
|
PdfDestination
|
addPage
|
class PdfDestination extends PdfArray {
// public static final member-variables
/**
* This is a possible destination type
*/
public static final int XYZ = 0;
/**
* This is a possible destination type
*/
public static final int FIT = 1;
/**
* This is a possible destination type
*/
public static final int FITH = 2;
/**
* This is a possible destination type
*/
public static final int FITV = 3;
/**
* This is a possible destination type
*/
public static final int FITR = 4;
/**
* This is a possible destination type
*/
public static final int FITB = 5;
/**
* This is a possible destination type
*/
public static final int FITBH = 6;
/**
* This is a possible destination type
*/
public static final int FITBV = 7;
// member variables
/**
* Is the indirect reference to a page already added?
*/
private boolean status = false;
// constructors
/**
* Constructs a new <CODE>PdfDestination</CODE>.
* <p>
* If <VAR>type</VAR> equals <VAR>FITB</VAR>, the bounding box of a page will fit the window of the Reader.
* Otherwise the type will be set to
* <VAR>FIT</VAR> so that the entire page will fit to the window.
*
* @param type The destination type
*/
public PdfDestination(int type) {
super();
if (type == FITB) {
add(PdfName.FITB);
} else {
add(PdfName.FIT);
}
}
/**
* Constructs a new <CODE>PdfDestination</CODE>.
* <p>
* If <VAR>type</VAR> equals <VAR>FITBH</VAR> / <VAR>FITBV</VAR>, the width / height of the bounding box of a page
* will fit the window of the Reader. The parameter will specify the y / x coordinate of the top / left edge of the
* window. If the <VAR>type</VAR> equals <VAR>FITH</VAR> or <VAR>FITV</VAR> the width / height of the entire page
* will fit the window and the parameter will specify the y / x coordinate of the top / left edge. In all other
* cases the type will be set to <VAR>FITH</VAR>.
*
* @param type the destination type
* @param parameter a parameter to combined with the destination type
*/
public PdfDestination(int type, float parameter) {
super(new PdfNumber(parameter));
switch (type) {
default:
addFirst(PdfName.FITH);
break;
case FITV:
addFirst(PdfName.FITV);
break;
case FITBH:
addFirst(PdfName.FITBH);
break;
case FITBV:
addFirst(PdfName.FITBV);
}
}
/**
* Constructs a new <CODE>PdfDestination</CODE>.
* <p>
* Display the page, with the coordinates (left, top) positioned at the top-left corner of the window and the
* contents of the page magnified by the factor zoom. A negative value for any of the parameters left or top, or a
* zoom value of 0 specifies that the current value of that parameter is to be retained unchanged.
*
* @param type must be a <VAR>PdfDestination.XYZ</VAR>
* @param left the left value. Negative to place a null
* @param top the top value. Negative to place a null
* @param zoom The zoom factor. A value of 0 keeps the current value
*/
public PdfDestination(int type, float left, float top, float zoom) {
super(PdfName.XYZ);
if (left < 0) {
add(PdfNull.PDFNULL);
} else {
add(new PdfNumber(left));
}
if (top < 0) {
add(PdfNull.PDFNULL);
} else {
add(new PdfNumber(top));
}
add(new PdfNumber(zoom));
}
/**
* Constructs a new <CODE>PdfDestination</CODE>.
* <p>
* Display the page, with its contents magnified just enough to fit the rectangle specified by the coordinates left,
* bottom, right, and top entirely within the window both horizontally and vertically. If the required horizontal
* and vertical magnification factors are different, use the smaller of the two, centering the rectangle within the
* window in the other dimension.
*
* @param type must be PdfDestination.FITR
* @param left a parameter
* @param bottom a parameter
* @param right a parameter
* @param top a parameter
* @since iText0.38
*/
public PdfDestination(int type, float left, float bottom, float right, float top) {
super(PdfName.FITR);
add(new PdfNumber(left));
add(new PdfNumber(bottom));
add(new PdfNumber(right));
add(new PdfNumber(top));
}
/**
* Creates a PdfDestination based on a String. Valid Strings are for instance the values returned by
* SimpleNamedDestination: "Fit", "XYZ 36 806 0",...
*
* @param dest a String notation of a destination.
* @since iText 5.0
*/
public PdfDestination(String dest) {
super();
StringTokenizer tokens = new StringTokenizer(dest);
if (tokens.hasMoreTokens()) {
add(new PdfName(tokens.nextToken()));
}
while (tokens.hasMoreTokens()) {
add(new PdfNumber(tokens.nextToken()));
}
}
// methods
/**
* Checks if an indirect reference to a page has been added.
*
* @return <CODE>true</CODE> or <CODE>false</CODE>
*/
public boolean hasPage() {
return status;
}
/**
* Adds the indirect reference of the destination page.
*
* @param page an indirect reference
* @return true if the page reference was added
*/
public boolean addPage(PdfIndirectReference page) {<FILL_FUNCTION_BODY>}
}
|
if (!status) {
addFirst(page);
status = true;
return true;
}
return false;
| 1,721
| 36
| 1,757
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.PdfObject) ,public void <init>(float[]) ,public void <init>(int[]) ,public void <init>(List<? extends com.lowagie.text.pdf.PdfObject>) ,public void <init>(com.lowagie.text.pdf.PdfArray) ,public boolean add(com.lowagie.text.pdf.PdfObject) ,public boolean add(float[]) ,public boolean add(int[]) ,public void add(int, com.lowagie.text.pdf.PdfObject) ,public void addFirst(com.lowagie.text.pdf.PdfObject) ,public boolean contains(com.lowagie.text.pdf.PdfObject) ,public com.lowagie.text.pdf.PdfArray getAsArray(int) ,public com.lowagie.text.pdf.PdfBoolean getAsBoolean(int) ,public com.lowagie.text.pdf.PdfDictionary getAsDict(int) ,public com.lowagie.text.pdf.PdfIndirectReference getAsIndirectObject(int) ,public com.lowagie.text.pdf.PdfName getAsName(int) ,public com.lowagie.text.pdf.PdfNumber getAsNumber(int) ,public com.lowagie.text.pdf.PdfStream getAsStream(int) ,public com.lowagie.text.pdf.PdfString getAsString(int) ,public com.lowagie.text.pdf.PdfObject getDirectObject(int) ,public List<com.lowagie.text.pdf.PdfObject> getElements() ,public com.lowagie.text.pdf.PdfObject getPdfObject(int) ,public boolean isEmpty() ,public ListIterator<com.lowagie.text.pdf.PdfObject> listIterator() ,public com.lowagie.text.pdf.PdfObject remove(int) ,public boolean remove(com.lowagie.text.pdf.PdfObject) ,public com.lowagie.text.pdf.PdfObject set(int, com.lowagie.text.pdf.PdfObject) ,public int size() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() <variables>protected List<com.lowagie.text.pdf.PdfObject> arrayList
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfDeveloperExtension.java
|
PdfDeveloperExtension
|
getDeveloperExtensions
|
class PdfDeveloperExtension {
/**
* An instance of this class for Adobe 1.7 Extension level 3.
*/
public static final PdfDeveloperExtension ADOBE_1_7_EXTENSIONLEVEL3 =
new PdfDeveloperExtension(PdfName.ADBE, PdfWriter.PDF_VERSION_1_7, 3);
/**
* The prefix used in the Extensions dictionary added to the Catalog.
*/
protected PdfName prefix;
/**
* The base version.
*/
protected PdfName baseversion;
/**
* The extension level within the baseversion.
*/
protected int extensionLevel;
/**
* Creates a PdfDeveloperExtension object.
*
* @param prefix the prefix referring to the developer
* @param baseversion the number of the base version
* @param extensionLevel the extension level within the baseverion.
*/
public PdfDeveloperExtension(PdfName prefix, PdfName baseversion, int extensionLevel) {
this.prefix = prefix;
this.baseversion = baseversion;
this.extensionLevel = extensionLevel;
}
/**
* Gets the prefix name.
*
* @return a PdfName
*/
public PdfName getPrefix() {
return prefix;
}
/**
* Gets the baseversion name.
*
* @return a PdfName
*/
public PdfName getBaseversion() {
return baseversion;
}
/**
* Gets the extension level within the baseversion.
*
* @return an integer
*/
public int getExtensionLevel() {
return extensionLevel;
}
/**
* Generations the developer extension dictionary corresponding with the prefix.
*
* @return a PdfDictionary
*/
public PdfDictionary getDeveloperExtensions() {<FILL_FUNCTION_BODY>}
}
|
PdfDictionary developerextensions = new PdfDictionary();
developerextensions.put(PdfName.BASEVERSION, baseversion);
developerextensions.put(PdfName.EXTENSIONLEVEL, new PdfNumber(extensionLevel));
return developerextensions;
| 490
| 76
| 566
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfEFStream.java
|
PdfEFStream
|
toPdf
|
class PdfEFStream extends PdfStream {
/**
* Creates a Stream object using an InputStream and a PdfWriter object
*
* @param in the InputStream that will be read to get the Stream object
* @param writer the writer to which the stream will be added
*/
public PdfEFStream(InputStream in, PdfWriter writer) {
super(in, writer);
}
/**
* Creates a Stream object using a byte array
*
* @param fileStore the bytes for the stream
*/
public PdfEFStream(byte[] fileStore) {
super(fileStore);
}
/**
* @see com.lowagie.text.pdf.PdfDictionary#toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream)
*/
public void toPdf(PdfWriter writer, OutputStream os) throws IOException {<FILL_FUNCTION_BODY>}
}
|
if (inputStream != null && compressed) {
put(PdfName.FILTER, PdfName.FLATEDECODE);
}
PdfEncryption crypto = null;
if (writer != null) {
crypto = writer.getEncryption();
}
if (crypto != null) {
PdfObject filter = get(PdfName.FILTER);
if (filter != null) {
if (PdfName.CRYPT.equals(filter)) {
crypto = null;
} else if (filter.isArray()) {
PdfArray a = (PdfArray) filter;
if (!a.isEmpty() && PdfName.CRYPT.equals(a.getPdfObject(0))) {
crypto = null;
}
}
}
}
if (crypto != null && crypto.isEmbeddedFilesOnly()) {
PdfArray filter = new PdfArray();
PdfArray decodeparms = new PdfArray();
PdfDictionary crypt = new PdfDictionary();
crypt.put(PdfName.NAME, PdfName.STDCF);
filter.add(PdfName.CRYPT);
decodeparms.add(crypt);
if (compressed) {
filter.add(PdfName.FLATEDECODE);
decodeparms.add(new PdfNull());
}
put(PdfName.FILTER, filter);
put(PdfName.DECODEPARMS, decodeparms);
}
PdfObject nn = get(PdfName.LENGTH);
if (crypto != null && nn != null && nn.isNumber()) {
int sz = ((PdfNumber) nn).intValue();
put(PdfName.LENGTH, new PdfNumber(crypto.calculateStreamSize(sz)));
superToPdf(writer, os);
put(PdfName.LENGTH, nn);
} else {
superToPdf(writer, os);
}
os.write(STARTSTREAM);
if (inputStream != null) {
rawLength = 0;
DeflaterOutputStream def = null;
OutputStreamCounter osc = new OutputStreamCounter(os);
OutputStreamEncryption ose = null;
OutputStream fout = osc;
if (crypto != null) {
fout = ose = crypto.getEncryptionStream(fout);
}
Deflater deflater = null;
if (compressed) {
deflater = new Deflater(compressionLevel);
fout = def = new DeflaterOutputStream(fout, deflater, 0x8000);
}
byte[] buf = new byte[4192];
while (true) {
int n = inputStream.read(buf);
if (n <= 0) {
break;
}
fout.write(buf, 0, n);
rawLength += n;
}
if (def != null) {
def.finish();
deflater.end();
}
if (ose != null) {
ose.finish();
}
inputStreamLength = osc.getCounter();
} else {
if (crypto == null) {
if (streamBytes != null) {
streamBytes.writeTo(os);
} else {
os.write(bytes);
}
} else {
byte[] b;
if (streamBytes != null) {
b = crypto.encryptByteArray(streamBytes.toByteArray());
} else {
b = crypto.encryptByteArray(bytes);
}
os.write(b);
}
}
os.write(ENDSTREAM);
| 243
| 958
| 1,201
|
<methods>public void <init>(byte[]) ,public void <init>(java.io.InputStream, com.lowagie.text.pdf.PdfWriter) ,public void flateCompress() ,public void flateCompress(int) ,public long getRawLength() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() ,public void writeContent(java.io.OutputStream) throws java.io.IOException,public void writeLength() throws java.io.IOException<variables>public static final int BEST_COMPRESSION,public static final int BEST_SPEED,public static final int DEFAULT_COMPRESSION,static final byte[] ENDSTREAM,public static final int NO_COMPRESSION,static final int SIZESTREAM,static final byte[] STARTSTREAM,protected boolean compressed,protected int compressionLevel,protected java.io.InputStream inputStream,protected long inputStreamLength,protected long rawLength,protected com.lowagie.text.pdf.PdfIndirectReference ref,protected java.io.ByteArrayOutputStream streamBytes,protected com.lowagie.text.pdf.PdfWriter writer
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfFont.java
|
PdfFont
|
compareTo
|
class PdfFont implements Comparable {
/**
* an image.
*/
protected Image image;
protected float hScale = 1;
/**
* the font metrics.
*/
private BaseFont font;
/**
* the size.
*/
private float size;
// constructors
PdfFont(BaseFont bf, float size) {
this.size = size;
font = bf;
}
// methods
static PdfFont getDefaultFont() {
try {
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false);
return new PdfFont(bf, 12);
} catch (Exception ee) {
throw new ExceptionConverter(ee);
}
}
/**
* Compares this <CODE>PdfFont</CODE> with another
*
* @param object the other <CODE>PdfFont</CODE>
* @return a value
*/
public int compareTo(Object object) {<FILL_FUNCTION_BODY>}
/**
* Returns the size of this font.
*
* @return a size
*/
float size() {
if (image == null) {
return size;
} else {
return image.getScaledHeight();
}
}
/**
* Returns the approximative width of 1 character of this font.
*
* @return a width in Text Space
*/
float width() {
return width(' ');
}
/**
* Returns the width of a certain character of this font.
*
* @param character a certain character
* @return a width in Text Space
*/
float width(int character) {
if (image == null) {
return font.getWidthPoint(character, size) * hScale;
} else {
return image.getScaledWidth();
}
}
float width(String s) {
if (image == null) {
return font.getWidthPoint(s, size) * hScale;
} else {
return image.getScaledWidth();
}
}
BaseFont getFont() {
return font;
}
void setImage(Image image) {
this.image = image;
}
void setHorizontalScaling(float hScale) {
this.hScale = hScale;
}
}
|
if (image != null) {
return 0;
}
if (object == null) {
return -1;
}
PdfFont pdfFont;
try {
pdfFont = (PdfFont) object;
if (font != pdfFont.font) {
return 1;
}
if (this.size() != pdfFont.size()) {
return 2;
}
return 0;
} catch (ClassCastException cce) {
return -2;
}
| 634
| 138
| 772
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfFunction.java
|
PdfFunction
|
type2
|
class PdfFunction {
protected PdfWriter writer;
protected PdfIndirectReference reference;
protected PdfDictionary dictionary;
/**
* Creates new PdfFunction
*
* @param writer the PdfWriter to associate to the PdfFunction
*/
protected PdfFunction(PdfWriter writer) {
this.writer = writer;
}
public static PdfFunction type0(PdfWriter writer, float[] domain, float[] range, int[] size,
int bitsPerSample, int order, float[] encode, float[] decode, byte[] stream) {
PdfFunction func = new PdfFunction(writer);
func.dictionary = new PdfStream(stream);
((PdfStream) func.dictionary).flateCompress(writer.getCompressionLevel());
func.dictionary.put(PdfName.FUNCTIONTYPE, new PdfNumber(0));
func.dictionary.put(PdfName.DOMAIN, new PdfArray(domain));
func.dictionary.put(PdfName.RANGE, new PdfArray(range));
func.dictionary.put(PdfName.SIZE, new PdfArray(size));
func.dictionary.put(PdfName.BITSPERSAMPLE, new PdfNumber(bitsPerSample));
if (order != 1) {
func.dictionary.put(PdfName.ORDER, new PdfNumber(order));
}
if (encode != null) {
func.dictionary.put(PdfName.ENCODE, new PdfArray(encode));
}
if (decode != null) {
func.dictionary.put(PdfName.DECODE, new PdfArray(decode));
}
return func;
}
public static PdfFunction type2(PdfWriter writer, float[] domain, float[] range, float[] c0, float[] c1, float n) {<FILL_FUNCTION_BODY>}
public static PdfFunction type3(PdfWriter writer, float[] domain, float[] range, PdfFunction[] functions,
float[] bounds, float[] encode) {
PdfFunction func = new PdfFunction(writer);
func.dictionary = new PdfDictionary();
func.dictionary.put(PdfName.FUNCTIONTYPE, new PdfNumber(3));
func.dictionary.put(PdfName.DOMAIN, new PdfArray(domain));
if (range != null) {
func.dictionary.put(PdfName.RANGE, new PdfArray(range));
}
PdfArray array = new PdfArray();
for (PdfFunction function : functions) {
array.add(function.getReference());
}
func.dictionary.put(PdfName.FUNCTIONS, array);
func.dictionary.put(PdfName.BOUNDS, new PdfArray(bounds));
func.dictionary.put(PdfName.ENCODE, new PdfArray(encode));
return func;
}
public static PdfFunction type4(PdfWriter writer, float[] domain, float[] range, String postscript) {
byte[] b = new byte[postscript.length()];
for (int k = 0; k < b.length; ++k) {
b[k] = (byte) postscript.charAt(k);
}
PdfFunction func = new PdfFunction(writer);
func.dictionary = new PdfStream(b);
((PdfStream) func.dictionary).flateCompress(writer.getCompressionLevel());
func.dictionary.put(PdfName.FUNCTIONTYPE, new PdfNumber(4));
func.dictionary.put(PdfName.DOMAIN, new PdfArray(domain));
func.dictionary.put(PdfName.RANGE, new PdfArray(range));
return func;
}
PdfIndirectReference getReference() {
try {
if (reference == null) {
reference = writer.addToBody(dictionary).getIndirectReference();
}
} catch (IOException ioe) {
throw new ExceptionConverter(ioe);
}
return reference;
}
}
|
PdfFunction func = new PdfFunction(writer);
func.dictionary = new PdfDictionary();
func.dictionary.put(PdfName.FUNCTIONTYPE, new PdfNumber(2));
func.dictionary.put(PdfName.DOMAIN, new PdfArray(domain));
if (range != null) {
func.dictionary.put(PdfName.RANGE, new PdfArray(range));
}
if (c0 != null) {
func.dictionary.put(PdfName.C0, new PdfArray(c0));
}
if (c1 != null) {
func.dictionary.put(PdfName.C1, new PdfArray(c1));
}
func.dictionary.put(PdfName.N, new PdfNumber(n));
return func;
| 1,040
| 215
| 1,255
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfGlyphArray.java
|
PdfGlyphArray
|
add
|
class PdfGlyphArray {
private final LinkedList<Object> list = new LinkedList<>();
public void add(float displacement) {
list.add(displacement);
}
public void add(int glyphCode) {<FILL_FUNCTION_BODY>}
List<Object> getList() {
return Collections.unmodifiableList(list);
}
public void clear() {
list.clear();
}
public boolean isEmpty() {
return list.isEmpty();
}
public static class GlyphSubList extends ArrayList<Integer> {
}
}
|
Object last = list.peekLast();
GlyphSubList glyphSublist;
if (last instanceof GlyphSubList) {
glyphSublist = (GlyphSubList) last;
} else {
glyphSublist = new GlyphSubList();
list.add(glyphSublist);
}
glyphSublist.add(glyphCode);
| 159
| 97
| 256
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfLister.java
|
PdfLister
|
listStream
|
class PdfLister {
/**
* the printStream you want to write the output to.
*/
PrintStream out;
/**
* Create a new lister object.
*
* @param out the PrintStream to write the output to
*/
public PdfLister(PrintStream out) {
this.out = out;
}
/**
* Visualizes a PDF object.
*
* @param object a com.lowagie.text.pdf object
*/
public void listAnyObject(PdfObject object) {
switch (object.type()) {
case PdfObject.ARRAY:
listArray((PdfArray) object);
break;
case PdfObject.DICTIONARY:
listDict((PdfDictionary) object);
break;
case PdfObject.STRING:
out.println("(" + object.toString() + ")");
break;
default:
out.println(object.toString());
break;
}
}
/**
* Visualizes a PdfDictionary object.
*
* @param dictionary a com.lowagie.text.pdf.PdfDictionary object
*/
public void listDict(PdfDictionary dictionary) {
out.println("<<");
PdfName key;
PdfObject value;
for (PdfName pdfName : dictionary.getKeys()) {
key = pdfName;
value = dictionary.get(key);
out.print(key.toString());
out.print(' ');
listAnyObject(value);
}
out.println(">>");
}
/**
* Visualizes a PdfArray object.
*
* @param array a com.lowagie.text.pdf.PdfArray object
*/
public void listArray(PdfArray array) {
out.println('[');
array.getElements().forEach(this::listAnyObject);
out.println(']');
}
/**
* Visualizes a Stream.
*
* @param stream the stream to read from
* @param reader not used currently
*/
public void listStream(PRStream stream, PdfReaderInstance reader) {<FILL_FUNCTION_BODY>}
/**
* Visualizes an imported page
*
* @param iPage the imported page
*/
public void listPage(PdfImportedPage iPage) {
int pageNum = iPage.getPageNumber();
PdfReaderInstance readerInst = iPage.getPdfReaderInstance();
PdfReader reader = readerInst.getReader();
PdfDictionary page = reader.getPageN(pageNum);
listDict(page);
PdfObject obj = PdfReader.getPdfObject(page.get(PdfName.CONTENTS));
if (obj == null) {
return;
}
switch (obj.type) {
case PdfObject.STREAM:
listStream((PRStream) obj, readerInst);
break;
case PdfObject.ARRAY:
for (PdfObject pdfObject : ((PdfArray) obj).getElements()) {
PdfObject o = PdfReader.getPdfObject(pdfObject);
listStream((PRStream) o, readerInst);
out.println("-----------");
}
break;
}
}
}
|
try {
listDict(stream);
out.println("startstream");
byte[] b = PdfReader.getStreamBytes(stream);
// byte buf[] = new byte[Math.min(stream.getLength(), 4096)];
// int r = 0;
// stream.openStream(reader);
// for (;;) {
// r = stream.readStream(buf, 0, buf.length);
// if (r == 0) break;
// out.write(buf, 0, r);
// }
// stream.closeStream();
int len = b.length - 1;
for (int k = 0; k < len; ++k) {
if (b[k] == '\r' && b[k + 1] != '\n') {
b[k] = (byte) '\n';
}
}
out.println(new String(b));
out.println("endstream");
} catch (IOException e) {
System.err.println("I/O exception: " + e);
// } catch (java.util.zip.DataFormatException e) {
// System.err.println("Data Format Exception: " + e);
}
| 842
| 304
| 1,146
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfLiteral.java
|
PdfLiteral
|
getPosLength
|
class PdfLiteral extends PdfObject {
/**
* Holds value of property position.
*/
private long position;
public PdfLiteral(String text) {
super(0, text);
}
public PdfLiteral(byte[] b) {
super(0, b);
}
public PdfLiteral(int size) {
super(0, (byte[]) null);
bytes = new byte[size];
java.util.Arrays.fill(bytes, (byte) 32);
}
public PdfLiteral(int type, String text) {
super(type, text);
}
public PdfLiteral(int type, byte[] b) {
super(type, b);
}
public void toPdf(PdfWriter writer, java.io.OutputStream os) throws java.io.IOException {
if (os instanceof OutputStreamCounter) {
position = ((OutputStreamCounter) os).getCounter();
}
super.toPdf(writer, os);
}
/**
* Getter for property position.
*
* @return Value of property position.
*/
public long getPosition() {
return this.position;
}
/**
* Getter for property posLength.
*
* @return Value of property posLength.
*/
public int getPosLength() {<FILL_FUNCTION_BODY>}
}
|
if (bytes != null) {
return bytes.length;
} else {
return 0;
}
| 361
| 34
| 395
|
<methods>public boolean canBeInObjStm() ,public byte[] getBytes() ,public com.lowagie.text.pdf.PRIndirectReference getIndRef() ,public boolean isArray() ,public boolean isBoolean() ,public boolean isDictionary() ,public boolean isIndirect() ,public boolean isName() ,public boolean isNull() ,public boolean isNumber() ,public boolean isStream() ,public boolean isString() ,public int length() ,public void setIndRef(com.lowagie.text.pdf.PRIndirectReference) ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() ,public int type() <variables>public static final int ARRAY,public static final int BOOLEAN,public static final int DICTIONARY,public static final int INDIRECT,public static final int NAME,public static final java.lang.String NOTHING,public static final int NULL,public static final int NUMBER,public static final int STREAM,public static final int STRING,public static final java.lang.String TEXT_PDFDOCENCODING,public static final java.lang.String TEXT_UNICODE,protected byte[] bytes,protected com.lowagie.text.pdf.PRIndirectReference indRef,protected int type
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfNameTree.java
|
PdfNameTree
|
writeTree
|
class PdfNameTree {
private static final int leafSize = 64;
/**
* Writes a name tree to a PdfWriter.
*
* @param items the item of the name tree. The key is a <CODE>String</CODE> and the value is a
* <CODE>PdfObject</CODE>. Note that although the keys are strings only the lower byte is used and no
* check is made for chars with the same lower byte and different upper byte. This will generate a
* wrong tree name.
* @param writer the writer
* @return the dictionary with the name tree. This dictionary is the one generally pointed to by the key /Dests, for
* example
* @throws IOException on error
*/
public static PdfDictionary writeTree(HashMap<String, ? extends PdfObject> items, PdfWriter writer)
throws IOException {
return writeTree((Map<String, ? extends PdfObject>) items, writer);
}
/**
* Writes a name tree to a PdfWriter.
*
* @param items the item of the name tree. The key is a <CODE>String</CODE> and the value is a
* <CODE>PdfObject</CODE>. Note that although the keys are strings only the lower byte is used and no
* check is made for chars with the same lower byte and different upper byte. This will generate a
* wrong tree name.
* @param writer the writer
* @return the dictionary with the name tree. This dictionary is the one generally pointed to by the key /Dests, for
* example
* @throws IOException on error
*/
public static PdfDictionary writeTree(Map<String, ? extends PdfObject> items, PdfWriter writer) throws IOException {<FILL_FUNCTION_BODY>}
private static void iterateItems(PdfDictionary dic, HashMap<String, PdfObject> items) {
PdfArray nn = (PdfArray) PdfReader.getPdfObjectRelease(dic.get(PdfName.NAMES));
if (nn != null) {
for (int k = 0; k < nn.size(); ++k) {
PdfString s = (PdfString) PdfReader.getPdfObjectRelease(nn.getPdfObject(k++));
items.put(PdfEncodings.convertToString(s.getBytes(), null), nn.getPdfObject(k));
}
} else if ((nn = (PdfArray) PdfReader.getPdfObjectRelease(dic.get(PdfName.KIDS))) != null) {
for (int k = 0; k < nn.size(); ++k) {
PdfDictionary kid = (PdfDictionary) PdfReader.getPdfObjectRelease(nn.getPdfObject(k));
iterateItems(kid, items);
}
}
}
public static HashMap<String, PdfObject> readTree(PdfDictionary dic) {
HashMap<String, PdfObject> items = new HashMap<>();
if (dic != null) {
iterateItems(dic, items);
}
return items;
}
}
|
if (items.isEmpty()) {
return null;
}
String[] names = items.keySet().toArray(new String[0]);
Arrays.sort(names);
if (names.length <= leafSize) {
PdfDictionary dic = new PdfDictionary();
PdfArray ar = new PdfArray();
for (String name : names) {
ar.add(new PdfString(name, null));
ar.add(items.get(name));
}
dic.put(PdfName.NAMES, ar);
return dic;
}
int skip = leafSize;
PdfIndirectReference[] kids = new PdfIndirectReference[(names.length + leafSize - 1) / leafSize];
for (int k = 0; k < kids.length; ++k) {
int offset = k * leafSize;
int end = Math.min(offset + leafSize, names.length);
PdfDictionary dic = new PdfDictionary();
PdfArray arr = new PdfArray();
arr.add(new PdfString(names[offset], null));
arr.add(new PdfString(names[end - 1], null));
dic.put(PdfName.LIMITS, arr);
arr = new PdfArray();
for (; offset < end; ++offset) {
arr.add(new PdfString(names[offset], null));
arr.add(items.get(names[offset]));
}
dic.put(PdfName.NAMES, arr);
kids[k] = writer.addToBody(dic).getIndirectReference();
}
int top = kids.length;
while (true) {
if (top <= leafSize) {
PdfArray arr = new PdfArray();
for (int k = 0; k < top; ++k) {
arr.add(kids[k]);
}
PdfDictionary dic = new PdfDictionary();
dic.put(PdfName.KIDS, arr);
return dic;
}
skip *= leafSize;
int tt = (names.length + skip - 1) / skip;
for (int k = 0; k < tt; ++k) {
int offset = k * leafSize;
int end = Math.min(offset + leafSize, top);
PdfDictionary dic = new PdfDictionary();
PdfArray arr = new PdfArray();
arr.add(new PdfString(names[k * skip], null));
arr.add(new PdfString(names[Math.min((k + 1) * skip, names.length) - 1], null));
dic.put(PdfName.LIMITS, arr);
arr = new PdfArray();
for (; offset < end; ++offset) {
arr.add(kids[offset]);
}
dic.put(PdfName.KIDS, arr);
kids[k] = writer.addToBody(dic).getIndirectReference();
}
top = tt;
}
| 792
| 755
| 1,547
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfNumber.java
|
PdfNumber
|
compareTo
|
class PdfNumber extends PdfObject implements Comparable<PdfNumber> {
// CLASS VARIABLES
/**
* actual value of this <CODE>PdfNumber</CODE>, represented as a
* <CODE>double</CODE>
*/
private double value;
// CONSTRUCTORS
/**
* Constructs a <CODE>PdfNumber</CODE>-object.
*
* @param content value of the new <CODE>PdfNumber</CODE>-object
*/
public PdfNumber(String content) {
super(NUMBER);
try {
value = Double.parseDouble(content.trim());
setContent(content);
} catch (NumberFormatException nfe) {
throw new RuntimeException(
MessageLocalization.getComposedMessage("1.is.not.a.valid.number.2", content, nfe.toString()));
}
}
/**
* Constructs a new <CODE>PdfNumber</CODE>-object of type integer.
*
* @param value value of the new <CODE>PdfNumber</CODE>-object
*/
public PdfNumber(int value) {
super(NUMBER);
this.value = value;
setContent(String.valueOf(value));
}
/**
* Constructs a new <CODE>PdfNumber</CODE>-object of type long.
*
* @param value value of the new <CODE>PdfNumber</CODE>-object
*/
public PdfNumber(long value) {
super(NUMBER);
this.value = value;
setContent(String.valueOf(value));
}
/**
* Constructs a new <CODE>PdfNumber</CODE>-object of type real.
*
* @param value value of the new <CODE>PdfNumber</CODE>-object
*/
public PdfNumber(double value) {
super(NUMBER);
this.value = value;
setContent(ByteBuffer.formatDouble(value));
}
/**
* Constructs a new <CODE>PdfNumber</CODE>-object of type real.
*
* @param value value of the new <CODE>PdfNumber</CODE>-object
*/
public PdfNumber(float value) {
this((double) value);
}
// methods returning the value of this object
/**
* Returns the primitive <CODE>int</CODE> value of this object.
*
* @return The value as <CODE>int</CODE>
*/
public int intValue() {
return (int) value;
}
/**
* Returns the primitive <CODE>double</CODE> value of this object.
*
* @return The value as <CODE>double</CODE>
*/
public double doubleValue() {
return value;
}
/**
* Returns the primitive <CODE>float</CODE> value of this object.
*
* @return The value as <CODE>float</CODE>
*/
public float floatValue() {
return (float) value;
}
// other methods
/**
* Increments the value of the <CODE>PdfNumber</CODE>-object by 1.
*/
public void increment() {
value += 1.0;
setContent(ByteBuffer.formatDouble(value));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PdfNumber)) {
return false;
}
PdfNumber pdfNumber = (PdfNumber) o;
return Double.compare(pdfNumber.value, value) == 0;
}
@Override
public int hashCode() {
return Objects.hash(value);
}
@Override
public int compareTo(PdfNumber o) {<FILL_FUNCTION_BODY>}
}
|
Objects.requireNonNull(o, "PdfNumber is null, can't be compared to current instance.");
if (this == o) {
return 0;
}
return Double.compare(o.value, value);
| 1,012
| 61
| 1,073
|
<methods>public boolean canBeInObjStm() ,public byte[] getBytes() ,public com.lowagie.text.pdf.PRIndirectReference getIndRef() ,public boolean isArray() ,public boolean isBoolean() ,public boolean isDictionary() ,public boolean isIndirect() ,public boolean isName() ,public boolean isNull() ,public boolean isNumber() ,public boolean isStream() ,public boolean isString() ,public int length() ,public void setIndRef(com.lowagie.text.pdf.PRIndirectReference) ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() ,public int type() <variables>public static final int ARRAY,public static final int BOOLEAN,public static final int DICTIONARY,public static final int INDIRECT,public static final int NAME,public static final java.lang.String NOTHING,public static final int NULL,public static final int NUMBER,public static final int STREAM,public static final int STRING,public static final java.lang.String TEXT_PDFDOCENCODING,public static final java.lang.String TEXT_UNICODE,protected byte[] bytes,protected com.lowagie.text.pdf.PRIndirectReference indRef,protected int type
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfNumberTree.java
|
PdfNumberTree
|
writeTree
|
class PdfNumberTree {
private static final int leafSize = 64;
/**
* Creates a number tree.
*
* @param items the item of the number tree. The key is an <CODE>Integer</CODE> and the value is a
* <CODE>PdfObject</CODE>.
* @param writer the writer
* @return the dictionary with the number tree.
* @throws IOException on error
*/
public static PdfDictionary writeTree(Map<Integer, ? extends PdfObject> items, PdfWriter writer)
throws IOException {<FILL_FUNCTION_BODY>}
private static void iterateItems(PdfDictionary dic, Map<Integer, PdfObject> items) {
PdfArray nn = (PdfArray) PdfReader.getPdfObjectRelease(dic.get(PdfName.NUMS));
if (nn != null) {
for (int k = 0; k < nn.size(); ++k) {
PdfNumber s = (PdfNumber) PdfReader.getPdfObjectRelease(nn.getPdfObject(k++));
items.put(s.intValue(), nn.getPdfObject(k));
}
} else if ((nn = (PdfArray) PdfReader.getPdfObjectRelease(dic.get(PdfName.KIDS))) != null) {
for (int k = 0; k < nn.size(); ++k) {
PdfDictionary kid = (PdfDictionary) PdfReader.getPdfObjectRelease(nn.getPdfObject(k));
iterateItems(kid, items);
}
}
}
public static HashMap<Integer, PdfObject> readTree(PdfDictionary dic) {
HashMap<Integer, PdfObject> items = new HashMap<>();
if (dic != null) {
iterateItems(dic, items);
}
return items;
}
}
|
if (items.isEmpty()) {
return null;
}
Integer[] numbers = new Integer[items.size()];
numbers = items.keySet().toArray(numbers);
Arrays.sort(numbers);
if (numbers.length <= leafSize) {
PdfDictionary dic = new PdfDictionary();
PdfArray ar = new PdfArray();
for (Integer number : numbers) {
ar.add(new PdfNumber(number));
ar.add(items.get(number));
}
dic.put(PdfName.NUMS, ar);
return dic;
}
int skip = leafSize;
PdfIndirectReference[] kids = new PdfIndirectReference[(numbers.length + leafSize - 1) / leafSize];
for (int k = 0; k < kids.length; ++k) {
int offset = k * leafSize;
int end = Math.min(offset + leafSize, numbers.length);
PdfDictionary dic = new PdfDictionary();
PdfArray arr = new PdfArray();
arr.add(new PdfNumber(numbers[offset]));
arr.add(new PdfNumber(numbers[end - 1]));
dic.put(PdfName.LIMITS, arr);
arr = new PdfArray();
for (; offset < end; ++offset) {
arr.add(new PdfNumber(numbers[offset]));
arr.add(items.get(numbers[offset]));
}
dic.put(PdfName.NUMS, arr);
kids[k] = writer.addToBody(dic).getIndirectReference();
}
int top = kids.length;
while (true) {
if (top <= leafSize) {
PdfArray arr = new PdfArray();
for (int k = 0; k < top; ++k) {
arr.add(kids[k]);
}
PdfDictionary dic = new PdfDictionary();
dic.put(PdfName.KIDS, arr);
return dic;
}
skip *= leafSize;
int tt = (numbers.length + skip - 1) / skip;
for (int k = 0; k < tt; ++k) {
int offset = k * leafSize;
int end = Math.min(offset + leafSize, top);
PdfDictionary dic = new PdfDictionary();
PdfArray arr = new PdfArray();
arr.add(new PdfNumber(numbers[k * skip]));
arr.add(new PdfNumber(numbers[Math.min((k + 1) * skip, numbers.length) - 1]));
dic.put(PdfName.LIMITS, arr);
arr = new PdfArray();
for (; offset < end; ++offset) {
arr.add(kids[offset]);
}
dic.put(PdfName.KIDS, arr);
kids[k] = writer.addToBody(dic).getIndirectReference();
}
top = tt;
}
| 488
| 770
| 1,258
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfPSXObject.java
|
PdfPSXObject
|
getFormXObject
|
class PdfPSXObject extends PdfTemplate {
/**
* Creates a new instance of PdfPSXObject
*/
protected PdfPSXObject() {
super();
}
/**
* Constructs a PSXObject
*
* @param wr the PdfWriter
*/
public PdfPSXObject(PdfWriter wr) {
super(wr);
}
/**
* Gets the stream representing this object.
*
* @param compressionLevel the compressionLevel
* @return the stream representing this template
* @since 2.1.3 (replacing the method without param compressionLevel)
*/
PdfStream getFormXObject(int compressionLevel) {<FILL_FUNCTION_BODY>}
/**
* Gets a duplicate of this <CODE>PdfPSXObject</CODE>. All the members are copied by reference but the buffer stays
* different.
*
* @return a copy of this <CODE>PdfPSXObject</CODE>
*/
public PdfContentByte getDuplicate() {
PdfPSXObject tpl = new PdfPSXObject();
tpl.writer = writer;
tpl.pdf = pdf;
tpl.thisReference = thisReference;
tpl.pageResources = pageResources;
tpl.separator = separator;
return tpl;
}
}
|
PdfStream s = new PdfStream(content.toByteArray());
s.put(PdfName.TYPE, PdfName.XOBJECT);
s.put(PdfName.SUBTYPE, PdfName.PS);
s.flateCompress(compressionLevel);
return s;
| 354
| 78
| 432
|
<methods>public void beginVariableText() ,public static com.lowagie.text.pdf.PdfTemplate createTemplate(com.lowagie.text.pdf.PdfWriter, float, float) ,public void endVariableText() ,public com.lowagie.text.Rectangle getBoundingBox() ,public com.lowagie.text.pdf.PdfContentByte getDuplicate() ,public com.lowagie.text.pdf.PdfTransparencyGroup getGroup() ,public float getHeight() ,public com.lowagie.text.pdf.PdfIndirectReference getIndirectReference() ,public com.lowagie.text.pdf.PdfOCG getLayer() ,public int getType() ,public float getWidth() ,public void setBoundingBox(com.lowagie.text.Rectangle) ,public void setGroup(com.lowagie.text.pdf.PdfTransparencyGroup) ,public void setHeight(float) ,public void setLayer(com.lowagie.text.pdf.PdfOCG) ,public void setMatrix(float, float, float, float, float, float) ,public void setWidth(float) <variables>public static final int TYPE_IMPORTED,public static final int TYPE_PATTERN,public static final int TYPE_TEMPLATE,protected com.lowagie.text.Rectangle bBox,protected com.lowagie.text.pdf.PdfTransparencyGroup group,protected com.lowagie.text.pdf.PdfOCG layer,protected com.lowagie.text.pdf.PdfArray matrix,protected com.lowagie.text.pdf.PageResources pageResources,protected com.lowagie.text.pdf.PdfIndirectReference thisReference,protected int type
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfPages.java
|
PdfPages
|
reorderPages
|
class PdfPages {
private final ArrayList<PdfIndirectReference> pages = new ArrayList<>();
private final ArrayList<PdfIndirectReference> parents = new ArrayList<>();
private final PdfWriter writer;
private int leafSize = 10;
private PdfIndirectReference topParent;
// constructors
/**
* Constructs a <CODE>PdfPages</CODE>-object.
*/
PdfPages(PdfWriter writer) {
this.writer = writer;
}
void addPage(PdfDictionary page) {
try {
if ((pages.size() % leafSize) == 0) {
parents.add(writer.getPdfIndirectReference());
}
PdfIndirectReference parent = parents.get(parents.size() - 1);
page.put(PdfName.PARENT, parent);
PdfIndirectReference current = writer.getCurrentPage();
writer.addToBody(page, current);
pages.add(current);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
PdfIndirectReference addPageRef(PdfIndirectReference pageRef) {
try {
if ((pages.size() % leafSize) == 0) {
parents.add(writer.getPdfIndirectReference());
}
pages.add(pageRef);
return parents.get(parents.size() - 1);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
// returns the top parent to include in the catalog
PdfIndirectReference writePageTree() throws IOException {
if (pages.isEmpty()) {
throw new IOException(MessageLocalization.getComposedMessage("the.document.has.no.pages"));
}
int leaf = 1;
ArrayList<PdfIndirectReference> tParents = parents;
ArrayList<PdfIndirectReference> tPages = pages;
ArrayList<PdfIndirectReference> nextParents = new ArrayList<>();
while (true) {
leaf *= leafSize;
int stdCount = leafSize;
int rightCount = tPages.size() % leafSize;
if (rightCount == 0) {
rightCount = leafSize;
}
for (int p = 0; p < tParents.size(); ++p) {
int count;
int thisLeaf = leaf;
if (p == tParents.size() - 1) {
count = rightCount;
thisLeaf = pages.size() % leaf;
if (thisLeaf == 0) {
thisLeaf = leaf;
}
} else {
count = stdCount;
}
PdfDictionary top = new PdfDictionary(PdfName.PAGES);
top.put(PdfName.COUNT, new PdfNumber(thisLeaf));
PdfArray kids = new PdfArray(tPages.subList(p * stdCount, p * stdCount + count));
top.put(PdfName.KIDS, kids);
if (tParents.size() > 1) {
if ((p % leafSize) == 0) {
nextParents.add(writer.getPdfIndirectReference());
}
top.put(PdfName.PARENT, nextParents.get(p / leafSize));
}
writer.addToBody(top, tParents.get(p));
}
if (tParents.size() == 1) {
topParent = tParents.get(0);
return topParent;
}
tPages = tParents;
tParents = nextParents;
nextParents = new ArrayList<>();
}
}
void setLinearMode(PdfIndirectReference topParent) {
if (parents.size() > 1) {
throw new RuntimeException(
MessageLocalization.getComposedMessage("linear.page.mode.can.only.be.called.with.a.single.parent"));
}
if (topParent != null) {
this.topParent = topParent;
parents.clear();
parents.add(topParent);
}
leafSize = 10000000;
}
int reorderPages(int[] order) throws DocumentException {<FILL_FUNCTION_BODY>}
}
|
if (order == null) {
return pages.size();
}
if (parents.size() > 1) {
throw new DocumentException(MessageLocalization.getComposedMessage(
"page.reordering.requires.a.single.parent.in.the.page.tree.call.pdfwriter.setlinearmode.after.open"));
}
if (order.length != pages.size()) {
throw new DocumentException(MessageLocalization.getComposedMessage(
"page.reordering.requires.an.array.with.the.same.size.as.the.number.of.pages"));
}
int max = pages.size();
boolean[] temp = new boolean[max];
for (int k = 0; k < max; ++k) {
int p = order[k];
if (p < 1 || p > max) {
throw new DocumentException(
MessageLocalization.getComposedMessage("page.reordering.requires.pages.between.1.and.1.found.2",
String.valueOf(max), String.valueOf(p)));
}
if (temp[p - 1]) {
throw new DocumentException(MessageLocalization.getComposedMessage(
"page.reordering.requires.no.page.repetition.page.1.is.repeated", p));
}
temp[p - 1] = true;
}
PdfIndirectReference[] copy = pages.toArray(new PdfIndirectReference[0]);
for (int k = 0; k < max; ++k) {
pages.set(k, copy[order[k] - 1]);
}
return max;
| 1,081
| 424
| 1,505
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfPublicKeySecurityHandler.java
|
PdfPublicKeySecurityHandler
|
computeRecipientInfo
|
class PdfPublicKeySecurityHandler {
static final int SEED_LENGTH = 20;
private final List<PdfPublicKeyRecipient> recipients;
private byte[] seed = new byte[SEED_LENGTH];
public PdfPublicKeySecurityHandler() {
KeyGenerator key;
try {
key = KeyGenerator.getInstance("AES");
key.init(192, new SecureRandom());
SecretKey sk = key.generateKey();
System.arraycopy(sk.getEncoded(), 0, seed, 0, SEED_LENGTH); // create the
// 20 bytes
// seed
} catch (NoSuchAlgorithmException e) {
seed = SecureRandom.getSeed(SEED_LENGTH);
}
recipients = new ArrayList<>();
}
public void addRecipient(PdfPublicKeyRecipient recipient) {
recipients.add(recipient);
}
protected byte[] getSeed() {
return seed.clone();
}
/*
* public PdfPublicKeyRecipient[] getRecipients() { recipients.toArray();
* return (PdfPublicKeyRecipient[])recipients.toArray(); }
*/
public int getRecipientsSize() {
return recipients.size();
}
public byte[] getEncodedRecipient(int index) throws IOException,
GeneralSecurityException {
// Certificate certificate = recipient.getX509();
PdfPublicKeyRecipient recipient = recipients
.get(index);
byte[] cms = recipient.getCms();
if (cms != null) {
return cms;
}
Certificate certificate = recipient.getCertificate();
int permission = recipient.getPermission();
permission |= 0xfffff0c0;
permission &= 0xfffffffc;
permission += 1;
byte[] pkcs7input = new byte[24];
byte one = (byte) (permission);
byte two = (byte) (permission >> 8);
byte three = (byte) (permission >> 16);
byte four = (byte) (permission >> 24);
System.arraycopy(seed, 0, pkcs7input, 0, 20); // put this seed in the pkcs7
// input
pkcs7input[20] = four;
pkcs7input[21] = three;
pkcs7input[22] = two;
pkcs7input[23] = one;
ASN1Primitive obj = createDERForRecipient(pkcs7input,
(X509Certificate) certificate);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ASN1OutputStream derOutputStream = ASN1OutputStream.create(baos, ASN1Encoding.DER);
derOutputStream.writeObject(obj);
cms = baos.toByteArray();
recipient.setCms(cms);
return cms;
}
public PdfArray getEncodedRecipients() throws IOException {
PdfArray encodedRecipients = new PdfArray();
byte[] cms;
for (int i = 0; i < recipients.size(); i++) {
try {
cms = getEncodedRecipient(i);
encodedRecipients.add(new PdfLiteral(PdfContentByte.escapeString(cms)));
} catch (GeneralSecurityException | IOException e) {
encodedRecipients = null;
break;
}
}
return encodedRecipients;
}
private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert)
throws IOException, GeneralSecurityException {
String s = "1.2.840.113549.3.2";
AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator
.getInstance(s);
AlgorithmParameters algorithmparameters = algorithmparametergenerator
.generateParameters();
ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(
algorithmparameters.getEncoded("ASN.1"));
ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
ASN1Primitive derobject = asn1inputstream.readObject();
KeyGenerator keygenerator = KeyGenerator.getInstance(s);
keygenerator.init(128);
SecretKey secretkey = keygenerator.generateKey();
Cipher cipher = Cipher.getInstance(s);
cipher.init(1, secretkey, algorithmparameters);
byte[] abyte1 = cipher.doFinal(in);
DEROctetString deroctetstring = new DEROctetString(abyte1);
KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert,
secretkey.getEncoded());
DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(
new ASN1ObjectIdentifier(s), derobject);
EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(
PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
ASN1Set set = null;
EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo,
set);
ContentInfo contentinfo = new ContentInfo(
PKCSObjectIdentifiers.envelopedData, env);
// OJO... Modificacion de
// Felix--------------------------------------------------
// return contentinfo.getDERObject();
return contentinfo.toASN1Primitive();
// ******************************************************************************
}
private KeyTransRecipientInfo computeRecipientInfo(
X509Certificate x509certificate, byte[] abyte0)
throws GeneralSecurityException, IOException {<FILL_FUNCTION_BODY>}
}
|
ASN1InputStream asn1inputstream = new ASN1InputStream(
new ByteArrayInputStream(x509certificate.getTBSCertificate()));
TBSCertificate tbsCertificate = TBSCertificate.getInstance(asn1inputstream.readObject());
AlgorithmIdentifier algorithmidentifier = tbsCertificate.getSubjectPublicKeyInfo().getAlgorithm();
IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(
tbsCertificate.getIssuer(), tbsCertificate.getSerialNumber().getValue());
Cipher cipher = Cipher.getInstance(algorithmidentifier.getAlgorithm().getId());
cipher.init(1, x509certificate);
DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring);
| 1,495
| 244
| 1,739
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfReaderInstance.java
|
PdfReaderInstance
|
getNewObjectNumber
|
class PdfReaderInstance {
static final PdfLiteral IDENTITYMATRIX = new PdfLiteral("[1 0 0 1 0 0]");
static final PdfNumber ONE = new PdfNumber(1);
int[] myXref;
PdfReader reader;
RandomAccessFileOrArray file;
HashMap<Integer, PdfImportedPage> importedPages = new HashMap<>();
PdfWriter writer;
HashMap<Integer, ?> visited = new HashMap<>();
ArrayList<Integer> nextRound = new ArrayList<>();
PdfReaderInstance(PdfReader reader, PdfWriter writer) {
this.reader = reader;
this.writer = writer;
file = reader.getSafeFile();
myXref = new int[reader.getXrefSize()];
}
PdfReader getReader() {
return reader;
}
PdfImportedPage getImportedPage(int pageNumber) {
if (!reader.isOpenedWithFullPermissions()) {
throw new IllegalArgumentException(
MessageLocalization.getComposedMessage("pdfreader.not.opened.with.owner.password"));
}
if (pageNumber < 1 || pageNumber > reader.getNumberOfPages()) {
throw new IllegalArgumentException(
MessageLocalization.getComposedMessage("invalid.page.number.1", pageNumber));
}
Integer i = pageNumber;
PdfImportedPage pageT = importedPages.get(i);
if (pageT == null) {
pageT = new PdfImportedPage(this, writer, pageNumber);
importedPages.put(i, pageT);
}
return pageT;
}
int getNewObjectNumber(int number, int generation) {<FILL_FUNCTION_BODY>}
RandomAccessFileOrArray getReaderFile() {
return file;
}
PdfObject getResources(int pageNumber) {
PdfObject obj = PdfReader.getPdfObjectRelease(reader.getPageNRelease(pageNumber).get(PdfName.RESOURCES));
return obj;
}
/**
* Gets the content stream of a page as a PdfStream object.
*
* @param pageNumber the page of which you want the stream
* @param compressionLevel the compression level you want to apply to the stream
* @return a PdfStream object
* @since 2.1.3 (the method already existed without param compressionLevel)
*/
PdfStream getFormXObject(int pageNumber, int compressionLevel) throws IOException {
PdfDictionary page = reader.getPageNRelease(pageNumber);
PdfObject contents = PdfReader.getPdfObjectRelease(page.get(PdfName.CONTENTS));
PdfDictionary dic = new PdfDictionary();
byte[] bout = null;
if (contents != null) {
if (contents.isStream()) {
dic.putAll((PRStream) contents);
} else {
bout = reader.getPageContent(pageNumber, file);
}
} else {
bout = new byte[0];
}
dic.put(PdfName.RESOURCES, PdfReader.getPdfObjectRelease(page.get(PdfName.RESOURCES)));
dic.put(PdfName.TYPE, PdfName.XOBJECT);
dic.put(PdfName.SUBTYPE, PdfName.FORM);
PdfImportedPage impPage = importedPages.get(pageNumber);
dic.put(PdfName.BBOX, new PdfRectangle(impPage.getBoundingBox()));
PdfArray matrix = impPage.getMatrix();
if (matrix == null) {
dic.put(PdfName.MATRIX, IDENTITYMATRIX);
} else {
dic.put(PdfName.MATRIX, matrix);
}
dic.put(PdfName.FORMTYPE, ONE);
PRStream stream;
if (bout == null) {
stream = new PRStream((PRStream) contents, dic);
} else {
stream = new PRStream(reader, bout, compressionLevel);
stream.putAll(dic);
}
return stream;
}
void writeAllVisited() throws IOException {
while (!nextRound.isEmpty()) {
List<Integer> vec = nextRound;
nextRound = new ArrayList<>();
for (Integer i : vec) {
if (!visited.containsKey(i)) {
visited.put(i, null);
int n = i;
writer.addToBody(reader.getPdfObjectRelease(n), myXref[n]);
}
}
}
}
void writeAllPages() throws IOException {
try {
file.reOpen();
for (Object o : importedPages.values()) {
PdfImportedPage ip = (PdfImportedPage) o;
writer.addToBody(ip.getFormXObject(writer.getCompressionLevel()), ip.getIndirectReference());
}
writeAllVisited();
} finally {
try {
reader.close();
file.close();
} catch (Exception e) {
//Empty on purpose
}
}
}
}
|
if (myXref[number] == 0) {
myXref[number] = writer.getIndirectReferenceNumber();
nextRound.add(number);
}
return myXref[number];
| 1,326
| 56
| 1,382
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfResources.java
|
PdfResources
|
add
|
class PdfResources extends PdfDictionary {
// constructor
/**
* Constructs a PDF ResourcesDictionary.
*/
public PdfResources() {
super();
}
// methods
void add(PdfName key, PdfDictionary resource) {<FILL_FUNCTION_BODY>}
}
|
if (resource.size() == 0) {
return;
}
PdfDictionary dic = getAsDict(key);
if (dic == null) {
put(key, resource);
} else {
dic.putAll(resource);
}
| 84
| 70
| 154
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.PdfName) ,public void clear() ,public boolean contains(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject get(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfArray getAsArray(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfBoolean getAsBoolean(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfDictionary getAsDict(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfIndirectReference getAsIndirectObject(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfName getAsName(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfNumber getAsNumber(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfStream getAsStream(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfString getAsString(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject getDirectObject(com.lowagie.text.pdf.PdfName) ,public Set<com.lowagie.text.pdf.PdfName> getKeys() ,public Set<Entry<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject>> getKeysAndValues() ,public boolean isCatalog() ,public boolean isFont() ,public boolean isOutlineTree() ,public boolean isPage() ,public boolean isPages() ,public void merge(com.lowagie.text.pdf.PdfDictionary) ,public void mergeDifferent(com.lowagie.text.pdf.PdfDictionary) ,public void put(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void putAll(com.lowagie.text.pdf.PdfDictionary) ,public void putEx(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void remove(com.lowagie.text.pdf.PdfName) ,public int size() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() <variables>public static final com.lowagie.text.pdf.PdfName CATALOG,public static final com.lowagie.text.pdf.PdfName FONT,public static final com.lowagie.text.pdf.PdfName OUTLINES,public static final com.lowagie.text.pdf.PdfName PAGE,public static final com.lowagie.text.pdf.PdfName PAGES,private com.lowagie.text.pdf.PdfName dictionaryType,protected Map<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject> hashMap
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfShadingPattern.java
|
PdfShadingPattern
|
getPatternReference
|
class PdfShadingPattern extends PdfDictionary {
protected PdfShading shading;
protected PdfWriter writer;
protected float[] matrix = {1, 0, 0, 1, 0, 0};
protected PdfName patternName;
protected PdfIndirectReference patternReference;
/**
* Creates new PdfShadingPattern
*
* @param shading the shading
*/
public PdfShadingPattern(PdfShading shading) {
writer = shading.getWriter();
put(PdfName.PATTERNTYPE, new PdfNumber(2));
this.shading = shading;
}
PdfName getPatternName() {
return patternName;
}
PdfName getShadingName() {
return shading.getShadingName();
}
PdfIndirectReference getPatternReference() {<FILL_FUNCTION_BODY>}
PdfIndirectReference getShadingReference() {
return shading.getShadingReference();
}
void setName(int number) {
patternName = new PdfName("P" + number);
}
void addToBody() throws IOException {
put(PdfName.SHADING, getShadingReference());
put(PdfName.MATRIX, new PdfArray(matrix));
writer.addToBody(this, getPatternReference());
}
public float[] getMatrix() {
return matrix;
}
public void setMatrix(float[] matrix) {
if (matrix.length != 6) {
throw new RuntimeException(MessageLocalization.getComposedMessage("the.matrix.size.must.be.6"));
}
this.matrix = matrix;
}
public PdfShading getShading() {
return shading;
}
ColorDetails getColorDetails() {
return shading.getColorDetails();
}
}
|
if (patternReference == null) {
patternReference = writer.getPdfIndirectReference();
}
return patternReference;
| 497
| 36
| 533
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.PdfName) ,public void clear() ,public boolean contains(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject get(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfArray getAsArray(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfBoolean getAsBoolean(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfDictionary getAsDict(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfIndirectReference getAsIndirectObject(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfName getAsName(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfNumber getAsNumber(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfStream getAsStream(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfString getAsString(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject getDirectObject(com.lowagie.text.pdf.PdfName) ,public Set<com.lowagie.text.pdf.PdfName> getKeys() ,public Set<Entry<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject>> getKeysAndValues() ,public boolean isCatalog() ,public boolean isFont() ,public boolean isOutlineTree() ,public boolean isPage() ,public boolean isPages() ,public void merge(com.lowagie.text.pdf.PdfDictionary) ,public void mergeDifferent(com.lowagie.text.pdf.PdfDictionary) ,public void put(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void putAll(com.lowagie.text.pdf.PdfDictionary) ,public void putEx(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void remove(com.lowagie.text.pdf.PdfName) ,public int size() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() <variables>public static final com.lowagie.text.pdf.PdfName CATALOG,public static final com.lowagie.text.pdf.PdfName FONT,public static final com.lowagie.text.pdf.PdfName OUTLINES,public static final com.lowagie.text.pdf.PdfName PAGE,public static final com.lowagie.text.pdf.PdfName PAGES,private com.lowagie.text.pdf.PdfName dictionaryType,protected Map<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject> hashMap
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfSigGenericPKCS.java
|
PdfSigGenericPKCS
|
setSignInfo
|
class PdfSigGenericPKCS extends PdfSignature {
/**
* The hash algorithm, for example "SHA1"
*/
protected String hashAlgorithm;
/**
* The crypto provider
*/
protected String provider = null;
/**
* The class instance that calculates the PKCS#1 and PKCS#7
*/
protected PdfPKCS7 pkcs;
/**
* The subject name in the signing certificate (the element "CN")
*/
protected String name;
private byte[] externalDigest;
private byte[] externalRSAdata;
private String digestEncryptionAlgorithm;
/**
* Creates a generic standard filter.
*
* @param filter the filter name
* @param subFilter the sub-filter name
*/
public PdfSigGenericPKCS(PdfName filter, PdfName subFilter) {
super(filter, subFilter);
}
/**
* Sets the crypto information to sign.
*
* @param privKey the private key
* @param certChain the certificate chain
* @param crlList the certificate revocation list. It can be <CODE>null</CODE>
*/
public void setSignInfo(PrivateKey privKey, Certificate[] certChain, CRL[] crlList) {<FILL_FUNCTION_BODY>}
/**
* Sets the digest/signature to an external calculated value.
*
* @param digest the digest. This is the actual signature
* @param RSAdata the extra data that goes into the data tag in PKCS#7
* @param digestEncryptionAlgorithm the encryption algorithm. It may must be <CODE>null</CODE> if the
* <CODE>digest</CODE> is also <CODE>null</CODE>. If the <CODE>digest</CODE> is
* not
* <CODE>null</CODE> then it may be "RSA" or "DSA"
*/
public void setExternalDigest(byte[] digest, byte[] RSAdata, String digestEncryptionAlgorithm) {
externalDigest = digest;
externalRSAdata = RSAdata;
this.digestEncryptionAlgorithm = digestEncryptionAlgorithm;
}
/**
* Gets the subject name in the signing certificate (the element "CN")
*
* @return the subject name in the signing certificate (the element "CN")
*/
public String getName() {
return name;
}
/**
* Gets the class instance that does the actual signing.
*
* @return the class instance that does the actual signing
*/
public PdfPKCS7 getSigner() {
return pkcs;
}
/**
* Gets the signature content. This can be a PKCS#1 or a PKCS#7. It corresponds to the /Contents key.
*
* @return the signature content
*/
public byte[] getSignerContents() {
if (PdfName.ADBE_X509_RSA_SHA1.equals(get(PdfName.SUBFILTER))) {
return pkcs.getEncodedPKCS1();
} else {
return pkcs.getEncodedPKCS7();
}
}
/**
* Creates a standard filter of the type VeriSign.
*/
public static class VeriSign extends PdfSigGenericPKCS {
/**
* The constructor for the default provider.
*/
public VeriSign() {
super(PdfName.VERISIGN_PPKVS, PdfName.ADBE_PKCS7_DETACHED);
hashAlgorithm = "MD5";
put(PdfName.R, new PdfNumber(65537));
}
/**
* The constructor for an explicit provider.
*
* @param provider the crypto provider
*/
public VeriSign(String provider) {
this();
this.provider = provider;
}
}
/**
* Creates a standard filter of the type self signed.
*/
public static class PPKLite extends PdfSigGenericPKCS {
/**
* The constructor for the default provider.
*/
public PPKLite() {
super(PdfName.ADOBE_PPKLITE, PdfName.ADBE_X509_RSA_SHA1);
hashAlgorithm = "SHA1";
put(PdfName.R, new PdfNumber(65541));
}
/**
* The constructor for an explicit provider.
*
* @param provider the crypto provider
*/
public PPKLite(String provider) {
this();
this.provider = provider;
}
}
/**
* Creates a standard filter of the type Windows Certificate.
*/
public static class PPKMS extends PdfSigGenericPKCS {
/**
* The constructor for the default provider.
*/
public PPKMS() {
super(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
hashAlgorithm = "SHA1";
}
/**
* The constructor for an explicit provider.
*
* @param provider the crypto provider
*/
public PPKMS(String provider) {
this();
this.provider = provider;
}
}
}
|
try {
pkcs = new PdfPKCS7(privKey, certChain, crlList, hashAlgorithm, provider,
PdfName.ADBE_PKCS7_SHA1.equals(get(PdfName.SUBFILTER)));
pkcs.setExternalDigest(externalDigest, externalRSAdata, digestEncryptionAlgorithm);
if (PdfName.ADBE_X509_RSA_SHA1.equals(get(PdfName.SUBFILTER))) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
for (Certificate certificate : certChain) {
bout.write(certificate.getEncoded());
}
bout.close();
setCert(bout.toByteArray());
setContents(pkcs.getEncodedPKCS1());
} else {
setContents(pkcs.getEncodedPKCS7());
}
name = PdfPKCS7.getSubjectFields(pkcs.getSigningCertificate()).getField("CN");
if (name != null) {
put(PdfName.NAME, new PdfString(name, PdfObject.TEXT_UNICODE));
}
pkcs = new PdfPKCS7(privKey, certChain, crlList, hashAlgorithm, provider,
PdfName.ADBE_PKCS7_SHA1.equals(get(PdfName.SUBFILTER)));
pkcs.setExternalDigest(externalDigest, externalRSAdata, digestEncryptionAlgorithm);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
| 1,375
| 400
| 1,775
|
<methods>public void <init>(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfSignatureBuildProperties getPdfSignatureBuildProperties() ,public void setByteRange(int[]) ,public void setCert(byte[]) ,public void setContact(java.lang.String) ,public void setContents(byte[]) ,public void setDate(com.lowagie.text.pdf.PdfDate) ,public void setLocation(java.lang.String) ,public void setName(java.lang.String) ,public void setReason(java.lang.String) <variables>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfSignature.java
|
PdfSignature
|
setByteRange
|
class PdfSignature extends PdfDictionary {
/**
* Creates new PdfSignature
*
* @param filter the filter
* @param subFilter the sub filter
*/
public PdfSignature(PdfName filter, PdfName subFilter) {
super(PdfName.SIG);
put(PdfName.FILTER, filter);
put(PdfName.SUBFILTER, subFilter);
}
public void setByteRange(int[] range) {<FILL_FUNCTION_BODY>}
public void setContents(byte[] contents) {
put(PdfName.CONTENTS, new PdfString(contents).setHexWriting(true));
}
public void setCert(byte[] cert) {
put(PdfName.CERT, new PdfString(cert));
}
public void setName(String name) {
put(PdfName.NAME, new PdfString(name, PdfObject.TEXT_UNICODE));
}
public void setDate(PdfDate date) {
put(PdfName.M, date);
}
public void setLocation(String name) {
put(PdfName.LOCATION, new PdfString(name, PdfObject.TEXT_UNICODE));
}
public void setReason(String name) {
put(PdfName.REASON, new PdfString(name, PdfObject.TEXT_UNICODE));
}
public void setContact(String name) {
put(PdfName.CONTACTINFO, new PdfString(name, PdfObject.TEXT_UNICODE));
}
/**
* Return the build properties dictionary (PDF Dictionary name: Prop_Build)
*
* @return the build properties dictionary
*/
public PdfSignatureBuildProperties getPdfSignatureBuildProperties() {
PdfSignatureBuildProperties buildPropDic = (PdfSignatureBuildProperties) getAsDict(PdfName.PROP_BUILD);
if (buildPropDic == null) {
buildPropDic = new PdfSignatureBuildProperties();
put(PdfName.PROP_BUILD, buildPropDic);
}
return buildPropDic;
}
}
|
PdfArray array = new PdfArray();
for (int i : range) {
array.add(new PdfNumber(i));
}
put(PdfName.BYTERANGE, array);
| 565
| 55
| 620
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.PdfName) ,public void clear() ,public boolean contains(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject get(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfArray getAsArray(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfBoolean getAsBoolean(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfDictionary getAsDict(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfIndirectReference getAsIndirectObject(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfName getAsName(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfNumber getAsNumber(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfStream getAsStream(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfString getAsString(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject getDirectObject(com.lowagie.text.pdf.PdfName) ,public Set<com.lowagie.text.pdf.PdfName> getKeys() ,public Set<Entry<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject>> getKeysAndValues() ,public boolean isCatalog() ,public boolean isFont() ,public boolean isOutlineTree() ,public boolean isPage() ,public boolean isPages() ,public void merge(com.lowagie.text.pdf.PdfDictionary) ,public void mergeDifferent(com.lowagie.text.pdf.PdfDictionary) ,public void put(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void putAll(com.lowagie.text.pdf.PdfDictionary) ,public void putEx(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void remove(com.lowagie.text.pdf.PdfName) ,public int size() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() <variables>public static final com.lowagie.text.pdf.PdfName CATALOG,public static final com.lowagie.text.pdf.PdfName FONT,public static final com.lowagie.text.pdf.PdfName OUTLINES,public static final com.lowagie.text.pdf.PdfName PAGE,public static final com.lowagie.text.pdf.PdfName PAGES,private com.lowagie.text.pdf.PdfName dictionaryType,protected Map<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject> hashMap
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfSignatureBuildProperties.java
|
PdfSignatureBuildProperties
|
getPdfSignatureAppProperty
|
class PdfSignatureBuildProperties extends PdfDictionary {
public PdfSignatureBuildProperties() {
super();
}
/**
* Returns the {@link PdfSignatureAppDataDict} from this dictionary. If it doesn't exist, a new
* {@link PdfSignatureAppDataDict} is added.
*
* @return {@link PdfSignatureAppDataDict}
*/
public PdfSignatureAppDataDict getPdfSignatureAppProperty() {<FILL_FUNCTION_BODY>}
}
|
PdfSignatureAppDataDict appPropDic = (PdfSignatureAppDataDict) getAsDict(PdfName.APP);
if (appPropDic == null) {
appPropDic = new PdfSignatureAppDataDict();
put(PdfName.APP, appPropDic);
}
return appPropDic;
| 131
| 91
| 222
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.PdfName) ,public void clear() ,public boolean contains(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject get(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfArray getAsArray(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfBoolean getAsBoolean(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfDictionary getAsDict(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfIndirectReference getAsIndirectObject(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfName getAsName(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfNumber getAsNumber(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfStream getAsStream(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfString getAsString(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject getDirectObject(com.lowagie.text.pdf.PdfName) ,public Set<com.lowagie.text.pdf.PdfName> getKeys() ,public Set<Entry<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject>> getKeysAndValues() ,public boolean isCatalog() ,public boolean isFont() ,public boolean isOutlineTree() ,public boolean isPage() ,public boolean isPages() ,public void merge(com.lowagie.text.pdf.PdfDictionary) ,public void mergeDifferent(com.lowagie.text.pdf.PdfDictionary) ,public void put(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void putAll(com.lowagie.text.pdf.PdfDictionary) ,public void putEx(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void remove(com.lowagie.text.pdf.PdfName) ,public int size() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() <variables>public static final com.lowagie.text.pdf.PdfName CATALOG,public static final com.lowagie.text.pdf.PdfName FONT,public static final com.lowagie.text.pdf.PdfName OUTLINES,public static final com.lowagie.text.pdf.PdfName PAGE,public static final com.lowagie.text.pdf.PdfName PAGES,private com.lowagie.text.pdf.PdfName dictionaryType,protected Map<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject> hashMap
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfSmartCopy.java
|
PdfSmartCopy
|
copyIndirect
|
class PdfSmartCopy extends PdfCopy {
/**
* the cache with the streams and references.
*/
private Map<ByteStore, PdfIndirectReference> streamMap = null;
/**
* Creates a PdfSmartCopy instance.
*
* @param os the OutputStream
* @param document the document
* @throws DocumentException on error
*/
public PdfSmartCopy(Document document, OutputStream os) throws DocumentException {
super(document, os);
this.streamMap = new HashMap<>();
}
/**
* Translate a PRIndirectReference to a PdfIndirectReference In addition, translates the object numbers, and copies
* the referenced object to the output file if it wasn't available in the cache yet. If it's in the cache, the
* reference to the already used stream is returned.
* <p>
* NB: PRIndirectReferences (and PRIndirectObjects) really need to know what file they came from, because each file
* has its own namespace. The translation we do from their namespace to ours is *at best* heuristic, and guaranteed
* to fail under some circumstances.
*/
protected PdfIndirectReference copyIndirect(PRIndirectReference in) throws IOException, BadPdfFormatException {<FILL_FUNCTION_BODY>}
static class ByteStore {
private final int MAX_LEVELS = 100;
private byte[] b;
private int hash;
private MessageDigest md5;
ByteStore(PRStream str) throws IOException {
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
throw new ExceptionConverter(e);
}
ByteBuffer bb = new ByteBuffer();
int level = MAX_LEVELS;
serObject(str, level, bb);
this.b = bb.toByteArray();
md5 = null;
}
private void serObject(PdfObject obj, int level, ByteBuffer bb) throws IOException {
if (level <= 0) {
throw new IOException("Max level reached");
}
if (obj == null) {
bb.append("$Lnull");
return;
}
obj = PdfReader.getPdfObject(obj);
if (obj.isStream()) {
bb.append("$B");
serDic((PdfDictionary) obj, level - 1, bb);
md5.reset();
bb.append(md5.digest(PdfReader.getStreamBytesRaw((PRStream) obj)));
} else if (obj.isDictionary()) {
serDic((PdfDictionary) obj, level - 1, bb);
} else if (obj.isArray()) {
serArray((PdfArray) obj, level - 1, bb);
} else if (obj.isString()) {
bb.append("$S").append(obj.toString());
} else if (obj.isName()) {
bb.append("$N").append(obj.toString());
} else {
bb.append("$L").append(obj.toString());
}
}
private void serDic(PdfDictionary dic, int level, ByteBuffer bb) throws IOException {
bb.append("$D");
if (level <= 0) {
throw new IOException("Max level reached");
}
Object[] keys = dic.getKeys().toArray();
Arrays.sort(keys);
for (Object key : keys) {
serObject((PdfObject) key, level, bb);
serObject(dic.get((PdfName) key), level, bb);
}
}
private void serArray(PdfArray array, int level, ByteBuffer bb) throws IOException {
bb.append("$A");
if (level <= 0) {
throw new IOException("Max level reached");
}
for (int k = 0; k < array.size(); ++k) {
serObject(array.getPdfObject(k), level, bb);
}
}
public boolean equals(Object obj) {
if (!(obj instanceof ByteStore)) {
return false;
}
if (hashCode() != obj.hashCode()) {
return false;
}
return Arrays.equals(b, ((ByteStore) obj).b);
}
public int hashCode() {
if (hash == 0) {
for (byte b1 : b) {
hash = hash * 31 + (b1 & 0xff);
}
}
return hash;
}
}
}
|
PdfObject srcObj = PdfReader.getPdfObjectRelease(in);
ByteStore streamKey = null;
boolean validStream = false;
if (srcObj == null) {
return null;
}
if (srcObj.isStream()) {
try {
streamKey = new ByteStore((PRStream) srcObj);
validStream = true;
PdfIndirectReference streamRef = streamMap.get(streamKey);
if (streamRef != null) {
return streamRef;
}
} catch (IOException ioe) {
//
}
}
PdfIndirectReference theRef;
RefKey key = new RefKey(in);
IndirectReferences iRef = indirects.get(key);
if (iRef != null) {
theRef = iRef.getRef();
if (iRef.getCopied()) {
return theRef;
}
} else {
theRef = body.getPdfIndirectReference();
iRef = new IndirectReferences(theRef);
indirects.put(key, iRef);
}
if (srcObj.isDictionary()) {
PdfObject type = PdfReader.getPdfObjectRelease(((PdfDictionary) srcObj).get(PdfName.TYPE));
if (PdfName.PAGE.equals(type)) {
return theRef;
}
}
iRef.setCopied();
if (validStream) {
streamMap.put(streamKey, theRef);
}
PdfObject obj = copyObject(srcObj);
addToBody(obj, theRef);
return theRef;
| 1,169
| 421
| 1,590
|
<methods>public void <init>(com.lowagie.text.Document, java.io.OutputStream) throws com.lowagie.text.DocumentException,public com.lowagie.text.pdf.PdfIndirectReference add(com.lowagie.text.pdf.PdfOutline) ,public void addAnnotation(com.lowagie.text.pdf.PdfAnnotation) ,public void addPage(com.lowagie.text.pdf.PdfImportedPage) throws java.io.IOException, com.lowagie.text.pdf.BadPdfFormatException,public void addPage(com.lowagie.text.Rectangle, int) ,public void close() ,public void copyAcroForm(com.lowagie.text.pdf.PdfReader) throws java.io.IOException, com.lowagie.text.pdf.BadPdfFormatException,public com.lowagie.text.pdf.PdfCopy.PageStamp createPageStamp(com.lowagie.text.pdf.PdfImportedPage) ,public void freeReader(com.lowagie.text.pdf.PdfReader) throws java.io.IOException,public com.lowagie.text.pdf.PdfImportedPage getImportedPage(com.lowagie.text.pdf.PdfReader, int) ,public boolean isRotateContents() ,public void setRotateContents(boolean) <variables>protected com.lowagie.text.pdf.PdfIndirectReference acroForm,protected com.lowagie.text.pdf.PdfArray fieldArray,protected HashMap<com.lowagie.text.pdf.PdfTemplate,java.lang.Object> fieldTemplates,protected HashMap<com.lowagie.text.pdf.PdfReader,HashMap<com.lowagie.text.pdf.PdfCopy.RefKey,com.lowagie.text.pdf.PdfCopy.IndirectReferences>> indirectMap,protected HashMap<com.lowagie.text.pdf.PdfCopy.RefKey,com.lowagie.text.pdf.PdfCopy.IndirectReferences> indirects,protected int[] namePtr,protected com.lowagie.text.pdf.PdfReader reader,private boolean rotateContents
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfSpotColor.java
|
PdfSpotColor
|
getSpotObject
|
class PdfSpotColor {
/**
* The color name
*/
public PdfName name;
/**
* The alternative color space
*/
public Color altcs;
// constructors
/**
* Constructs a new <CODE>PdfSpotColor</CODE>.
*
* @param name a String value
* @param altcs an alternative colorspace value
*/
public PdfSpotColor(String name, Color altcs) {
this.name = new PdfName(name);
this.altcs = altcs;
}
/**
* Gets the alternative ColorSpace.
*
* @return a Color
*/
public Color getAlternativeCS() {
return altcs;
}
protected PdfObject getSpotObject(PdfWriter writer) {<FILL_FUNCTION_BODY>}
}
|
PdfArray array = new PdfArray(PdfName.SEPARATION);
array.add(name);
PdfFunction func = null;
if (altcs instanceof ExtendedColor) {
int type = ((ExtendedColor) altcs).type;
switch (type) {
case ExtendedColor.TYPE_GRAY:
array.add(PdfName.DEVICEGRAY);
func = PdfFunction.type2(writer, new float[]{0, 1}, null, new float[]{0},
new float[]{((GrayColor) altcs).getGray()}, 1);
break;
case ExtendedColor.TYPE_CMYK:
array.add(PdfName.DEVICECMYK);
CMYKColor cmyk = (CMYKColor) altcs;
func = PdfFunction.type2(writer, new float[]{0, 1}, null, new float[]{0, 0, 0, 0},
new float[]{cmyk.getCyan(), cmyk.getMagenta(), cmyk.getYellow(), cmyk.getBlack()}, 1);
break;
default:
throw new RuntimeException(MessageLocalization.getComposedMessage(
"only.rgb.gray.and.cmyk.are.supported.as.alternative.color.spaces"));
}
} else {
array.add(PdfName.DEVICERGB);
func = PdfFunction.type2(writer, new float[]{0, 1}, null, new float[]{1, 1, 1},
new float[]{(float) altcs.getRed() / 255, (float) altcs.getGreen() / 255,
(float) altcs.getBlue() / 255}, 1);
}
array.add(func.getReference());
return array;
| 228
| 465
| 693
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfString.java
|
PdfString
|
getOriginalChars
|
class PdfString extends PdfObject {
// CLASS VARIABLES
/**
* The value of this object.
*/
protected String value = NOTHING;
protected String originalValue = null;
/**
* The encoding.
*/
protected String encoding = TEXT_PDFDOCENCODING;
protected int objNum = 0;
protected int objGen = 0;
protected boolean hexWriting = false;
// CONSTRUCTORS
/**
* Constructs an empty <CODE>PdfString</CODE>-object.
*/
public PdfString() {
super(STRING);
}
/**
* Constructs a <CODE>PdfString</CODE>-object containing a string in the standard encoding
* <CODE>TEXT_PDFDOCENCODING</CODE>.
*
* @param value the content of the string
*/
public PdfString(String value) {
super(STRING);
this.value = value;
}
/**
* Constructs a <CODE>PdfString</CODE>-object containing a string in the specified encoding.
*
* @param value the content of the string
* @param encoding an encoding
*/
public PdfString(String value, String encoding) {
super(STRING);
this.value = value;
this.encoding = encoding;
}
/**
* Constructs a <CODE>PdfString</CODE>-object.
*
* @param bytes an array of <CODE>byte</CODE>
*/
public PdfString(byte[] bytes) {
super(STRING);
value = PdfEncodings.convertToString(bytes, null);
encoding = NOTHING;
}
// methods overriding some methods in PdfObject
/**
* Writes the PDF representation of this <CODE>PdfString</CODE> as an array of <CODE>byte</CODE> to the specified
* <CODE>OutputStream</CODE>.
*
* @param writer for backwards compatibility
* @param os The <CODE>OutputStream</CODE> to write the bytes to.
*/
public void toPdf(PdfWriter writer, OutputStream os) throws IOException {
byte[] b = getBytes();
PdfEncryption crypto = null;
if (writer != null) {
crypto = writer.getEncryption();
}
if (crypto != null && !crypto.isEmbeddedFilesOnly()) {
b = crypto.encryptByteArray(b);
}
if (hexWriting) {
ByteBuffer buf = new ByteBuffer();
buf.append('<');
int len = b.length;
for (byte b1 : b) {
buf.appendHex(b1);
}
buf.append('>');
os.write(buf.toByteArray());
} else {
os.write(PdfContentByte.escapeString(b));
}
}
/**
* Returns the <CODE>String</CODE> value of this <CODE>PdfString</CODE>-object.
*
* @return A <CODE>String</CODE>
*/
public String toString() {
return value;
}
public byte[] getBytes() {
if (bytes == null) {
if (encoding != null && encoding.equals(TEXT_UNICODE) && PdfEncodings.isPdfDocEncoding(value)) {
bytes = PdfEncodings.convertToBytes(value, TEXT_PDFDOCENCODING);
} else {
bytes = PdfEncodings.convertToBytes(value, encoding);
}
}
return bytes;
}
// other methods
/**
* Returns the Unicode <CODE>String</CODE> value of this
* <CODE>PdfString</CODE>-object.
*
* @return A <CODE>String</CODE>
*/
public String toUnicodeString() {
if (encoding != null && encoding.length() != 0) {
return value;
}
getBytes();
if (bytes.length >= 2 && bytes[0] == (byte) 254 && bytes[1] == (byte) 255) {
return PdfEncodings.convertToString(bytes, PdfObject.TEXT_UNICODE);
} else {
return PdfEncodings.convertToString(bytes, PdfObject.TEXT_PDFDOCENCODING);
}
}
/**
* Gets the encoding of this string.
*
* @return a <CODE>String</CODE>
*/
public String getEncoding() {
return encoding;
}
void setObjNum(int objNum, int objGen) {
this.objNum = objNum;
this.objGen = objGen;
}
/**
* Decrypt an encrypted <CODE>PdfString</CODE>
*/
void decrypt(PdfReader reader) {
PdfEncryption decrypt = reader.getDecrypt();
if (decrypt != null) {
originalValue = value;
decrypt.setHashKey(objNum, objGen);
bytes = PdfEncodings.convertToBytes(value, null);
bytes = decrypt.decryptByteArray(bytes);
value = PdfEncodings.convertToString(bytes, null);
}
}
/**
* @return The original bytes used to create this PDF string, or the bytes of our current value if the original
* bytes are missing.
*/
public byte[] getOriginalBytes() {
if (originalValue == null) {
return getBytes();
}
return PdfEncodings.convertToBytes(originalValue, null);
}
/**
* return the characters in our value without any translation. This allows a string to be built that holds 2-byte or
* one-byte character codes, as needed for processing by fonts when extracting text.
* <p>
* Intended for use when no encoding transformations are desired.
*
* @return The code points in this font as chars.
*/
public char[] getOriginalChars() {<FILL_FUNCTION_BODY>}
public boolean isHexWriting() {
return hexWriting;
}
public PdfString setHexWriting(boolean hexWriting) {
this.hexWriting = hexWriting;
return this;
}
}
|
char[] chars;
if (encoding == null || encoding.length() == 0) {
byte[] bytes = getOriginalBytes();
chars = new char[bytes.length];
for (int i = 0; i < bytes.length; i++) {
chars[i] = (char) (bytes[i] & 0xff);
}
} else if (encoding.equals("IDENTITY_H2")) {
//change it to char array according to two byte mapping.
byte[] bytes = value.getBytes(StandardCharsets.ISO_8859_1);
chars = new char[bytes.length / 2];
for (int i = 0; i < bytes.length / 2; i++) {
chars[i] = (char) (((bytes[2 * i] & 255) << 8) + (bytes[2 * i + 1] & 255));
}
} else if (encoding.equals("IDENTITY_H1")) {
//change it to char array according to one byte mapping.
byte[] bytes = value.getBytes(StandardCharsets.ISO_8859_1);
chars = new char[bytes.length];
for (int i = 0; i < bytes.length; i++) {
chars[i] = (char) (bytes[i] & 0xff);
}
} else {
chars = new char[0];
}
return chars;
| 1,653
| 366
| 2,019
|
<methods>public boolean canBeInObjStm() ,public byte[] getBytes() ,public com.lowagie.text.pdf.PRIndirectReference getIndRef() ,public boolean isArray() ,public boolean isBoolean() ,public boolean isDictionary() ,public boolean isIndirect() ,public boolean isName() ,public boolean isNull() ,public boolean isNumber() ,public boolean isStream() ,public boolean isString() ,public int length() ,public void setIndRef(com.lowagie.text.pdf.PRIndirectReference) ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() ,public int type() <variables>public static final int ARRAY,public static final int BOOLEAN,public static final int DICTIONARY,public static final int INDIRECT,public static final int NAME,public static final java.lang.String NOTHING,public static final int NULL,public static final int NUMBER,public static final int STREAM,public static final int STRING,public static final java.lang.String TEXT_PDFDOCENCODING,public static final java.lang.String TEXT_UNICODE,protected byte[] bytes,protected com.lowagie.text.pdf.PRIndirectReference indRef,protected int type
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfStructureElement.java
|
PdfStructureElement
|
init
|
class PdfStructureElement extends PdfDictionary {
/**
* Holds value of property kids.
*/
private PdfStructureElement parent;
private PdfStructureTreeRoot top;
/**
* Holds value of property reference.
*/
private PdfIndirectReference reference;
/**
* Creates a new instance of PdfStructureElement.
*
* @param parent the parent of this node
* @param structureType the type of structure. It may be a standard type or a user type mapped by the role map
*/
public PdfStructureElement(PdfStructureElement parent, PdfName structureType) {
top = parent.top;
init(parent, structureType);
this.parent = parent;
put(PdfName.P, parent.reference);
put(PdfName.TYPE, new PdfName("StructElem"));
}
/**
* Creates a new instance of PdfStructureElement.
*
* @param parent the parent of this node
* @param structureType the type of structure. It may be a standard type or a user type mapped by the role map
*/
public PdfStructureElement(PdfStructureTreeRoot parent, PdfName structureType) {
top = parent;
init(parent, structureType);
put(PdfName.P, parent.getReference());
put(PdfName.TYPE, new PdfName("StructElem"));
}
private void init(PdfDictionary parent, PdfName structureType) {<FILL_FUNCTION_BODY>}
/**
* Gets the parent of this node.
*
* @return the parent of this node
*/
public PdfDictionary getParent() {
return parent;
}
void setPageMark(int page, int mark) {
if (mark >= 0) {
put(PdfName.K, new PdfNumber(mark));
}
top.setPageMark(page, reference);
}
/**
* Gets the reference this object will be written to.
*
* @return the reference this object will be written to
* @since 2.1.6 method removed in 2.1.5, but restored in 2.1.6
*/
public PdfIndirectReference getReference() {
return this.reference;
}
}
|
PdfObject kido = parent.get(PdfName.K);
PdfArray kids = null;
if (kido != null && !kido.isArray()) {
throw new IllegalArgumentException(
MessageLocalization.getComposedMessage("the.parent.has.already.another.function"));
}
if (kido == null) {
kids = new PdfArray();
parent.put(PdfName.K, kids);
} else {
kids = (PdfArray) kido;
}
kids.add(this);
put(PdfName.S, structureType);
reference = top.getWriter().getPdfIndirectReference();
| 593
| 171
| 764
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.PdfName) ,public void clear() ,public boolean contains(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject get(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfArray getAsArray(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfBoolean getAsBoolean(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfDictionary getAsDict(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfIndirectReference getAsIndirectObject(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfName getAsName(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfNumber getAsNumber(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfStream getAsStream(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfString getAsString(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject getDirectObject(com.lowagie.text.pdf.PdfName) ,public Set<com.lowagie.text.pdf.PdfName> getKeys() ,public Set<Entry<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject>> getKeysAndValues() ,public boolean isCatalog() ,public boolean isFont() ,public boolean isOutlineTree() ,public boolean isPage() ,public boolean isPages() ,public void merge(com.lowagie.text.pdf.PdfDictionary) ,public void mergeDifferent(com.lowagie.text.pdf.PdfDictionary) ,public void put(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void putAll(com.lowagie.text.pdf.PdfDictionary) ,public void putEx(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void remove(com.lowagie.text.pdf.PdfName) ,public int size() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() <variables>public static final com.lowagie.text.pdf.PdfName CATALOG,public static final com.lowagie.text.pdf.PdfName FONT,public static final com.lowagie.text.pdf.PdfName OUTLINES,public static final com.lowagie.text.pdf.PdfName PAGE,public static final com.lowagie.text.pdf.PdfName PAGES,private com.lowagie.text.pdf.PdfName dictionaryType,protected Map<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject> hashMap
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfStructureTreeRoot.java
|
PdfStructureTreeRoot
|
getOrCreatePageKey
|
class PdfStructureTreeRoot extends PdfDictionary {
private final Map<Integer, PdfObject> parentTree = new HashMap<>();
private final PdfIndirectReference reference;
/** Next key to be used for adding to the parentTree */
private int parentTreeNextKey = 0;
/** Map which connects [page number] with corresponding [parentTree entry key] */
private final Map<Integer, Integer> pageKeysMap = new HashMap<>();
/**
* Holds value of property writer.
*/
private final PdfWriter writer;
/**
* Creates a new instance of PdfStructureTreeRoot
*/
PdfStructureTreeRoot(PdfWriter writer) {
super(PdfName.STRUCTTREEROOT);
this.writer = writer;
reference = writer.getPdfIndirectReference();
}
/**
* Maps the user tags to the standard tags. The mapping will allow a standard application to make some sense of the
* tagged document whatever the user tags may be.
*
* @param used the user tag
* @param standard the standard tag
*/
public void mapRole(PdfName used, PdfName standard) {
PdfDictionary rm = (PdfDictionary) get(PdfName.ROLEMAP);
if (rm == null) {
rm = new PdfDictionary();
put(PdfName.ROLEMAP, rm);
}
rm.put(used, standard);
}
/**
* Gets the writer.
*
* @return the writer
*/
public PdfWriter getWriter() {
return this.writer;
}
/**
* Gets the reference this object will be written to.
*
* @return the reference this object will be written to
* @since 2.1.6 method removed in 2.1.5, but restored in 2.1.6
*/
public PdfIndirectReference getReference() {
return this.reference;
}
/**
* Adds a reference to the existing (already added to the document) object to the parentTree.
* This method can be used when the object is need to be referenced via /StructParent key.
*
* @return key which define the object record key (e.g. in /NUMS array)
*/
public int addExistingObject(PdfIndirectReference reference) {
int key = parentTreeNextKey;
parentTree.put(key, reference);
parentTreeNextKey++;
return key;
}
void setPageMark(int pageNumber, PdfIndirectReference reference) {
PdfArray pageArray = (PdfArray) parentTree.get(getOrCreatePageKey(pageNumber));
pageArray.add(reference);
}
/**
* Returns array ID for a page-related entry or creates a new one if not exists.
* Can be used for STRUCTPARENTS tag value
*
* @param pageNumber number of page for which the ID is required
* @return Optional with array ID, empty Optional otherwise
*/
int getOrCreatePageKey(int pageNumber) {<FILL_FUNCTION_BODY>}
private void nodeProcess(PdfDictionary dictionary, PdfIndirectReference reference)
throws IOException {
PdfObject obj = dictionary.get(PdfName.K);
if (obj != null && obj.isArray() && !((PdfArray) obj).getElements().isEmpty() && !((PdfArray) obj).getElements()
.get(0).isNumber()) {
PdfArray ar = (PdfArray) obj;
for (int k = 0; k < ar.size(); ++k) {
PdfObject pdfObj = ar.getDirectObject(k);
if (pdfObj instanceof PdfStructureElement e) {
ar.set(k, e.getReference());
nodeProcess(e, e.getReference());
} else if (pdfObj instanceof PdfIndirectReference) {
ar.set(k, pdfObj);
}
}
}
if (reference != null) {
writer.addToBody(dictionary, reference);
}
}
void buildTree() throws IOException {
Map<Integer, PdfIndirectReference> numTree = new HashMap<>();
for (Integer i : parentTree.keySet()) {
PdfObject pdfObj = parentTree.get(i);
if (pdfObj instanceof PdfIndirectReference pdfRef) {
//saving the reference to the object which was already added to the body
numTree.put(i, pdfRef);
} else {
numTree.put(i, writer.addToBody(pdfObj).getIndirectReference());
}
}
PdfDictionary dicTree = PdfNumberTree.writeTree(numTree, writer);
if (dicTree != null) {
put(PdfName.PARENTTREE, writer.addToBody(dicTree).getIndirectReference());
}
nodeProcess(this, reference);
}
}
|
Integer entryForPageArray = pageKeysMap.get(pageNumber);
if (entryForPageArray == null) {
//putting page array
PdfArray ar = new PdfArray();
entryForPageArray = parentTreeNextKey;
parentTree.put(entryForPageArray, ar);
parentTreeNextKey++;
pageKeysMap.put(pageNumber, entryForPageArray);
}
return entryForPageArray;
| 1,260
| 112
| 1,372
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.PdfName) ,public void clear() ,public boolean contains(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject get(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfArray getAsArray(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfBoolean getAsBoolean(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfDictionary getAsDict(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfIndirectReference getAsIndirectObject(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfName getAsName(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfNumber getAsNumber(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfStream getAsStream(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfString getAsString(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject getDirectObject(com.lowagie.text.pdf.PdfName) ,public Set<com.lowagie.text.pdf.PdfName> getKeys() ,public Set<Entry<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject>> getKeysAndValues() ,public boolean isCatalog() ,public boolean isFont() ,public boolean isOutlineTree() ,public boolean isPage() ,public boolean isPages() ,public void merge(com.lowagie.text.pdf.PdfDictionary) ,public void mergeDifferent(com.lowagie.text.pdf.PdfDictionary) ,public void put(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void putAll(com.lowagie.text.pdf.PdfDictionary) ,public void putEx(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void remove(com.lowagie.text.pdf.PdfName) ,public int size() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() <variables>public static final com.lowagie.text.pdf.PdfName CATALOG,public static final com.lowagie.text.pdf.PdfName FONT,public static final com.lowagie.text.pdf.PdfName OUTLINES,public static final com.lowagie.text.pdf.PdfName PAGE,public static final com.lowagie.text.pdf.PdfName PAGES,private com.lowagie.text.pdf.PdfName dictionaryType,protected Map<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject> hashMap
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfTable.java
|
PdfTable
|
updateRowAdditionsInternal
|
class PdfTable extends Rectangle {
// membervariables
/**
* Original table used to build this object
*/
protected Table table;
/**
* Cached column widths.
*/
protected float[] positions;
/**
* this is the number of columns in the table.
*/
private int columns;
/**
* this is the ArrayList with all the cell of the table header.
*/
private ArrayList<PdfCell> headercells;
/**
* this is the ArrayList with all the cells in the table.
*/
private ArrayList<PdfCell> cells;
// constructors
/**
* Constructs a <CODE>PdfTable</CODE>-object.
*
* @param table a <CODE>Table</CODE>
* @param left the left border on the page
* @param right the right border on the page
* @param top the start position of the top of the table
* @since a parameter of this method has been removed in iText 2.0.8
*/
PdfTable(Table table, float left, float right, float top) {
// constructs a Rectangle (the bottom value will be changed afterwards)
super(left, top, right, top);
this.table = table;
table.complete();
// copying the attributes from class Table
cloneNonPositionParameters(table);
this.columns = table.getColumns();
positions = table.getWidths(left, right - left);
// initialization of some parameters
setLeft(positions[0]);
setRight(positions[positions.length - 1]);
headercells = new ArrayList<>();
cells = new ArrayList<>();
updateRowAdditionsInternal();
}
// methods
/**
* Updates the table row additions in the underlying table object and deletes all table rows, in order to preserve
* memory and detect future row additions.
* <p><b>Pre-requisite</b>: the object must have been built with the parameter
* <code>supportUpdateRowAdditions</code> equals to true.
*/
void updateRowAdditions() {
table.complete();
updateRowAdditionsInternal();
table.deleteAllRows();
}
/**
* Updates the table row additions in the underlying table object
*/
private void updateRowAdditionsInternal() {<FILL_FUNCTION_BODY>}
/**
* Get the number of rows
*/
int rows() {
return cells.isEmpty() ? 0 : cells.get(cells.size() - 1).rownumber() + 1;
}
/**
* @see com.lowagie.text.Element#type()
*/
public int type() {
return Element.TABLE;
}
/**
* Returns the arraylist with the cells of the table header.
*
* @return an <CODE>ArrayList</CODE>
*/
ArrayList<PdfCell> getHeaderCells() {
return headercells;
}
/**
* Checks if there is a table header.
*
* @return an <CODE>ArrayList</CODE>
*/
boolean hasHeader() {
return !headercells.isEmpty();
}
/**
* Returns the arraylist with the cells of the table.
*
* @return an <CODE>ArrayList</CODE>
*/
ArrayList<PdfCell> getCells() {
return cells;
}
/**
* Returns the number of columns of the table.
*
* @return the number of columns
*/
int columns() {
return columns;
}
/**
* Returns the cellpadding of the table.
*
* @return the cellpadding
*/
final float cellpadding() {
return table.getPadding();
}
/**
* Returns the cellspacing of the table.
*
* @return the cellspacing
*/
final float cellspacing() {
return table.getSpacing();
}
/**
* Checks if this <CODE>Table</CODE> has to fit a page.
*
* @return true if the table may not be split
*/
public final boolean hasToFitPageTable() {
return table.isTableFitsPage();
}
/**
* Checks if the cells of this <CODE>Table</CODE> have to fit a page.
*
* @return true if the cells may not be split
*/
public final boolean hasToFitPageCells() {
return table.isCellsFitPage();
}
/**
* Gets the offset of this table.
*
* @return the space between this table and the previous element.
*/
public float getOffset() {
return table.getOffset();
}
}
|
// correct table : fill empty cells/ parse table in table
Row row;
int prevRows = rows();
int rowNumber = 0;
int groupNumber = 0;
boolean groupChange;
int firstDataRow = table.getLastHeaderRow() + 1;
Cell cell;
PdfCell currentCell;
ArrayList<PdfCell> newCells = new ArrayList<>();
int rows = table.size() + 1;
float[] offsets = new float[rows];
for (int i = 0; i < rows; i++) {
offsets[i] = getBottom();
}
// loop over all the rows
for (Iterator rowIterator = table.iterator(); rowIterator.hasNext(); ) {
groupChange = false;
row = (Row) rowIterator.next();
if (row.isEmpty()) {
if (rowNumber < rows - 1 && offsets[rowNumber + 1] > offsets[rowNumber]) {
offsets[rowNumber + 1] = offsets[rowNumber];
}
} else {
for (int i = 0; i < row.getColumns(); i++) {
cell = (Cell) row.getCell(i);
if (cell != null) {
currentCell = new PdfCell(cell, rowNumber + prevRows, positions[i],
positions[i + cell.getColspan()], offsets[rowNumber], cellspacing(), cellpadding());
if (rowNumber < firstDataRow) {
currentCell.setHeader();
headercells.add(currentCell);
if (!table.isNotAddedYet()) {
continue;
}
}
try {
if (offsets[rowNumber] - currentCell.getHeight() - cellpadding() < offsets[rowNumber
+ currentCell.rowspan()]) {
offsets[rowNumber + currentCell.rowspan()] =
offsets[rowNumber] - currentCell.getHeight() - cellpadding();
}
} catch (ArrayIndexOutOfBoundsException aioobe) {
if (offsets[rowNumber] - currentCell.getHeight() < offsets[rows - 1]) {
offsets[rows - 1] = offsets[rowNumber] - currentCell.getHeight();
}
}
currentCell.setGroupNumber(groupNumber);
groupChange |= cell.getGroupChange();
newCells.add(currentCell);
}
}
}
rowNumber++;
if (groupChange) {
groupNumber++;
}
}
// loop over all the cells
int n = newCells.size();
for (Object newCell : newCells) {
currentCell = (PdfCell) newCell;
try {
currentCell.setBottom(offsets[currentCell.rownumber() - prevRows + currentCell.rowspan()]);
} catch (ArrayIndexOutOfBoundsException aioobe) {
currentCell.setBottom(offsets[rows - 1]);
}
}
cells.addAll(newCells);
setBottom(offsets[rows - 1]);
| 1,244
| 769
| 2,013
|
<methods>public void <init>(float, float, float, float) ,public void <init>(float, float) ,public void <init>(float, float, float, float, int) ,public void <init>(float, float, int) ,public void <init>(com.lowagie.text.Rectangle) ,public void cloneNonPositionParameters(com.lowagie.text.Rectangle) ,public void disableBorderSide(int) ,public void enableBorderSide(int) ,public java.awt.Color getBackgroundColor() ,public int getBorder() ,public java.awt.Color getBorderColor() ,public java.awt.Color getBorderColorBottom() ,public java.awt.Color getBorderColorLeft() ,public java.awt.Color getBorderColorRight() ,public java.awt.Color getBorderColorTop() ,public float getBorderWidth() ,public float getBorderWidthBottom() ,public float getBorderWidthLeft() ,public float getBorderWidthRight() ,public float getBorderWidthTop() ,public float getBottom() ,public float getBottom(float) ,public ArrayList<com.lowagie.text.Element> getChunks() ,public float getGrayFill() ,public float getHeight() ,public float getLeft() ,public float getLeft(float) ,public float getRelativeTop() ,public float getRight() ,public float getRight(float) ,public int getRotation() ,public float getTop() ,public float getTop(float) ,public float getWidth() ,public boolean hasBorder(int) ,public boolean hasBorders() ,public boolean isContent() ,public boolean isNestable() ,public boolean isUseVariableBorders() ,public void normalize() ,public boolean process(com.lowagie.text.ElementListener) ,public com.lowagie.text.Rectangle rectangle(float, float) ,public com.lowagie.text.Rectangle rotate() ,public void setBackgroundColor(java.awt.Color) ,public void setBorder(int) ,public void setBorderColor(java.awt.Color) ,public void setBorderColorBottom(java.awt.Color) ,public void setBorderColorLeft(java.awt.Color) ,public void setBorderColorRight(java.awt.Color) ,public void setBorderColorTop(java.awt.Color) ,public void setBorderWidth(float) ,public void setBorderWidthBottom(float) ,public void setBorderWidthLeft(float) ,public void setBorderWidthRight(float) ,public void setBorderWidthTop(float) ,public void setBottom(float) ,public void setGrayFill(float) ,public void setLeft(float) ,public void setRelativeTop(float) ,public void setRight(float) ,public void setRotation(int) ,public void setTop(float) ,public void setUseVariableBorders(boolean) ,public void softCloneNonPositionParameters(com.lowagie.text.Rectangle) ,public java.lang.String toString() ,public int type() <variables>public static final int BOTTOM,public static final int BOX,public static final int LEFT,public static final int NO_BORDER,public static final int RIGHT,public static final int TOP,public static final int UNDEFINED,protected java.awt.Color backgroundColor,protected int border,protected java.awt.Color borderColor,protected java.awt.Color borderColorBottom,protected java.awt.Color borderColorLeft,protected java.awt.Color borderColorRight,protected java.awt.Color borderColorTop,protected float borderWidth,protected float borderWidthBottom,protected float borderWidthLeft,protected float borderWidthRight,protected float borderWidthTop,protected float llx,protected float lly,protected float offsetToTop,protected int rotation,protected float urx,protected float ury,protected boolean useVariableBorders
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfTemplate.java
|
PdfTemplate
|
createTemplate
|
class PdfTemplate extends PdfContentByte {
public static final int TYPE_TEMPLATE = 1;
public static final int TYPE_IMPORTED = 2;
public static final int TYPE_PATTERN = 3;
protected int type;
/**
* The indirect reference to this template
*/
protected PdfIndirectReference thisReference;
/**
* The resources used by this template
*/
protected PageResources pageResources;
/**
* The bounding box of this template
*/
protected Rectangle bBox = new Rectangle(0, 0);
protected PdfArray matrix;
protected PdfTransparencyGroup group;
protected PdfOCG layer;
/**
* Creates a <CODE>PdfTemplate</CODE>.
*/
protected PdfTemplate() {
super(null);
type = TYPE_TEMPLATE;
}
/**
* Creates new PdfTemplate
*
* @param wr the <CODE>PdfWriter</CODE>
*/
PdfTemplate(PdfWriter wr) {
super(wr);
type = TYPE_TEMPLATE;
pageResources = new PageResources();
pageResources.addDefaultColor(wr.getDefaultColorspace());
thisReference = writer.getPdfIndirectReference();
}
/**
* Creates a new template.
* <p>
* Creates a new template that is nothing more than a form XObject. This template can be included in this template
* or in another template. Templates are only written to the output when the document is closed permitting things
* like showing text in the first page that is only defined in the last page.
*
* @param writer the PdfWriter to use
* @param width the bounding box width
* @param height the bounding box height
* @return the created template
*/
public static PdfTemplate createTemplate(PdfWriter writer, float width, float height) {
return createTemplate(writer, width, height, null);
}
static PdfTemplate createTemplate(PdfWriter writer, float width, float height, PdfName forcedName) {<FILL_FUNCTION_BODY>}
/**
* Gets the bounding width of this template.
*
* @return width the bounding width
*/
public float getWidth() {
return bBox.getWidth();
}
/**
* Sets the bounding width of this template.
*
* @param width the bounding width
*/
public void setWidth(float width) {
bBox.setLeft(0);
bBox.setRight(width);
}
/**
* Gets the bounding height of this template.
*
* @return height the bounding height
*/
public float getHeight() {
return bBox.getHeight();
}
/**
* Sets the bounding height of this template.
*
* @param height the bounding height
*/
public void setHeight(float height) {
bBox.setBottom(0);
bBox.setTop(height);
}
public Rectangle getBoundingBox() {
return bBox;
}
public void setBoundingBox(Rectangle bBox) {
this.bBox = bBox;
}
/**
* Gets the layer this template belongs to.
*
* @return the layer this template belongs to or <code>null</code> for no layer defined
*/
public PdfOCG getLayer() {
return layer;
}
/**
* Sets the layer this template belongs to.
*
* @param layer the layer this template belongs to
*/
public void setLayer(PdfOCG layer) {
this.layer = layer;
}
public void setMatrix(float a, float b, float c, float d, float e, float f) {
matrix = new PdfArray();
matrix.add(new PdfNumber(a));
matrix.add(new PdfNumber(b));
matrix.add(new PdfNumber(c));
matrix.add(new PdfNumber(d));
matrix.add(new PdfNumber(e));
matrix.add(new PdfNumber(f));
}
PdfArray getMatrix() {
return matrix;
}
/**
* Gets the indirect reference to this template.
*
* @return the indirect reference to this template
*/
public PdfIndirectReference getIndirectReference() {
// uncomment the null check as soon as we're sure all examples still work
if (thisReference == null /* && writer != null */) {
thisReference = writer.getPdfIndirectReference();
}
return thisReference;
}
public void beginVariableText() {
content.append("/Tx BMC ");
}
public void endVariableText() {
content.append("EMC ");
}
/**
* Constructs the resources used by this template.
*
* @return the resources used by this template
*/
PdfObject getResources() {
return getPageResources().getResources();
}
/**
* Gets the stream representing this template.
*
* @param compressionLevel the compressionLevel
* @return the stream representing this template
* @since 2.1.3 (replacing the method without param compressionLevel)
*/
PdfStream getFormXObject(int compressionLevel) throws IOException {
return new PdfFormXObject(this, compressionLevel);
}
/**
* Gets a duplicate of this <CODE>PdfTemplate</CODE>. All the members are copied by reference but the buffer stays
* different.
*
* @return a copy of this <CODE>PdfTemplate</CODE>
*/
public PdfContentByte getDuplicate() {
PdfTemplate tpl = new PdfTemplate();
tpl.writer = writer;
tpl.pdf = pdf;
tpl.thisReference = thisReference;
tpl.pageResources = pageResources;
tpl.bBox = new Rectangle(bBox);
tpl.group = group;
tpl.layer = layer;
if (matrix != null) {
tpl.matrix = new PdfArray(matrix);
}
tpl.separator = separator;
return tpl;
}
public int getType() {
return type;
}
PageResources getPageResources() {
return pageResources;
}
/**
* Getter for property group.
*
* @return Value of property group.
*/
public PdfTransparencyGroup getGroup() {
return this.group;
}
/**
* Setter for property group.
*
* @param group New value of property group.
*/
public void setGroup(PdfTransparencyGroup group) {
this.group = group;
}
}
|
PdfTemplate template = new PdfTemplate(writer);
template.setWidth(width);
template.setHeight(height);
writer.addDirectTemplateSimple(template, forcedName);
return template;
| 1,768
| 54
| 1,822
|
<methods>public void <init>(com.lowagie.text.pdf.PdfWriter) ,public void add(com.lowagie.text.pdf.PdfContentByte) ,public void addImage(com.lowagie.text.Image) throws com.lowagie.text.DocumentException,public void addImage(com.lowagie.text.Image, boolean) throws com.lowagie.text.DocumentException,public void addImage(com.lowagie.text.Image, float, float, float, float, float, float) throws com.lowagie.text.DocumentException,public void addImage(com.lowagie.text.Image, float, float, float, float, float, float, boolean) throws com.lowagie.text.DocumentException,public void addOutline(com.lowagie.text.pdf.PdfOutline, java.lang.String) ,public void addPSXObject(com.lowagie.text.pdf.PdfPSXObject) ,public void addTemplate(com.lowagie.text.pdf.PdfTemplate, float, float, float, float, float, float) ,public void addTemplate(com.lowagie.text.pdf.PdfTemplate, float, float) ,public void addTemplate(com.lowagie.text.pdf.PdfTemplate, double, double, double, double, double, double) ,public void arc(float, float, float, float, float, float) ,public void beginLayer(com.lowagie.text.pdf.PdfOCG) ,public void beginMarkedContentSequence(com.lowagie.text.pdf.PdfStructureElement) ,public void beginMarkedContentSequence(com.lowagie.text.pdf.PdfStructureElement, com.lowagie.text.pdf.PdfDictionary) ,public void beginMarkedContentSequence(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfDictionary, boolean) ,public void beginMarkedContentSequence(com.lowagie.text.pdf.PdfName) ,public void beginText() ,public static List<float[]> bezierArc(float, float, float, float, float, float) ,public void circle(float, float, float) ,public void clip() ,public void closePath() ,public void closePathEoFillStroke() ,public void closePathFillStroke() ,public void closePathStroke() ,public void concatCTM(float, float, float, float, float, float) ,public com.lowagie.text.pdf.PdfAppearance createAppearance(float, float) ,public java.awt.Graphics2D createGraphics(float, float) ,public java.awt.Graphics2D createGraphics(float, float, boolean, float) ,public java.awt.Graphics2D createGraphics(float, float, com.lowagie.text.pdf.FontMapper) ,public java.awt.Graphics2D createGraphics(float, float, com.lowagie.text.pdf.FontMapper, boolean, float) ,public java.awt.Graphics2D createGraphicsShapes(float, float) ,public java.awt.Graphics2D createGraphicsShapes(float, float, boolean, float) ,public com.lowagie.text.pdf.PdfPatternPainter createPattern(float, float, float, float) ,public com.lowagie.text.pdf.PdfPatternPainter createPattern(float, float) ,public com.lowagie.text.pdf.PdfPatternPainter createPattern(float, float, float, float, java.awt.Color) ,public com.lowagie.text.pdf.PdfPatternPainter createPattern(float, float, java.awt.Color) ,public java.awt.Graphics2D createPrinterGraphics(float, float, java.awt.print.PrinterJob) ,public java.awt.Graphics2D createPrinterGraphics(float, float, boolean, float, java.awt.print.PrinterJob) ,public java.awt.Graphics2D createPrinterGraphics(float, float, com.lowagie.text.pdf.FontMapper, java.awt.print.PrinterJob) ,public java.awt.Graphics2D createPrinterGraphics(float, float, com.lowagie.text.pdf.FontMapper, boolean, float, java.awt.print.PrinterJob) ,public java.awt.Graphics2D createPrinterGraphicsShapes(float, float, java.awt.print.PrinterJob) ,public java.awt.Graphics2D createPrinterGraphicsShapes(float, float, boolean, float, java.awt.print.PrinterJob) ,public com.lowagie.text.pdf.PdfTemplate createTemplate(float, float) ,public void curveFromTo(float, float, float, float) ,public void curveTo(float, float, float, float, float, float) ,public void curveTo(float, float, float, float) ,public void drawButton(float, float, float, float, java.lang.String, com.lowagie.text.pdf.BaseFont, float) ,public void drawRadioField(float, float, float, float, boolean) ,public void drawTextField(float, float, float, float) ,public void ellipse(float, float, float, float) ,public void endLayer() ,public void endMarkedContentSequence() ,public void endText() ,public void eoClip() ,public void eoFill() ,public void eoFillStroke() ,public void fill() ,public void fillStroke() ,public float getCharacterSpacing() ,public com.lowagie.text.pdf.PdfContentByte getDuplicate() ,public float getEffectiveStringWidth(java.lang.String, boolean) ,public float getHorizontalScaling() ,public com.lowagie.text.pdf.ByteBuffer getInternalBuffer() ,public static com.lowagie.text.pdf.PdfTextArray getKernArray(java.lang.String, com.lowagie.text.pdf.BaseFont) ,public float getLeading() ,public com.lowagie.text.pdf.PdfDocument getPdfDocument() ,public com.lowagie.text.pdf.PdfWriter getPdfWriter() ,public com.lowagie.text.pdf.PdfOutline getRootOutline() ,public float getWordSpacing() ,public float getXTLM() ,public float getYTLM() ,public void lineTo(float, float) ,public boolean localDestination(java.lang.String, com.lowagie.text.pdf.PdfDestination) ,public void localGoto(java.lang.String, float, float, float, float) ,public void moveText(float, float) ,public void moveTextWithLeading(float, float) ,public void moveTo(float, float) ,public void newPath() ,public void newlineShowText(java.lang.String) ,public void newlineShowText(float, float, java.lang.String) ,public void newlineText() ,public void paintShading(com.lowagie.text.pdf.PdfShading) ,public void paintShading(com.lowagie.text.pdf.PdfShadingPattern) ,public void rectangle(float, float, float, float) ,public void rectangle(com.lowagie.text.Rectangle) ,public void remoteGoto(java.lang.String, java.lang.String, float, float, float, float) ,public void remoteGoto(java.lang.String, int, float, float, float, float) ,public void reset() ,public void reset(boolean) ,public void resetCMYKColorFill() ,public void resetCMYKColorStroke() ,public void resetGrayFill() ,public void resetGrayStroke() ,public void resetRGBColorFill() ,public void resetRGBColorStroke() ,public void restoreState() ,public void roundRectangle(float, float, float, float, float) ,public void sanityCheck() ,public void saveState() ,public void setAction(com.lowagie.text.pdf.PdfAction, float, float, float, float) ,public void setCMYKColorFill(int, int, int, int) ,public void setCMYKColorFillF(float, float, float, float) ,public void setCMYKColorFillF(float, float, float, float, float) ,public void setCMYKColorStroke(int, int, int, int) ,public void setCMYKColorStrokeF(float, float, float, float) ,public void setCMYKColorStrokeF(float, float, float, float, float) ,public void setCharacterSpacing(float) ,public void setColorFill(java.awt.Color) ,public void setColorFill(com.lowagie.text.pdf.PdfSpotColor, float) ,public void setColorStroke(java.awt.Color) ,public void setColorStroke(com.lowagie.text.pdf.PdfSpotColor, float) ,public void setDefaultColorspace(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void setFlatness(float) ,public void setFontAndSize(com.lowagie.text.pdf.BaseFont, float) ,public void setGState(com.lowagie.text.pdf.PdfGState) ,public void setGrayFill(float) ,public void setGrayFill(float, float) ,public void setGrayStroke(float) ,public void setGrayStroke(float, float) ,public void setHorizontalScaling(float) ,public void setLeading(float) ,public void setLineCap(int) ,public void setLineDash(float) ,public void setLineDash(float, float) ,public void setLineDash(float, float, float) ,public final void setLineDash(float[], float) ,public void setLineJoin(int) ,public void setLineWidth(float) ,public void setLiteral(java.lang.String) ,public void setLiteral(char) ,public void setLiteral(float) ,public void setMiterLimit(float) ,public void setPatternFill(com.lowagie.text.pdf.PdfPatternPainter) ,public void setPatternFill(com.lowagie.text.pdf.PdfPatternPainter, java.awt.Color) ,public void setPatternFill(com.lowagie.text.pdf.PdfPatternPainter, java.awt.Color, float) ,public void setPatternStroke(com.lowagie.text.pdf.PdfPatternPainter, java.awt.Color) ,public void setPatternStroke(com.lowagie.text.pdf.PdfPatternPainter, java.awt.Color, float) ,public void setPatternStroke(com.lowagie.text.pdf.PdfPatternPainter) ,public void setRGBColorFill(int, int, int) ,public void setRGBColorFill(int, int, int, int) ,public void setRGBColorFillF(float, float, float) ,public void setRGBColorFillF(float, float, float, float) ,public void setRGBColorStroke(int, int, int) ,public void setRGBColorStroke(int, int, int, int) ,public void setRGBColorStrokeF(float, float, float) ,public void setShadingFill(com.lowagie.text.pdf.PdfShadingPattern) ,public void setShadingStroke(com.lowagie.text.pdf.PdfShadingPattern) ,public void setTextMatrix(float, float, float, float, float, float) ,public void setTextMatrix(float, float) ,public void setTextRenderingMode(int) ,public void setTextRise(float) ,public void setWordSpacing(float) ,public void showText(java.lang.String) ,public void showText(java.awt.font.GlyphVector) ,public void showText(java.awt.font.GlyphVector, int, int) ,public void showText(com.lowagie.text.pdf.PdfGlyphArray) ,public void showText(com.lowagie.text.pdf.PdfTextArray) ,public void showTextAligned(int, java.lang.String, float, float, float) ,public void showTextAlignedKerned(int, java.lang.String, float, float, float) ,public void showTextBasic(java.lang.String) ,public void showTextKerned(java.lang.String) ,public void stroke() ,public byte[] toPdf(com.lowagie.text.pdf.PdfWriter) ,public java.lang.String toString() ,public void transform(java.awt.geom.AffineTransform) ,public void variableRectangle(com.lowagie.text.Rectangle) <variables>public static final int ALIGN_CENTER,public static final int ALIGN_LEFT,public static final int ALIGN_RIGHT,public static final int LINE_CAP_BUTT,public static final int LINE_CAP_PROJECTING_SQUARE,public static final int LINE_CAP_ROUND,public static final int LINE_JOIN_BEVEL,public static final int LINE_JOIN_MITER,public static final int LINE_JOIN_ROUND,static final float MIN_FONT_SIZE,public static final int TEXT_RENDER_MODE_CLIP,public static final int TEXT_RENDER_MODE_FILL,public static final int TEXT_RENDER_MODE_FILL_CLIP,public static final int TEXT_RENDER_MODE_FILL_STROKE,public static final int TEXT_RENDER_MODE_FILL_STROKE_CLIP,public static final int TEXT_RENDER_MODE_INVISIBLE,public static final int TEXT_RENDER_MODE_STROKE,public static final int TEXT_RENDER_MODE_STROKE_CLIP,private static final Map<com.lowagie.text.pdf.PdfName,java.lang.String> abrev,protected com.lowagie.text.pdf.ByteBuffer content,private boolean inText,private int lastFillAlpha,private int lastStrokeAlpha,protected List<java.lang.Integer> layerDepth,private java.awt.geom.Point2D layoutPositionCorrection,private int mcDepth,protected com.lowagie.text.pdf.PdfDocument pdf,protected int separator,protected com.lowagie.text.pdf.PdfContentByte.GraphicState state,protected List<com.lowagie.text.pdf.PdfContentByte.GraphicState> stateList,private static final float[] unitRect,protected com.lowagie.text.pdf.PdfWriter writer
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfTextArray.java
|
PdfTextArray
|
add
|
class PdfTextArray {
private List<Object> arrayList = new LinkedList<>();
// To emit a more efficient array, we consolidate
// repeated numbers or strings into single array entries.
// "add( 50 ); add( -50 );" will REMOVE the combined zero from the array.
// the alternative (leaving a zero in there) was Just Weird.
// --Mark Storer, May 12, 2008
private String lastStr;
private Float lastNum;
private boolean isRTL = false;
// constructors
public PdfTextArray(String str) {
add(str);
}
public PdfTextArray() {
}
/**
* Adds a <CODE>PdfNumber</CODE> to the <CODE>PdfArray</CODE>.
*
* @param number displacement of the string
*/
public void add(PdfNumber number) {
add((float) number.doubleValue());
}
public void add(float number) {<FILL_FUNCTION_BODY>}
public void add(String str) {
if (isRTL) {
str = new StringBuffer(str).reverse().toString();
}
if (str.length() > 0) {
if (lastStr != null) {
if (isRTL) {
lastStr = str + lastStr;
} else {
lastStr = lastStr + str;
}
replaceLast(lastStr);
} else {
lastStr = str;
if (isRTL) {
arrayList.add(0, lastStr);
} else {
arrayList.add(lastStr);
}
}
lastNum = null;
}
// adding an empty string doesn't modify the TextArray at all
}
List getArrayList() {
return arrayList;
}
private void replaceLast(Object obj) {
// deliberately throw the IndexOutOfBoundsException if we screw up.
if (isRTL) {
arrayList.set(0, obj);
} else {
arrayList.set(arrayList.size() - 1, obj);
}
}
public boolean getRTL() {
return this.isRTL;
}
public void setRTL(boolean isRTL) {
this.isRTL = isRTL;
}
}
|
if (number != 0) {
if (lastNum != null) {
lastNum = number + lastNum;
if (lastNum != 0) {
replaceLast(lastNum);
} else {
arrayList.remove(isRTL ? 0 : arrayList.size() - 1);
}
} else {
lastNum = number;
if (isRTL) {
arrayList.add(0, lastNum);
} else {
arrayList.add(lastNum);
}
}
lastStr = null;
}
// adding zero doesn't modify the TextArray at all
| 615
| 163
| 778
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfTransition.java
|
PdfTransition
|
getTransitionDictionary
|
class PdfTransition {
/**
* Out Vertical Split
*/
public static final int SPLITVOUT = 1;
/**
* Out Horizontal Split
*/
public static final int SPLITHOUT = 2;
/**
* In Vertical Split
*/
public static final int SPLITVIN = 3;
/**
* IN Horizontal Split
*/
public static final int SPLITHIN = 4;
/**
* Vertical Blinds
*/
public static final int BLINDV = 5;
/**
* Vertical Blinds
*/
public static final int BLINDH = 6;
/**
* Inward Box
*/
public static final int INBOX = 7;
/**
* Outward Box
*/
public static final int OUTBOX = 8;
/**
* Left-Right Wipe
*/
public static final int LRWIPE = 9;
/**
* Right-Left Wipe
*/
public static final int RLWIPE = 10;
/**
* Bottom-Top Wipe
*/
public static final int BTWIPE = 11;
/**
* Top-Bottom Wipe
*/
public static final int TBWIPE = 12;
/**
* Dissolve
*/
public static final int DISSOLVE = 13;
/**
* Left-Right Glitter
*/
public static final int LRGLITTER = 14;
/**
* Top-Bottom Glitter
*/
public static final int TBGLITTER = 15;
/**
* Diagonal Glitter
*/
public static final int DGLITTER = 16;
/**
* duration of the transition effect
*/
protected int duration;
/**
* type of the transition effect
*/
protected int type;
/**
* Constructs a <CODE>Transition</CODE>.
*/
public PdfTransition() {
this(BLINDH);
}
/**
* Constructs a <CODE>Transition</CODE>.
*
* @param type type of the transition effect
*/
public PdfTransition(int type) {
this(type, 1);
}
/**
* Constructs a <CODE>Transition</CODE>.
*
* @param type type of the transition effect
* @param duration duration of the transition effect
*/
public PdfTransition(int type, int duration) {
this.duration = duration;
this.type = type;
}
public int getDuration() {
return duration;
}
public int getType() {
return type;
}
public PdfDictionary getTransitionDictionary() {<FILL_FUNCTION_BODY>}
}
|
PdfDictionary trans = new PdfDictionary(PdfName.TRANS);
switch (type) {
case SPLITVOUT:
trans.put(PdfName.S, PdfName.SPLIT);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.DM, PdfName.V);
trans.put(PdfName.M, PdfName.O);
break;
case SPLITHOUT:
trans.put(PdfName.S, PdfName.SPLIT);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.DM, PdfName.H);
trans.put(PdfName.M, PdfName.O);
break;
case SPLITVIN:
trans.put(PdfName.S, PdfName.SPLIT);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.DM, PdfName.V);
trans.put(PdfName.M, PdfName.I);
break;
case SPLITHIN:
trans.put(PdfName.S, PdfName.SPLIT);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.DM, PdfName.H);
trans.put(PdfName.M, PdfName.I);
break;
case BLINDV:
trans.put(PdfName.S, PdfName.BLINDS);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.DM, PdfName.V);
break;
case BLINDH:
trans.put(PdfName.S, PdfName.BLINDS);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.DM, PdfName.H);
break;
case INBOX:
trans.put(PdfName.S, PdfName.BOX);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.M, PdfName.I);
break;
case OUTBOX:
trans.put(PdfName.S, PdfName.BOX);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.M, PdfName.O);
break;
case LRWIPE:
trans.put(PdfName.S, PdfName.WIPE);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.DI, new PdfNumber(0));
break;
case RLWIPE:
trans.put(PdfName.S, PdfName.WIPE);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.DI, new PdfNumber(180));
break;
case BTWIPE:
trans.put(PdfName.S, PdfName.WIPE);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.DI, new PdfNumber(90));
break;
case TBWIPE:
trans.put(PdfName.S, PdfName.WIPE);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.DI, new PdfNumber(270));
break;
case DISSOLVE:
trans.put(PdfName.S, PdfName.DISSOLVE);
trans.put(PdfName.D, new PdfNumber(duration));
break;
case LRGLITTER:
trans.put(PdfName.S, PdfName.GLITTER);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.DI, new PdfNumber(0));
break;
case TBGLITTER:
trans.put(PdfName.S, PdfName.GLITTER);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.DI, new PdfNumber(270));
break;
case DGLITTER:
trans.put(PdfName.S, PdfName.GLITTER);
trans.put(PdfName.D, new PdfNumber(duration));
trans.put(PdfName.DI, new PdfNumber(315));
break;
}
return trans;
| 734
| 1,203
| 1,937
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PdfTransparencyGroup.java
|
PdfTransparencyGroup
|
setKnockout
|
class PdfTransparencyGroup extends PdfDictionary {
/**
* Constructs a transparencyGroup.
*/
public PdfTransparencyGroup() {
super();
put(PdfName.S, PdfName.TRANSPARENCY);
}
/**
* Determining the initial backdrop against which its stack is composited.
*
* @param isolated true to set, false to remove
*/
public void setIsolated(boolean isolated) {
if (isolated) {
put(PdfName.I, PdfBoolean.PDFTRUE);
} else {
remove(PdfName.I);
}
}
/**
* Determining whether the objects within the stack are composited with one another or only with the group's
* backdrop.
*
* @param knockout boolean value to set
*/
public void setKnockout(boolean knockout) {<FILL_FUNCTION_BODY>}
}
|
if (knockout) {
put(PdfName.K, PdfBoolean.PDFTRUE);
} else {
remove(PdfName.K);
}
| 246
| 47
| 293
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.PdfName) ,public void clear() ,public boolean contains(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject get(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfArray getAsArray(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfBoolean getAsBoolean(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfDictionary getAsDict(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfIndirectReference getAsIndirectObject(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfName getAsName(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfNumber getAsNumber(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfStream getAsStream(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfString getAsString(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject getDirectObject(com.lowagie.text.pdf.PdfName) ,public Set<com.lowagie.text.pdf.PdfName> getKeys() ,public Set<Entry<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject>> getKeysAndValues() ,public boolean isCatalog() ,public boolean isFont() ,public boolean isOutlineTree() ,public boolean isPage() ,public boolean isPages() ,public void merge(com.lowagie.text.pdf.PdfDictionary) ,public void mergeDifferent(com.lowagie.text.pdf.PdfDictionary) ,public void put(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void putAll(com.lowagie.text.pdf.PdfDictionary) ,public void putEx(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void remove(com.lowagie.text.pdf.PdfName) ,public int size() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() <variables>public static final com.lowagie.text.pdf.PdfName CATALOG,public static final com.lowagie.text.pdf.PdfName FONT,public static final com.lowagie.text.pdf.PdfName OUTLINES,public static final com.lowagie.text.pdf.PdfName PAGE,public static final com.lowagie.text.pdf.PdfName PAGES,private com.lowagie.text.pdf.PdfName dictionaryType,protected Map<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject> hashMap
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/SequenceList.java
|
SequenceList
|
getAttributes
|
class SequenceList {
protected static final int COMMA = 1;
protected static final int MINUS = 2;
protected static final int NOT = 3;
protected static final int TEXT = 4;
protected static final int NUMBER = 5;
protected static final int END = 6;
protected static final char EOT = '\uffff';
private static final int FIRST = 0;
private static final int DIGIT = 1;
private static final int OTHER = 2;
private static final int DIGIT2 = 3;
private static final String NOT_OTHER = "-,!0123456789";
protected char[] text;
protected int ptr;
protected int number;
protected String other;
protected int low;
protected int high;
protected boolean odd;
protected boolean even;
protected boolean inverse;
protected SequenceList(String range) {
ptr = 0;
text = range.toCharArray();
}
/**
* Generates a list of numbers from a string.
*
* @param ranges the comma separated ranges
* @param maxNumber the maximum number in the range
* @return a list with the numbers as <CODE>Integer</CODE>
*/
public static List<Integer> expand(String ranges, int maxNumber) {
SequenceList parse = new SequenceList(ranges);
List<Integer> list = new LinkedList<>();
boolean sair = false;
while (!sair) {
sair = parse.getAttributes();
if (parse.low == -1 && parse.high == -1 && !parse.even && !parse.odd) {
continue;
}
if (parse.low < 1) {
parse.low = 1;
}
if (parse.high < 1 || parse.high > maxNumber) {
parse.high = maxNumber;
}
if (parse.low > maxNumber) {
parse.low = maxNumber;
}
//System.out.println("low="+parse.low+",high="+parse.high+",odd="+parse.odd+",even="+parse.even+",inverse="+parse.inverse);
int inc = 1;
if (parse.inverse) {
if (parse.low > parse.high) {
int t = parse.low;
parse.low = parse.high;
parse.high = t;
}
for (ListIterator it = list.listIterator(); it.hasNext(); ) {
int n = (Integer) it.next();
if (parse.even && (n & 1) == 1) {
continue;
}
if (parse.odd && (n & 1) == 0) {
continue;
}
if (n >= parse.low && n <= parse.high) {
it.remove();
}
}
} else {
if (parse.low > parse.high) {
inc = -1;
if (parse.odd || parse.even) {
--inc;
if (parse.even) {
parse.low &= ~1;
} else {
parse.low -= ((parse.low & 1) == 1 ? 0 : 1);
}
}
for (int k = parse.low; k >= parse.high; k += inc) {
list.add(k);
}
} else {
if (parse.odd || parse.even) {
++inc;
if (parse.odd) {
parse.low |= 1;
} else {
parse.low += ((parse.low & 1) == 1 ? 1 : 0);
}
}
for (int k = parse.low; k <= parse.high; k += inc) {
list.add(k);
}
}
}
// for (int k = 0; k < list.size(); ++k)
// System.out.print(((Integer)list.get(k)).intValue() + ",");
// System.out.println();
}
return list;
}
protected char nextChar() {
while (true) {
if (ptr >= text.length) {
return EOT;
}
char c = text[ptr++];
if (c > ' ') {
return c;
}
}
}
protected void putBack() {
--ptr;
if (ptr < 0) {
ptr = 0;
}
}
protected int getType() {
StringBuilder buf = new StringBuilder();
int state = FIRST;
while (true) {
char c = nextChar();
if (c == EOT) {
if (state == DIGIT) {
number = Integer.parseInt(other = buf.toString());
return NUMBER;
} else if (state == OTHER) {
other = buf.toString().toLowerCase();
return TEXT;
}
return END;
}
switch (state) {
case FIRST:
switch (c) {
case '!':
return NOT;
case '-':
return MINUS;
case ',':
return COMMA;
}
buf.append(c);
if (c >= '0' && c <= '9') {
state = DIGIT;
} else {
state = OTHER;
}
break;
case DIGIT:
if (c >= '0' && c <= '9') {
buf.append(c);
} else {
putBack();
number = Integer.parseInt(other = buf.toString());
return NUMBER;
}
break;
case OTHER:
if (NOT_OTHER.indexOf(c) < 0) {
buf.append(c);
} else {
putBack();
other = buf.toString().toLowerCase();
return TEXT;
}
break;
}
}
}
private void otherProc() {
if (other.equals("odd") || other.equals("o")) {
odd = true;
even = false;
} else if (other.equals("even") || other.equals("e")) {
odd = false;
even = true;
}
}
protected boolean getAttributes() {<FILL_FUNCTION_BODY>}
}
|
low = -1;
high = -1;
odd = even = inverse = false;
int state = OTHER;
while (true) {
int type = getType();
if (type == END || type == COMMA) {
if (state == DIGIT) {
high = low;
}
return (type == END);
}
switch (state) {
case OTHER:
switch (type) {
case NOT:
inverse = true;
break;
case MINUS:
state = DIGIT2;
break;
default:
if (type == NUMBER) {
low = number;
state = DIGIT;
} else {
otherProc();
}
break;
}
break;
case DIGIT:
switch (type) {
case NOT:
inverse = true;
state = OTHER;
high = low;
break;
case MINUS:
state = DIGIT2;
break;
default:
high = low;
state = OTHER;
otherProc();
break;
}
break;
case DIGIT2:
switch (type) {
case NOT:
inverse = true;
state = OTHER;
break;
case MINUS:
break;
case NUMBER:
high = number;
state = OTHER;
break;
default:
state = OTHER;
otherProc();
break;
}
break;
}
}
| 1,618
| 403
| 2,021
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/StandardDecryption.java
|
StandardDecryption
|
finish
|
class StandardDecryption {
private static final int AES_128 = 4;
private static final int AES_256_V3 = 6;
protected ARCFOUREncryption arcfour;
protected AESCipher cipher;
private byte[] key;
private boolean aes;
private boolean initiated;
private byte[] iv = new byte[16];
private int ivptr;
/**
* Creates a new instance of StandardDecryption
*
* @param key a byte array containing the key
* @param off the begining of the key in the array
* @param len the length
* @param revision the aes revision
*/
public StandardDecryption(byte[] key, int off, int len, int revision) {
aes = revision == AES_128 || revision == AES_256_V3;
if (aes) {
this.key = new byte[len];
System.arraycopy(key, off, this.key, 0, len);
} else {
arcfour = new ARCFOUREncryption();
arcfour.prepareARCFOURKey(key, off, len);
}
}
public byte[] update(byte[] b, int off, int len) {
if (aes) {
if (initiated) {
return cipher.update(b, off, len);
} else {
int left = Math.min(iv.length - ivptr, len);
System.arraycopy(b, off, iv, ivptr, left);
off += left;
len -= left;
ivptr += left;
if (ivptr == iv.length) {
cipher = new AESCipher(false, key, iv);
initiated = true;
if (len > 0) {
return cipher.update(b, off, len);
}
}
return null;
}
} else {
byte[] b2 = new byte[len];
arcfour.encryptARCFOUR(b, off, len, b2, 0);
return b2;
}
}
public byte[] finish() {<FILL_FUNCTION_BODY>}
}
|
if (aes && cipher != null) {
return cipher.doFinal();
} else {
return null;
}
| 564
| 39
| 603
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/TTFCache.java
|
TTFCache
|
loadTTF
|
class TTFCache {
private static Map<String, TTFFile> ttfFileMap = new ConcurrentHashMap<>();
public static TTFFile getTTFFile(String fileName, TrueTypeFontUnicode ttu) {
if (ttfFileMap.containsKey(fileName)) {
return ttfFileMap.get(fileName);
}
TTFReader app = new TTFReader();
TTFFile ttf = null;
try {
ttf = loadTTF(app, fileName, ttu);
ttfFileMap.put(fileName, ttf);
return ttf;
} catch (IOException e) {
throw new ExceptionConverter(e);
}
}
private static TTFFile loadTTF(TTFReader app, String fileName, TrueTypeFontUnicode ttu) throws IOException {<FILL_FUNCTION_BODY>}
private static InputStream getStreamFromFont(TrueTypeFontUnicode ttu) throws IOException {
return new ByteArrayInputStream(ttu.getFullFont());
}
}
|
try {
return app.loadTTF(fileName, null, true, true);
} catch (IOException e) {
TTFFile ttfFile = new TTFFile(true, true);
InputStream stream = BaseFont.getResourceStream(fileName, null);
try {
if (stream == null) {
stream = getStreamFromFont(ttu);
}
FontFileReader reader = new FontFileReader(stream);
String fontName = null;
ttfFile.readFont(reader, fontName);
} finally {
if (stream != null) {
stream.close();
}
}
if (ttfFile.isCFF()) {
throw new UnsupportedOperationException(
"OpenType fonts with CFF data are not supported, yet");
}
return ttfFile;
}
| 270
| 215
| 485
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/Type3Glyph.java
|
Type3Glyph
|
addImage
|
class Type3Glyph extends PdfContentByte {
private PageResources pageResources;
private boolean colorized;
private Type3Glyph() {
super(null);
}
Type3Glyph(PdfWriter writer, PageResources pageResources, float wx, float llx, float lly, float urx, float ury,
boolean colorized) {
super(writer);
this.pageResources = pageResources;
this.colorized = colorized;
if (colorized) {
content.append(wx).append(" 0 d0\n");
} else {
content.append(wx).append(" 0 ").append(llx).append(' ').append(lly).append(' ').append(urx).append(' ')
.append(ury).append(" d1\n");
}
}
PageResources getPageResources() {
return pageResources;
}
public void addImage(Image image, float a, float b, float c, float d, float e, float f, boolean inlineImage)
throws DocumentException {<FILL_FUNCTION_BODY>}
public PdfContentByte getDuplicate() {
Type3Glyph dup = new Type3Glyph();
dup.writer = writer;
dup.pdf = pdf;
dup.pageResources = pageResources;
dup.colorized = colorized;
return dup;
}
}
|
if (!colorized && (!image.isMask() || !(image.getBpc() == 1 || image.getBpc() > 0xff))) {
throw new DocumentException(
MessageLocalization.getComposedMessage("not.colorized.typed3.fonts.only.accept.mask.images"));
}
super.addImage(image, a, b, c, d, e, f, inlineImage);
| 358
| 103
| 461
|
<methods>public void <init>(com.lowagie.text.pdf.PdfWriter) ,public void add(com.lowagie.text.pdf.PdfContentByte) ,public void addImage(com.lowagie.text.Image) throws com.lowagie.text.DocumentException,public void addImage(com.lowagie.text.Image, boolean) throws com.lowagie.text.DocumentException,public void addImage(com.lowagie.text.Image, float, float, float, float, float, float) throws com.lowagie.text.DocumentException,public void addImage(com.lowagie.text.Image, float, float, float, float, float, float, boolean) throws com.lowagie.text.DocumentException,public void addOutline(com.lowagie.text.pdf.PdfOutline, java.lang.String) ,public void addPSXObject(com.lowagie.text.pdf.PdfPSXObject) ,public void addTemplate(com.lowagie.text.pdf.PdfTemplate, float, float, float, float, float, float) ,public void addTemplate(com.lowagie.text.pdf.PdfTemplate, float, float) ,public void addTemplate(com.lowagie.text.pdf.PdfTemplate, double, double, double, double, double, double) ,public void arc(float, float, float, float, float, float) ,public void beginLayer(com.lowagie.text.pdf.PdfOCG) ,public void beginMarkedContentSequence(com.lowagie.text.pdf.PdfStructureElement) ,public void beginMarkedContentSequence(com.lowagie.text.pdf.PdfStructureElement, com.lowagie.text.pdf.PdfDictionary) ,public void beginMarkedContentSequence(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfDictionary, boolean) ,public void beginMarkedContentSequence(com.lowagie.text.pdf.PdfName) ,public void beginText() ,public static List<float[]> bezierArc(float, float, float, float, float, float) ,public void circle(float, float, float) ,public void clip() ,public void closePath() ,public void closePathEoFillStroke() ,public void closePathFillStroke() ,public void closePathStroke() ,public void concatCTM(float, float, float, float, float, float) ,public com.lowagie.text.pdf.PdfAppearance createAppearance(float, float) ,public java.awt.Graphics2D createGraphics(float, float) ,public java.awt.Graphics2D createGraphics(float, float, boolean, float) ,public java.awt.Graphics2D createGraphics(float, float, com.lowagie.text.pdf.FontMapper) ,public java.awt.Graphics2D createGraphics(float, float, com.lowagie.text.pdf.FontMapper, boolean, float) ,public java.awt.Graphics2D createGraphicsShapes(float, float) ,public java.awt.Graphics2D createGraphicsShapes(float, float, boolean, float) ,public com.lowagie.text.pdf.PdfPatternPainter createPattern(float, float, float, float) ,public com.lowagie.text.pdf.PdfPatternPainter createPattern(float, float) ,public com.lowagie.text.pdf.PdfPatternPainter createPattern(float, float, float, float, java.awt.Color) ,public com.lowagie.text.pdf.PdfPatternPainter createPattern(float, float, java.awt.Color) ,public java.awt.Graphics2D createPrinterGraphics(float, float, java.awt.print.PrinterJob) ,public java.awt.Graphics2D createPrinterGraphics(float, float, boolean, float, java.awt.print.PrinterJob) ,public java.awt.Graphics2D createPrinterGraphics(float, float, com.lowagie.text.pdf.FontMapper, java.awt.print.PrinterJob) ,public java.awt.Graphics2D createPrinterGraphics(float, float, com.lowagie.text.pdf.FontMapper, boolean, float, java.awt.print.PrinterJob) ,public java.awt.Graphics2D createPrinterGraphicsShapes(float, float, java.awt.print.PrinterJob) ,public java.awt.Graphics2D createPrinterGraphicsShapes(float, float, boolean, float, java.awt.print.PrinterJob) ,public com.lowagie.text.pdf.PdfTemplate createTemplate(float, float) ,public void curveFromTo(float, float, float, float) ,public void curveTo(float, float, float, float, float, float) ,public void curveTo(float, float, float, float) ,public void drawButton(float, float, float, float, java.lang.String, com.lowagie.text.pdf.BaseFont, float) ,public void drawRadioField(float, float, float, float, boolean) ,public void drawTextField(float, float, float, float) ,public void ellipse(float, float, float, float) ,public void endLayer() ,public void endMarkedContentSequence() ,public void endText() ,public void eoClip() ,public void eoFill() ,public void eoFillStroke() ,public void fill() ,public void fillStroke() ,public float getCharacterSpacing() ,public com.lowagie.text.pdf.PdfContentByte getDuplicate() ,public float getEffectiveStringWidth(java.lang.String, boolean) ,public float getHorizontalScaling() ,public com.lowagie.text.pdf.ByteBuffer getInternalBuffer() ,public static com.lowagie.text.pdf.PdfTextArray getKernArray(java.lang.String, com.lowagie.text.pdf.BaseFont) ,public float getLeading() ,public com.lowagie.text.pdf.PdfDocument getPdfDocument() ,public com.lowagie.text.pdf.PdfWriter getPdfWriter() ,public com.lowagie.text.pdf.PdfOutline getRootOutline() ,public float getWordSpacing() ,public float getXTLM() ,public float getYTLM() ,public void lineTo(float, float) ,public boolean localDestination(java.lang.String, com.lowagie.text.pdf.PdfDestination) ,public void localGoto(java.lang.String, float, float, float, float) ,public void moveText(float, float) ,public void moveTextWithLeading(float, float) ,public void moveTo(float, float) ,public void newPath() ,public void newlineShowText(java.lang.String) ,public void newlineShowText(float, float, java.lang.String) ,public void newlineText() ,public void paintShading(com.lowagie.text.pdf.PdfShading) ,public void paintShading(com.lowagie.text.pdf.PdfShadingPattern) ,public void rectangle(float, float, float, float) ,public void rectangle(com.lowagie.text.Rectangle) ,public void remoteGoto(java.lang.String, java.lang.String, float, float, float, float) ,public void remoteGoto(java.lang.String, int, float, float, float, float) ,public void reset() ,public void reset(boolean) ,public void resetCMYKColorFill() ,public void resetCMYKColorStroke() ,public void resetGrayFill() ,public void resetGrayStroke() ,public void resetRGBColorFill() ,public void resetRGBColorStroke() ,public void restoreState() ,public void roundRectangle(float, float, float, float, float) ,public void sanityCheck() ,public void saveState() ,public void setAction(com.lowagie.text.pdf.PdfAction, float, float, float, float) ,public void setCMYKColorFill(int, int, int, int) ,public void setCMYKColorFillF(float, float, float, float) ,public void setCMYKColorFillF(float, float, float, float, float) ,public void setCMYKColorStroke(int, int, int, int) ,public void setCMYKColorStrokeF(float, float, float, float) ,public void setCMYKColorStrokeF(float, float, float, float, float) ,public void setCharacterSpacing(float) ,public void setColorFill(java.awt.Color) ,public void setColorFill(com.lowagie.text.pdf.PdfSpotColor, float) ,public void setColorStroke(java.awt.Color) ,public void setColorStroke(com.lowagie.text.pdf.PdfSpotColor, float) ,public void setDefaultColorspace(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void setFlatness(float) ,public void setFontAndSize(com.lowagie.text.pdf.BaseFont, float) ,public void setGState(com.lowagie.text.pdf.PdfGState) ,public void setGrayFill(float) ,public void setGrayFill(float, float) ,public void setGrayStroke(float) ,public void setGrayStroke(float, float) ,public void setHorizontalScaling(float) ,public void setLeading(float) ,public void setLineCap(int) ,public void setLineDash(float) ,public void setLineDash(float, float) ,public void setLineDash(float, float, float) ,public final void setLineDash(float[], float) ,public void setLineJoin(int) ,public void setLineWidth(float) ,public void setLiteral(java.lang.String) ,public void setLiteral(char) ,public void setLiteral(float) ,public void setMiterLimit(float) ,public void setPatternFill(com.lowagie.text.pdf.PdfPatternPainter) ,public void setPatternFill(com.lowagie.text.pdf.PdfPatternPainter, java.awt.Color) ,public void setPatternFill(com.lowagie.text.pdf.PdfPatternPainter, java.awt.Color, float) ,public void setPatternStroke(com.lowagie.text.pdf.PdfPatternPainter, java.awt.Color) ,public void setPatternStroke(com.lowagie.text.pdf.PdfPatternPainter, java.awt.Color, float) ,public void setPatternStroke(com.lowagie.text.pdf.PdfPatternPainter) ,public void setRGBColorFill(int, int, int) ,public void setRGBColorFill(int, int, int, int) ,public void setRGBColorFillF(float, float, float) ,public void setRGBColorFillF(float, float, float, float) ,public void setRGBColorStroke(int, int, int) ,public void setRGBColorStroke(int, int, int, int) ,public void setRGBColorStrokeF(float, float, float) ,public void setShadingFill(com.lowagie.text.pdf.PdfShadingPattern) ,public void setShadingStroke(com.lowagie.text.pdf.PdfShadingPattern) ,public void setTextMatrix(float, float, float, float, float, float) ,public void setTextMatrix(float, float) ,public void setTextRenderingMode(int) ,public void setTextRise(float) ,public void setWordSpacing(float) ,public void showText(java.lang.String) ,public void showText(java.awt.font.GlyphVector) ,public void showText(java.awt.font.GlyphVector, int, int) ,public void showText(com.lowagie.text.pdf.PdfGlyphArray) ,public void showText(com.lowagie.text.pdf.PdfTextArray) ,public void showTextAligned(int, java.lang.String, float, float, float) ,public void showTextAlignedKerned(int, java.lang.String, float, float, float) ,public void showTextBasic(java.lang.String) ,public void showTextKerned(java.lang.String) ,public void stroke() ,public byte[] toPdf(com.lowagie.text.pdf.PdfWriter) ,public java.lang.String toString() ,public void transform(java.awt.geom.AffineTransform) ,public void variableRectangle(com.lowagie.text.Rectangle) <variables>public static final int ALIGN_CENTER,public static final int ALIGN_LEFT,public static final int ALIGN_RIGHT,public static final int LINE_CAP_BUTT,public static final int LINE_CAP_PROJECTING_SQUARE,public static final int LINE_CAP_ROUND,public static final int LINE_JOIN_BEVEL,public static final int LINE_JOIN_MITER,public static final int LINE_JOIN_ROUND,static final float MIN_FONT_SIZE,public static final int TEXT_RENDER_MODE_CLIP,public static final int TEXT_RENDER_MODE_FILL,public static final int TEXT_RENDER_MODE_FILL_CLIP,public static final int TEXT_RENDER_MODE_FILL_STROKE,public static final int TEXT_RENDER_MODE_FILL_STROKE_CLIP,public static final int TEXT_RENDER_MODE_INVISIBLE,public static final int TEXT_RENDER_MODE_STROKE,public static final int TEXT_RENDER_MODE_STROKE_CLIP,private static final Map<com.lowagie.text.pdf.PdfName,java.lang.String> abrev,protected com.lowagie.text.pdf.ByteBuffer content,private boolean inText,private int lastFillAlpha,private int lastStrokeAlpha,protected List<java.lang.Integer> layerDepth,private java.awt.geom.Point2D layoutPositionCorrection,private int mcDepth,protected com.lowagie.text.pdf.PdfDocument pdf,protected int separator,protected com.lowagie.text.pdf.PdfContentByte.GraphicState state,protected List<com.lowagie.text.pdf.PdfContentByte.GraphicState> stateList,private static final float[] unitRect,protected com.lowagie.text.pdf.PdfWriter writer
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/UnembedFontPdfSmartCopy.java
|
UnembedFontPdfSmartCopy
|
copyDictionary
|
class UnembedFontPdfSmartCopy extends PdfSmartCopy {
public UnembedFontPdfSmartCopy(Document document, OutputStream os)
throws DocumentException {
super(document, os);
}
protected PdfDictionary copyDictionary(PdfDictionary in)
throws IOException, BadPdfFormatException {<FILL_FUNCTION_BODY>}
}
|
PdfDictionary out = new PdfDictionary();
PdfObject type = PdfReader.getPdfObjectRelease(in.get(PdfName.TYPE));
for (PdfName key : in.getKeys()) {
PdfObject value = in.get(key);
if ((PdfName.FONTFILE.equals(key)
|| PdfName.FONTFILE2.equals(key)
|| PdfName.FONTFILE3.equals(key))
&& !PdfReader.isFontSubset(PdfReader.getFontNameFromDescriptor(in))) {
continue;
} else {
out.put(key, copyObject(value));
}
}
return out;
| 94
| 178
| 272
|
<methods>public void <init>(com.lowagie.text.Document, java.io.OutputStream) throws com.lowagie.text.DocumentException<variables>private Map<com.lowagie.text.pdf.PdfSmartCopy.ByteStore,com.lowagie.text.pdf.PdfIndirectReference> streamMap
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/XfdfReader.java
|
XfdfReader
|
endElement
|
class XfdfReader implements SimpleXMLDocHandler, FieldReader {
// stuff used during parsing to handle state
private boolean foundRoot = false;
private Stack<String> fieldNames = new Stack<>();
private Stack<String> fieldValues = new Stack<>();
// storage for the field list and their values
private Map<String, String> fields;
/**
* Storage for field values if there's more than one value for a field.
*
* @since 2.1.4
*/
private Map<String, List<String>> listFields;
// storage for the path to referenced PDF, if any
private String fileSpec;
/**
* Reads an XFDF form.
*
* @param filename the file name of the form
* @throws IOException on error
*/
public XfdfReader(String filename) throws IOException {
try (FileInputStream fin = new FileInputStream(filename)) {
SimpleXMLParser.parse(this, fin);
}
}
/**
* Reads an XFDF form.
*
* @param xfdfIn the byte array with the form
* @throws IOException on error
*/
public XfdfReader(byte[] xfdfIn) throws IOException {
SimpleXMLParser.parse(this, new ByteArrayInputStream(xfdfIn));
}
@Override
public Map<String, String> getAllFields() {
return fields;
}
/**
* Gets the field value.
*
* @param name the fully qualified field name
* @return the field's value
*/
public String getField(String name) {
return fields.get(name);
}
/**
* Gets the field value or <CODE>null</CODE> if the field does not exist or has no value defined.
*
* @param name the fully qualified field name
* @return the field value or <CODE>null</CODE>
*/
@Override
public String getFieldValue(String name) {
return fields.get(name);
}
/**
* Gets the field values for a list or <CODE>null</CODE> if the field does not exist or has no value defined.
*
* @param name the fully qualified field name
* @return the field values or <CODE>null</CODE>
* @since 2.1.4
*/
@Override
public List<String> getListValues(String name) {
return listFields.get(name);
}
/**
* Gets the PDF file specification contained in the FDF.
*
* @return the PDF file specification contained in the FDF
*/
public String getFileSpec() {
return fileSpec;
}
/**
* Called when a start tag is found.
*
* @param tag the tag name
* @param h the tag's attributes
*/
@Override
public void startElement(String tag, Map<String, String> h) {
if (!foundRoot) {
if (!tag.equals("xfdf")) {
throw new RuntimeException(MessageLocalization.getComposedMessage("root.element.is.not.xfdf.1", tag));
} else {
foundRoot = true;
}
}
switch (tag) {
case "xfdf":
// intentionally left blank
break;
case "f":
fileSpec = h.get("href");
break;
case "fields":
fields = new HashMap<>(); // init it!
listFields = new HashMap<>();
break;
case "field":
String fName = h.get("name");
fieldNames.push(fName);
break;
case "value":
fieldValues.push("");
break;
}
}
/**
* Called when an end tag is found.
*
* @param tag the tag name
*/
@Override
public void endElement(String tag) {<FILL_FUNCTION_BODY>}
/**
* Called when the document starts to be parsed.
*/
public void startDocument() {
fileSpec = "";
}
/**
* Called after the document is parsed.
*/
public void endDocument() {
}
/**
* Called when a text element is found.
*
* @param str the text element, probably a fragment.
*/
public void text(String str) {
if (fieldNames.isEmpty() || fieldValues.isEmpty()) {
return;
}
String val = fieldValues.pop();
val += str;
fieldValues.push(val);
}
}
|
if (tag.equals("value")) {
StringBuilder fName = new StringBuilder();
for (int k = 0; k < fieldNames.size(); ++k) {
fName.append(".").append(fieldNames.elementAt(k));
}
if (fName.toString().startsWith(".")) {
fName = new StringBuilder(fName.substring(1));
}
String fVal = fieldValues.pop();
String old = fields.put(fName.toString(), fVal);
if (old != null) {
List<String> l = listFields.get(fName.toString());
if (l == null) {
l = new ArrayList<>();
l.add(old);
}
l.add(fVal);
listFields.put(fName.toString(), l);
}
} else if (tag.equals("field")) {
if (!fieldNames.isEmpty()) {
fieldNames.pop();
}
}
| 1,182
| 249
| 1,431
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/codec/wmf/InputMeta.java
|
InputMeta
|
readInt
|
class InputMeta {
InputStream in;
int length;
public InputMeta(InputStream in) {
this.in = in;
}
public int readWord() throws IOException {
length += 2;
int k1 = in.read();
if (k1 < 0) {
return 0;
}
return (k1 + (in.read() << 8)) & 0xffff;
}
public int readShort() throws IOException {
int k = readWord();
if (k > 0x7fff) {
k -= 0x10000;
}
return k;
}
public int readInt() throws IOException {<FILL_FUNCTION_BODY>}
public int readByte() throws IOException {
++length;
return in.read() & 0xff;
}
public void skip(int len) throws IOException {
length += len;
Utilities.skip(in, len);
}
public int getLength() {
return length;
}
public Color readColor() throws IOException {
int red = readByte();
int green = readByte();
int blue = readByte();
readByte();
return new Color(red, green, blue);
}
}
|
length += 4;
int k1 = in.read();
if (k1 < 0) {
return 0;
}
int k2 = in.read() << 8;
int k3 = in.read() << 16;
return k1 + k2 + k3 + (in.read() << 24);
| 326
| 86
| 412
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/codec/wmf/MetaBrush.java
|
MetaBrush
|
init
|
class MetaBrush extends MetaObject {
public static final int BS_SOLID = 0;
public static final int BS_NULL = 1;
public static final int BS_HATCHED = 2;
public static final int BS_PATTERN = 3;
public static final int BS_DIBPATTERN = 5;
public static final int HS_HORIZONTAL = 0;
public static final int HS_VERTICAL = 1;
public static final int HS_FDIAGONAL = 2;
public static final int HS_BDIAGONAL = 3;
public static final int HS_CROSS = 4;
public static final int HS_DIAGCROSS = 5;
int style = BS_SOLID;
int hatch;
Color color = Color.white;
public MetaBrush() {
type = META_BRUSH;
}
public void init(InputMeta in) throws IOException {<FILL_FUNCTION_BODY>}
public int getStyle() {
return style;
}
public int getHatch() {
return hatch;
}
public Color getColor() {
return color;
}
}
|
style = in.readWord();
color = in.readColor();
hatch = in.readWord();
| 312
| 31
| 343
|
<methods>public void <init>() ,public void <init>(int) ,public int getType() <variables>public static final int META_BRUSH,public static final int META_FONT,public static final int META_NOT_SUPPORTED,public static final int META_PEN,public int type
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/codec/wmf/MetaFont.java
|
MetaFont
|
init
|
class MetaFont extends MetaObject {
static final String[] fontNames = {
"Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique",
"Helvetica", "Helvetica-Bold", "Helvetica-Oblique", "Helvetica-BoldOblique",
"Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic",
"Symbol", "ZapfDingbats"};
static final int MARKER_BOLD = 1;
static final int MARKER_ITALIC = 2;
static final int MARKER_COURIER = 0;
static final int MARKER_HELVETICA = 4;
static final int MARKER_TIMES = 8;
static final int MARKER_SYMBOL = 12;
static final int DEFAULT_PITCH = 0;
static final int FIXED_PITCH = 1;
static final int VARIABLE_PITCH = 2;
static final int FF_DONTCARE = 0;
static final int FF_ROMAN = 1;
static final int FF_SWISS = 2;
static final int FF_MODERN = 3;
static final int FF_SCRIPT = 4;
static final int FF_DECORATIVE = 5;
static final int BOLDTHRESHOLD = 600;
static final int nameSize = 32;
static final int ETO_OPAQUE = 2;
static final int ETO_CLIPPED = 4;
int height;
float angle;
int bold;
int italic;
boolean underline;
boolean strikeout;
int charset;
int pitchAndFamily;
String faceName = "arial";
BaseFont font = null;
public MetaFont() {
type = META_FONT;
}
public void init(InputMeta in) throws IOException {<FILL_FUNCTION_BODY>}
public BaseFont getFont() {
if (font != null) {
return font;
}
Font ff2 = FontFactory.getFont(faceName, BaseFont.CP1252, true, 10,
((italic != 0) ? Font.ITALIC : 0) | ((bold != 0) ? Font.BOLD : 0));
font = ff2.getBaseFont();
if (font != null) {
return font;
}
String fontName;
if (faceName.contains("courier") || faceName.contains("terminal")
|| faceName.contains("fixedsys")) {
fontName = fontNames[MARKER_COURIER + italic + bold];
} else if (faceName.contains("ms sans serif") || faceName.contains("arial")
|| faceName.contains("system")) {
fontName = fontNames[MARKER_HELVETICA + italic + bold];
} else if (faceName.contains("arial black")) {
fontName = fontNames[MARKER_HELVETICA + italic + MARKER_BOLD];
} else if (faceName.contains("times") || faceName.contains("ms serif")
|| faceName.contains("roman")) {
fontName = fontNames[MARKER_TIMES + italic + bold];
} else if (faceName.contains("symbol")) {
fontName = fontNames[MARKER_SYMBOL];
} else {
int pitch = pitchAndFamily & 3;
int family = (pitchAndFamily >> 4) & 7;
switch (family) {
case FF_MODERN:
fontName = fontNames[MARKER_COURIER + italic + bold];
break;
case FF_ROMAN:
fontName = fontNames[MARKER_TIMES + italic + bold];
break;
case FF_SWISS:
case FF_SCRIPT:
case FF_DECORATIVE:
fontName = fontNames[MARKER_HELVETICA + italic + bold];
break;
default: {
switch (pitch) {
case FIXED_PITCH:
fontName = fontNames[MARKER_COURIER + italic + bold];
break;
default:
fontName = fontNames[MARKER_HELVETICA + italic + bold];
break;
}
}
}
}
try {
font = BaseFont.createFont(fontName, "Cp1252", false);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
return font;
}
public float getAngle() {
return angle;
}
public boolean isUnderline() {
return underline;
}
public boolean isStrikeout() {
return strikeout;
}
public float getFontSize(MetaState state) {
return Math.abs(state.transformY(height) - state.transformY(0)) * Document.wmfFontCorrection;
}
}
|
height = Math.abs(in.readShort());
in.skip(2);
angle = (float) (in.readShort() / 1800.0 * Math.PI);
in.skip(2);
bold = (in.readShort() >= BOLDTHRESHOLD ? MARKER_BOLD : 0);
italic = (in.readByte() != 0 ? MARKER_ITALIC : 0);
underline = (in.readByte() != 0);
strikeout = (in.readByte() != 0);
charset = in.readByte();
in.skip(3);
pitchAndFamily = in.readByte();
byte[] name = new byte[nameSize];
int k;
for (k = 0; k < nameSize; ++k) {
int c = in.readByte();
if (c == 0) {
break;
}
name[k] = (byte) c;
}
try {
faceName = new String(name, 0, k, "Cp1252");
} catch (UnsupportedEncodingException e) {
faceName = new String(name, 0, k);
}
faceName = faceName.toLowerCase(Locale.ROOT);
| 1,323
| 320
| 1,643
|
<methods>public void <init>() ,public void <init>(int) ,public int getType() <variables>public static final int META_BRUSH,public static final int META_FONT,public static final int META_NOT_SUPPORTED,public static final int META_PEN,public int type
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/codec/wmf/MetaPen.java
|
MetaPen
|
init
|
class MetaPen extends MetaObject {
public static final int PS_SOLID = 0;
public static final int PS_DASH = 1;
public static final int PS_DOT = 2;
public static final int PS_DASHDOT = 3;
public static final int PS_DASHDOTDOT = 4;
public static final int PS_NULL = 5;
public static final int PS_INSIDEFRAME = 6;
int style = PS_SOLID;
int penWidth = 1;
Color color = Color.black;
public MetaPen() {
type = META_PEN;
}
public void init(InputMeta in) throws IOException {<FILL_FUNCTION_BODY>}
public int getStyle() {
return style;
}
public int getPenWidth() {
return penWidth;
}
public Color getColor() {
return color;
}
}
|
style = in.readWord();
penWidth = in.readShort();
in.readWord();
color = in.readColor();
| 245
| 38
| 283
|
<methods>public void <init>() ,public void <init>(int) ,public int getType() <variables>public static final int META_BRUSH,public static final int META_FONT,public static final int META_NOT_SUPPORTED,public static final int META_PEN,public int type
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/collection/PdfCollectionField.java
|
PdfCollectionField
|
isCollectionItem
|
class PdfCollectionField extends PdfDictionary {
/**
* A possible type of collection field.
*/
public static final int TEXT = 0;
/**
* A possible type of collection field.
*/
public static final int DATE = 1;
/**
* A possible type of collection field.
*/
public static final int NUMBER = 2;
/**
* A possible type of collection field.
*/
public static final int FILENAME = 3;
/**
* A possible type of collection field.
*/
public static final int DESC = 4;
/**
* A possible type of collection field.
*/
public static final int MODDATE = 5;
/**
* A possible type of collection field.
*/
public static final int CREATIONDATE = 6;
/**
* A possible type of collection field.
*/
public static final int SIZE = 7;
/**
* The type of the PDF collection field.
*
* @since 2.1.2 (was called <code>type</code> previously)
*/
protected int fieldType;
/**
* Creates a PdfCollectionField.
*
* @param name the field name
* @param type the field type
*/
public PdfCollectionField(String name, int type) {
super(PdfName.COLLECTIONFIELD);
put(PdfName.N, new PdfString(name, PdfObject.TEXT_UNICODE));
this.fieldType = type;
switch (type) {
default:
put(PdfName.SUBTYPE, PdfName.S);
break;
case DATE:
put(PdfName.SUBTYPE, PdfName.D);
break;
case NUMBER:
put(PdfName.SUBTYPE, PdfName.N);
break;
case FILENAME:
put(PdfName.SUBTYPE, PdfName.F);
break;
case DESC:
put(PdfName.SUBTYPE, PdfName.DESC);
break;
case MODDATE:
put(PdfName.SUBTYPE, PdfName.MODDATE);
break;
case CREATIONDATE:
put(PdfName.SUBTYPE, PdfName.CREATIONDATE);
break;
case SIZE:
put(PdfName.SUBTYPE, PdfName.SIZE);
break;
}
}
/**
* The relative order of the field name. Fields are sorted in ascending order.
*
* @param i a number indicating the order of the field
*/
public void setOrder(int i) {
put(PdfName.O, new PdfNumber(i));
}
/**
* Sets the initial visibility of the field.
*
* @param visible the default is true (visible)
*/
public void setVisible(boolean visible) {
put(PdfName.V, new PdfBoolean(visible));
}
/**
* Indication if the field value should be editable in the viewer.
*
* @param editable the default is false (not editable)
*/
public void setEditable(boolean editable) {
put(PdfName.E, new PdfBoolean(editable));
}
/**
* Checks if the type of the field is suitable for a Collection Item.
*
* @return true if it is a Collection item, false otherwise
*/
public boolean isCollectionItem() {<FILL_FUNCTION_BODY>}
/**
* Returns a PdfObject that can be used as the value of a Collection Item.
*
* @param v value the value that has to be changed into a PdfObject (PdfString, PdfDate or PdfNumber)
* @return a PdfObject that can be used as the value of a Collection Item.
*/
public PdfObject getValue(String v) {
switch (fieldType) {
case TEXT:
return new PdfString(v, PdfObject.TEXT_UNICODE);
case DATE:
return new PdfDate(PdfDate.decode(v));
case NUMBER:
return new PdfNumber(v);
}
throw new IllegalArgumentException(
MessageLocalization.getComposedMessage("1.is.not.an.acceptable.value.for.the.field.2", v,
get(PdfName.N).toString()));
}
}
|
switch (fieldType) {
case TEXT:
case DATE:
case NUMBER:
return true;
default:
return false;
}
| 1,134
| 47
| 1,181
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.PdfName) ,public void clear() ,public boolean contains(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject get(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfArray getAsArray(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfBoolean getAsBoolean(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfDictionary getAsDict(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfIndirectReference getAsIndirectObject(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfName getAsName(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfNumber getAsNumber(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfStream getAsStream(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfString getAsString(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject getDirectObject(com.lowagie.text.pdf.PdfName) ,public Set<com.lowagie.text.pdf.PdfName> getKeys() ,public Set<Entry<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject>> getKeysAndValues() ,public boolean isCatalog() ,public boolean isFont() ,public boolean isOutlineTree() ,public boolean isPage() ,public boolean isPages() ,public void merge(com.lowagie.text.pdf.PdfDictionary) ,public void mergeDifferent(com.lowagie.text.pdf.PdfDictionary) ,public void put(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void putAll(com.lowagie.text.pdf.PdfDictionary) ,public void putEx(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void remove(com.lowagie.text.pdf.PdfName) ,public int size() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() <variables>public static final com.lowagie.text.pdf.PdfName CATALOG,public static final com.lowagie.text.pdf.PdfName FONT,public static final com.lowagie.text.pdf.PdfName OUTLINES,public static final com.lowagie.text.pdf.PdfName PAGE,public static final com.lowagie.text.pdf.PdfName PAGES,private com.lowagie.text.pdf.PdfName dictionaryType,protected Map<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject> hashMap
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/collection/PdfCollectionItem.java
|
PdfCollectionItem
|
addItem
|
class PdfCollectionItem extends PdfDictionary {
/**
* The PdfCollectionSchema with the names and types of the items.
*/
PdfCollectionSchema schema;
/**
* Constructs a Collection Item that can be added to a PdfFileSpecification.
*
* @param schema the PdfCollectionSchema
*/
public PdfCollectionItem(PdfCollectionSchema schema) {
super(PdfName.COLLECTIONITEM);
this.schema = schema;
}
/**
* Sets the value of the collection item.
*
* @param value the value (a String)
* @param key the key
*/
public void addItem(String key, String value) {
PdfName fieldname = new PdfName(key);
PdfCollectionField field = (PdfCollectionField) schema.get(fieldname);
put(fieldname, field.getValue(value));
}
/**
* Sets the value of the collection item.
*
* @param value the value (a PdfString)
* @param key the key
*/
public void addItem(String key, PdfString value) {<FILL_FUNCTION_BODY>}
/**
* Sets the value of the collection item.
*
* @param d the value (a PdfDate)
* @param key the key
*/
public void addItem(String key, PdfDate d) {
PdfName fieldname = new PdfName(key);
PdfCollectionField field = (PdfCollectionField) schema.get(fieldname);
if (field.fieldType == PdfCollectionField.DATE) {
put(fieldname, d);
}
}
/**
* Sets the value of the collection item.
*
* @param n the value (a PdfNumber)
* @param key the key
*/
public void addItem(String key, PdfNumber n) {
PdfName fieldname = new PdfName(key);
PdfCollectionField field = (PdfCollectionField) schema.get(fieldname);
if (field.fieldType == PdfCollectionField.NUMBER) {
put(fieldname, n);
}
}
/**
* Sets the value of the collection item.
*
* @param c the value (a Calendar)
* @param key the key
*/
public void addItem(String key, Calendar c) {
addItem(key, new PdfDate(c));
}
/**
* Sets the value of the collection item.
*
* @param i the value
* @param key the key
*/
public void addItem(String key, int i) {
addItem(key, new PdfNumber(i));
}
/**
* Sets the value of the collection item.
*
* @param f the value
* @param key the key
*/
public void addItem(String key, float f) {
addItem(key, new PdfNumber(f));
}
/**
* Sets the value of the collection item.
*
* @param d the value
* @param key the key
*/
public void addItem(String key, double d) {
addItem(key, new PdfNumber(d));
}
/**
* Adds a prefix for the Collection item. You can only use this method after you have set the value of the item.
*
* @param prefix a prefix
* @param key the key
*/
public void setPrefix(String key, String prefix) {
PdfName fieldname = new PdfName(key);
PdfObject o = get(fieldname);
if (o == null) {
throw new IllegalArgumentException(
MessageLocalization.getComposedMessage("you.must.set.a.value.before.adding.a.prefix"));
}
PdfDictionary dict = new PdfDictionary(PdfName.COLLECTIONSUBITEM);
dict.put(PdfName.D, o);
dict.put(PdfName.P, new PdfString(prefix, PdfObject.TEXT_UNICODE));
put(fieldname, dict);
}
}
|
PdfName fieldname = new PdfName(key);
PdfCollectionField field = (PdfCollectionField) schema.get(fieldname);
if (field.fieldType == PdfCollectionField.TEXT) {
put(fieldname, value);
}
| 1,066
| 68
| 1,134
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.PdfName) ,public void clear() ,public boolean contains(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject get(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfArray getAsArray(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfBoolean getAsBoolean(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfDictionary getAsDict(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfIndirectReference getAsIndirectObject(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfName getAsName(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfNumber getAsNumber(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfStream getAsStream(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfString getAsString(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject getDirectObject(com.lowagie.text.pdf.PdfName) ,public Set<com.lowagie.text.pdf.PdfName> getKeys() ,public Set<Entry<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject>> getKeysAndValues() ,public boolean isCatalog() ,public boolean isFont() ,public boolean isOutlineTree() ,public boolean isPage() ,public boolean isPages() ,public void merge(com.lowagie.text.pdf.PdfDictionary) ,public void mergeDifferent(com.lowagie.text.pdf.PdfDictionary) ,public void put(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void putAll(com.lowagie.text.pdf.PdfDictionary) ,public void putEx(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void remove(com.lowagie.text.pdf.PdfName) ,public int size() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() <variables>public static final com.lowagie.text.pdf.PdfName CATALOG,public static final com.lowagie.text.pdf.PdfName FONT,public static final com.lowagie.text.pdf.PdfName OUTLINES,public static final com.lowagie.text.pdf.PdfName PAGE,public static final com.lowagie.text.pdf.PdfName PAGES,private com.lowagie.text.pdf.PdfName dictionaryType,protected Map<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject> hashMap
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/collection/PdfCollectionSort.java
|
PdfCollectionSort
|
setSortOrder
|
class PdfCollectionSort extends PdfDictionary {
/**
* Constructs a PDF Collection Sort Dictionary.
*
* @param key the key of the field that will be used to sort entries
*/
public PdfCollectionSort(String key) {
super(PdfName.COLLECTIONSORT);
put(PdfName.S, new PdfName(key));
}
/**
* Constructs a PDF Collection Sort Dictionary.
*
* @param keys the keys of the fields that will be used to sort entries
*/
public PdfCollectionSort(String[] keys) {
super(PdfName.COLLECTIONSORT);
PdfArray array = new PdfArray();
for (String key : keys) {
array.add(new PdfName(key));
}
put(PdfName.S, array);
}
/**
* Defines the sort order of the field (ascending or descending).
*
* @param ascending true is the default, use false for descending order
*/
public void setSortOrder(boolean ascending) {
PdfObject o = get(PdfName.S);
if (o instanceof PdfName) {
put(PdfName.A, new PdfBoolean(ascending));
} else {
throw new IllegalArgumentException(MessageLocalization.getComposedMessage(
"you.have.to.define.a.boolean.array.for.this.collection.sort.dictionary"));
}
}
/**
* Defines the sort order of the field (ascending or descending).
*
* @param ascending an array with every element corresponding with a name of a field.
*/
public void setSortOrder(boolean[] ascending) {<FILL_FUNCTION_BODY>}
}
|
PdfObject o = get(PdfName.S);
if (o instanceof PdfArray) {
if (((PdfArray) o).size() != ascending.length) {
throw new IllegalArgumentException(MessageLocalization.getComposedMessage(
"the.number.of.booleans.in.this.array.doesn.t.correspond.with.the.number.of.fields"));
}
PdfArray array = new PdfArray();
for (boolean b : ascending) {
array.add(new PdfBoolean(b));
}
put(PdfName.A, array);
} else {
throw new IllegalArgumentException(MessageLocalization.getComposedMessage(
"you.need.a.single.boolean.for.this.collection.sort.dictionary"));
}
| 449
| 204
| 653
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.PdfName) ,public void clear() ,public boolean contains(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject get(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfArray getAsArray(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfBoolean getAsBoolean(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfDictionary getAsDict(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfIndirectReference getAsIndirectObject(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfName getAsName(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfNumber getAsNumber(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfStream getAsStream(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfString getAsString(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject getDirectObject(com.lowagie.text.pdf.PdfName) ,public Set<com.lowagie.text.pdf.PdfName> getKeys() ,public Set<Entry<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject>> getKeysAndValues() ,public boolean isCatalog() ,public boolean isFont() ,public boolean isOutlineTree() ,public boolean isPage() ,public boolean isPages() ,public void merge(com.lowagie.text.pdf.PdfDictionary) ,public void mergeDifferent(com.lowagie.text.pdf.PdfDictionary) ,public void put(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void putAll(com.lowagie.text.pdf.PdfDictionary) ,public void putEx(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void remove(com.lowagie.text.pdf.PdfName) ,public int size() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() <variables>public static final com.lowagie.text.pdf.PdfName CATALOG,public static final com.lowagie.text.pdf.PdfName FONT,public static final com.lowagie.text.pdf.PdfName OUTLINES,public static final com.lowagie.text.pdf.PdfName PAGE,public static final com.lowagie.text.pdf.PdfName PAGES,private com.lowagie.text.pdf.PdfName dictionaryType,protected Map<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject> hashMap
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/crypto/AESCipher.java
|
AESCipher
|
doFinal
|
class AESCipher {
private final PaddedBufferedBlockCipher bp;
/**
* Creates a new instance of AESCipher
*
* @param forEncryption If it is for encryption
* @param iv An initialization vector
* @param key Bytes for key
*/
public AESCipher(boolean forEncryption, byte[] key, byte[] iv) {
BlockCipher aes = new AESEngine();
BlockCipher cbc = new CBCBlockCipher(aes);
bp = new PaddedBufferedBlockCipher(cbc);
KeyParameter kp = new KeyParameter(key);
ParametersWithIV piv = new ParametersWithIV(kp, iv);
bp.init(forEncryption, piv);
}
public byte[] update(byte[] inp, int inpOff, int inpLen) {
int neededLen = bp.getUpdateOutputSize(inpLen);
byte[] outp = null;
if (neededLen > 0) {
outp = new byte[neededLen];
}
bp.processBytes(inp, inpOff, inpLen, outp, 0);
return outp;
}
public byte[] doFinal() {<FILL_FUNCTION_BODY>}
}
|
int neededLen = bp.getOutputSize(0);
byte[] outp = new byte[neededLen];
int n;
try {
n = bp.doFinal(outp, 0);
} catch (Exception ex) {
return outp;
}
if (n != outp.length) {
byte[] outp2 = new byte[n];
System.arraycopy(outp, 0, outp2, 0, n);
return outp2;
} else {
return outp;
}
| 337
| 144
| 481
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/crypto/ARCFOUREncryption.java
|
ARCFOUREncryption
|
encryptARCFOUR
|
class ARCFOUREncryption {
private byte[] state = new byte[256];
private int x;
private int y;
/**
* Creates a new instance of ARCFOUREncryption
*/
public ARCFOUREncryption() {
}
public void prepareARCFOURKey(byte[] key) {
prepareARCFOURKey(key, 0, key.length);
}
public void prepareARCFOURKey(byte[] key, int off, int len) {
int index1 = 0;
int index2 = 0;
for (int k = 0; k < 256; ++k) {
state[k] = (byte) k;
}
x = 0;
y = 0;
byte tmp;
for (int k = 0; k < 256; ++k) {
index2 = (key[index1 + off] + state[k] + index2) & 255;
tmp = state[k];
state[k] = state[index2];
state[index2] = tmp;
index1 = (index1 + 1) % len;
}
}
public void encryptARCFOUR(byte[] dataIn, int off, int len, byte[] dataOut, int offOut) {<FILL_FUNCTION_BODY>}
public void encryptARCFOUR(byte[] data, int off, int len) {
encryptARCFOUR(data, off, len, data, off);
}
public void encryptARCFOUR(byte[] dataIn, byte[] dataOut) {
encryptARCFOUR(dataIn, 0, dataIn.length, dataOut, 0);
}
public void encryptARCFOUR(byte[] data) {
encryptARCFOUR(data, 0, data.length, data, 0);
}
}
|
int length = len + off;
byte tmp;
for (int k = off; k < length; ++k) {
x = (x + 1) & 255;
y = (state[x] + y) & 255;
tmp = state[x];
state[x] = state[y];
state[y] = tmp;
dataOut[k - off + offOut] = (byte) (dataIn[k] ^ state[(state[x] + state[y]) & 255]);
}
| 484
| 138
| 622
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/crypto/IVGenerator.java
|
IVGenerator
|
getIV
|
class IVGenerator {
private static ARCFOUREncryption arcfour;
static {
arcfour = new ARCFOUREncryption();
long time = System.currentTimeMillis();
long mem = Runtime.getRuntime().freeMemory();
String s = time + "+" + mem;
arcfour.prepareARCFOURKey(s.getBytes());
}
/**
* Creates a new instance of IVGenerator
*/
private IVGenerator() {
}
/**
* Gets a 16 byte random initialization vector.
*
* @return a 16 byte random initialization vector
*/
public static byte[] getIV() {
return getIV(16);
}
/**
* Gets a random initialization vector.
*
* @param len the length of the initialization vector
* @return a random initialization vector
*/
public static byte[] getIV(int len) {<FILL_FUNCTION_BODY>}
}
|
byte[] b = new byte[len];
synchronized (arcfour) {
arcfour.encryptARCFOUR(b);
}
return b;
| 251
| 46
| 297
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/draw/DottedLineSeparator.java
|
DottedLineSeparator
|
draw
|
class DottedLineSeparator extends LineSeparator {
/**
* the gap between the dots.
*/
protected float gap = 5;
/**
* @see com.lowagie.text.pdf.draw.DrawInterface#draw(com.lowagie.text.pdf.PdfContentByte, float, float, float,
* float, float)
*/
public void draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) {<FILL_FUNCTION_BODY>}
/**
* Getter for the gap between the center of the dots of the dotted line.
*
* @return the gap between the center of the dots
*/
public float getGap() {
return gap;
}
/**
* Setter for the gap between the center of the dots of the dotted line.
*
* @param gap the gap between the center of the dots
*/
public void setGap(float gap) {
this.gap = gap;
}
}
|
canvas.saveState();
canvas.setLineWidth(lineWidth);
canvas.setLineCap(PdfContentByte.LINE_CAP_ROUND);
canvas.setLineDash(0, gap, gap / 2);
drawLine(canvas, llx, urx, y);
canvas.restoreState();
| 265
| 82
| 347
|
<methods>public void <init>(float, float, java.awt.Color, int, float) ,public void <init>() ,public void draw(com.lowagie.text.pdf.PdfContentByte, float, float, float, float, float) ,public void drawLine(com.lowagie.text.pdf.PdfContentByte, float, float, float) ,public int getAlignment() ,public java.awt.Color getLineColor() ,public float getLineWidth() ,public float getPercentage() ,public void setAlignment(int) ,public void setLineColor(java.awt.Color) ,public void setLineWidth(float) ,public void setPercentage(float) <variables>protected int alignment,protected java.awt.Color lineColor,protected float lineWidth,protected float percentage
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/draw/LineSeparator.java
|
LineSeparator
|
drawLine
|
class LineSeparator extends VerticalPositionMark {
/**
* The thickness of the line.
*/
protected float lineWidth = 1;
/**
* The width of the line as a percentage of the available page width.
*/
protected float percentage = 100;
/**
* The color of the line.
*/
protected Color lineColor;
/**
* The alignment of the line.
*/
protected int alignment = Element.ALIGN_CENTER;
/**
* Creates a new instance of the LineSeparator class.
*
* @param lineWidth the thickness of the line
* @param percentage the width of the line as a percentage of the available page width
* @param lineColor the color of the line
* @param align the alignment
* @param offset the offset of the line relative to the current baseline (negative = under the baseline)
*/
public LineSeparator(float lineWidth, float percentage, Color lineColor, int align, float offset) {
this.lineWidth = lineWidth;
this.percentage = percentage;
this.lineColor = lineColor;
this.alignment = align;
this.offset = offset;
}
/**
* Creates a new instance of the LineSeparator class with default values: lineWidth 1 user unit, width 100%,
* centered with offset 0.
*/
public LineSeparator() {
}
/**
* @see com.lowagie.text.pdf.draw.DrawInterface#draw(com.lowagie.text.pdf.PdfContentByte, float, float, float,
* float, float)
*/
public void draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) {
canvas.saveState();
drawLine(canvas, llx, urx, y);
canvas.restoreState();
}
/**
* Draws a horizontal line.
*
* @param canvas the canvas to draw on
* @param leftX the left x coordinate
* @param rightX the right x coordindate
* @param y the y coordinate
*/
public void drawLine(PdfContentByte canvas, float leftX, float rightX, float y) {<FILL_FUNCTION_BODY>}
/**
* Getter for the line width.
*
* @return the thickness of the line that will be drawn.
*/
public float getLineWidth() {
return lineWidth;
}
/**
* Setter for the line width.
*
* @param lineWidth the thickness of the line that will be drawn.
*/
public void setLineWidth(float lineWidth) {
this.lineWidth = lineWidth;
}
/**
* Setter for the width as a percentage of the available width.
*
* @return a width percentage
*/
public float getPercentage() {
return percentage;
}
/**
* Setter for the width as a percentage of the available width.
*
* @param percentage a width percentage
*/
public void setPercentage(float percentage) {
this.percentage = percentage;
}
/**
* Getter for the color of the line that will be drawn.
*
* @return a color
*/
public Color getLineColor() {
return lineColor;
}
/**
* Setter for the color of the line that will be drawn.
*
* @param color a color
*/
public void setLineColor(Color color) {
this.lineColor = color;
}
/**
* Getter for the alignment of the line.
*
* @return an alignment value
*/
public int getAlignment() {
return alignment;
}
/**
* Setter for the alignment of the line.
*
* @param align an alignment value
*/
public void setAlignment(int align) {
this.alignment = align;
}
}
|
float w;
if (getPercentage() < 0) {
w = -getPercentage();
} else {
w = (rightX - leftX) * getPercentage() / 100.0f;
}
float s;
switch (getAlignment()) {
case Element.ALIGN_LEFT:
s = 0;
break;
case Element.ALIGN_RIGHT:
s = rightX - leftX - w;
break;
default:
s = (rightX - leftX - w) / 2;
break;
}
canvas.setLineWidth(getLineWidth());
if (getLineColor() != null) {
canvas.setColorStroke(getLineColor());
}
canvas.moveTo(s + leftX, y + offset);
canvas.lineTo(s + w + leftX, y + offset);
canvas.stroke();
| 1,022
| 237
| 1,259
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.draw.DrawInterface, float) ,public void draw(com.lowagie.text.pdf.PdfContentByte, float, float, float, float, float) ,public ArrayList<com.lowagie.text.Element> getChunks() ,public com.lowagie.text.pdf.draw.DrawInterface getDrawInterface() ,public float getOffset() ,public boolean isContent() ,public boolean isNestable() ,public boolean process(com.lowagie.text.ElementListener) ,public void setDrawInterface(com.lowagie.text.pdf.draw.DrawInterface) ,public void setOffset(float) ,public int type() <variables>protected com.lowagie.text.pdf.draw.DrawInterface drawInterface,protected float offset
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/draw/VerticalPositionMark.java
|
VerticalPositionMark
|
getChunks
|
class VerticalPositionMark implements DrawInterface, Element {
/**
* Another implementation of the DrawInterface; its draw method will overrule LineSeparator.draw().
*/
protected DrawInterface drawInterface = null;
/**
* The offset for the line.
*/
protected float offset = 0;
/**
* Creates a vertical position mark that won't draw anything unless you define a DrawInterface.
*/
public VerticalPositionMark() {
}
/**
* Creates a vertical position mark that won't draw anything unless you define a DrawInterface.
*
* @param drawInterface the drawInterface for this vertical position mark.
* @param offset the offset for this vertical position mark.
*/
public VerticalPositionMark(DrawInterface drawInterface, float offset) {
this.drawInterface = drawInterface;
this.offset = offset;
}
/**
* @see com.lowagie.text.pdf.draw.DrawInterface#draw(com.lowagie.text.pdf.PdfContentByte, float, float, float,
* float, float)
*/
public void draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) {
if (drawInterface != null) {
drawInterface.draw(canvas, llx, lly, urx, ury, y + offset);
}
}
/**
* @see com.lowagie.text.Element#process(com.lowagie.text.ElementListener)
*/
public boolean process(ElementListener listener) {
try {
return listener.add(this);
} catch (DocumentException e) {
return false;
}
}
/**
* @see com.lowagie.text.Element#type()
*/
public int type() {
return Element.YMARK;
}
/**
* @see com.lowagie.text.Element#isContent()
*/
public boolean isContent() {
return true;
}
/**
* @see com.lowagie.text.Element#isNestable()
*/
public boolean isNestable() {
return false;
}
/**
* @see com.lowagie.text.Element#getChunks()
*/
public ArrayList<Element> getChunks() {<FILL_FUNCTION_BODY>}
/**
* Getter for the interface with the overruling draw() method.
*
* @return a DrawInterface implementation
*/
public DrawInterface getDrawInterface() {
return drawInterface;
}
/**
* Setter for the interface with the overruling draw() method.
*
* @param drawInterface a DrawInterface implementation
*/
public void setDrawInterface(DrawInterface drawInterface) {
this.drawInterface = drawInterface;
}
/**
* Getter for the offset relative to the baseline of the current line.
*
* @return an offset
*/
public float getOffset() {
return offset;
}
/**
* Setter for the offset. The offset is relative to the current Y position. If you want to underline something, you
* have to choose a negative offset.
*
* @param offset an offset
*/
public void setOffset(float offset) {
this.offset = offset;
}
}
|
ArrayList<Element> list = new ArrayList<>();
list.add(new Chunk(this, true));
return list;
| 858
| 34
| 892
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/events/FieldPositioningEvents.java
|
FieldPositioningEvents
|
onGenericTag
|
class FieldPositioningEvents extends PdfPageEventHelper implements PdfPCellEvent {
/**
* Some extra padding that will be taken into account when defining the widget.
*/
public float padding;
/**
* Keeps a map with fields that are to be positioned in inGenericTag.
*/
protected Map<String, PdfFormField> genericChunkFields = new HashMap<>();
/**
* Keeps the form field that is to be positioned in a cellLayout event.
*/
protected PdfFormField cellField = null;
/**
* The PdfWriter to use when a field has to added in a cell event.
*/
protected PdfWriter fieldWriter = null;
/**
* The PdfFormField that is the parent of the field added in a cell event.
*/
protected PdfFormField parent = null;
/**
* Creates a new event. This constructor will be used if you need to position fields with Chunk objects.
*/
public FieldPositioningEvents() {
}
/**
* Creates a new event. This constructor will be used if you need to position fields with a Cell Event.
*
* @param writer The PdfWriter
* @param field The field to label the Event
*/
public FieldPositioningEvents(PdfWriter writer, PdfFormField field) {
this.cellField = field;
this.fieldWriter = writer;
}
/**
* Creates a new event. This constructor will be used if you need to position fields with a Cell Event.
*
* @param parent The parent of the Event
* @param field The field to label the Event
*/
public FieldPositioningEvents(PdfFormField parent, PdfFormField field) {
this.cellField = field;
this.parent = parent;
}
/**
* Creates a new event. This constructor will be used if you need to position fields with a Cell Event.
*
* @param writer The PdfWriter
* @param text The text to label the TextField
* @throws DocumentException thrown when an error occurs in a Document
* @throws IOException throw when an I/O operation fails
*/
public FieldPositioningEvents(PdfWriter writer, String text) throws IOException, DocumentException {
this.fieldWriter = writer;
TextField tf = new TextField(writer, new Rectangle(0, 0), text);
tf.setFontSize(14);
cellField = tf.getTextField();
}
/**
* Creates a new event. This constructor will be used if you need to position fields with a Cell Event.
*
* @param text The label of the event
* @param parent The parent of the new event
* @param writer The PdfWriter
* @throws DocumentException thrown when an error occurs in a Document
* @throws IOException throw when an I/O operation fails
*/
public FieldPositioningEvents(PdfWriter writer, PdfFormField parent, String text)
throws IOException, DocumentException {
this.parent = parent;
TextField tf = new TextField(writer, new Rectangle(0, 0), text);
tf.setFontSize(14);
cellField = tf.getTextField();
}
/**
* Add a PdfFormField that has to be tied to a generic Chunk.
*
* @param field The PdfFormField
* @param text The text
*/
public void addField(String text, PdfFormField field) {
genericChunkFields.put(text, field);
}
/**
* @param padding The padding to set.
*/
public void setPadding(float padding) {
this.padding = padding;
}
/**
* @param parent The parent to set.
*/
public void setParent(PdfFormField parent) {
this.parent = parent;
}
/**
* @see com.lowagie.text.pdf.PdfPageEvent#onGenericTag(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document,
* com.lowagie.text.Rectangle, java.lang.String)
*/
public void onGenericTag(PdfWriter writer, Document document,
Rectangle rect, String text) {<FILL_FUNCTION_BODY>}
/**
* @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(com.lowagie.text.pdf.PdfPCell, com.lowagie.text.Rectangle,
* com.lowagie.text.pdf.PdfContentByte[])
*/
public void cellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] canvases) {
if (cellField == null || (fieldWriter == null && parent == null)) {
throw new IllegalArgumentException(MessageLocalization.getComposedMessage(
"you.have.used.the.wrong.constructor.for.this.fieldpositioningevents.class"));
}
cellField.put(PdfName.RECT,
new PdfRectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding),
rect.getTop(padding)));
if (parent == null) {
fieldWriter.addAnnotation(cellField);
} else {
parent.addKid(cellField);
}
}
}
|
rect.setBottom(rect.getBottom() - 3);
PdfFormField field = genericChunkFields.get(text);
if (field == null) {
TextField tf = new TextField(writer,
new Rectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding),
rect.getTop(padding)), text);
tf.setFontSize(14);
try {
field = tf.getTextField();
} catch (Exception e) {
throw new ExceptionConverter(e);
}
} else {
field.put(PdfName.RECT,
new PdfRectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding),
rect.getTop(padding)));
}
if (parent == null) {
writer.addAnnotation(field);
} else {
parent.addKid(field);
}
| 1,358
| 238
| 1,596
|
<methods>public non-sealed void <init>() ,public void onChapter(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document, float, com.lowagie.text.Paragraph) ,public void onChapterEnd(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document, float) ,public void onCloseDocument(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document) ,public void onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document) ,public void onGenericTag(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document, com.lowagie.text.Rectangle, java.lang.String) ,public void onOpenDocument(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document) ,public void onParagraph(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document, float) ,public void onParagraphEnd(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document, float) ,public void onSection(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document, float, int, com.lowagie.text.Paragraph) ,public void onSectionEnd(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document, float) ,public void onStartPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document) <variables>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/events/PdfPCellEventForwarder.java
|
PdfPCellEventForwarder
|
cellLayout
|
class PdfPCellEventForwarder implements PdfPCellEvent {
/**
* ArrayList containing all the PageEvents that have to be executed.
*/
protected List<PdfPCellEvent> events = new ArrayList<>();
/**
* Add a page event to the forwarder.
*
* @param event an event that has to be added to the forwarder.
*/
public void addCellEvent(PdfPCellEvent event) {
events.add(event);
}
/**
* @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(com.lowagie.text.pdf.PdfPCell, com.lowagie.text.Rectangle,
* com.lowagie.text.pdf.PdfContentByte[])
*/
public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {<FILL_FUNCTION_BODY>}
}
|
PdfPCellEvent event;
for (Object event1 : events) {
event = (PdfPCellEvent) event1;
event.cellLayout(cell, position, canvases);
}
| 241
| 55
| 296
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/events/PdfPTableEventForwarder.java
|
PdfPTableEventForwarder
|
tableLayout
|
class PdfPTableEventForwarder implements PdfPTableEvent {
/**
* ArrayList containing all the PageEvents that have to be executed.
*/
protected List<PdfPTableEvent> events = new ArrayList<>();
/**
* Add a page event to the forwarder.
*
* @param event an event that has to be added to the forwarder.
*/
public void addTableEvent(PdfPTableEvent event) {
events.add(event);
}
/**
* @see com.lowagie.text.pdf.PdfPTableEvent#tableLayout(com.lowagie.text.pdf.PdfPTable, float[][], float[], int,
* int, com.lowagie.text.pdf.PdfContentByte[])
*/
public void tableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart,
PdfContentByte[] canvases) {<FILL_FUNCTION_BODY>}
}
|
PdfPTableEvent event;
for (Object event1 : events) {
event = (PdfPTableEvent) event1;
event.tableLayout(table, widths, heights, headerRows, rowStart, canvases);
}
| 256
| 64
| 320
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/events/PdfPageEventForwarder.java
|
PdfPageEventForwarder
|
onChapterEnd
|
class PdfPageEventForwarder implements PdfPageEvent {
/**
* ArrayList containing all the PageEvents that have to be executed.
*/
protected List<PdfPageEvent> events = new ArrayList<>();
/**
* Add a page event to the forwarder.
*
* @param event an event that has to be added to the forwarder.
*/
public void addPageEvent(PdfPageEvent event) {
events.add(event);
}
/**
* Called when the document is opened.
*
* @param writer the <CODE>PdfWriter</CODE> for this document
* @param document the document
*/
public void onOpenDocument(PdfWriter writer, Document document) {
PdfPageEvent event;
for (Object event1 : events) {
event = (PdfPageEvent) event1;
event.onOpenDocument(writer, document);
}
}
/**
* Called when a page is initialized.
* <p>
* Note that if even if a page is not written this method is still called. It is preferable to use
* <CODE>onEndPage</CODE> to avoid infinite loops.
*
* @param writer the <CODE>PdfWriter</CODE> for this document
* @param document the document
*/
public void onStartPage(PdfWriter writer, Document document) {
PdfPageEvent event;
for (Object event1 : events) {
event = (PdfPageEvent) event1;
event.onStartPage(writer, document);
}
}
/**
* Called when a page is finished, just before being written to the document.
*
* @param writer the <CODE>PdfWriter</CODE> for this document
* @param document the document
*/
public void onEndPage(PdfWriter writer, Document document) {
PdfPageEvent event;
for (Object event1 : events) {
event = (PdfPageEvent) event1;
event.onEndPage(writer, document);
}
}
/**
* Called when the document is closed.
* <p>
* Note that this method is called with the page number equal to the last page plus one.
*
* @param writer the <CODE>PdfWriter</CODE> for this document
* @param document the document
*/
public void onCloseDocument(PdfWriter writer, Document document) {
PdfPageEvent event;
for (Object event1 : events) {
event = (PdfPageEvent) event1;
event.onCloseDocument(writer, document);
}
}
/**
* Called when a Paragraph is written.
* <p>
* <CODE>paragraphPosition</CODE> will hold the height at which the
* paragraph will be written to. This is useful to insert bookmarks with more control.
*
* @param writer the <CODE>PdfWriter</CODE> for this document
* @param document the document
* @param paragraphPosition the position the paragraph will be written to
*/
public void onParagraph(PdfWriter writer, Document document,
float paragraphPosition) {
PdfPageEvent event;
for (Object event1 : events) {
event = (PdfPageEvent) event1;
event.onParagraph(writer, document, paragraphPosition);
}
}
/**
* Called when a Paragraph is written.
* <p>
* <CODE>paragraphPosition</CODE> will hold the height of the end of the
* paragraph.
*
* @param writer the <CODE>PdfWriter</CODE> for this document
* @param document the document
* @param paragraphPosition the position of the end of the paragraph
*/
public void onParagraphEnd(PdfWriter writer, Document document,
float paragraphPosition) {
PdfPageEvent event;
for (Object event1 : events) {
event = (PdfPageEvent) event1;
event.onParagraphEnd(writer, document, paragraphPosition);
}
}
/**
* Called when a Chapter is written.
* <p>
* <CODE>position</CODE> will hold the height at which the chapter will be
* written to.
*
* @param writer the <CODE>PdfWriter</CODE> for this document
* @param document the document
* @param paragraphPosition the position the chapter will be written to
* @param title the title of the Chapter
*/
public void onChapter(PdfWriter writer, Document document,
float paragraphPosition, Paragraph title) {
PdfPageEvent event;
for (Object event1 : events) {
event = (PdfPageEvent) event1;
event.onChapter(writer, document, paragraphPosition, title);
}
}
/**
* Called when the end of a Chapter is reached.
* <p>
* <CODE>position</CODE> will hold the height of the end of the chapter.
*
* @param writer the <CODE>PdfWriter</CODE> for this document
* @param document the document
* @param position the position of the end of the chapter.
*/
public void onChapterEnd(PdfWriter writer, Document document, float position) {<FILL_FUNCTION_BODY>}
/**
* Called when a Section is written.
* <p>
* <CODE>position</CODE> will hold the height at which the section will be
* written to.
*
* @param writer the <CODE>PdfWriter</CODE> for this document
* @param document the document
* @param paragraphPosition the position the section will be written to
* @param depth the number depth of the Section
* @param title the title of the section
*/
public void onSection(PdfWriter writer, Document document,
float paragraphPosition, int depth, Paragraph title) {
PdfPageEvent event;
for (Object event1 : events) {
event = (PdfPageEvent) event1;
event.onSection(writer, document, paragraphPosition, depth, title);
}
}
/**
* Called when the end of a Section is reached.
* <p>
* <CODE>position</CODE> will hold the height of the section end.
*
* @param writer the <CODE>PdfWriter</CODE> for this document
* @param document the document
* @param position the position of the end of the section
*/
public void onSectionEnd(PdfWriter writer, Document document, float position) {
PdfPageEvent event;
for (Object event1 : events) {
event = (PdfPageEvent) event1;
event.onSectionEnd(writer, document, position);
}
}
/**
* Called when a <CODE>Chunk</CODE> with a generic tag is written.
* <p>
* It is useful to pinpoint the <CODE>Chunk</CODE> location to generate bookmarks, for example.
*
* @param writer the <CODE>PdfWriter</CODE> for this document
* @param document the document
* @param rect the <CODE>Rectangle</CODE> containing the <CODE>Chunk
* </CODE>
* @param text the text of the tag
*/
public void onGenericTag(PdfWriter writer, Document document,
Rectangle rect, String text) {
PdfPageEvent event;
for (Object event1 : events) {
event = (PdfPageEvent) event1;
event.onGenericTag(writer, document, rect, text);
}
}
}
|
PdfPageEvent event;
for (Object event1 : events) {
event = (PdfPageEvent) event1;
event.onChapterEnd(writer, document, position);
}
| 1,952
| 52
| 2,004
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/fonts/cmaps/CMap.java
|
CMap
|
addMapping
|
class CMap {
private List<CodespaceRange> codeSpaceRanges = new ArrayList<>();
private Map<Integer, String> singleByteMappings = new HashMap<>();
private Map<Integer, String> doubleByteMappings = new HashMap<>();
/**
* Creates a new instance of CMap.
*/
public CMap() {
//default constructor
}
/**
* This will tell if this cmap has any one byte mappings.
*
* @return true If there are any one byte mappings, false otherwise.
*/
public boolean hasOneByteMappings() {
return !singleByteMappings.isEmpty();
}
/**
* This will tell if this cmap has any two byte mappings.
*
* @return true If there are any two byte mappings, false otherwise.
*/
public boolean hasTwoByteMappings() {
return !doubleByteMappings.isEmpty();
}
/**
* This will perform a lookup into the map.
* <p>
* Some characters (e.g. ligatures) decode to character sequences.
*
* @param code The code used to lookup.
* @return The string that matches the lookup.
*/
public String lookup(char code) {
String result = null;
if (hasTwoByteMappings()) {
result = doubleByteMappings.get((int) code);
}
if (result == null && code <= 0xff && hasOneByteMappings()) {
result = singleByteMappings.get(code & 0xff);
}
return result;
}
/**
* This will perform a lookup into the map.
*
* @param code The code used to lookup.
* @param offset The offset into the byte array.
* @param length The length of the data we are getting.
* @return The string that matches the lookup.
*/
public String lookup(byte[] code, int offset, int length) {
String result = null;
Integer key = null;
if (length == 1) {
key = code[offset] & 0xff;
result = singleByteMappings.get(key);
} else if (length == 2) {
int intKey = code[offset] & 0xff;
intKey <<= 8;
intKey += code[offset + 1] & 0xff;
key = intKey;
result = doubleByteMappings.get(key);
}
return result;
}
/**
* This will add a mapping.
*
* @param src The src to the mapping.
* @param dest The dest to the mapping.
* @throws IOException if the src is invalid.
*/
public void addMapping(byte[] src, String dest) throws IOException {<FILL_FUNCTION_BODY>}
/**
* This will add a codespace range.
*
* @param range A single codespace range.
*/
public void addCodespaceRange(CodespaceRange range) {
codeSpaceRanges.add(range);
}
/**
* Getter for property codeSpaceRanges.
*
* @return Value of property codeSpaceRanges.
*/
public List getCodeSpaceRanges() {
return codeSpaceRanges;
}
}
|
if (src.length == 1) {
singleByteMappings.put(src[0] & 0xff, dest);
} else if (src.length == 2) {
int intSrc = src[0] & 0xFF;
intSrc <<= 8;
intSrc |= (src[1] & 0xFF);
doubleByteMappings.put(intSrc, dest);
} else {
throw new IOException(
MessageLocalization.getComposedMessage("mapping.code.should.be.1.or.two.bytes.and.not.1",
src.length));
}
| 844
| 159
| 1,003
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/hyphenation/ByteVector.java
|
ByteVector
|
alloc
|
class ByteVector implements Serializable {
private static final long serialVersionUID = -1096301185375029343L;
/**
* Capacity increment size
*/
private static final int DEFAULT_BLOCK_SIZE = 2048;
private int blockSize;
/**
* The encapsulated array
*/
private byte[] array;
/**
* Points to next free item
*/
private int n;
public ByteVector() {
this(DEFAULT_BLOCK_SIZE);
}
public ByteVector(int capacity) {
if (capacity > 0) {
blockSize = capacity;
} else {
blockSize = DEFAULT_BLOCK_SIZE;
}
array = new byte[blockSize];
n = 0;
}
public ByteVector(byte[] a) {
blockSize = DEFAULT_BLOCK_SIZE;
array = a;
n = 0;
}
public ByteVector(byte[] a, int capacity) {
if (capacity > 0) {
blockSize = capacity;
} else {
blockSize = DEFAULT_BLOCK_SIZE;
}
array = a;
n = 0;
}
public byte[] getArray() {
return array;
}
/**
* @return number of items in array
*/
public int length() {
return n;
}
/**
* @return current capacity of array
*/
public int capacity() {
return array.length;
}
public void put(int index, byte val) {
array[index] = val;
}
public byte get(int index) {
return array[index];
}
/**
* This is to implement memory allocation in the array. Like malloc().
*
* @param size The size to add
* @return The index of the size of the old array
*/
public int alloc(int size) {<FILL_FUNCTION_BODY>}
public void trimToSize() {
if (n < array.length) {
byte[] aux = new byte[n];
System.arraycopy(array, 0, aux, 0, n);
array = aux;
}
}
}
|
int index = n;
int len = array.length;
if (n + size >= len) {
byte[] aux = new byte[len + blockSize];
System.arraycopy(array, 0, aux, 0, len);
array = aux;
}
n += size;
return index;
| 587
| 83
| 670
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/hyphenation/CharVector.java
|
CharVector
|
clone
|
class CharVector implements Cloneable, Serializable {
private static final long serialVersionUID = -4875768298308363544L;
/**
* Capacity increment size
*/
private static final int DEFAULT_BLOCK_SIZE = 2048;
private int blockSize;
/**
* The encapsulated array
*/
private char[] array;
/**
* Points to next free item
*/
private int n;
public CharVector() {
this(DEFAULT_BLOCK_SIZE);
}
public CharVector(int capacity) {
if (capacity > 0) {
blockSize = capacity;
} else {
blockSize = DEFAULT_BLOCK_SIZE;
}
array = new char[blockSize];
n = 0;
}
public CharVector(char[] a) {
blockSize = DEFAULT_BLOCK_SIZE;
array = a;
n = a.length;
}
public CharVector(char[] a, int capacity) {
if (capacity > 0) {
blockSize = capacity;
} else {
blockSize = DEFAULT_BLOCK_SIZE;
}
array = a;
n = a.length;
}
/**
* Reset Vector but don't resize or clear elements
*/
public void clear() {
n = 0;
}
public Object clone() {<FILL_FUNCTION_BODY>}
public char[] getArray() {
return array;
}
/**
* @return the number of items in array
*/
public int length() {
return n;
}
/**
* returns current capacity of array
*
* @return the current capacity of array
*/
public int capacity() {
return array.length;
}
public void put(int index, char val) {
array[index] = val;
}
public char get(int index) {
return array[index];
}
public int alloc(int size) {
int index = n;
int len = array.length;
if (n + size >= len) {
char[] aux = new char[len + blockSize];
System.arraycopy(array, 0, aux, 0, len);
array = aux;
}
n += size;
return index;
}
public void trimToSize() {
if (n < array.length) {
char[] aux = new char[n];
System.arraycopy(array, 0, aux, 0, n);
array = aux;
}
}
}
|
CharVector cv = new CharVector(array.clone(), blockSize);
cv.n = this.n;
return cv;
| 686
| 38
| 724
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/hyphenation/Hyphen.java
|
Hyphen
|
toString
|
class Hyphen implements Serializable {
private static final long serialVersionUID = -7666138517324763063L;
public String preBreak;
public String noBreak;
public String postBreak;
Hyphen(String pre, String no, String post) {
preBreak = pre;
noBreak = no;
postBreak = post;
}
Hyphen(String pre) {
preBreak = pre;
noBreak = null;
postBreak = null;
}
public String toString() {<FILL_FUNCTION_BODY>}
}
|
if (noBreak == null
&& postBreak == null
&& preBreak != null
&& preBreak.equals("-")) {
return "-";
}
StringBuilder res = new StringBuilder("{");
res.append(preBreak);
res.append("}{");
res.append(postBreak);
res.append("}{");
res.append(noBreak);
res.append('}');
return res.toString();
| 163
| 115
| 278
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/hyphenation/Hyphenation.java
|
Hyphenation
|
toString
|
class Hyphenation {
private int[] hyphenPoints;
private String word;
/**
* number of hyphenation points in word
*/
private int len;
/**
* rawWord as made of alternating strings and {@link Hyphen Hyphen} instances
*/
Hyphenation(String word, int[] points) {
this.word = word;
hyphenPoints = points;
len = points.length;
}
/**
* @return the number of hyphenation points in the word
*/
public int length() {
return len;
}
/**
* @param index The index of the hyphen character
* @return the pre-break text, not including the hyphen character
*/
public String getPreHyphenText(int index) {
return word.substring(0, hyphenPoints[index]);
}
/**
* @param index The index of the hyphen character in the word
* @return the post-break text
*/
public String getPostHyphenText(int index) {
return word.substring(hyphenPoints[index]);
}
/**
* @return the hyphenation points
*/
public int[] getHyphenationPoints() {
return hyphenPoints;
}
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder str = new StringBuilder();
int start = 0;
for (int i = 0; i < len; i++) {
str.append(word, start, hyphenPoints[i]).append('-');
start = hyphenPoints[i];
}
str.append(word.substring(start));
return str.toString();
| 355
| 91
| 446
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/hyphenation/Hyphenator.java
|
Hyphenator
|
getHyphenationTree
|
class Hyphenator {
private static final String defaultHyphLocation = "com/lowagie/text/pdf/hyphenation/hyph/";
/**
* TODO: Don't use statics
*/
private static Map<String, HyphenationTree> hyphenTrees = new Hashtable<>();
/**
* Holds value of property hyphenDir.
*/
private static String hyphenDir = "";
private HyphenationTree hyphenTree = null;
private int remainCharCount = 2;
private int pushCharCount = 2;
/**
* @param lang The language
* @param country the Country
* @param leftMin The minimum letters on the left
* @param rightMin The minimum letters on the right
*/
public Hyphenator(String lang, String country, int leftMin,
int rightMin) {
hyphenTree = getHyphenationTree(lang, country);
remainCharCount = leftMin;
pushCharCount = rightMin;
}
/**
* @param lang The language
* @param country The country
* @return the hyphenation tree
*/
public static HyphenationTree getHyphenationTree(String lang,
String country) {<FILL_FUNCTION_BODY>}
/**
* @param key A String of the key of the hyphenation tree
* @return a hyphenation tree
*/
public static HyphenationTree getResourceHyphenationTree(String key) {
try {
InputStream stream = BaseFont.getResourceStream(defaultHyphLocation + key + ".xml");
if (stream == null && key.length() > 2) {
stream = BaseFont.getResourceStream(defaultHyphLocation + key.substring(0, 2) + ".xml");
}
if (stream == null) {
return null;
}
HyphenationTree hTree = new HyphenationTree();
hTree.loadSimplePatterns(stream);
return hTree;
} catch (Exception e) {
return null;
}
}
/**
* @param key The language to get the tree from
* @return a hyphenation tree
*/
public static HyphenationTree getFileHyphenationTree(String key) {
try {
if (hyphenDir == null) {
return null;
}
InputStream stream = null;
File hyphenFile = new File(hyphenDir, key + ".xml");
if (hyphenFile.canRead()) {
stream = new FileInputStream(hyphenFile);
}
if (stream == null && key.length() > 2) {
hyphenFile = new File(hyphenDir, key.substring(0, 2) + ".xml");
if (hyphenFile.canRead()) {
stream = new FileInputStream(hyphenFile);
}
}
if (stream == null) {
return null;
}
HyphenationTree hTree = new HyphenationTree();
hTree.loadSimplePatterns(stream);
return hTree;
} catch (Exception e) {
return null;
}
}
/**
* @param lang The language
* @param country The country
* @param word char array containing the word
* @param leftMin Minimum number of characters allowed before the hyphenation point
* @param rightMin Minimum number of characters allowed after the hyphenation point
* @return a hyphenation object
*/
public static Hyphenation hyphenate(String lang, String country,
String word, int leftMin,
int rightMin) {
HyphenationTree hTree = getHyphenationTree(lang, country);
if (hTree == null) {
//log.error("Error building hyphenation tree for language "
// + lang);
return null;
}
return hTree.hyphenate(word, leftMin, rightMin);
}
/**
* @param lang The language
* @param country The country
* @param word char array that contains the word to hyphenate
* @param offset Offset to the first character in word
* @param len The length of the word
* @param leftMin Minimum number of characters allowed before the hyphenation point
* @param rightMin Minimum number of characters allowed after the hyphenation point
* @return a hyphenation object
*/
public static Hyphenation hyphenate(String lang, String country,
char[] word, int offset, int len,
int leftMin, int rightMin) {
HyphenationTree hTree = getHyphenationTree(lang, country);
if (hTree == null) {
//log.error("Error building hyphenation tree for language "
// + lang);
return null;
}
return hTree.hyphenate(word, offset, len, leftMin, rightMin);
}
/**
* Getter for property hyphenDir.
*
* @return Value of property hyphenDir.
*/
public static String getHyphenDir() {
return hyphenDir;
}
/**
* Setter for property hyphenDir.
*
* @param _hyphenDir New value of property hyphenDir.
*/
public static void setHyphenDir(String _hyphenDir) {
hyphenDir = _hyphenDir;
}
/**
* @param min Minimum number of characters allowed before the hyphenation point
*/
public void setMinRemainCharCount(int min) {
remainCharCount = min;
}
/**
* @param min Minimum number of characters allowed after the hyphenation point
*/
public void setMinPushCharCount(int min) {
pushCharCount = min;
}
/**
* @param lang The language
* @param country The country
*/
public void setLanguage(String lang, String country) {
hyphenTree = getHyphenationTree(lang, country);
}
/**
* @param word Char array that contains the word
* @param offset Offset to the first character in word
* @param len Length of the word
* @return a hyphenation object
*/
public Hyphenation hyphenate(char[] word, int offset, int len) {
if (hyphenTree == null) {
return null;
}
return hyphenTree.hyphenate(word, offset, len, remainCharCount,
pushCharCount);
}
/**
* @param word The word to hyphenate
* @return a hyphenation object
*/
public Hyphenation hyphenate(String word) {
if (hyphenTree == null) {
return null;
}
return hyphenTree.hyphenate(word, remainCharCount, pushCharCount);
}
}
|
String key = lang;
// check whether the country code has been used
if (country != null && !country.equals("none")) {
key += "_" + country;
}
// first try to find it in the cache
if (hyphenTrees.containsKey(key)) {
return hyphenTrees.get(key);
}
if (hyphenTrees.containsKey(lang)) {
return hyphenTrees.get(lang);
}
HyphenationTree hTree = getResourceHyphenationTree(key);
if (hTree == null) {
hTree = getFileHyphenationTree(key);
}
// put it into the pattern cache
if (hTree != null) {
hyphenTrees.put(key, hTree);
}
return hTree;
| 1,755
| 213
| 1,968
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/hyphenation/SimplePatternParser.java
|
SimplePatternParser
|
normalizeException
|
class SimplePatternParser implements SimpleXMLDocHandler,
PatternConsumer {
static final int ELEM_CLASSES = 1;
static final int ELEM_EXCEPTIONS = 2;
static final int ELEM_PATTERNS = 3;
static final int ELEM_HYPHEN = 4;
int currElement;
PatternConsumer consumer;
StringBuffer token;
List<Object> exception;
char hyphenChar;
SimpleXMLParser parser;
/**
* Creates a new instance of PatternParser2
*/
public SimplePatternParser() {
token = new StringBuffer();
hyphenChar = '-'; // default
}
protected static String getPattern(String word) {
StringBuilder pat = new StringBuilder();
int len = word.length();
for (int i = 0; i < len; i++) {
if (!Character.isDigit(word.charAt(i))) {
pat.append(word.charAt(i));
}
}
return pat.toString();
}
protected static String getInterletterValues(String pat) {
StringBuilder il = new StringBuilder();
String word = pat + "a"; // add dummy letter to serve as sentinel
int len = word.length();
for (int i = 0; i < len; i++) {
char c = word.charAt(i);
if (Character.isDigit(c)) {
il.append(c);
i++;
} else {
il.append('0');
}
}
return il.toString();
}
public static void main(String[] args) {
try {
if (args.length > 0) {
SimplePatternParser pp = new SimplePatternParser();
pp.parse(new FileInputStream(args[0]), pp);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void parse(InputStream stream, PatternConsumer consumer) {
this.consumer = consumer;
try (stream) {
SimpleXMLParser.parse(this, stream);
} catch (IOException e) {
throw new ExceptionConverter(e);
}
}
protected List<Object> normalizeException(List<Object> ex) {<FILL_FUNCTION_BODY>}
protected String getExceptionWord(List<Object> ex) {
StringBuilder res = new StringBuilder();
for (Object item : ex) {
if (item instanceof String) {
res.append((String) item);
} else {
if (((Hyphen) item).noBreak != null) {
res.append(((Hyphen) item).noBreak);
}
}
}
return res.toString();
}
public void endDocument() {
}
public void endElement(String tag) {
if (token.length() > 0) {
String word = token.toString();
switch (currElement) {
case ELEM_CLASSES:
consumer.addClass(word);
break;
case ELEM_EXCEPTIONS:
exception.add(word);
exception = normalizeException(exception);
consumer.addException(getExceptionWord(exception),
(ArrayList) ((ArrayList) exception).clone());
break;
case ELEM_PATTERNS:
consumer.addPattern(getPattern(word),
getInterletterValues(word));
break;
case ELEM_HYPHEN:
// nothing to do
break;
}
if (currElement != ELEM_HYPHEN) {
token.setLength(0);
}
}
if (currElement == ELEM_HYPHEN) {
currElement = ELEM_EXCEPTIONS;
} else {
currElement = 0;
}
}
@Override
public void startDocument() {
}
@Override
public void startElement(String tag, Map<String, String> h) {
switch (tag) {
case "hyphen-char":
String hh = h.get("value");
if (hh != null && hh.length() == 1) {
hyphenChar = hh.charAt(0);
}
break;
case "classes":
currElement = ELEM_CLASSES;
break;
case "patterns":
currElement = ELEM_PATTERNS;
break;
case "exceptions":
currElement = ELEM_EXCEPTIONS;
exception = new ArrayList<>();
break;
case "hyphen":
if (token.length() > 0) {
exception.add(token.toString());
}
exception.add(new Hyphen(h.get("pre"), h.get("no"), h.get("post")));
currElement = ELEM_HYPHEN;
break;
}
token.setLength(0);
}
public void text(String str) {
StringTokenizer tk = new StringTokenizer(str);
while (tk.hasMoreTokens()) {
String word = tk.nextToken();
// System.out.println("\"" + word + "\"");
switch (currElement) {
case ELEM_CLASSES:
consumer.addClass(word);
break;
case ELEM_EXCEPTIONS:
exception.add(word);
exception = normalizeException(exception);
consumer.addException(getExceptionWord(exception),
(ArrayList) ((ArrayList) exception).clone());
exception.clear();
break;
case ELEM_PATTERNS:
consumer.addPattern(getPattern(word),
getInterletterValues(word));
break;
}
}
}
// PatternConsumer implementation for testing purposes
public void addClass(String c) {
System.out.println("class: " + c);
}
public void addException(String w, ArrayList e) {
System.out.println("exception: " + w + " : " + e.toString());
}
public void addPattern(String p, String v) {
System.out.println("pattern: " + p + " : " + v);
}
}
|
List<Object> res = new ArrayList<>();
for (Object item : ex) {
if (item instanceof String) {
String str = (String) item;
StringBuilder buf = new StringBuilder();
for (int j = 0; j < str.length(); j++) {
char c = str.charAt(j);
if (c != hyphenChar) {
buf.append(c);
} else {
res.add(buf.toString());
buf.setLength(0);
char[] h = new char[1];
h[0] = hyphenChar;
// we use here hyphenChar which is not necessarily
// the one to be printed
res.add(new Hyphen(new String(h), null, null));
}
}
if (buf.length() > 0) {
res.add(buf.toString());
}
} else {
res.add(item);
}
}
return res;
| 1,599
| 247
| 1,846
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/internal/PdfVersionImp.java
|
PdfVersionImp
|
addToCatalog
|
class PdfVersionImp implements PdfVersion {
/**
* Contains different strings that are part of the header.
*/
public static final byte[][] HEADER = {
DocWriter.getISOBytes("\n"),
DocWriter.getISOBytes("%PDF-"),
DocWriter.getISOBytes("\n%\u00e2\u00e3\u00cf\u00d3\n")
};
/**
* Indicates if the header was already written.
*/
protected boolean headerWasWritten = false;
/**
* Indicates if we are working in append mode.
*/
protected boolean appendmode = false;
/**
* The version that was or will be written to the header.
*/
protected char header_version = PdfWriter.VERSION_1_5;
/**
* The version that will be written to the catalog.
*/
protected PdfName catalog_version = null;
/**
* The extensions dictionary.
*
* @since 2.1.6
*/
protected PdfDictionary extensions = null;
/**
* @see com.lowagie.text.pdf.interfaces.PdfVersion#setPdfVersion(char)
*/
public void setPdfVersion(char version) {
if (headerWasWritten || appendmode) {
setPdfVersion(getVersionAsName(version));
} else {
this.header_version = version;
}
}
/**
* @see com.lowagie.text.pdf.interfaces.PdfVersion#setAtLeastPdfVersion(char)
*/
public void setAtLeastPdfVersion(char version) {
if (version > header_version) {
setPdfVersion(version);
}
}
/**
* @see com.lowagie.text.pdf.interfaces.PdfVersion#setPdfVersion(com.lowagie.text.pdf.PdfName)
*/
public void setPdfVersion(PdfName version) {
if (catalog_version == null || catalog_version.compareTo(version) < 0) {
this.catalog_version = version;
}
}
/**
* Sets the append mode.
*
* @param appendmode Boolean that indicates if we are working in append mode.
*/
public void setAppendmode(boolean appendmode) {
this.appendmode = appendmode;
}
/**
* Writes the header to the OutputStreamCounter.
*
* @param os the OutputStreamCounter
* @throws IOException thrown when an I/O operation goes wrong
*/
public void writeHeader(OutputStreamCounter os) throws IOException {
if (appendmode) {
os.write(HEADER[0]);
} else {
os.write(HEADER[1]);
os.write(getVersionAsByteArray(header_version));
os.write(HEADER[2]);
headerWasWritten = true;
}
}
/**
* Returns the PDF version as a name.
*
* @param version the version character.
* @return a PdfName that contains the version
*/
public PdfName getVersionAsName(char version) {
switch (version) {
case PdfWriter.VERSION_1_2:
return PdfWriter.PDF_VERSION_1_2;
case PdfWriter.VERSION_1_3:
return PdfWriter.PDF_VERSION_1_3;
case PdfWriter.VERSION_1_4:
return PdfWriter.PDF_VERSION_1_4;
case PdfWriter.VERSION_1_5:
return PdfWriter.PDF_VERSION_1_5;
case PdfWriter.VERSION_1_6:
return PdfWriter.PDF_VERSION_1_6;
case PdfWriter.VERSION_1_7:
return PdfWriter.PDF_VERSION_1_7;
default:
return PdfWriter.PDF_VERSION_1_4;
}
}
/**
* Returns the version as a byte[].
*
* @param version the version character
* @return a byte array containing the version according to the ISO-8859-1 codepage.
*/
public byte[] getVersionAsByteArray(char version) {
return DocWriter.getISOBytes(getVersionAsName(version).toString().substring(1));
}
/**
* Adds the version to the Catalog dictionary.
*
* @param catalog The PdfDictionary to add the version to
*/
public void addToCatalog(PdfDictionary catalog) {<FILL_FUNCTION_BODY>}
/**
* @see com.lowagie.text.pdf.interfaces.PdfVersion#addDeveloperExtension(com.lowagie.text.pdf.PdfDeveloperExtension)
* @since 2.1.6
*/
public void addDeveloperExtension(PdfDeveloperExtension de) {
if (extensions == null) {
extensions = new PdfDictionary();
} else {
PdfDictionary extension = extensions.getAsDict(de.getPrefix());
if (extension != null) {
int diff = de.getBaseversion().compareTo(extension.getAsName(PdfName.BASEVERSION));
if (diff < 0) {
return;
}
diff = de.getExtensionLevel() - extension.getAsNumber(PdfName.EXTENSIONLEVEL).intValue();
if (diff <= 0) {
return;
}
}
}
extensions.put(de.getPrefix(), de.getDeveloperExtensions());
}
}
|
if (catalog_version != null) {
catalog.put(PdfName.VERSION, catalog_version);
}
if (extensions != null) {
catalog.put(PdfName.EXTENSIONS, extensions);
}
| 1,430
| 65
| 1,495
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/internal/PolylineShape.java
|
PolylineShape
|
rect
|
class PolylineShape implements Shape {
/**
* All the X-values of the coordinates in the polyline.
*/
protected int[] x;
/**
* All the Y-values of the coordinates in the polyline.
*/
protected int[] y;
/**
* The total number of points.
*/
protected int np;
/**
* Creates a PolylineShape.
*
* @param nPoints The total number of points
* @param x An int array containing all the X-values of the coordinates in the polyline
* @param y An int array containing all the Y-values of the coordinates in the polyline
*/
public PolylineShape(int[] x, int[] y, int nPoints) {
// Should copy array (as done in Polygon)
this.np = nPoints;
// Take a copy.
this.x = new int[np];
this.y = new int[np];
System.arraycopy(x, 0, this.x, 0, np);
System.arraycopy(y, 0, this.y, 0, np);
}
/**
* Returns the bounding box of this polyline.
*
* @return a {@link Rectangle2D} that is the high-precision bounding box of this line.
* @see java.awt.Shape#getBounds2D()
*/
public Rectangle2D getBounds2D() {
int[] r = rect();
return r == null ? null : new Rectangle2D.Double(r[0], r[1], r[2], r[3]);
}
/**
* Returns the bounding box of this polyline.
*
* @see java.awt.Shape#getBounds()
*/
public Rectangle getBounds() {
return getBounds2D().getBounds();
}
/**
* Calculates the origin (X, Y) and the width and height of a rectangle that contains all the segments of the
* polyline.
*/
private int[] rect() {<FILL_FUNCTION_BODY>}
/**
* A polyline can't contain a point.
*
* @see java.awt.Shape#contains(double, double)
*/
public boolean contains(double x, double y) {
return false;
}
/**
* A polyline can't contain a point.
*
* @see java.awt.Shape#contains(java.awt.geom.Point2D)
*/
public boolean contains(Point2D p) {
return false;
}
/**
* A polyline can't contain a point.
*
* @see java.awt.Shape#contains(double, double, double, double)
*/
public boolean contains(double x, double y, double w, double h) {
return false;
}
/**
* A polyline can't contain a point.
*
* @see java.awt.Shape#contains(java.awt.geom.Rectangle2D)
*/
public boolean contains(Rectangle2D r) {
return false;
}
/**
* Checks if one of the lines in the polyline intersects with a given rectangle.
*
* @see java.awt.Shape#intersects(double, double, double, double)
*/
public boolean intersects(double x, double y, double w, double h) {
return intersects(new Rectangle2D.Double(x, y, w, h));
}
/**
* Checks if one of the lines in the polyline intersects with a given rectangle.
*
* @see java.awt.Shape#intersects(java.awt.geom.Rectangle2D)
*/
public boolean intersects(Rectangle2D r) {
if (np == 0) {
return false;
}
Line2D line = new Line2D.Double(x[0], y[0], x[0], y[0]);
for (int i = 1; i < np; i++) {
line.setLine(x[i - 1], y[i - 1], x[i], y[i]);
if (line.intersects(r)) {
return true;
}
}
return false;
}
/**
* Returns an iteration object that defines the boundary of the polyline.
*
* @param at the specified {@link AffineTransform}
* @return a {@link PathIterator} that defines the boundary of this polyline.
* @see java.awt.Shape#intersects(java.awt.geom.Rectangle2D)
*/
public PathIterator getPathIterator(AffineTransform at) {
return new PolylineShapeIterator(this, at);
}
/**
* There's no difference with getPathIterator(AffineTransform at); we just need this method to implement the Shape
* interface.
*/
public PathIterator getPathIterator(AffineTransform at, double flatness) {
return new PolylineShapeIterator(this, at);
}
}
|
if (np == 0) {
return null;
}
int xMin = x[0], yMin = y[0], xMax = x[0], yMax = y[0];
for (int i = 1; i < np; i++) {
if (x[i] < xMin) {
xMin = x[i];
} else if (x[i] > xMax) {
xMax = x[i];
}
if (y[i] < yMin) {
yMin = y[i];
} else if (y[i] > yMax) {
yMax = y[i];
}
}
return new int[]{xMin, yMin, xMax - xMin, yMax - yMin};
| 1,290
| 195
| 1,485
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/internal/PolylineShapeIterator.java
|
PolylineShapeIterator
|
currentSegment
|
class PolylineShapeIterator implements PathIterator {
/**
* The polyline over which we are going to iterate.
*/
protected PolylineShape poly;
/**
* an affine transformation to be performed on the polyline.
*/
protected AffineTransform affine;
/**
* the index of the current segment in the iterator.
*/
protected int index;
/**
* Creates a PolylineShapeIterator.
*/
PolylineShapeIterator(PolylineShape l, AffineTransform at) {
this.poly = l;
this.affine = at;
}
/**
* Returns the coordinates and type of the current path segment in the iteration. The return value is the path
* segment type: SEG_MOVETO, SEG_LINETO, SEG_QUADTO, SEG_CUBICTO, or SEG_CLOSE. A double array of length 6 must be
* passed in and may be used to store the coordinates of the point(s). Each point is stored as a pair of double x,y
* coordinates. SEG_MOVETO and SEG_LINETO types will return one point, SEG_QUADTO will return two points,
* SEG_CUBICTO will return 3 points and SEG_CLOSE will not return any points.
*
* @see #SEG_MOVETO
* @see #SEG_LINETO
* @see #SEG_QUADTO
* @see #SEG_CUBICTO
* @see #SEG_CLOSE
* @see java.awt.geom.PathIterator#currentSegment(double[])
*/
public int currentSegment(double[] coords) {
if (isDone()) {
throw new NoSuchElementException(MessageLocalization.getComposedMessage("line.iterator.out.of.bounds"));
}
int type = (index == 0) ? SEG_MOVETO : SEG_LINETO;
coords[0] = poly.x[index];
coords[1] = poly.y[index];
if (affine != null) {
affine.transform(coords, 0, coords, 0, 1);
}
return type;
}
/**
* Returns the coordinates and type of the current path segment in the iteration. The return value is the path
* segment type: SEG_MOVETO, SEG_LINETO, SEG_QUADTO, SEG_CUBICTO, or SEG_CLOSE. A double array of length 6 must be
* passed in and may be used to store the coordinates of the point(s). Each point is stored as a pair of double x,y
* coordinates. SEG_MOVETO and SEG_LINETO types will return one point, SEG_QUADTO will return two points,
* SEG_CUBICTO will return 3 points and SEG_CLOSE will not return any points.
*
* @see #SEG_MOVETO
* @see #SEG_LINETO
* @see #SEG_QUADTO
* @see #SEG_CUBICTO
* @see #SEG_CLOSE
* @see java.awt.geom.PathIterator#currentSegment(float[])
*/
public int currentSegment(float[] coords) {<FILL_FUNCTION_BODY>}
/**
* Return the winding rule for determining the insideness of the path.
*
* @see #WIND_EVEN_ODD
* @see #WIND_NON_ZERO
* @see java.awt.geom.PathIterator#getWindingRule()
*/
public int getWindingRule() {
return WIND_NON_ZERO;
}
/**
* Tests if there are more points to read.
*
* @return true if there are more points to read
* @see java.awt.geom.PathIterator#isDone()
*/
public boolean isDone() {
return (index >= poly.np);
}
/**
* Moves the iterator to the next segment of the path forwards along the primary direction of traversal as long as
* there are more points in that direction.
*
* @see java.awt.geom.PathIterator#next()
*/
public void next() {
index++;
}
}
|
if (isDone()) {
throw new NoSuchElementException(MessageLocalization.getComposedMessage("line.iterator.out.of.bounds"));
}
int type = (index == 0) ? SEG_MOVETO : SEG_LINETO;
coords[0] = poly.x[index];
coords[1] = poly.y[index];
if (affine != null) {
affine.transform(coords, 0, coords, 0, 1);
}
return type;
| 1,120
| 138
| 1,258
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/parser/GraphicsState.java
|
GraphicsState
|
calculateCharacterWidthWithSpace
|
class GraphicsState {
/**
* The current transformation matrix.
*/
private Matrix ctm;
/**
* The current character spacing.
*/
private float characterSpacing;
/**
* The current word spacing.
*/
private float wordSpacing;
/**
* The current horizontal scaling
*/
private float horizontalScaling;
/**
* The current leading.
*/
private float leading;
/**
* The active font.
*/
private CMapAwareDocumentFont font;
/**
* The current font size.
*/
private float fontSize;
/**
* The current render mode.
*/
private int renderMode;
/**
* The current text rise
*/
private float rise;
/**
* The current knockout value.
*/
private boolean knockout;
/**
* Constructs a new Graphics State object with the default values.
*/
public GraphicsState() {
ctm = new Matrix();
characterSpacing = 0;
wordSpacing = 0;
horizontalScaling = 1.0f;
leading = 0;
font = null;
fontSize = 0;
renderMode = 0;
rise = 0;
knockout = true;
}
/**
* Copy constructor.
*
* @param source another GraphicsState object
*/
public GraphicsState(GraphicsState source) {
// note: all of the following are immutable, with the possible exception of font
// so it is safe to copy them as-is
ctm = source.ctm;
characterSpacing = source.characterSpacing;
wordSpacing = source.wordSpacing;
horizontalScaling = source.horizontalScaling;
leading = source.leading;
font = source.font;
fontSize = source.fontSize;
renderMode = source.renderMode;
rise = source.rise;
knockout = source.knockout;
}
/**
* Get the current transformation matrix.
*
* @return current transformation matrix
*/
public Matrix getCtm() {
return ctm;
}
public float getCharacterSpacing() {
return characterSpacing;
}
public void setCharacterSpacing(float characterSpacing) {
this.characterSpacing = characterSpacing;
}
public float getWordSpacing() {
return wordSpacing;
}
public void setWordSpacing(float wordSpacing) {
this.wordSpacing = wordSpacing;
}
public float getHorizontalScaling() {
return horizontalScaling;
}
public void setHorizontalScaling(float horizontalScaling) {
this.horizontalScaling = horizontalScaling;
}
public float getLeading() {
return leading;
}
public void setLeading(float leading) {
this.leading = leading;
}
/**
* Get maximum height above the baseline reached by glyphs in this font, excluding the height of glyphs for accented
* characters.
*
* @return ascent descriptor value
*/
public float getFontAscentDescriptor() {
return font.getFontDescriptor(DocumentFont.ASCENT, fontSize);
}
/**
* Get maximum depth below the baseline reached by glyphs in this font. The value is a negative number
*
* @return descent descriptor value
*/
public float getFontDescentDescriptor() {
return font.getFontDescriptor(DocumentFont.DESCENT, fontSize);
}
public float calculateCharacterWidthWithSpace(float charFontWidth) {<FILL_FUNCTION_BODY>}
public float calculateCharacterWidthWithoutSpace(float charFontWidth) {
return (charFontWidth * fontSize + characterSpacing) * horizontalScaling;
}
public CMapAwareDocumentFont getFont() {
return font;
}
public void setFont(CMapAwareDocumentFont font) {
this.font = font;
}
public float getFontSize() {
return fontSize;
}
public void setFontSize(float fontSize) {
this.fontSize = fontSize;
}
public int getRenderMode() {
return renderMode;
}
public void setRenderMode(int renderMode) {
this.renderMode = renderMode;
}
public float getRise() {
return rise;
}
public void setRise(float rise) {
this.rise = rise;
}
public boolean isKnockout() {
return knockout;
}
/**
* Multiply transformation matrix and get result. Result would be also stored in this {@link GraphicsState}
* instance
*
* @param matrix multiply by matrix
* @return result matrix
*/
public Matrix multiplyCtm(Matrix matrix) {
ctm = ctm.multiply(matrix);
return ctm;
}
}
|
return (charFontWidth * fontSize + characterSpacing + wordSpacing) * horizontalScaling;
| 1,272
| 27
| 1,299
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/parser/MarkedUpTextAssembler.java
|
MarkedUpTextAssembler
|
concatenateResult
|
class MarkedUpTextAssembler implements TextAssembler {
/**
* our result may be partially processed already, in which case we'll just add things to it, once ready.
*/
List<FinalText> result = new ArrayList<>();
private PdfReader reader;
private ParsedTextImpl inProgress = null;
private int page;
private int wordIdCounter = 1;
private boolean usePdfMarkupElements = false;
/**
* as we get new content (final or not), we accumulate it until we reach the end of a parsing unit
* <p>
* Each parsing unit may have a tag name that should wrap its content
*/
private List<TextAssemblyBuffer> partialWords = new ArrayList<>();
MarkedUpTextAssembler(PdfReader reader) {
this.reader = reader;
}
MarkedUpTextAssembler(PdfReader reader, boolean usePdfMarkupElements) {
this.reader = reader;
this.usePdfMarkupElements = usePdfMarkupElements;
}
/**
* Remember an unassembled chunk until we hit the end of this element, or we hit an assembled chunk, and need to
* pull things together.
*
* @param unassembled chunk of text rendering instruction to contribute to final text
*/
@Override
public void process(ParsedText unassembled, String contextName) {
partialWords.addAll(unassembled.getAsPartialWords());
}
/**
* Slot fully-assembled chunk into our result at the current location. If there are unassembled chunks waiting,
* assemble them first.
*
* @param completed This is a chunk from a nested element
*/
@Override
public void process(FinalText completed, String contextName) {
clearAccumulator();
result.add(completed);
}
/**
* {@inheritDoc}
*
* @see com.lowagie.text.pdf.parser.TextAssembler#process(Word, String)
*/
@Override
public void process(Word completed, String contextName) {
partialWords.add(completed);
}
/**
*
*/
private void clearAccumulator() {
for (TextAssemblyBuffer partialWord : partialWords) {
// Visit each partialWord, calling renderText
partialWord.assemble(this);
}
partialWords.clear();
if (inProgress != null) {
result.add(inProgress.getFinalText(reader, page, this, usePdfMarkupElements));
inProgress = null;
}
}
private FinalText concatenateResult(String containingElementName) {<FILL_FUNCTION_BODY>}
/**
* {@inheritDoc}
*
* @see com.lowagie.text.pdf.parser.TextAssembler#endParsingContext(String)
*/
@Override
public FinalText endParsingContext(String containingElementName) {
clearAccumulator();
return concatenateResult(containingElementName);
}
/**
* @see com.lowagie.text.pdf.parser.TextAssembler#reset()
*/
@Override
public void reset() {
result.clear();
partialWords.clear();
inProgress = null;
}
@Override
public void renderText(FinalText finalText) {
result.add(finalText);
}
/**
* Captures text using a simplified algorithm for inserting hard returns and spaces
*
* @see com.lowagie.text.pdf.parser.GraphicsState
* @see com.lowagie.text.pdf.parser.Matrix
*/
@Override
public void renderText(ParsedTextImpl partialWord) {
boolean firstRender = inProgress == null;
boolean hardReturn = false;
if (firstRender) {
inProgress = partialWord;
return;
}
Vector start = partialWord.getStartPoint();
Vector lastStart = inProgress.getStartPoint();
Vector lastEnd = inProgress.getEndPoint();
// see
// http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
float dist = inProgress.getBaseline()
.subtract(lastStart)
.cross(lastStart.subtract(start))
.lengthSquared() / inProgress.getBaseline().subtract(lastStart).lengthSquared();
float sameLineThreshold = partialWord.getAscent() * 0.5f;
// let's try using 25% of current leading for vertical slop.
if (dist > sameLineThreshold || Float.isNaN(dist)) {
hardReturn = true;
}
/*
* Note: Technically, we should check both the start and end positions,
* in case the angle of the text changed without any displacement but
* this sort of thing probably doesn't happen much in reality, so we'll
* leave it alone for now
*/
float spacing = lastEnd.subtract(start).length();
if (hardReturn || partialWord.breakBefore()) {
result.add(inProgress.getFinalText(reader, page, this, usePdfMarkupElements));
if (hardReturn) {
result.add(new FinalText("\n"));
if (usePdfMarkupElements) {
result.add(new FinalText("<br class='t-pdf' />"));
}
}
inProgress = partialWord;
// System.out.println("<< Hard Return >>");
} else if (spacing < partialWord.getSingleSpaceWidth() / 2.3 || inProgress.shouldNotSplit()) {
inProgress = new Word(inProgress.getText() + partialWord.getText().trim(),
partialWord.getAscent(),
partialWord.getDescent(),
lastStart,
partialWord.getEndPoint(),
inProgress.getBaseline(),
partialWord.getSingleSpaceWidth(),
inProgress.shouldNotSplit(),
inProgress.breakBefore());
} else {
result.add(inProgress.getFinalText(reader, page, this, usePdfMarkupElements));
inProgress = partialWord;
}
}
/**
* Getter.
*
* @return reader
*/
protected PdfReader getReader() {
return reader;
}
/**
* {@inheritDoc}
*
* @see com.lowagie.text.pdf.parser.TextAssembler#setPage(int)
*/
@Override
public void setPage(int page) {
this.page = page;
}
/**
* {@inheritDoc}
*
* @see com.lowagie.text.pdf.parser.TextAssembler#getWordId()
*/
@Override
public String getWordId() {
return "word" + wordIdCounter++;
}
}
|
// null element means that this is a formatting artifact, not content.
if (containingElementName == null) {
// at some point, we may want to extract alternate text for some
// artifacts.
return null;
}
StringBuilder res = new StringBuilder();
if (usePdfMarkupElements && !containingElementName.isEmpty()) {
res.append('<').append(containingElementName).append('>');
}
for (FinalText item : result) {
res.append(item.getText());
}
// important, as the stuff buffered in the result is now used up!
result.clear();
if (usePdfMarkupElements && !containingElementName.isEmpty()) {
res.append("</");
int spacePos = containingElementName.indexOf(' ');
if (spacePos >= 0) {
containingElementName = containingElementName.substring(0, spacePos);
}
res.append(containingElementName).append('>');
}
return new FinalText(res.toString());
| 1,772
| 265
| 2,037
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/parser/PdfContentReaderTool.java
|
PdfContentReaderTool
|
main
|
class PdfContentReaderTool {
/**
* Shows the detail of a dictionary. This is similar to the PdfLister functionality.
*
* @param dic the dictionary of which you want the detail
* @return a String representation of the dictionary
*/
public static String getDictionaryDetail(PdfDictionary dic) {
return getDictionaryDetail(dic, 0);
}
/**
* Shows the detail of a dictionary.
*
* @param dic the dictionary of which you want the detail
* @param depth the depth of the current dictionary (for nested dictionaries)
* @return a String representation of the dictionary
*/
public static String getDictionaryDetail(PdfDictionary dic, int depth) {
StringBuilder builder = new StringBuilder();
builder.append('(');
List<PdfName> subDictionaries = new ArrayList<>();
for (PdfName key : dic.getKeys()) {
PdfObject val = dic.getDirectObject(key);
if (val.isDictionary()) {
subDictionaries.add(key);
}
builder.append(key);
builder.append('=');
builder.append(val);
builder.append(", ");
}
builder.setLength(builder.length() - 2);
builder.append(')');
PdfName pdfSubDictionaryName;
for (Object subDictionary : subDictionaries) {
pdfSubDictionaryName = (PdfName) subDictionary;
builder.append('\n');
for (int i = 0; i < depth + 1; i++) {
builder.append('\t');
}
builder.append("Subdictionary ");
builder.append(pdfSubDictionaryName);
builder.append(" = ");
builder.append(getDictionaryDetail(
dic.getAsDict(pdfSubDictionaryName), depth + 1));
}
return builder.toString();
}
/**
* Writes information about a specific page from PdfReader to the specified output stream.
*
* @param reader the PdfReader to read the page content from
* @param pageNum the page number to read
* @param out the output stream to send the content to
* @throws IOException thrown when an I/O operation goes wrong
* @since 2.1.5
*/
public static void listContentStreamForPage(PdfReader reader, int pageNum, PrintWriter out)
throws IOException {
out.println("==============Page " + pageNum + "====================");
out.println("- - - - - Dictionary - - - - - -");
PdfDictionary pageDictionary = reader.getPageN(pageNum);
out.println(getDictionaryDetail(pageDictionary));
out.println("- - - - - Content Stream - - - - - -");
RandomAccessFileOrArray f = reader.getSafeFile();
byte[] contentBytes = reader.getPageContent(pageNum, f);
f.close();
InputStream is = new ByteArrayInputStream(contentBytes);
int ch;
while ((ch = is.read()) != -1) {
out.print((char) ch);
}
out.println("\n- - - - - Text Extraction - - - - - -");
PdfTextExtractor extractor = new PdfTextExtractor(reader,
new MarkedUpTextAssembler(reader));
String extractedText = extractor.getTextFromPage(pageNum);
if (extractedText.length() != 0) {
out.println(extractedText);
} else {
out.println("No text found on page " + pageNum);
}
out.println();
}
/**
* Writes information about each page in a PDF file to the specified output stream.
*
* @param pdfFile a File instance referring to a PDF file
* @param out the output stream to send the content to
* @throws IOException thrown when an I/O operation goes wrong
* @since 2.1.5
*/
public static void listContentStream(File pdfFile, PrintWriter out)
throws IOException {
PdfReader reader = new PdfReader(pdfFile.getCanonicalPath());
int maxPageNum = reader.getNumberOfPages();
for (int pageNum = 1; pageNum <= maxPageNum; pageNum++) {
listContentStreamForPage(reader, pageNum, out);
}
}
/**
* Writes information about the specified page in a PDF file to the specified output stream.
*
* @param pdfFile a File instance referring to a PDF file
* @param pageNum the page number to read
* @param out the output stream to send the content to
* @throws IOException thrown when an I/O operation goes wrong
* @since 2.1.5
*/
public static void listContentStream(File pdfFile, int pageNum,
PrintWriter out) throws IOException {
PdfReader reader = new PdfReader(pdfFile.getCanonicalPath());
listContentStreamForPage(reader, pageNum, out);
}
/**
* Writes information about each page in a PDF file to the specified file, or System.out.
*
* @param args the arguments passed to the command line
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
try {
if (args.length < 1 || args.length > 3) {
System.out.println("Usage: PdfContentReaderTool <pdf file> [<output file>|stdout] [<page num>]");
return;
}
PrintWriter writer = new PrintWriter(System.out);
if (args.length >= 2) {
if (args[1].compareToIgnoreCase("stdout") != 0) {
System.out.println("Writing PDF content to " + args[1]);
writer = new PrintWriter(new FileOutputStream(new File(args[1])));
}
}
int pageNum = -1;
if (args.length >= 3) {
pageNum = Integer.parseInt(args[2]);
}
if (pageNum == -1) {
listContentStream(new File(args[0]), writer);
} else {
listContentStream(new File(args[0]), pageNum, writer);
}
writer.flush();
if (args.length >= 2) {
writer.close();
System.out.println("Finished writing content to " + args[1]);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
| 1,330
| 322
| 1,652
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/parser/PdfContentStreamHandler.java
|
TextMoveStartNextLineWithLeading
|
invoke
|
class TextMoveStartNextLineWithLeading implements ContentOperator {
private final PdfContentStreamHandler.TextMoveStartNextLine moveStartNextLine;
private final PdfContentStreamHandler.SetTextLeading setTextLeading;
public TextMoveStartNextLineWithLeading(
PdfContentStreamHandler.TextMoveStartNextLine moveStartNextLine,
PdfContentStreamHandler.SetTextLeading setTextLeading) {
this.moveStartNextLine = moveStartNextLine;
this.setTextLeading = setTextLeading;
}
/**
* @see com.lowagie.text.pdf.parser.ContentOperator#getOperatorName()
*/
@Override
public String getOperatorName() {
return "TD";
}
@Override
public void invoke(List<PdfObject> operands, PdfContentStreamHandler handler, PdfDictionary resources) {<FILL_FUNCTION_BODY>}
}
|
float ty = ((PdfNumber) operands.get(1)).floatValue();
List<PdfObject> tlOperands = new ArrayList<>(1);
tlOperands.add(0, new PdfNumber(-ty));
setTextLeading.invoke(tlOperands, handler, resources);
moveStartNextLine.invoke(operands, handler, resources);
| 235
| 94
| 329
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/parser/PdfTextExtractor.java
|
PdfTextExtractor
|
getContentBytesFromContentObject
|
class PdfTextExtractor {
/**
* The PdfReader that holds the PDF file.
*/
private final PdfReader reader;
/**
* The {@link TextAssembler} that will receive render notifications and provide resultant text
*/
private final TextAssembler renderListener;
/**
* Creates a new Text Extractor object, using a {@link TextAssembler} as the render listener
*
* @param reader the reader with the PDF
*/
public PdfTextExtractor(PdfReader reader) {
this(reader, new MarkedUpTextAssembler(reader));
}
/**
* Creates a new Text Extractor object, using a {@link TextAssembler} as the render listener
*
* @param reader the reader with the PDF
* @param usePdfMarkupElements should we use higher level tags for PDF markup entities?
*/
public PdfTextExtractor(PdfReader reader, boolean usePdfMarkupElements) {
this(reader, new MarkedUpTextAssembler(reader, usePdfMarkupElements));
}
/**
* Creates a new Text Extractor object.
*
* @param reader the reader with the PDF
* @param renderListener the render listener that will be used to analyze renderText operations and provide
* resultant text
*/
public PdfTextExtractor(PdfReader reader, TextAssembler renderListener) {
this.reader = reader;
this.renderListener = renderListener;
}
/**
* Gets the content bytes of a page.
*
* @param pageNum the 1-based page number of page you want get the content stream from
* @return a byte array with the effective content stream of a page
* @throws IOException
*/
private byte[] getContentBytesForPage(int pageNum) throws IOException {
try (RandomAccessFileOrArray ignored = reader.getSafeFile()) {
PdfDictionary pageDictionary = reader.getPageN(pageNum);
PdfObject contentObject = pageDictionary.get(PdfName.CONTENTS);
return getContentBytesFromContentObject(contentObject);
}
}
/**
* Gets the content bytes from a content object, which may be a reference a stream or an array.
*
* @param contentObject the object to read bytes from
* @return the content bytes
* @throws IOException
*/
private byte[] getContentBytesFromContentObject(PdfObject contentObject) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Gets the text from a page.
*
* @param page the 1-based page number of page
* @return a String with the content as plain text (without PDF syntax)
* @throws IOException on error
*/
public String getTextFromPage(int page) throws IOException {
return getTextFromPage(page, false);
}
/**
* get the text from the page
*
* @param page page number we are interested in
* @param useContainerMarkup should we put tags in for PDf markup container elements (not really HTML at the
* moment).
* @return result of extracting the text, with tags as requested.
* @throws IOException on error
*/
public String getTextFromPage(int page, boolean useContainerMarkup) throws IOException {
PdfDictionary pageDict = reader.getPageN(page);
if (pageDict == null) {
return "";
}
PdfDictionary resources = pageDict.getAsDict(PdfName.RESOURCES);
renderListener.reset();
renderListener.setPage(page);
PdfContentStreamHandler handler = new PdfContentStreamHandler(renderListener);
processContent(getContentBytesForPage(page), resources, handler);
return handler.getResultantText();
}
/**
* Processes PDF syntax
*
* @param contentBytes the bytes of a content stream
* @param resources the resources that come with the content stream
* @param handler interprets events caused by recognition of operations in a content stream.
*/
public void processContent(byte[] contentBytes, PdfDictionary resources,
PdfContentStreamHandler handler) {
handler.pushContext("div class='t-extracted-page'");
try {
PdfContentParser ps = new PdfContentParser(new PRTokeniser(contentBytes));
List<PdfObject> operands = new ArrayList<>();
while (ps.parse(operands).size() > 0) {
PdfLiteral operator = (PdfLiteral) operands.get(operands.size() - 1);
handler.invokeOperator(operator, operands, resources);
}
} catch (Exception e) {
throw new ExceptionConverter(e);
}
handler.popContext();
}
}
|
final byte[] result;
switch (contentObject.type()) {
case PdfObject.INDIRECT:
PRIndirectReference ref = (PRIndirectReference) contentObject;
PdfObject directObject = PdfReader.getPdfObject(ref);
result = getContentBytesFromContentObject(directObject);
break;
case PdfObject.STREAM:
PRStream stream = (PRStream) PdfReader.getPdfObject(contentObject);
result = PdfReader.getStreamBytes(stream);
break;
case PdfObject.ARRAY:
// Stitch together all content before calling processContent(),
// because
// processContent() resets state.
ByteArrayOutputStream allBytes = new ByteArrayOutputStream();
PdfArray contentArray = (PdfArray) contentObject;
for (PdfObject pdfObject : contentArray.getElements()) {
allBytes.write(getContentBytesFromContentObject(pdfObject));
}
result = allBytes.toByteArray();
break;
default:
throw new IllegalStateException("Unable to handle Content of type " + contentObject.getClass());
}
return result;
| 1,208
| 289
| 1,497
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/parser/Vector.java
|
Vector
|
cross
|
class Vector {
/**
* index of the X coordinate
*/
private static final int I1 = 0;
/**
* index of the Y coordinate
*/
private static final int I2 = 1;
/**
* index of the Z coordinate
*/
private static final int I3 = 2;
/**
* the values inside the vector
*/
private final float[] values = new float[]{
0, 0, 0
};
/**
* Creates a new Vector
*
* @param x the X coordinate
* @param y the Y coordinate
* @param z the Z coordinate
*/
public Vector(float x, float y, float z) {
values[I1] = x;
values[I2] = y;
values[I3] = z;
}
/**
* Gets the value from a coordinate of the vector
*
* @param index the index of the value to get (I1, I2 or I3)
* @return value from a coordinate of the vector
*/
public float get(int index) {
return values[index];
}
/**
* Computes the cross product of this vector and the specified matrix
*
* @param by the matrix to cross this vector with
* @return the result of the cross product
*/
public Vector cross(Matrix by) {<FILL_FUNCTION_BODY>}
/**
* Computes the difference between this vector and the specified vector
*
* @param v the vector to subtract from this one
* @return the results of the subtraction
*/
public Vector subtract(Vector v) {
float x = values[I1] - v.values[I1];
float y = values[I2] - v.values[I2];
float z = values[I3] - v.values[I3];
return new Vector(x, y, z);
}
/**
* Computes the sum of this vector and the specified vector
*
* @param v the vector to subtract from this one
* @return the results of the subtraction
*/
public Vector add(Vector v) {
float x = values[I1] + v.values[I1];
float y = values[I2] + v.values[I2];
float z = values[I3] + v.values[I3];
return new Vector(x, y, z);
}
/**
* Computes the cross product of this vector and the specified vector
*
* @param with the vector to cross this vector with
* @return the cross product
*/
public Vector cross(Vector with) {
float x = values[I2] * with.values[I3] - values[I3] * with.values[I2];
float y = values[I3] * with.values[I1] - values[I1] * with.values[I3];
float z = values[I1] * with.values[I2] - values[I2] * with.values[I1];
return new Vector(x, y, z);
}
/**
* Computes the dot product of this vector with the specified vector
*
* @param with the vector to dot product this vector with
* @return the dot product
*/
public float dot(Vector with) {
return values[I1] * with.values[I1] + values[I2] * with.values[I2] + values[I3] * with.values[I3];
}
/**
* Computes the length of this vector
*
* <b>Note:</b> If you are working with raw vectors from PDF, be careful -
* the Z axis will generally be set to 1. If you want to compute the length of a vector, subtract it from the
* origin first (this will set the Z axis to 0).
* <p>
* For example:
* <code>aVector.subtract(originVector).length();</code>
*
* @return the length of this vector
*/
public float length() {
return (float) Math.sqrt(lengthSquared());
}
/**
* Computes the length squared of this vector.
* <p>
* The square of the length is less expensive to compute, and is often useful without taking the square root.
* <br><br>
* <b>Note:</b> See the important note under {@link Vector#length()}
*
* @return the square of the length of the vector
*/
public float lengthSquared() {
return values[I1] * values[I1] + values[I2] * values[I2] + values[I3] * values[I3];
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return values[I1] + "," + values[I2] + "," + values[I3];
}
}
|
float x = values[I1] * by.get(Matrix.I11) + values[I2] * by.get(Matrix.I21) + values[I3] * by.get(Matrix.I31);
float y = values[I1] * by.get(Matrix.I12) + values[I2] * by.get(Matrix.I22) + values[I3] * by.get(Matrix.I32);
float z = values[I1] * by.get(Matrix.I13) + values[I2] * by.get(Matrix.I23) + values[I3] * by.get(Matrix.I33);
return new Vector(x, y, z);
| 1,266
| 181
| 1,447
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/parser/Word.java
|
Word
|
getFinalText
|
class Word extends ParsedTextImpl {
/**
* Is this an indivisible fragment, because it contained a space or was split from a space- containing string.
* Non-splittable words can be merged (into new non-splittable words).
*/
private final boolean shouldNotSplit;
/**
* If this word or fragment was preceded by a space, or a line break, it should never be merged into a preceding
* word.
*/
private final boolean breakBefore;
/**
* @param text text content
* @param ascent font ascent (e.g. height)
* @param descent How far below the baseline letters go
* @param startPoint first point of the text
* @param endPoint ending offset of text
* @param baseline line along which text is set.
* @param spaceWidth how much space is a space supposed to take.
* @param isCompleteWord word should never be split
* @param breakBefore word starts here, should never combine to the left.
*/
Word(String text, float ascent, float descent, Vector startPoint,
Vector endPoint, Vector baseline, float spaceWidth, boolean isCompleteWord, boolean breakBefore) {
super(text, startPoint, endPoint, baseline, ascent, descent, spaceWidth);
shouldNotSplit = isCompleteWord;
this.breakBefore = breakBefore;
}
private static String formatPercent(float f) {
return String.format("%.2f%%", f);
}
private static String escapeHTML(String s) {
return s.replaceAll("&", "&").replaceAll("<", "<")
.replaceAll(">", ">");
}
/**
* accept a visitor that is assembling text
*
* @param p the assembler that is visiting us.
* @param contextName What is the wrapping markup element name if any
* @see com.lowagie.text.pdf.parser.ParsedTextImpl#accumulate(com.lowagie.text.pdf.parser.TextAssembler, String)
* @see com.lowagie.text.pdf.parser.TextAssemblyBuffer#accumulate(com.lowagie.text.pdf.parser.TextAssembler, String)
*/
@Override
public void accumulate(TextAssembler p, String contextName) {
p.process(this, contextName);
}
/**
* Accept a visitor that is assembling text
*
* @param p the assembler that is visiting us.
* @see com.lowagie.text.pdf.parser.TextAssemblyBuffer#assemble(com.lowagie.text.pdf.parser.TextAssembler)
* @see com.lowagie.text.pdf.parser.ParsedTextImpl#assemble(com.lowagie.text.pdf.parser.TextAssembler)
*/
@Override
public void assemble(TextAssembler p) {
p.renderText(this);
}
/**
* Generate markup for this word. send the assembler a strings representing a CSS style that will format us nicely.
*
* @param text passed in because we may have wanted to alter it, e.g. by trimming white space, or filtering
* characters or something.
* @param reader the file reader from which we are extracting
* @param page number of the page we are reading text from
* @param assembler object to assemble text from fragments and larger strings on a page.
* @return markup to represent this one word.
*/
private String wordMarkup(String text, PdfReader reader, int page, TextAssembler assembler) {
if (text == null) {
return "";
}
Rectangle mediaBox = reader.getPageSize(page);
Rectangle cropBox = reader.getBoxSize(page, "crop");
text = text.replaceAll("[\u00A0\u202f]", " ").trim();
if (text.length() == 0) {
return text;
}
mediaBox.normalize();
if (cropBox != null) {
cropBox.normalize();
} else {
cropBox = reader.getBoxSize(page, "trim");
if (cropBox != null) {
cropBox.normalize();
} else {
cropBox = mediaBox;
}
}
float xOffset = cropBox.getLeft() - mediaBox.getLeft();
float yOffset = cropBox.getTop() - mediaBox.getTop();
Vector startPoint = getStartPoint();
Vector endPoint = getEndPoint();
float pageWidth = cropBox.getWidth();
float pageHeight = cropBox.getHeight();
float leftPercent = (float) ((startPoint.get(0) - xOffset - mediaBox.getLeft()) / pageWidth * 100.0);
float bottom = endPoint.get(1) + yOffset - getDescent() - mediaBox.getBottom();
float bottomPercent = bottom / pageHeight * 100f;
StringBuilder result = new StringBuilder();
float width = getWidth();
float widthPercent = width / pageWidth * 100.0f;
float height = getAscent();
float heightPercent = height / pageHeight * 100.0f;
String myId = assembler.getWordId();
Rectangle resultRect = new Rectangle(leftPercent, bottomPercent, leftPercent + widthPercent,
bottomPercent + heightPercent);
result.append("<span class=\"t-word\" style=\"bottom: ")
.append(formatPercent(resultRect.getBottom())).append("; left: ")
.append(formatPercent(resultRect.getLeft())).append("; width: ")
.append(formatPercent(resultRect.getWidth())).append("; height: ")
.append(formatPercent(resultRect.getHeight())).append(";\"")
.append(" id=\"").append(myId).append("\">")
.append(escapeHTML(text)).append(" ");
result.append("</span> ");
return result.toString();
}
/**
* @see com.lowagie.text.pdf.parser.TextAssemblyBuffer#getFinalText(PdfReader, int, TextAssembler, boolean)
*/
@Override
public FinalText getFinalText(PdfReader reader, int page,
TextAssembler assembler, boolean useMarkup) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "[Word: [" + getText() + "] " + getStartPoint() + ", "
+ getEndPoint() + "] lead" + getAscent() + "]";
}
/**
* @see com.lowagie.text.pdf.parser.ParsedTextImpl#shouldNotSplit()
*/
@Override
public boolean shouldNotSplit() {
return shouldNotSplit;
}
/**
* @see com.lowagie.text.pdf.parser.ParsedTextImpl#breakBefore()
*/
@Override
public boolean breakBefore() {
return breakBefore;
}
}
|
final String text = getText() == null ? "" : getText();
if (useMarkup) {
return new FinalText(wordMarkup(text, reader, page, assembler));
} else {
final boolean hasSpaceAlready = text.startsWith(" ") || text.endsWith(" ");
String prefixSpace = hasSpaceAlready ? "" : " ";
return new FinalText(prefixSpace + text);
}
| 1,838
| 108
| 1,946
|
<methods>public abstract boolean breakBefore() ,public float getAscent() ,public com.lowagie.text.pdf.parser.Vector getBaseline() ,public float getDescent() ,public com.lowagie.text.pdf.parser.Vector getEndPoint() ,public float getSingleSpaceWidth() ,public com.lowagie.text.pdf.parser.Vector getStartPoint() ,public java.lang.String getText() ,public float getWidth() ,public abstract boolean shouldNotSplit() <variables>private float ascent,private com.lowagie.text.pdf.parser.Vector baseline,private float descent,private com.lowagie.text.pdf.parser.Vector endPoint,private float spaceWidth,private com.lowagie.text.pdf.parser.Vector startPoint,private final non-sealed java.lang.String text
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/utils/NumberUtilities.java
|
NumberUtilities
|
parseFloat
|
class NumberUtilities {
private NumberUtilities() {
}
/**
* Try parse float from string and return {@link Optional#empty()} in case of {@link NumberFormatException}
*
* @param value string value
* @return {@link Optional} containing parsed value or empty
*/
public static Optional<Float> parseFloat(String value) {<FILL_FUNCTION_BODY>}
/**
* Try parse int from string and return {@link Optional#empty()} in case of {@link NumberFormatException}
*
* @param value string value
* @return {@link Optional} containing parsed value or empty
*/
public static Optional<Integer> parseInt(String value) {
try {
return Optional.of(Integer.parseInt(value));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
}
|
try {
return Optional.of(Float.parseFloat(value));
} catch (NumberFormatException e) {
return Optional.empty();
}
| 220
| 42
| 262
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/utils/SystemPropertyUtil.java
|
SystemPropertyUtil
|
getBoolean
|
class SystemPropertyUtil {
/**
* Similar to {@link Boolean#getBoolean(String)} but uses the given default value if property were not set.
*
* @param propertyKey the system property key
* @param defaultValue the default value to use if property is not defined.
* @return true if the property is defined and contains "true" (ignoring case), else if system property is not set
* then the provided defaultValue, else false.
*/
public static boolean getBoolean(String propertyKey, boolean defaultValue) {<FILL_FUNCTION_BODY>}
}
|
String propertyValue = System.getProperty(propertyKey);
if (propertyValue == null) {
return defaultValue;
}
return Boolean.parseBoolean(propertyValue);
| 143
| 48
| 191
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/xml/SAXmyHandler.java
|
SAXmyHandler
|
endElement
|
class SAXmyHandler extends SAXiTextHandler<XmlPeer> {
/**
* Constructs a new SAXiTextHandler that will translate all the events triggered by the parser to actions on the
* <CODE>Document</CODE>-object.
*
* @param document this is the document on which events must be triggered
* @param myTags a user defined tagmap
*/
public SAXmyHandler(DocListener document, Map<String, XmlPeer> myTags) {
super(document, myTags);
}
/**
* This method gets called when a start tag is encountered.
*
* @param uri the Uniform Resource Identifier
* @param localName the local name (without prefix), or the empty string if Namespace processing is not being
* performed.
* @param name the name of the tag that is encountered
* @param attrs the list of attributes
*/
public void startElement(String uri, String localName, String name, Attributes attrs) {
if (myTags.containsKey(name)) {
XmlPeer peer = myTags.get(name);
handleStartingTags(peer.getTag(), peer.getAttributes(attrs));
} else {
Properties attributes = new Properties();
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String attribute = attrs.getQName(i);
attributes.setProperty(attribute, attrs.getValue(i));
}
}
handleStartingTags(name, attributes);
}
}
/**
* This method gets called when an end tag is encountered.
*
* @param uri the Uniform Resource Identifier
* @param lname the local name (without prefix), or the empty string if Namespace processing is not being
* performed.
* @param name the name of the tag that ends
*/
public void endElement(String uri, String lname, String name) {<FILL_FUNCTION_BODY>}
}
|
if (myTags.containsKey(name)) {
XmlPeer peer = myTags.get(name);
handleEndingTags(peer.getTag());
} else {
handleEndingTags(name);
}
| 514
| 61
| 575
|
<methods>public void <init>(com.lowagie.text.DocListener) ,public void <init>(com.lowagie.text.DocListener, Map<java.lang.String,com.lowagie.text.xml.XmlPeer>, com.lowagie.text.pdf.BaseFont) ,public void <init>(com.lowagie.text.DocListener, Map<java.lang.String,com.lowagie.text.xml.XmlPeer>) ,public void characters(char[], int, int) ,public void endElement(java.lang.String, java.lang.String, java.lang.String) ,public void handleEndingTags(java.lang.String) ,public void handleStartingTags(java.lang.String, java.util.Properties) ,public void ignorableWhitespace(char[], int, int) ,public void setBaseFont(com.lowagie.text.pdf.BaseFont) ,public void setControlOpenClose(boolean) ,public void startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) <variables>private com.lowagie.text.pdf.BaseFont bf,private float bottomMargin,protected int chapters,private boolean controlOpenClose,protected com.lowagie.text.Chunk currentChunk,protected com.lowagie.text.DocListener document,protected boolean ignore,private float leftMargin,protected Map<java.lang.String,com.lowagie.text.xml.XmlPeer> myTags,private float rightMargin,protected Stack<com.lowagie.text.Element> stack,private float topMargin
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/xml/TagMap.java
|
TagMap
|
init
|
class TagMap extends HashMap<String, XmlPeer> {
private static final long serialVersionUID = -6809383366554350820L;
/**
* Constructs a TagMap
*
* @param tagfile the path to an XML file with the tagmap
*/
public TagMap(String tagfile) {
try {
init(TagMap.class.getClassLoader().getResourceAsStream(tagfile));
} catch (Exception e) {
try {
init(new FileInputStream(tagfile));
} catch (FileNotFoundException fnfe) {
throw new ExceptionConverter(fnfe);
}
}
}
/**
* Constructs a TagMap.
*
* @param in An InputStream with the tagmap xml
*/
public TagMap(InputStream in) {
init(in);
}
protected void init(InputStream in) {<FILL_FUNCTION_BODY>}
class AttributeHandler extends DefaultHandler {
/**
* This is a tag
*/
public static final String TAG = "tag";
/**
* This is a tag
*/
public static final String ATTRIBUTE = "attribute";
/**
* This is an attribute
*/
public static final String NAME = "name";
/**
* This is an attribute
*/
public static final String ALIAS = "alias";
/**
* This is an attribute
*/
public static final String VALUE = "value";
/**
* This is an attribute
*/
public static final String CONTENT = "content";
/**
* This is the tagmap using the AttributeHandler
*/
private Map<String, XmlPeer> tagMap;
/**
* This is the current peer.
*/
private XmlPeer currentPeer;
public AttributeHandler(Map<String, XmlPeer> tagMap) {
this.tagMap = tagMap;
}
/**
* This method gets called when a start tag is encountered.
*
* @param uri the Uniform Resource Identifier
* @param lname the local name (without prefix), or the empty string if Namespace processing is not being
* performed.
* @param tag the name of the tag that is encountered
* @param attrs the list of attributes
*/
public void startElement(String uri, String lname, String tag, Attributes attrs) {
String name = attrs.getValue(NAME);
String alias = attrs.getValue(ALIAS);
String value = attrs.getValue(VALUE);
if (name != null) {
if (TAG.equals(tag)) {
currentPeer = new XmlPeer(name, alias);
} else if (ATTRIBUTE.equals(tag)) {
if (alias != null) {
currentPeer.addAlias(name, alias);
}
if (value != null) {
currentPeer.addValue(name, value);
}
}
}
value = attrs.getValue(CONTENT);
if (value != null) {
currentPeer.setContent(value);
}
}
/**
* This method gets called when ignorable white space encountered.
*
* @param ch an array of characters
* @param start the start position in the array
* @param length the number of characters to read from the array
*/
public void ignorableWhitespace(char[] ch, int start, int length) {
// do nothing
}
/**
* This method gets called when characters are encountered.
*
* @param ch an array of characters
* @param start the start position in the array
* @param length the number of characters to read from the array
*/
public void characters(char[] ch, int start, int length) {
// do nothing
}
/**
* This method gets called when an end tag is encountered.
*
* @param uri the Uniform Resource Identifier
* @param lname the local name (without prefix), or the empty string if Namespace processing is not being
* performed.
* @param tag the name of the tag that ends
*/
public void endElement(String uri, String lname, String tag) {
if (TAG.equals(tag)) {
tagMap.put(currentPeer.getAlias(), currentPeer);
}
}
}
}
|
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
SAXParser parser = factory.newSAXParser();
parser.parse(new InputSource(in), new AttributeHandler((Map<String, XmlPeer>) this));
} catch (Exception e) {
throw new ExceptionConverter(e);
}
| 1,145
| 141
| 1,286
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends java.lang.String,? extends com.lowagie.text.xml.XmlPeer>) ,public void <init>(int, float) ,public void clear() ,public java.lang.Object clone() ,public com.lowagie.text.xml.XmlPeer compute(java.lang.String, BiFunction<? super java.lang.String,? super com.lowagie.text.xml.XmlPeer,? extends com.lowagie.text.xml.XmlPeer>) ,public com.lowagie.text.xml.XmlPeer computeIfAbsent(java.lang.String, Function<? super java.lang.String,? extends com.lowagie.text.xml.XmlPeer>) ,public com.lowagie.text.xml.XmlPeer computeIfPresent(java.lang.String, BiFunction<? super java.lang.String,? super com.lowagie.text.xml.XmlPeer,? extends com.lowagie.text.xml.XmlPeer>) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Set<Entry<java.lang.String,com.lowagie.text.xml.XmlPeer>> entrySet() ,public void forEach(BiConsumer<? super java.lang.String,? super com.lowagie.text.xml.XmlPeer>) ,public com.lowagie.text.xml.XmlPeer get(java.lang.Object) ,public com.lowagie.text.xml.XmlPeer getOrDefault(java.lang.Object, com.lowagie.text.xml.XmlPeer) ,public boolean isEmpty() ,public Set<java.lang.String> keySet() ,public com.lowagie.text.xml.XmlPeer merge(java.lang.String, com.lowagie.text.xml.XmlPeer, BiFunction<? super com.lowagie.text.xml.XmlPeer,? super com.lowagie.text.xml.XmlPeer,? extends com.lowagie.text.xml.XmlPeer>) ,public com.lowagie.text.xml.XmlPeer put(java.lang.String, com.lowagie.text.xml.XmlPeer) ,public void putAll(Map<? extends java.lang.String,? extends com.lowagie.text.xml.XmlPeer>) ,public com.lowagie.text.xml.XmlPeer putIfAbsent(java.lang.String, com.lowagie.text.xml.XmlPeer) ,public com.lowagie.text.xml.XmlPeer remove(java.lang.Object) ,public boolean remove(java.lang.Object, java.lang.Object) ,public com.lowagie.text.xml.XmlPeer replace(java.lang.String, com.lowagie.text.xml.XmlPeer) ,public boolean replace(java.lang.String, com.lowagie.text.xml.XmlPeer, com.lowagie.text.xml.XmlPeer) ,public void replaceAll(BiFunction<? super java.lang.String,? super com.lowagie.text.xml.XmlPeer,? extends com.lowagie.text.xml.XmlPeer>) ,public int size() ,public Collection<com.lowagie.text.xml.XmlPeer> values() <variables>static final int DEFAULT_INITIAL_CAPACITY,static final float DEFAULT_LOAD_FACTOR,static final int MAXIMUM_CAPACITY,static final int MIN_TREEIFY_CAPACITY,static final int TREEIFY_THRESHOLD,static final int UNTREEIFY_THRESHOLD,transient Set<Entry<java.lang.String,com.lowagie.text.xml.XmlPeer>> entrySet,final float loadFactor,transient int modCount,private static final long serialVersionUID,transient int size,transient Node<java.lang.String,com.lowagie.text.xml.XmlPeer>[] table,int threshold
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/xml/XMLUtil.java
|
XMLUtil
|
escapeXML
|
class XMLUtil {
/**
* Escapes a string with the appropriated XML codes.
*
* @param s the string to be escaped
* @param onlyASCII codes above 127 will always be escaped with &#nn; if <CODE>true</CODE>
* @return the escaped string
*/
public static String escapeXML(String s, boolean onlyASCII) {<FILL_FUNCTION_BODY>}
}
|
char[] cc = s.toCharArray();
int len = cc.length;
StringBuilder sb = new StringBuilder();
for (int c : cc) {
switch (c) {
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '&':
sb.append("&");
break;
case '"':
sb.append(""");
break;
case '\'':
sb.append("'");
break;
default:
if ((c == 0x9) || (c == 0xA) || (c == 0xD)
|| ((c >= 0x20) && (c <= 0xD7FF))
|| ((c >= 0xE000) && (c <= 0xFFFD))
|| ((c >= 0x10000) && (c <= 0x10FFFF))) {
if (onlyASCII && c > 127) {
sb.append("&#").append(c).append(';');
} else {
sb.append((char) c);
}
}
}
}
return sb.toString();
| 116
| 314
| 430
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/xml/XmlPeer.java
|
XmlPeer
|
getAttributes
|
class XmlPeer {
/**
* This is the name of the alias.
*/
protected String tagname;
/**
* This is the name of the alias.
*/
protected String customTagname;
/**
* This is the Map that contains the aliases of the attributes.
*/
protected Properties attributeAliases = new Properties();
/**
* This is the Map that contains the default values of the attributes.
*/
protected Properties attributeValues = new Properties();
/**
* This is String that contains the default content of the attributes.
*/
protected String defaultContent = null;
/**
* Creates a XmlPeer.
*
* @param name the iText name of a tag
* @param alias the user defined name of a tag
*/
public XmlPeer(String name, String alias) {
this.tagname = name;
this.customTagname = alias;
}
/**
* Gets the tagname of the peer.
*
* @return the iText name of a tag
*/
public String getTag() {
return tagname;
}
/**
* Gets the tagname of the peer.
*
* @return the user defined tagname
*/
public String getAlias() {
return customTagname;
}
/**
* Gets the list of attributes of the peer.
*
* @param attrs the user defined set of attributes
* @return the set of attributes translated to iText attributes
*/
public Properties getAttributes(Attributes attrs) {<FILL_FUNCTION_BODY>}
/**
* Sets an alias for an attribute.
*
* @param name the iText tagname
* @param alias the custom tagname
*/
public void addAlias(String name, String alias) {
attributeAliases.put(alias, name);
}
/**
* Sets a value for an attribute.
*
* @param name the iText tagname
* @param value the default value for this tag
*/
public void addValue(String name, String value) {
attributeValues.put(name, value);
}
/**
* Sets the default content.
*
* @param content the default content
*/
public void setContent(String content) {
this.defaultContent = content;
}
/**
* Returns the iText attribute name.
*
* @param name the custom attribute name
* @return iText translated attribute name
*/
public String getName(String name) {
String value;
if ((value = attributeAliases.getProperty(name)) != null) {
return value;
}
return name;
}
/**
* Returns the default values.
*
* @return A set of default (user defined) values
*/
public Properties getDefaultValues() {
return attributeValues;
}
}
|
Properties attributes = new Properties();
attributes.putAll(attributeValues);
if (defaultContent != null) {
attributes.put(ElementTags.ITEXT, defaultContent);
}
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String attribute = getName(attrs.getQName(i));
attributes.setProperty(attribute, attrs.getValue(i));
}
}
return attributes;
| 760
| 126
| 886
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/xml/xmp/LangAlt.java
|
LangAlt
|
toString
|
class LangAlt extends Properties {
/**
* Key for the default language.
*/
public static final String DEFAULT = "x-default";
/**
* A serial version id.
*/
private static final long serialVersionUID = 4396971487200843099L;
/**
* Creates a Properties object that stores languages for use in an XmpSchema
*
* @param defaultValue default value
*/
public LangAlt(String defaultValue) {
super();
addLanguage(DEFAULT, defaultValue);
}
/**
* Creates a Properties object that stores languages for use in an XmpSchema
*/
public LangAlt() {
super();
}
/**
* Add a language.
*
* @param language language
* @param value value
*/
public void addLanguage(String language, String value) {
setProperty(language, XmpSchema.escape(value));
}
/**
* Process a property.
*
* @param buf buffer
* @param lang object
*/
protected void process(StringBuffer buf, Object lang) {
buf.append("<rdf:li xml:lang=\"");
buf.append(lang);
buf.append("\" >");
buf.append(get(lang));
buf.append("</rdf:li>");
}
/**
* Creates a String that can be used in an XmpSchema.
*/
public synchronized String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuffer sb = new StringBuffer();
sb.append("<rdf:Alt>");
for (Enumeration e = this.propertyNames(); e.hasMoreElements(); ) {
process(sb, e.nextElement());
}
sb.append("</rdf:Alt>");
return sb.toString();
| 405
| 83
| 488
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(java.util.Properties) ,public synchronized void clear() ,public synchronized java.lang.Object clone() ,public synchronized java.lang.Object compute(java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public synchronized java.lang.Object computeIfAbsent(java.lang.Object, Function<? super java.lang.Object,?>) ,public synchronized java.lang.Object computeIfPresent(java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public boolean contains(java.lang.Object) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Enumeration<java.lang.Object> elements() ,public Set<Entry<java.lang.Object,java.lang.Object>> entrySet() ,public synchronized boolean equals(java.lang.Object) ,public synchronized void forEach(BiConsumer<? super java.lang.Object,? super java.lang.Object>) ,public java.lang.Object get(java.lang.Object) ,public java.lang.Object getOrDefault(java.lang.Object, java.lang.Object) ,public java.lang.String getProperty(java.lang.String) ,public java.lang.String getProperty(java.lang.String, java.lang.String) ,public synchronized int hashCode() ,public boolean isEmpty() ,public Set<java.lang.Object> keySet() ,public Enumeration<java.lang.Object> keys() ,public void list(java.io.PrintStream) ,public void list(java.io.PrintWriter) ,public synchronized void load(java.io.Reader) throws java.io.IOException,public synchronized void load(java.io.InputStream) throws java.io.IOException,public synchronized void loadFromXML(java.io.InputStream) throws java.io.IOException, java.util.InvalidPropertiesFormatException,public synchronized java.lang.Object merge(java.lang.Object, java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public Enumeration<?> propertyNames() ,public synchronized java.lang.Object put(java.lang.Object, java.lang.Object) ,public synchronized void putAll(Map<?,?>) ,public synchronized java.lang.Object putIfAbsent(java.lang.Object, java.lang.Object) ,public synchronized java.lang.Object remove(java.lang.Object) ,public synchronized boolean remove(java.lang.Object, java.lang.Object) ,public synchronized java.lang.Object replace(java.lang.Object, java.lang.Object) ,public synchronized boolean replace(java.lang.Object, java.lang.Object, java.lang.Object) ,public synchronized void replaceAll(BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public void save(java.io.OutputStream, java.lang.String) ,public synchronized java.lang.Object setProperty(java.lang.String, java.lang.String) ,public int size() ,public void store(java.io.Writer, java.lang.String) throws java.io.IOException,public void store(java.io.OutputStream, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String, java.nio.charset.Charset) throws java.io.IOException,public Set<java.lang.String> stringPropertyNames() ,public synchronized java.lang.String toString() ,public Collection<java.lang.Object> values() <variables>private static final jdk.internal.misc.Unsafe UNSAFE,protected volatile java.util.Properties defaults,private volatile transient ConcurrentHashMap<java.lang.Object,java.lang.Object> map,private static final long serialVersionUID
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/xml/xmp/XmpArray.java
|
XmpArray
|
toString
|
class XmpArray extends ArrayList<String> {
/**
* An array that is unordered.
*/
public static final String UNORDERED = "rdf:Bag";
/**
* An array that is ordered.
*/
public static final String ORDERED = "rdf:Seq";
/**
* An array with alternatives.
*/
public static final String ALTERNATIVE = "rdf:Alt";
private static final long serialVersionUID = 5722854116328732742L;
/**
* the type of array.
*/
protected String type;
/**
* Creates an XmpArray.
*
* @param type the type of array: UNORDERED, ORDERED or ALTERNATIVE.
*/
public XmpArray(String type) {
this.type = type;
}
/**
* Returns the String representation of the XmpArray.
*
* @return a String representation
*/
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder buf = new StringBuilder("<");
buf.append(type);
buf.append('>');
for (String s : this) {
buf.append("<rdf:li>");
buf.append(XmpSchema.escape(s));
buf.append("</rdf:li>");
}
buf.append("</");
buf.append(type);
buf.append('>');
return buf.toString();
| 276
| 117
| 393
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Collection<? extends java.lang.String>) ,public boolean add(java.lang.String) ,public void add(int, java.lang.String) ,public boolean addAll(Collection<? extends java.lang.String>) ,public boolean addAll(int, Collection<? extends java.lang.String>) ,public void clear() ,public java.lang.Object clone() ,public boolean contains(java.lang.Object) ,public void ensureCapacity(int) ,public boolean equals(java.lang.Object) ,public void forEach(Consumer<? super java.lang.String>) ,public java.lang.String get(int) ,public int hashCode() ,public int indexOf(java.lang.Object) ,public boolean isEmpty() ,public Iterator<java.lang.String> iterator() ,public int lastIndexOf(java.lang.Object) ,public ListIterator<java.lang.String> listIterator() ,public ListIterator<java.lang.String> listIterator(int) ,public java.lang.String remove(int) ,public boolean remove(java.lang.Object) ,public boolean removeAll(Collection<?>) ,public boolean removeIf(Predicate<? super java.lang.String>) ,public void replaceAll(UnaryOperator<java.lang.String>) ,public boolean retainAll(Collection<?>) ,public java.lang.String set(int, java.lang.String) ,public int size() ,public void sort(Comparator<? super java.lang.String>) ,public Spliterator<java.lang.String> spliterator() ,public List<java.lang.String> subList(int, int) ,public java.lang.Object[] toArray() ,public T[] toArray(T[]) ,public void trimToSize() <variables>private static final java.lang.Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA,private static final int DEFAULT_CAPACITY,private static final java.lang.Object[] EMPTY_ELEMENTDATA,transient java.lang.Object[] elementData,private static final long serialVersionUID,private int size
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/xml/xmp/XmpReader.java
|
XmpReader
|
replace
|
class XmpReader {
private Document domDocument;
/**
* Constructs an XMP reader
*
* @param bytes the XMP content
* @throws ExceptionConverter on error
* @throws IOException on error
* @throws SAXException on error
*/
public XmpReader(byte[] bytes) throws SAXException, IOException {
try {
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
fact.setNamespaceAware(true);
DocumentBuilder db = fact.newDocumentBuilder();
db.setEntityResolver((publicId, systemId) -> new InputSource(new StringReader("")));
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
domDocument = db.parse(bais);
} catch (ParserConfigurationException e) {
throw new ExceptionConverter(e);
}
}
/**
* Replaces the content of a tag.
*
* @param namespaceURI the URI of the namespace
* @param localName the tag name
* @param value the new content for the tag
* @return true if the content was successfully replaced
* @since 2.1.6 the return type has changed from void to boolean
*/
public boolean replace(String namespaceURI, String localName, String value) {<FILL_FUNCTION_BODY>}
/**
* Adds a tag.
*
* @param namespaceURI the URI of the namespace
* @param parent the tag name of the parent
* @param localName the name of the tag to add
* @param value the new content for the tag
* @return true if the content was successfully added
* @since 2.1.6
*/
public boolean add(String parent, String namespaceURI, String localName, String value) {
NodeList nodes = domDocument.getElementsByTagName(parent);
if (nodes.getLength() == 0) {
return false;
}
Node pNode;
Node node;
for (int i = 0; i < nodes.getLength(); i++) {
pNode = nodes.item(i);
NamedNodeMap attrs = pNode.getAttributes();
for (int j = 0; j < attrs.getLength(); j++) {
node = attrs.item(j);
if (namespaceURI.equals(node.getNodeValue())) {
node = domDocument.createElement(localName);
node.appendChild(domDocument.createTextNode(value));
pNode.appendChild(node);
return true;
}
}
}
return false;
}
/**
* Sets the text of this node. All the child's node are deleted and a new child text node is created.
*
* @param domDocument the <CODE>Document</CODE> that contains the node
* @param n the <CODE>Node</CODE> to add the text to
* @param value the text to add
* @return <code>true</code> if added successfully, else <code>false</code>
*/
public boolean setNodeText(Document domDocument, Node n, String value) {
if (n == null) {
return false;
}
Node nc = null;
while ((nc = n.getFirstChild()) != null) {
n.removeChild(nc);
}
n.appendChild(domDocument.createTextNode(value));
return true;
}
/**
* Writes the document to a byte array.
*
* @return byte array of serialized doc
* @throws IOException on error
*/
public byte[] serializeDoc() throws IOException {
XmlDomWriter xw = new XmlDomWriter();
ByteArrayOutputStream fout = new ByteArrayOutputStream();
xw.setOutput(fout, null);
fout.write(XmpWriter.XPACKET_PI_BEGIN.getBytes(StandardCharsets.UTF_8));
fout.flush();
NodeList xmpmeta = domDocument.getElementsByTagName("x:xmpmeta");
xw.write(xmpmeta.item(0));
fout.flush();
for (int i = 0; i < 20; i++) {
fout.write(XmpWriter.EXTRASPACE.getBytes());
}
fout.write(XmpWriter.XPACKET_PI_END_W.getBytes());
fout.close();
return fout.toByteArray();
}
}
|
NodeList nodes = domDocument.getElementsByTagNameNS(namespaceURI, localName);
Node node;
if (nodes.getLength() == 0) {
return false;
}
for (int i = 0; i < nodes.getLength(); i++) {
node = nodes.item(i);
setNodeText(domDocument, node, value);
}
return true;
| 1,127
| 102
| 1,229
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/xml/xmp/XmpSchema.java
|
XmpSchema
|
escape
|
class XmpSchema extends Properties {
private static final long serialVersionUID = -176374295948945272L;
/**
* the namesspace
*/
protected String xmlns;
/**
* Constructs an XMP schema.
*
* @param xmlns xml namespace name
*/
public XmpSchema(String xmlns) {
super();
this.xmlns = xmlns;
}
/**
* @param content content
* @return an escaped string
*/
public static String escape(String content) {<FILL_FUNCTION_BODY>}
/**
* The String representation of the contents.
*
* @return a String representation.
*/
@Override
public synchronized String toString() {
StringBuffer buf = new StringBuffer();
for (Enumeration e = this.propertyNames(); e.hasMoreElements(); ) {
process(buf, e.nextElement());
}
return buf.toString();
}
/**
* Processes a property
*
* @param buf buffer
* @param p object
*/
protected void process(StringBuffer buf, Object p) {
buf.append('<');
buf.append(p);
buf.append('>');
buf.append(this.get(p));
buf.append("</");
buf.append(p);
buf.append('>');
}
/**
* @return Returns the xmlns.
*/
public String getXmlns() {
return xmlns;
}
/**
* @param key property key
* @param value value
* @return the previous property (null if there wasn't one)
*/
public Object addProperty(String key, String value) {
return this.setProperty(key, value);
}
/**
* @see java.util.Properties#setProperty(java.lang.String, java.lang.String)
*/
@Override
public synchronized Object setProperty(String key, String value) {
return super.setProperty(key, escape(value));
}
/**
* @param key used as key
* @param value toString called on this value
* @return the previous property (null if there wasn't one)
* @see java.util.Properties#setProperty(java.lang.String, java.lang.String)
*/
public Object setProperty(String key, XmpArray value) {
return super.setProperty(key, value.toString());
}
/**
* @param key used as key
* @param value toString called on this value
* @return the previous property (null if there wasn't one)
* @see java.util.Properties#setProperty(java.lang.String, java.lang.String)
*/
public Object setProperty(String key, LangAlt value) {
return super.setProperty(key, value.toString());
}
}
|
StringBuilder buf = new StringBuilder();
for (int i = 0; i < content.length(); i++) {
switch (content.charAt(i)) {
case '<':
buf.append("<");
break;
case '>':
buf.append(">");
break;
case '\'':
buf.append("'");
break;
case '\"':
buf.append(""");
break;
case '&':
buf.append("&");
break;
default:
buf.append(content.charAt(i));
}
}
return buf.toString();
| 754
| 174
| 928
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(java.util.Properties) ,public synchronized void clear() ,public synchronized java.lang.Object clone() ,public synchronized java.lang.Object compute(java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public synchronized java.lang.Object computeIfAbsent(java.lang.Object, Function<? super java.lang.Object,?>) ,public synchronized java.lang.Object computeIfPresent(java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public boolean contains(java.lang.Object) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Enumeration<java.lang.Object> elements() ,public Set<Entry<java.lang.Object,java.lang.Object>> entrySet() ,public synchronized boolean equals(java.lang.Object) ,public synchronized void forEach(BiConsumer<? super java.lang.Object,? super java.lang.Object>) ,public java.lang.Object get(java.lang.Object) ,public java.lang.Object getOrDefault(java.lang.Object, java.lang.Object) ,public java.lang.String getProperty(java.lang.String) ,public java.lang.String getProperty(java.lang.String, java.lang.String) ,public synchronized int hashCode() ,public boolean isEmpty() ,public Set<java.lang.Object> keySet() ,public Enumeration<java.lang.Object> keys() ,public void list(java.io.PrintStream) ,public void list(java.io.PrintWriter) ,public synchronized void load(java.io.Reader) throws java.io.IOException,public synchronized void load(java.io.InputStream) throws java.io.IOException,public synchronized void loadFromXML(java.io.InputStream) throws java.io.IOException, java.util.InvalidPropertiesFormatException,public synchronized java.lang.Object merge(java.lang.Object, java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public Enumeration<?> propertyNames() ,public synchronized java.lang.Object put(java.lang.Object, java.lang.Object) ,public synchronized void putAll(Map<?,?>) ,public synchronized java.lang.Object putIfAbsent(java.lang.Object, java.lang.Object) ,public synchronized java.lang.Object remove(java.lang.Object) ,public synchronized boolean remove(java.lang.Object, java.lang.Object) ,public synchronized java.lang.Object replace(java.lang.Object, java.lang.Object) ,public synchronized boolean replace(java.lang.Object, java.lang.Object, java.lang.Object) ,public synchronized void replaceAll(BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public void save(java.io.OutputStream, java.lang.String) ,public synchronized java.lang.Object setProperty(java.lang.String, java.lang.String) ,public int size() ,public void store(java.io.Writer, java.lang.String) throws java.io.IOException,public void store(java.io.OutputStream, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String, java.nio.charset.Charset) throws java.io.IOException,public Set<java.lang.String> stringPropertyNames() ,public synchronized java.lang.String toString() ,public Collection<java.lang.Object> values() <variables>private static final jdk.internal.misc.Unsafe UNSAFE,protected volatile java.util.Properties defaults,private volatile transient ConcurrentHashMap<java.lang.Object,java.lang.Object> map,private static final long serialVersionUID
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/Rups.java
|
Rups
|
startApplication
|
class Rups {
// main method
/**
* Serial Version UID.
*/
private static final long serialVersionUID = 4386633640535735848L;
// methods
/**
* Main method. Starts the RUPS application.
*
* @param args no arguments needed
*/
public static void main(String[] args) {
startApplication();
}
// other member variables
/**
* Initializes the main components of the Rups application.
*/
public static void startApplication() {<FILL_FUNCTION_BODY>}
}
|
// creates a JFrame
JFrame frame = new JFrame();
// defines the size and location
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize((int) (screen.getWidth() * .90), (int) (screen.getHeight() * .90));
frame.setLocation((int) (screen.getWidth() * .05), (int) (screen.getHeight() * .05));
frame.setResizable(true);
// title bar
frame.setTitle("iText RUPS");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// the content
RupsController controller = new RupsController(frame.getSize());
frame.setJMenuBar(controller.getMenuBar());
frame.getContentPane().add(controller.getMasterComponent(), java.awt.BorderLayout.CENTER);
frame.setVisible(true);
| 167
| 236
| 403
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/controller/PdfReaderController.java
|
PdfReaderController
|
update
|
class PdfReaderController extends Observable implements Observer {
/**
* Treeview of the PDF file.
*/
protected PdfTree pdfTree;
/**
* Tabbed Pane containing other components.
*/
protected JTabbedPane navigationTabs;
/**
* JTable with all the pages and their labels.
*/
protected PagesTable pages;
/**
* Treeview of the outlines.
*/
protected OutlineTree outlines;
/**
* Treeview of the form.
*/
protected FormTree form;
/**
* JTable corresponding with the CrossReference table.
*/
protected XRefTable xref;
/**
* A panel that will show PdfObjects.
*/
protected PdfObjectPanel objectPanel;
/**
* Tabbed Pane containing other components.
*/
protected JTabbedPane editorTabs;
/**
* A panel that will show a stream.
*/
protected StreamTextArea streamArea;
/**
* The factory producing tree nodes.
*/
protected TreeNodeFactory nodes;
/**
* Constructs the PdfReaderController. This is an Observable object to which all iText related GUI components are
* added as Observers.
*
* @param treeSelectionListener when somebody selects a tree node, this listener listens to the event
* @param pageSelectionListener when somebody changes a page, this listener changes accordingly
*/
public PdfReaderController(TreeSelectionListener treeSelectionListener,
PageSelectionListener pageSelectionListener) {
pdfTree = new PdfTree();
pdfTree.addTreeSelectionListener(treeSelectionListener);
addObserver(pdfTree);
pages = new PagesTable(this, pageSelectionListener);
addObserver(pages);
outlines = new OutlineTree(this);
addObserver(outlines);
form = new FormTree(this);
addObserver(form);
xref = new XRefTable(this);
addObserver(xref);
navigationTabs = new JTabbedPane();
navigationTabs.addTab("Pages", null, new JScrollPane(pages), "Pages");
navigationTabs.addTab("Outlines", null, new JScrollPane(outlines), "Outlines (Bookmarks)");
navigationTabs.addTab("Form", null, new JScrollPane(form), "Interactive Form");
navigationTabs.addTab("XFA", null, form.getXfaTree(), "Tree view of the XFA form");
navigationTabs.addTab("XRef", null, new JScrollPane(xref), "Cross-reference table");
objectPanel = new PdfObjectPanel();
addObserver(objectPanel);
streamArea = new StreamTextArea();
addObserver(streamArea);
editorTabs = new JTabbedPane();
editorTabs.addTab("Stream", null, streamArea, "Stream");
editorTabs.addTab("XFA", null, form.getXfaTextArea(), "XFA Form XML file");
}
/**
* Getter for the PDF Tree.
*
* @return the PdfTree object
*/
public PdfTree getPdfTree() {
return pdfTree;
}
/**
* Getter for the tabs that allow you to navigate through the PdfTree quickly (pages, form, outlines, xref table).
*
* @return a JTabbedPane
*/
public JTabbedPane getNavigationTabs() {
return navigationTabs;
}
/**
* Getter for the panel that will show the contents of a PDF Object (except for PdfStreams: only the Stream
* Dictionary will be shown; the content stream is shown in a StreamTextArea object).
*
* @return the PdfObjectPanel
*/
public PdfObjectPanel getObjectPanel() {
return objectPanel;
}
/**
* Getter for the tabs with the editor windows (to which the Console window will be added).
*
* @return the tabs with the editor windows
*/
public JTabbedPane getEditorTabs() {
return editorTabs;
}
/**
* Getter for the object that holds the TextArea with the content stream of a PdfStream object.
*
* @return a StreamTextArea
*/
public StreamTextArea getStreamArea() {
return streamArea;
}
/**
* Starts loading the PDF Objects in background.
*
* @param file the wrapper object that holds the PdfReader as member variable
*/
public void startObjectLoader(PdfFile file) {
setChanged();
notifyObservers();
setChanged();
new ObjectLoader(this, file.getPdfReader());
}
/**
* The GUI components that show the internals of a PDF file, can only be shown if all objects are loaded into the
* IndirectObjectFactory using the ObjectLoader. As soon as this is done, the GUI components are notified.
*
* @param obj in this case the Object should be an ObjectLoader
* @see java.util.Observable#notifyObservers(java.lang.Object)
*/
@Override
public void notifyObservers(Object obj) {
if (obj instanceof ObjectLoader loader) {
nodes = loader.getNodes();
PdfTrailerTreeNode root = pdfTree.getRoot();
root.setTrailer(loader.getReader().getTrailer());
root.setUserObject("PDF Object Tree");
nodes.expandNode(root);
}
super.notifyObservers(obj);
}
/**
* Selects a node in the PdfTree.
*
* @param node a node in the PdfTree
*/
public void selectNode(PdfObjectTreeNode node) {
pdfTree.selectNode(node);
}
/**
* Selects a node in the PdfTree.
*
* @param objectNumber a number of a node in the PdfTree
*/
public void selectNode(int objectNumber) {
selectNode(nodes.getNode(objectNumber));
}
/**
* Renders the syntax of a PdfObject in the objectPanel. If the object is a PDF Stream, then the stream is shown in
* the streamArea too.
*
* @param object the object to render
*/
public void render(PdfObject object) {
objectPanel.render(object);
streamArea.render(object);
if (object instanceof PRStream) {
editorTabs.setSelectedComponent(streamArea);
} else {
editorTabs.setSelectedIndex(editorTabs.getComponentCount() - 1);
}
}
/**
* Selects the row in the pageTable that corresponds with a certain page number.
*
* @param pageNumber the page number that needs to be selected
*/
public void gotoPage(int pageNumber) {
pageNumber--;
if (pages == null || pages.getSelectedRow() == pageNumber) {
return;
}
if (pageNumber < pages.getRowCount()) {
pages.setRowSelectionInterval(pageNumber, pageNumber);
}
}
/**
* Forwards updates from the RupsController to the Observers of this class.
*
* @param observable this should be the RupsController
* @param obj the object that has to be forwarded to the observers of PdfReaderController
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void update(Observable observable, Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (RupsMenuBar.CLOSE.equals(obj)) {
setChanged();
notifyObservers(null);
nodes = null;
}
if (obj instanceof PdfObjectTreeNode node) {
nodes.expandNode(node);
if (node.isRecursive()) {
pdfTree.selectNode(node.getAncestor());
return;
}
render(node.getPdfObject());
}
| 1,901
| 115
| 2,016
|
<methods>public void <init>() ,public synchronized void addObserver(java.util.Observer) ,public synchronized int countObservers() ,public synchronized void deleteObserver(java.util.Observer) ,public synchronized void deleteObservers() ,public synchronized boolean hasChanged() ,public void notifyObservers() ,public void notifyObservers(java.lang.Object) <variables>private boolean changed,private Vector<java.util.Observer> obs
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/controller/RupsController.java
|
RupsController
|
notifyObservers
|
class RupsController extends Observable
implements TreeSelectionListener, PageSelectionListener {
// member variables
/* file and controller */
/**
* The Pdf file that is currently open in the application.
*/
protected PdfFile pdfFile;
/**
* Object with the GUI components for iText.
*
* @since iText 5.0.0 (renamed from reader which was confusing because reader is normally used for a PdfReader
* instance)
*/
protected PdfReaderController readerController;
/* main components */
/**
* The JMenuBar for the RUPS application.
*/
protected RupsMenuBar menuBar;
/**
* Contains all other components: the page panel, the outline tree, etc.
*/
protected JSplitPane masterComponent;
// constructor
/**
* Constructs the GUI components of the RUPS application.
*
* @param dimension the Dimension of the GUi components
*/
public RupsController(Dimension dimension) {
// creating components and controllers
menuBar = new RupsMenuBar(this);
addObserver(menuBar);
Console console = Console.getInstance();
addObserver(console);
readerController = new PdfReaderController(this, this);
addObserver(readerController);
// creating the master component
masterComponent = new JSplitPane();
masterComponent.setOrientation(JSplitPane.VERTICAL_SPLIT);
masterComponent.setDividerLocation((int) (dimension.getHeight() * .70));
masterComponent.setDividerSize(2);
JSplitPane content = new JSplitPane();
masterComponent.add(content, JSplitPane.TOP);
JSplitPane info = new JSplitPane();
masterComponent.add(info, JSplitPane.BOTTOM);
content.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
content.setDividerLocation((int) (dimension.getWidth() * .6));
content.setDividerSize(1);
content.add(new JScrollPane(readerController.getPdfTree()), JSplitPane.LEFT);
content.add(readerController.getNavigationTabs(), JSplitPane.RIGHT);
info.setDividerLocation((int) (dimension.getWidth() * .3));
info.setDividerSize(1);
info.add(readerController.getObjectPanel(), JSplitPane.LEFT);
JTabbedPane editorPane = readerController.getEditorTabs();
JScrollPane cons = new JScrollPane(console.getTextArea());
editorPane.addTab("Console", null, cons, "Console window (System.out/System.err)");
editorPane.setSelectedComponent(cons);
info.add(editorPane, JSplitPane.RIGHT);
}
/**
* Getter for the menubar.
*
* @return the menubar
*/
public RupsMenuBar getMenuBar() {
return menuBar;
}
/**
* Getter for the master component.
*
* @return the master component
*/
public Component getMasterComponent() {
return masterComponent;
}
// Observable
/**
* @see java.util.Observable#notifyObservers(java.lang.Object)
*/
@Override
public void notifyObservers(Object obj) {<FILL_FUNCTION_BODY>}
// tree selection
/**
* @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
*/
public void valueChanged(TreeSelectionEvent evt) {
Object selectednode = readerController.getPdfTree().getLastSelectedPathComponent();
if (selectednode instanceof PdfTrailerTreeNode) {
menuBar.update(this, RupsMenuBar.FILE_MENU);
return;
}
if (selectednode instanceof PdfObjectTreeNode) {
readerController.update(this, selectednode);
}
}
// page navigation
/**
* @see com.lowagie.rups.view.PageSelectionListener#gotoPage(int)
*/
public int gotoPage(int pageNumber) {
readerController.gotoPage(pageNumber);
return pageNumber;
}
}
|
if (obj instanceof FileChooserAction) {
File file = ((FileChooserAction) obj).getFile();
try {
pdfFile = new PdfFile(file);
setChanged();
super.notifyObservers(RupsMenuBar.OPEN);
readerController.startObjectLoader(pdfFile);
} catch (IOException | DocumentException ioe) {
JOptionPane.showMessageDialog(masterComponent, ioe.getMessage(), "Dialog", JOptionPane.ERROR_MESSAGE);
}
return;
}
if (obj instanceof FileCloseAction) {
pdfFile = null;
setChanged();
super.notifyObservers(RupsMenuBar.CLOSE);
return;
}
| 1,091
| 183
| 1,274
|
<methods>public void <init>() ,public synchronized void addObserver(java.util.Observer) ,public synchronized int countObservers() ,public synchronized void deleteObserver(java.util.Observer) ,public synchronized void deleteObservers() ,public synchronized boolean hasChanged() ,public void notifyObservers() ,public void notifyObservers(java.lang.Object) <variables>private boolean changed,private Vector<java.util.Observer> obs
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/io/FileChooserAction.java
|
FileChooserAction
|
actionPerformed
|
class FileChooserAction extends AbstractAction {
/**
* A serial version UID.
*/
private static final long serialVersionUID = 2225830878098387118L;
/**
* An object that is expecting the result of the file chooser action.
*/
protected Observable observable;
/**
* A file filter to apply when browsing for a file.
*/
protected FileFilter filter;
/**
* Indicates if you're browsing to create a new or an existing file.
*/
protected boolean newFile;
/**
* The file that was chosen.
*/
protected File file;
/**
* Creates a new file chooser action.
*
* @param observable the object waiting for you to select file
* @param caption a description for the action
* @param filter a filter to apply when browsing
* @param newFile indicates if you should browse for a new or existing file
*/
public FileChooserAction(Observable observable, String caption, FileFilter filter, boolean newFile) {
super(caption);
this.observable = observable;
this.filter = filter;
this.newFile = newFile;
}
/**
* Getter for the file.
*
* @return a file
*/
public File getFile() {
return file;
}
/**
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent evt) {<FILL_FUNCTION_BODY>}
}
|
JFileChooser fc = new JFileChooser();
if (filter != null) {
fc.setFileFilter(filter);
}
int okCancel;
if (newFile) {
okCancel = fc.showSaveDialog(null);
} else {
okCancel = fc.showOpenDialog(null);
}
if (okCancel == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
observable.notifyObservers(this);
}
| 419
| 139
| 558
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.String, javax.swing.Icon) ,public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener) ,public java.lang.Object[] getKeys() ,public synchronized java.beans.PropertyChangeListener[] getPropertyChangeListeners() ,public java.lang.Object getValue(java.lang.String) ,public boolean isEnabled() ,public void putValue(java.lang.String, java.lang.Object) ,public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener) ,public void setEnabled(boolean) <variables>private static java.lang.Boolean RECONFIGURE_ON_NULL,private transient javax.swing.ArrayTable arrayTable,protected javax.swing.event.SwingPropertyChangeSupport changeSupport,protected boolean enabled
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/io/TextAreaOutputStream.java
|
TextAreaOutputStream
|
write
|
class TextAreaOutputStream extends OutputStream {
/**
* The text area to which we want to write.
*/
protected JTextArea text;
/**
* Keeps track of the offset of the text in the text area.
*/
protected int offset;
/**
* Constructs a TextAreaOutputStream.
*
* @param text the text area to which we want to write.
*/
public TextAreaOutputStream(JTextArea text) {
this.text = text;
clear();
}
/**
* Clear the text area.
*/
public void clear() {
text.setText(null);
offset = 0;
}
/**
* @see java.io.OutputStream#write(int)
*/
@Override
public void write(int i) throws IOException {
byte[] b = {(byte) i};
write(b, 0, 1);
}
/**
* @see java.io.OutputStream#write(byte[], int, int)
*/
@Override
public void write(byte[] b, int off, int len) {<FILL_FUNCTION_BODY>}
/**
* @see java.io.OutputStream#write(byte[])
*/
@Override
public void write(byte[] b) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
byte[] snippet = new byte[1024];
int bytesread;
while ((bytesread = bais.read(snippet)) > 0) {
write(snippet, 0, bytesread);
}
}
}
|
String snippet = new String(b, off, len);
text.insert(snippet, offset);
offset += len - off;
| 414
| 39
| 453
|
<methods>public void <init>() ,public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public static java.io.OutputStream nullOutputStream() ,public abstract void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException<variables>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/model/BackgroundTask.java
|
BackgroundTask
|
interrupt
|
class BackgroundTask {
/**
* A wrapper for the tread that executes a time-consuming task.
*/
private ThreadWrapper thread;
/**
* Starts a thread. Executes the time-consuming task in the construct method; finally calls the finish().
*/
public BackgroundTask() {
final Runnable doFinished = this::finished;
Runnable doConstruct = () -> {
try {
doTask();
} finally {
thread.clear();
}
SwingUtilities.invokeLater(doFinished);
};
Thread t = new Thread(doConstruct);
thread = new ThreadWrapper(t);
}
/**
* Implement this class; the time-consuming task will go here.
*/
public abstract void doTask();
/**
* Starts the thread.
*/
public void start() {
Thread t = thread.get();
if (t != null) {
t.start();
}
}
/**
* Forces the thread to stop what it's doing.
*/
public void interrupt() {<FILL_FUNCTION_BODY>}
/**
* Called on the event dispatching thread once the construct method has finished its task.
*/
public void finished() {
}
/**
* Inner class that holds the reference to the thread.
*/
private static class ThreadWrapper {
private Thread thread;
ThreadWrapper(Thread t) {
thread = t;
}
synchronized Thread get() {
return thread;
}
synchronized void clear() {
thread = null;
}
}
}
|
Thread t = thread.get();
if (t != null) {
t.interrupt();
}
thread.clear();
| 431
| 38
| 469
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/model/IndirectObjectFactory.java
|
IndirectObjectFactory
|
store
|
class IndirectObjectFactory {
/**
* The reader object.
*/
protected PdfReader reader;
/**
* The current xref number.
*/
protected int current;
/**
* The highest xref number.
*/
protected int n;
/**
* A list of all the indirect objects in a PDF file.
*/
protected ArrayList<PdfObject> objects = new ArrayList<>();
/**
* Mapping between the index in the objects list and the reference number in the xref table.
*/
protected IntHashtable idxToRef = new IntHashtable();
/**
* Mapping between the reference number in the xref table and the index in the objects list .
*/
protected IntHashtable refToIdx = new IntHashtable();
/**
* Creates a list that will contain all the indirect objects in a PDF document.
*
* @param reader the reader that will read the PDF document
*/
public IndirectObjectFactory(PdfReader reader) {
this.reader = reader;
current = -1;
n = reader.getXrefSize();
}
/**
* Gets the last object that has been registered. This method only makes sense while loading the factory. with
* loadNextObject().
*
* @return the number of the last object that was stored
*/
public int getCurrent() {
return current;
}
/**
* Gets the highest possible object number in the XRef table.
*
* @return an object number
*/
public int getXRefMaximum() {
return n;
}
/**
* Stores the next object of the XRef table. As soon as this method returns false, it makes no longer sense calling
* it as all the objects have been stored.
*
* @return false if there are no objects left to check.
*/
public boolean storeNextObject() {
while (current < n) {
current++;
PdfObject object = reader.getPdfObjectRelease(current);
if (object != null) {
int idx = size();
idxToRef.put(idx, current);
refToIdx.put(current, idx);
store(object);
return true;
}
}
return false;
}
/**
* If we store all the objects, we might run out of memory; that's why we'll only store the objects that are
* necessary to construct other objects (for instance the page table).
*
* @param object an object we might want to store
*/
private void store(PdfObject object) {<FILL_FUNCTION_BODY>}
/**
* Gets the total number of indirect objects in the PDF file. This isn't necessarily the same number as returned by
* getXRefMaximum(). The PDF specification allows gaps between object numbers.
*
* @return the total number of indirect objects in the PDF.
*/
public int size() {
return objects.size();
}
/**
* Gets the index of an object based on its number in the xref table.
*
* @param ref a number in the xref table
* @return the index in the list of indirect objects
*/
public int getIndexByRef(int ref) {
return refToIdx.get(ref);
}
/**
* Gets the reference number in the xref table based on the index in the indirect object list.
*
* @param i the index of an object in the indirect object list
* @return the corresponding reference number in the xref table
*/
public int getRefByIndex(int i) {
return idxToRef.get(i);
}
/**
* Gets an object based on its index in the indirect object list.
*
* @param i an index in the indirect object list
* @return a PDF object
*/
public PdfObject getObjectByIndex(int i) {
return getObjectByReference(getRefByIndex(i));
}
/**
* Gets an object based on its reference number in the xref table.
*
* @param ref a number in the xref table
* @return a PDF object
*/
public PdfObject getObjectByReference(int ref) {
return objects.get(getIndexByRef(ref));
}
/**
* Loads an object based on its reference number in the xref table.
*
* @param ref a reference number in the xref table.
* @return a PDF object
*/
public PdfObject loadObjectByReference(int ref) {
PdfObject object = getObjectByReference(ref);
if (object instanceof PdfNull) {
int idx = getIndexByRef(ref);
object = reader.getPdfObject(ref);
objects.set(idx, object);
}
return object;
}
}
|
if (object.isDictionary()) {
PdfDictionary dict = (PdfDictionary) object;
if (PdfName.PAGE.equals(dict.get(PdfName.TYPE))) {
objects.add(dict);
return;
}
}
objects.add(PdfNull.PDFNULL);
| 1,227
| 82
| 1,309
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/model/ObjectLoader.java
|
ObjectLoader
|
doTask
|
class ObjectLoader extends BackgroundTask {
/**
* This is the object that will forward the updates to the observers.
*/
protected Observable observable;
/**
* iText's PdfReader object.
*/
protected PdfReader reader;
/**
* The factory that can provide PDF objects.
*/
protected IndirectObjectFactory objects;
/**
* The factory that can provide tree nodes.
*/
protected TreeNodeFactory nodes;
/**
* Creates a new ObjectLoader.
*
* @param observable the object that will forward the changes.
* @param reader the PdfReader from which the objects will be read.
*/
public ObjectLoader(Observable observable, PdfReader reader) {
this.observable = observable;
this.reader = reader;
start();
}
/**
* Getter for the PdfReader object.
*
* @return a reader object
*/
public PdfReader getReader() {
return reader;
}
/**
* Getter for the object factory.
*
* @return an indirect object factory
*/
public IndirectObjectFactory getObjects() {
return objects;
}
/**
* Getter for the tree node factory.
*
* @return a tree node factory
*/
public TreeNodeFactory getNodes() {
return nodes;
}
/**
* @see com.lowagie.rups.model.BackgroundTask#doTask()
*/
@Override
public void doTask() {<FILL_FUNCTION_BODY>}
}
|
ProgressDialog progress = new ProgressDialog(null, "Reading PDF file");
objects = new IndirectObjectFactory(reader);
int n = objects.getXRefMaximum();
progress.setMessage("Reading the Cross-Reference table");
progress.setTotal(n);
while (objects.storeNextObject()) {
progress.setValue(objects.getCurrent());
}
progress.setTotal(0);
nodes = new TreeNodeFactory(objects);
progress.setMessage("Updating GUI");
observable.notifyObservers(this);
progress.dispose();
| 409
| 143
| 552
|
<methods>public void <init>() ,public abstract void doTask() ,public void finished() ,public void interrupt() ,public void start() <variables>private com.lowagie.rups.model.BackgroundTask.ThreadWrapper thread
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/model/PageLoader.java
|
PageLoader
|
loadPage
|
class PageLoader extends BackgroundTask {
/**
* The PDFFile (SUN's PDF Renderer class)
*/
protected PDFFile file;
/**
* The total number of pages.
*/
protected int numberOfPages;
/**
* True for pages with page number equal to index + 1 that are being loaded.
*/
protected boolean[] busy;
/**
* True for pages with page number equal to index + 1 that have already been loaded.
*/
protected boolean[] done;
/**
* Creates a new page loader.
*
* @param file the PDFFile (SUN's PDF Renderer)
*/
public PageLoader(PDFFile file) {
super();
this.file = file;
numberOfPages = file.getNumPages();
busy = new boolean[numberOfPages];
done = new boolean[numberOfPages];
start();
}
/**
* Getter for the number of pages.
*
* @return the number of pages in the PDF file.
*/
public int getNumberOfPages() {
return numberOfPages;
}
/**
* Loads a page.
*
* @param pageNumber the number of the page that has to be loaded.
* @return the PDFPage that has been loaded.
*/
public synchronized PDFPage loadPage(int pageNumber) {<FILL_FUNCTION_BODY>}
/**
* @see com.lowagie.rups.model.BackgroundTask#doTask()
*/
@Override
public void doTask() {
for (int i = 0; i < numberOfPages; i++) {
loadPage(i + 1);
}
}
}
|
pageNumber--;
if (busy[pageNumber]) {
return null;
}
busy[pageNumber] = true;
PDFPage page = file.getPage(pageNumber + 1, true);
if (!done[pageNumber]) {
System.out.println("Loading page " + (pageNumber + 1));
}
done[pageNumber] = true;
busy[pageNumber] = false;
return page;
| 446
| 112
| 558
|
<methods>public void <init>() ,public abstract void doTask() ,public void finished() ,public void interrupt() ,public void start() <variables>private com.lowagie.rups.model.BackgroundTask.ThreadWrapper thread
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/model/PdfFile.java
|
PdfFile
|
readFile
|
class PdfFile {
// member variables
/**
* The directory where the file can be found (if the PDF was passed as a file).
*/
protected File directory = null;
/**
* The original filename.
*/
protected String filename = null;
/**
* The PdfReader object.
*/
protected PdfReader reader = null;
/**
* The file permissions
*/
protected Permissions permissions = null;
// constructors
/**
* Constructs a PdfFile object.
*
* @param file the File to read
* @throws IOException thrown when an I/O operation fails
* @throws DocumentException thrown when an error occurs with the Document
*/
public PdfFile(File file) throws IOException, DocumentException {
if (file == null) {
throw new IOException("No file selected.");
}
RandomAccessFileOrArray pdf = new RandomAccessFileOrArray(file.getAbsolutePath());
directory = file.getParentFile();
filename = file.getName();
readFile(pdf);
}
/**
* Constructs a PdfFile object.
*
* @param file the byte[] to read
* @throws IOException thrown when an I/O operation fails
* @throws DocumentException thrown when an error occurs with the Document
*/
public PdfFile(byte[] file) throws IOException, DocumentException {
RandomAccessFileOrArray pdf = new RandomAccessFileOrArray(file);
readFile(pdf);
}
/**
* Does the actual reading of the file into PdfReader and PDFFile.
*
* @param pdf a Random Access File or Array
* @throws IOException thrown when an I/O operation goes wrong
* @throws DocumentException thrown when something goes wrong with a Document
*/
protected void readFile(RandomAccessFileOrArray pdf) throws IOException, DocumentException {<FILL_FUNCTION_BODY>}
/**
* Getter for iText's PdfReader object.
*
* @return a PdfReader object
*/
public PdfReader getPdfReader() {
return reader;
}
}
|
// reading the file into PdfReader
permissions = new Permissions();
try {
reader = new PdfReader(pdf, null);
permissions.setEncrypted(false);
} catch (BadPasswordException bpe) {
JPasswordField passwordField = new JPasswordField(32);
JOptionPane.showConfirmDialog(null, passwordField, "Enter the User or Owner Password of this PDF file",
JOptionPane.OK_CANCEL_OPTION);
byte[] password = new String(passwordField.getPassword()).getBytes();
reader = new PdfReader(pdf, password);
permissions.setEncrypted(true);
permissions.setCryptoMode(reader.getCryptoMode());
permissions.setPermissions(reader.getPermissions());
if (reader.isOpenedWithFullPermissions()) {
permissions.setOwnerPassword(password);
permissions.setUserPassword(reader.computeUserPassword());
} else {
throw new IOException("You need the owner password of this file to open it in iText Trapeze.");
}
}
| 543
| 269
| 812
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/model/ProgressDialog.java
|
ProgressDialog
|
setTotal
|
class ProgressDialog extends JDialog {
/**
* the icon used for this dialog box.
*/
public static final JLabel INFO = new JLabel(UIManager.getIcon("OptionPane.informationIcon"));
/**
* a serial version uid.
*/
private static final long serialVersionUID = -8286949678008659120L;
/**
* label showing the message describing what's in progress.
*/
protected JLabel message;
/**
* the progress bar
*/
protected JProgressBar progress;
/**
* Creates a Progress frame displaying a certain message and a progress bar in indeterminate mode.
*
* @param parent the parent frame of this dialog (used to position the dialog)
* @param msg the message that will be displayed.
*/
public ProgressDialog(JFrame parent, String msg) {
super();
this.setTitle("Progress...");
setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
setSize(300, 100);
this.setLocationRelativeTo(parent);
setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridheight = 2;
getContentPane().add(INFO, constraints);
constraints.gridheight = 1;
constraints.gridx = 1;
constraints.insets = new Insets(5, 5, 5, 5);
message = new JLabel(msg);
getContentPane().add(message, constraints);
constraints.gridy = 1;
progress = new JProgressBar();
progress.setIndeterminate(true);
getContentPane().add(progress, constraints);
setVisible(true);
}
/**
* Changes the message describing what's in progress
*
* @param msg the message describing what's in progress
*/
public void setMessage(String msg) {
message.setText(msg);
}
/**
* Changes the value of the progress bar.
*
* @param value the current value
*/
public void setValue(int value) {
progress.setValue(value);
}
/**
* Sets the maximum value for the progress bar. If 0 or less, sets the progress bar to indeterminate mode.
*
* @param n the maximum value for the progress bar
*/
public void setTotal(int n) {<FILL_FUNCTION_BODY>}
}
|
if (n > 0) {
progress.setMaximum(n);
progress.setIndeterminate(false);
progress.setStringPainted(true);
} else {
progress.setIndeterminate(true);
progress.setStringPainted(false);
}
| 659
| 74
| 733
|
<methods>public void <init>() ,public void <init>(java.awt.Frame) ,public void <init>(java.awt.Dialog) ,public void <init>(java.awt.Window) ,public void <init>(java.awt.Frame, boolean) ,public void <init>(java.awt.Frame, java.lang.String) ,public void <init>(java.awt.Dialog, boolean) ,public void <init>(java.awt.Dialog, java.lang.String) ,public void <init>(java.awt.Window, java.awt.Dialog.ModalityType) ,public void <init>(java.awt.Window, java.lang.String) ,public void <init>(java.awt.Frame, java.lang.String, boolean) ,public void <init>(java.awt.Dialog, java.lang.String, boolean) ,public void <init>(java.awt.Window, java.lang.String, java.awt.Dialog.ModalityType) ,public void <init>(java.awt.Frame, java.lang.String, boolean, java.awt.GraphicsConfiguration) ,public void <init>(java.awt.Dialog, java.lang.String, boolean, java.awt.GraphicsConfiguration) ,public void <init>(java.awt.Window, java.lang.String, java.awt.Dialog.ModalityType, java.awt.GraphicsConfiguration) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public java.awt.Container getContentPane() ,public int getDefaultCloseOperation() ,public java.awt.Component getGlassPane() ,public java.awt.Graphics getGraphics() ,public javax.swing.JMenuBar getJMenuBar() ,public javax.swing.JLayeredPane getLayeredPane() ,public javax.swing.JRootPane getRootPane() ,public javax.swing.TransferHandler getTransferHandler() ,public static boolean isDefaultLookAndFeelDecorated() ,public void remove(java.awt.Component) ,public void repaint(long, int, int, int, int) ,public void setContentPane(java.awt.Container) ,public void setDefaultCloseOperation(int) ,public static void setDefaultLookAndFeelDecorated(boolean) ,public void setGlassPane(java.awt.Component) ,public void setJMenuBar(javax.swing.JMenuBar) ,public void setLayeredPane(javax.swing.JLayeredPane) ,public void setLayout(java.awt.LayoutManager) ,public void setTransferHandler(javax.swing.TransferHandler) ,public void update(java.awt.Graphics) <variables>protected javax.accessibility.AccessibleContext accessibleContext,private int defaultCloseOperation,private static final java.lang.Object defaultLookAndFeelDecoratedKey,protected javax.swing.JRootPane rootPane,protected boolean rootPaneCheckingEnabled,private javax.swing.TransferHandler transferHandler
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/model/TreeNodeFactory.java
|
TreeNodeFactory
|
expandNode
|
class TreeNodeFactory {
/**
* The factory that can produce all indirect objects.
*/
protected IndirectObjectFactory objects;
/**
* An list containing the nodes of every indirect object.
*/
protected ArrayList<PdfObjectTreeNode> nodes = new ArrayList<>();
/**
* Creates a factory that can produce TreeNode objects corresponding with PDF objects.
*
* @param objects a factory that can produce all the indirect objects of a PDF file.
*/
public TreeNodeFactory(IndirectObjectFactory objects) {
this.objects = objects;
for (int i = 0; i < objects.size(); i++) {
int ref = objects.getRefByIndex(i);
nodes.add(PdfObjectTreeNode.getInstance(PdfNull.PDFNULL, ref));
}
}
/**
* Gets a TreeNode for an indirect objects.
*
* @param ref the reference number of the indirect object.
* @return the TreeNode representing the PDF object
*/
public PdfObjectTreeNode getNode(int ref) {
int idx = objects.getIndexByRef(ref);
PdfObjectTreeNode node = nodes.get(idx);
if (node.getPdfObject().isNull()) {
node = PdfObjectTreeNode.getInstance(objects.loadObjectByReference(ref), ref);
nodes.set(idx, node);
}
return node;
}
/**
* Creates the Child TreeNode objects for a PDF object TreeNode.
*
* @param node the parent node
*/
public void expandNode(PdfObjectTreeNode node) {<FILL_FUNCTION_BODY>}
/**
* Finds a specific child of dictionary node.
*
* @param node the node with a dictionary among its children
* @param key the key of the item corresponding with the node we need
* @return the PdfObjectTreeNode that is the child of the dictionary node
*/
public PdfObjectTreeNode getChildNode(PdfObjectTreeNode node, PdfName key) {
Enumeration children = node.breadthFirstEnumeration();
PdfObjectTreeNode child;
while (children.hasMoreElements()) {
child = (PdfObjectTreeNode) children.nextElement();
if (child.isDictionaryNode(key)) {
if (child.isIndirectReference()) {
expandNode(child);
child = (PdfObjectTreeNode) child.getFirstChild();
}
expandNode(child);
return child;
}
}
return null;
}
/**
* Tries adding a child node to a parent node without throwing an exception. Normally, if the child node is already
* added as one of the ancestors, an IllegalArgumentException is thrown (to avoid an endless loop). Loops like this
* are allowed in PDF, not in a JTree.
*
* @param parent the parent node
* @param child a child node
*/
private void addNodes(PdfObjectTreeNode parent, PdfObjectTreeNode child) {
try {
parent.add(child);
} catch (IllegalArgumentException iae) {
parent.setRecursive(true);
}
}
}
|
if (node.getChildCount() > 0) {
return;
}
PdfObject object = node.getPdfObject();
PdfObjectTreeNode leaf;
switch (object.type()) {
case PdfObject.INDIRECT:
PdfIndirectReference ref = (PdfIndirectReference) object;
leaf = getNode(ref.getNumber());
addNodes(node, leaf);
if (leaf instanceof PdfPagesTreeNode) {
expandNode(leaf);
}
return;
case PdfObject.ARRAY:
PdfArray array = (PdfArray) object;
for (PdfObject pdfObject : array.getElements()) {
leaf = PdfObjectTreeNode.getInstance(pdfObject);
addNodes(node, leaf);
expandNode(leaf);
}
return;
case PdfObject.DICTIONARY:
case PdfObject.STREAM:
PdfDictionary dict = (PdfDictionary) object;
for (PdfName pdfName : dict.getKeys()) {
leaf = PdfObjectTreeNode.getInstance(dict, pdfName);
addNodes(node, leaf);
expandNode(leaf);
}
return;
}
| 806
| 306
| 1,112
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.