Browse Source

Merge pull request #4 in ~NEIL/base-third from feature/10.0 to release/10.0

* commit '9f7b4b9fb5f5aced05af953a45f74a8cdd1e871e':
  REPORT-13005 sub标签设置color属性,实际导出没有效果
  REPORT-11969 注册增强 1. 修改 el 后缀, 通用 win/linux
  REPORT-11969 注册增强
  删除无用代码
  删除无用代码
  REPORT-11624 Excel和Word导出的html解析(third部分)
  CORE-135 插件禁用再启用后Jackson实例化的java对象仍然用的插件卸载前的classLoader
  fix
  fix
  fix
  fix
  MOBILE-17909&MOBILE-17908 10.0微信》定时调度有微信任务时卸载微信插件,报错
  无JIRA任务,third打包分支错误.
  无
  REPORT-11624 Excel和Word导出的html解析支持
final/10.0.3
neil 6 years ago
parent
commit
d731b2ab8d
  1. 4
      build.third_step0.gradle
  2. 2
      build.third_step1.gradle
  3. 11
      build.third_step2.gradle
  4. 2
      build.third_step3.gradle
  5. 2
      build.third_step4.gradle
  6. 2
      build.third_step5.gradle
  7. 2
      build.third_step6.gradle
  8. 44
      fine-itext-old/src/com/fr/third/com/lowagie/text/Chunk.java
  9. 160
      fine-itext-old/src/com/fr/third/com/lowagie/text/Font.java
  10. 409
      fine-itext-old/src/com/fr/third/com/lowagie/text/Image.java
  11. 323
      fine-itext-old/src/com/fr/third/com/lowagie/text/List.java
  12. 44
      fine-itext-old/src/com/fr/third/com/lowagie/text/Paragraph.java
  13. 2
      fine-itext-old/src/com/fr/third/com/lowagie/text/factories/ElementFactory.java
  14. 200
      fine-itext-old/src/com/fr/third/com/lowagie/text/html/CSS.java
  15. 105
      fine-itext-old/src/com/fr/third/com/lowagie/text/html/CSSUtils.java
  16. 55
      fine-itext-old/src/com/fr/third/com/lowagie/text/html/IndentAttribute.java
  17. 125
      fine-itext-old/src/com/fr/third/com/lowagie/text/html/Markup.java
  18. 84
      fine-itext-old/src/com/fr/third/com/lowagie/text/html/ParseIndentAttrUtils.java
  19. 4
      fine-itext-old/src/com/fr/third/com/lowagie/text/html/WebColors.java
  20. 67
      fine-itext-old/src/com/fr/third/com/lowagie/text/html/simpleparser/ChainedProperties.java
  21. 82
      fine-itext-old/src/com/fr/third/com/lowagie/text/html/simpleparser/FactoryProperties.java
  22. 87
      fine-itext-old/src/com/fr/third/com/lowagie/text/html/simpleparser/HTMLWorker.java
  23. 45
      fine-itext-old/src/com/fr/third/com/lowagie/text/html/simpleparser/HtmlConstants.java
  24. 76
      fine-itext-old/src/com/fr/third/com/lowagie/text/html/simpleparser/IncCell.java
  25. 100
      fine-itext-old/src/com/fr/third/com/lowagie/text/html/simpleparser/IncTable.java
  26. 58
      fine-itext-old/src/com/fr/third/com/lowagie/text/pdf/BorderStyle.java
  27. 269
      fine-itext-old/src/com/fr/third/com/lowagie/text/pdf/PdfPCell.java
  28. 432
      fine-itext-old/src/com/fr/third/com/lowagie/text/pdf/PdfPRow.java
  29. 642
      fine-itext-old/src/com/fr/third/com/lowagie/text/pdf/PdfPTable.java
  30. 54
      fine-itext-old/src/com/fr/third/com/lowagie/text/pdf/TableProperties.java
  31. 4
      fine-itext-old/src/com/fr/third/com/lowagie/text/rtf/text/RtfChunk.java
  32. 9
      fine-itext/src/com/fr/third/v2/lowagie/text/html/simpleparser/HTMLWorker.java
  33. BIN
      fine-sense4/lib/jna-3.2.2.jar
  34. 63
      fine-sense4/src/Sense4/Elite4.java
  35. 20
      fine-sense4/src/Sense4/EliteLockIO.java
  36. 277
      fine-sense4/src/Sense4/EliteLockIO32.java
  37. 274
      fine-sense4/src/Sense4/EliteLockIO64.java
  38. 65
      fine-sense4/src/Sense4/LockUtils.java
  39. 218
      fine-sense4/src/Sense4/Sense32.java
  40. 219
      fine-sense4/src/Sense4/Sense64.java
  41. 690
      fine-sense4/src/Sense4/sense4.h

4
build.third_step0.gradle

@ -40,7 +40,7 @@ def buildDir=files[0].path.substring(0,files[0].path.lastIndexOf (java.io.File.s
def branchName=buildDir.substring(buildDir.lastIndexOf (java.io.File.separator)+1)
def srcDir="."
def maven_version="${version}-RELEASE-SNAPSHOT"
def maven_version="${version}-FEATURE-SNAPSHOT"
def jar_version = version
configurations {
@ -49,7 +49,7 @@ configurations {
}
dependencies {
thirdjar "com.fr.third:fine-third:10.0-RELEASE-SNAPSHOT"
thirdjar "com.fr.third:fine-third:10.0-FEATURE-SNAPSHOT"
sigar "com.fr.third:sigar:1.6.0"
testCompile 'junit:junit:4.12'
}

2
build.third_step1.gradle

@ -56,7 +56,7 @@ dependencies{
compile fileTree(dir:"${srcDir}/fine-poi/lib",include:'**/*.jar')
compile fileTree(dir:"${srcDir}/fine-quartz/lib",include:'**/*.jar')
compile fileTree(dir:"${srcDir}/build/libs/",include:'**/*.jar')
compile "com.fr.third:fine-third:10.0-RELEASE-SNAPSHOT"
compile "com.fr.third:fine-third:10.0-FEATURE-SNAPSHOT"
compile fileTree(dir:"../../finereport-lib-other/${branchName}",include:'**/*.jar')
testCompile 'junit:junit:4.12'
}

11
build.third_step2.gradle

@ -18,12 +18,13 @@ def srcDir="."
//
sourceSets{
main{
java{
srcDirs=[
java {
srcDirs = [
"${srcDir}/fine-aspectj/src",
"${srcDir}/fine-spring/src",
"${srcDir}/fine-sense4/src",
"${srcDir}/fine-spring/resources"
]
]
}
}
@ -44,8 +45,9 @@ def branchName=buildDir.substring(buildDir.lastIndexOf (java.io.File.separator)+
dependencies{
compile fileTree(dir:"${srcDir}/fine-aspectj/lib",include:'**/*.jar')
compile fileTree(dir:"${srcDir}/fine-spring/lib",include:'**/*.jar')
compile fileTree(dir:"${srcDir}/fine-sense4/lib",include:'**/*.jar')
compile fileTree(dir:"${srcDir}/build/libs/",include:'**/*.jar')
compile "com.fr.third:fine-third:10.0-RELEASE-SNAPSHOT"
compile "com.fr.third:fine-third:10.0-FEATURE-SNAPSHOT"
compile fileTree(dir:"../../finereport-lib-other/${branchName}",include:'**/*.jar')
testCompile 'junit:junit:4.12'
}
@ -67,6 +69,7 @@ task copyFiles(type:Copy,dependsOn:'compileJava'){
println "------------------------------------------------copyfiles"
with dataContent.call("${srcDir}/fine-spring/src")
with dataContent.call("${srcDir}/fine-spring/resources")
with dataContent.call("${srcDir}/fine-sense4/src")
into "${classesDir}"
}
}

2
build.third_step3.gradle

@ -46,7 +46,7 @@ def branchName=buildDir.substring(buildDir.lastIndexOf (java.io.File.separator)+
dependencies{
compile fileTree(dir:"${srcDir}/fine-jboss-logging/lib",include:'**/*.jar')
compile fileTree(dir:"${srcDir}/build/libs/",include:'**/*.jar')
compile "com.fr.third:fine-third:10.0-RELEASE-SNAPSHOT"
compile "com.fr.third:fine-third:10.0-FEATURE-SNAPSHOT"
compile fileTree(dir:"../../finereport-lib-other/${branchName}",include:'**/*.jar')
testCompile 'junit:junit:4.12'
}

2
build.third_step4.gradle

@ -45,7 +45,7 @@ def branchName=buildDir.substring(buildDir.lastIndexOf (java.io.File.separator)+
dependencies{
compile fileTree(dir:"${srcDir}/fine-hibernate/lib",include:'**/*.jar')
compile fileTree(dir:"${srcDir}/build/libs/",include:'**/*.jar')
compile "com.fr.third:fine-third:10.0-RELEASE-SNAPSHOT"
compile "com.fr.third:fine-third:10.0-FEATURE-SNAPSHOT"
compile fileTree(dir:"../../finereport-lib-other/${branchName}",include:'**/*.jar')
testCompile 'junit:junit:4.12'
}

2
build.third_step5.gradle

@ -44,7 +44,7 @@ dependencies{
compile fileTree(dir:"${srcDir}/fine-druid/lib",include:'ojdbc7-12.1.0.jar')
compile fileTree(dir:"${srcDir}/fine-druid/lib",include:'**/*.jar')
compile fileTree(dir:"${srcDir}/build/libs/",include:'**/*.jar')
compile "com.fr.third:fine-third:10.0-RELEASE-SNAPSHOT"
compile "com.fr.third:fine-third:10.0-FEATURE-SNAPSHOT"
compile fileTree(dir:"../../finereport-lib-other/${branchName}",include:'**/*.jar')
testCompile 'junit:junit:4.12'
}

2
build.third_step6.gradle

@ -72,7 +72,7 @@ dependencies{
compile fileTree(dir:"${srcDir}/fine-redisson/lib",include:'**/*.jar')
compile fileTree(dir:"${srcDir}/fine-socketio/lib",include:'**/*.jar')
compile fileTree(dir:"${srcDir}/build/libs/",include:'**/*.jar')
compile "com.fr.third:fine-third:10.0-RELEASE-SNAPSHOT"
compile "com.fr.third:fine-third:10.0-FEATURE-SNAPSHOT"
compile fileTree(dir:"../../finereport-lib-other/${branchName}",include:'**/*.jar')
testCompile 'junit:junit:4.12'
}

44
fine-itext-old/src/com/fr/third/com/lowagie/text/Chunk.java

@ -49,16 +49,18 @@
package com.fr.third.com.lowagie.text;
import java.awt.Color;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import com.fr.third.com.lowagie.text.pdf.HyphenationEvent;
import com.fr.third.com.lowagie.text.pdf.PdfAction;
import com.fr.third.com.lowagie.text.pdf.PdfAnnotation;
import com.fr.third.com.lowagie.text.pdf.PdfContentByte;
import com.fr.third.com.lowagie.text.pdf.draw.DrawInterface;
import sun.font.FontDesignMetrics;
import java.awt.Color;
import java.awt.FontMetrics;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
/**
* This is the smallest significant part of text that can be added to a
@ -277,7 +279,7 @@ public class Chunk implements Element {
* true if the leading has to be adapted to the image
*/
public Chunk(Image image, float offsetX, float offsetY,
boolean changeLeading) {
boolean changeLeading) {
this(OBJECT_REPLACEMENT_CHARACTER, new Font());
setAttribute(IMAGE, new Object[] { image, new Float(offsetX),
new Float(offsetY), Boolean.valueOf(changeLeading) });
@ -394,9 +396,9 @@ public class Chunk implements Element {
if (getImage() != null) {
return getImage().getScaledWidth();
}
return font.getCalculatedBaseFont(true).getWidthPoint(getContent(),
font.getCalculatedSize())
* getHorizontalScaling();
java.awt.Font awtFont = new java.awt.Font(font.getFontName(), font.getStyle(), (int)font.getSize());
FontMetrics metrics = FontDesignMetrics.getMetrics(awtFont);
return metrics.stringWidth(getContent())* getHorizontalScaling();
}
// attributes
@ -441,7 +443,7 @@ public class Chunk implements Element {
* @return this <CODE>Chunk</CODE>
*/
private Chunk setAttribute(String name, Object obj) {
public Chunk setAttribute(String name, Object obj) {
if (attributes == null)
attributes = new HashMap();
attributes.put(name, obj);
@ -523,7 +525,7 @@ public class Chunk implements Element {
* @return this <CODE>Chunk</CODE>
*/
public Chunk setUnderline(Color color, float thickness, float thicknessMul,
float yPosition, float yPositionMul, int cap) {
float yPosition, float yPositionMul, int cap) {
if (attributes == null)
attributes = new HashMap();
Object obj[] = {
@ -590,18 +592,18 @@ public class Chunk implements Element {
/**
* Sets the color of the background <CODE>Chunk</CODE>.
*
* @param color
* @param background
* the color of the background
* @return this <CODE>Chunk</CODE>
*/
public Chunk setBackground(Color color) {
return setBackground(color, 0, 0, 0, 0);
public Chunk setBackground(String background) {
return setBackground(background, 0, 0, 0, 0);
}
/**
* Sets the color and the size of the background <CODE>Chunk</CODE>.
*
* @param color
* @param background
* the color of the background
* @param extraLeft
* increase the size of the rectangle in the left
@ -613,9 +615,9 @@ public class Chunk implements Element {
* increase the size of the rectangle in the top
* @return this <CODE>Chunk</CODE>
*/
public Chunk setBackground(Color color, float extraLeft, float extraBottom,
float extraRight, float extraTop) {
return setAttribute(BACKGROUND, new Object[] { color,
public Chunk setBackground(String background, float extraLeft, float extraBottom,
float extraRight, float extraTop) {
return setAttribute(BACKGROUND, new Object[] { background,
new float[] { extraLeft, extraBottom, extraRight, extraTop } });
}
@ -642,7 +644,7 @@ public class Chunk implements Element {
* @return this <CODE>Chunk</CODE>
*/
public Chunk setTextRenderMode(int mode, float strokeWidth,
Color strokeColor) {
Color strokeColor) {
return setAttribute(TEXTRENDERMODE, new Object[] { new Integer(mode),
new Float(strokeWidth), strokeColor });
}
@ -843,7 +845,7 @@ public class Chunk implements Element {
}
/**
* @see com.fr.third.com.lowagie.text.Element#isContent()
* @see Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
@ -851,7 +853,7 @@ public class Chunk implements Element {
}
/**
* @see com.fr.third.com.lowagie.text.Element#isNestable()
* @see Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {

160
fine-itext-old/src/com/fr/third/com/lowagie/text/Font.java

@ -133,6 +133,14 @@ public class Font implements Comparable {
/** the external font */
private BaseFont baseFont = null;
private String fontName = "";
public String getFontName(){
return fontName;
}
// constructors
/**
@ -169,6 +177,13 @@ public class Font implements Comparable {
this.color = color;
}
public Font(String face, float size, int style, Color color) {
this.fontName = face;
this.size =size;
this.style = style;
this.color = color;
}
/**
* Constructs a Font.
*
@ -335,35 +350,7 @@ public class Font implements Comparable {
* @return the familyname
*/
public String getFamilyname() {
String tmp = "unknown";
switch (getFamily()) {
case Font.COURIER:
return FontFactory.COURIER;
case Font.HELVETICA:
return FontFactory.HELVETICA;
case Font.TIMES_ROMAN:
return FontFactory.TIMES_ROMAN;
case Font.SYMBOL:
return FontFactory.SYMBOL;
case Font.ZAPFDINGBATS:
return FontFactory.ZAPFDINGBATS;
default:
if (baseFont != null) {
String[][] names = baseFont.getFamilyFontName();
for (int i = 0; i < names.length; i++) {
if ("0".equals(names[i][2])) {
return names[i][3];
}
if ("1033".equals(names[i][2])) {
tmp = names[i][3];
}
if ("".equals(names[i][2])) {
tmp = names[i][3];
}
}
}
}
return tmp;
return getFontName();
}
/**
@ -374,9 +361,10 @@ public class Font implements Comparable {
* A <CODE>String</CODE> representing a certain font-family.
*/
public void setFamily(String family) {
this.family = getFamilyIndex(family);
this.fontName = family;
}
/**
* Translates a <CODE>String</CODE> -value of a certain family into the
* index that is used for this family in this class.
@ -652,68 +640,68 @@ public class Font implements Comparable {
String encoding = BaseFont.WINANSI;
BaseFont cfont = null;
switch (family) {
case COURIER:
switch (style & BOLDITALIC) {
case BOLD:
fontName = BaseFont.COURIER_BOLD;
break;
case ITALIC:
fontName = BaseFont.COURIER_OBLIQUE;
break;
case BOLDITALIC:
fontName = BaseFont.COURIER_BOLDOBLIQUE;
break;
default:
//case NORMAL:
fontName = BaseFont.COURIER;
break;
}
break;
case TIMES_ROMAN:
switch (style & BOLDITALIC) {
case BOLD:
fontName = BaseFont.TIMES_BOLD;
break;
case ITALIC:
fontName = BaseFont.TIMES_ITALIC;
break;
case BOLDITALIC:
fontName = BaseFont.TIMES_BOLDITALIC;
break;
default:
case NORMAL:
fontName = BaseFont.TIMES_ROMAN;
case COURIER:
switch (style & BOLDITALIC) {
case BOLD:
fontName = BaseFont.COURIER_BOLD;
break;
case ITALIC:
fontName = BaseFont.COURIER_OBLIQUE;
break;
case BOLDITALIC:
fontName = BaseFont.COURIER_BOLDOBLIQUE;
break;
default:
//case NORMAL:
fontName = BaseFont.COURIER;
break;
}
break;
}
break;
case SYMBOL:
fontName = BaseFont.SYMBOL;
if (specialEncoding)
encoding = BaseFont.SYMBOL;
break;
case ZAPFDINGBATS:
fontName = BaseFont.ZAPFDINGBATS;
if (specialEncoding)
encoding = BaseFont.ZAPFDINGBATS;
break;
default:
case Font.HELVETICA:
switch (style & BOLDITALIC) {
case BOLD:
fontName = BaseFont.HELVETICA_BOLD;
case TIMES_ROMAN:
switch (style & BOLDITALIC) {
case BOLD:
fontName = BaseFont.TIMES_BOLD;
break;
case ITALIC:
fontName = BaseFont.TIMES_ITALIC;
break;
case BOLDITALIC:
fontName = BaseFont.TIMES_BOLDITALIC;
break;
default:
case NORMAL:
fontName = BaseFont.TIMES_ROMAN;
break;
}
break;
case ITALIC:
fontName = BaseFont.HELVETICA_OBLIQUE;
case SYMBOL:
fontName = BaseFont.SYMBOL;
if (specialEncoding)
encoding = BaseFont.SYMBOL;
break;
case BOLDITALIC:
fontName = BaseFont.HELVETICA_BOLDOBLIQUE;
case ZAPFDINGBATS:
fontName = BaseFont.ZAPFDINGBATS;
if (specialEncoding)
encoding = BaseFont.ZAPFDINGBATS;
break;
default:
case NORMAL:
fontName = BaseFont.HELVETICA;
case Font.HELVETICA:
switch (style & BOLDITALIC) {
case BOLD:
fontName = BaseFont.HELVETICA_BOLD;
break;
case ITALIC:
fontName = BaseFont.HELVETICA_OBLIQUE;
break;
case BOLDITALIC:
fontName = BaseFont.HELVETICA_BOLDOBLIQUE;
break;
default:
case NORMAL:
fontName = BaseFont.HELVETICA;
break;
}
break;
}
break;
}
try {
cfont = BaseFont.createFont(fontName, encoding, false);

409
fine-itext-old/src/com/fr/third/com/lowagie/text/Image.java

@ -49,15 +49,6 @@
package com.fr.third.com.lowagie.text;
import java.awt.Graphics2D;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import com.fr.third.com.lowagie.text.pdf.PRIndirectReference;
import com.fr.third.com.lowagie.text.pdf.PdfArray;
import com.fr.third.com.lowagie.text.pdf.PdfContentByte;
@ -79,6 +70,15 @@ import com.fr.third.com.lowagie.text.pdf.codec.JBIG2Image;
import com.fr.third.com.lowagie.text.pdf.codec.PngImage;
import com.fr.third.com.lowagie.text.pdf.codec.TiffImage;
import java.awt.Graphics2D;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
/**
* An <CODE>Image</CODE> is the representation of a graphic element (JPEG, PNG
* or GIF) that has to be inserted into the document
@ -155,7 +155,7 @@ public abstract class Image extends Rectangle {
public static final int ORIGINAL_WMF = 6;
/** type of image */
public static final int ORIGINAL_PS = 7;
public static final int ORIGINAL_PS = 7;
/** type of image */
public static final int ORIGINAL_JPEG2000 = 8;
@ -166,7 +166,7 @@ public abstract class Image extends Rectangle {
*/
public static final int ORIGINAL_JBIG2 = 9;
// member variables
// member variables
/** The image type. */
protected int type;
@ -207,17 +207,27 @@ public abstract class Image extends Rectangle {
/** This is the original height of the image taking rotation into account. */
protected float scaledHeight;
/**
* The compression level of the content streams.
* @since 2.1.3
*/
protected int compressionLevel = PdfStream.DEFAULT_COMPRESSION;
/**
* The compression level of the content streams.
* @since 2.1.3
*/
protected int compressionLevel = PdfStream.DEFAULT_COMPRESSION;
/** an iText attributed unique id for this image. */
protected Long mySerialId = getSerialId();
// image from file or URL
private String srcString = "";
public String getSrcString() {
return srcString;
}
public void setSrcString(String srcString) {
this.srcString = srcString;
}
/**
* Constructs an <CODE>Image</CODE> -object, using an <VAR>url </VAR>.
*
@ -288,7 +298,7 @@ public abstract class Image extends Rectangle {
try {
if (url.getProtocol().equals("file")) {
String file = url.getFile();
file = Utilities.unEscapeURL(file);
file = Utilities.unEscapeURL(file);
ra = new RandomAccessFileOrArray(file);
} else
ra = new RandomAccessFileOrArray(url);
@ -308,20 +318,22 @@ public abstract class Image extends Rectangle {
if (url.getProtocol().equals("file")) {
String file = url.getFile();
file = Utilities.unEscapeURL(file);
ra = new RandomAccessFileOrArray(file);
ra = new RandomAccessFileOrArray(file);
} else
ra = new RandomAccessFileOrArray(url);
Image img = JBIG2Image.getJbig2Image(ra, 1);
img.url = url;
return img;
} finally {
if (ra != null)
ra.close();
if (ra != null)
ra.close();
}
}
throw new IOException(url.toString()
+ " is not a recognized imageformat.");
} finally {
}catch (Exception e){
return null;
}finally {
if (is != null) {
is.close();
}
@ -395,8 +407,8 @@ public abstract class Image extends Rectangle {
try {
ra = new RandomAccessFileOrArray(imgb);
Image img = TiffImage.getTiffImage(ra, 1);
if (img.getOriginalData() == null)
img.setOriginalData(imgb);
if (img.getOriginalData() == null)
img.setOriginalData(imgb);
return img;
} finally {
if (ra != null)
@ -461,7 +473,7 @@ public abstract class Image extends Rectangle {
* on error
*/
public static Image getInstance(int width, int height, int components,
int bpc, byte data[]) throws BadElementException {
int bpc, byte data[]) throws BadElementException {
return Image.getInstance(width, height, components, bpc, data, null);
}
@ -503,7 +515,7 @@ public abstract class Image extends Rectangle {
* on error
*/
public static Image getInstance(int width, int height, boolean reverseBits,
int typeCCITT, int parameters, byte[] data)
int typeCCITT, int parameters, byte[] data)
throws BadElementException {
return Image.getInstance(width, height, reverseBits, typeCCITT,
parameters, data, null);
@ -537,7 +549,7 @@ public abstract class Image extends Rectangle {
* on error
*/
public static Image getInstance(int width, int height, boolean reverseBits,
int typeCCITT, int parameters, byte[] data, int transparency[])
int typeCCITT, int parameters, byte[] data, int transparency[])
throws BadElementException {
if (transparency != null && transparency.length != 2)
throw new BadElementException(
@ -569,7 +581,7 @@ public abstract class Image extends Rectangle {
* on error
*/
public static Image getInstance(int width, int height, int components,
int bpc, byte data[], int transparency[])
int bpc, byte data[], int transparency[])
throws BadElementException {
if (transparency != null && transparency.length != components * 2)
throw new BadElementException(
@ -599,7 +611,7 @@ public abstract class Image extends Rectangle {
return new ImgTemplate(template);
}
// images from a java.awt.Image
// images from a java.awt.Image
/**
* Gets an instance of an Image from a java.awt.Image.
@ -618,7 +630,7 @@ public abstract class Image extends Rectangle {
* on error
*/
public static Image getInstance(java.awt.Image image, java.awt.Color color,
boolean forceBW) throws BadElementException, IOException {
boolean forceBW) throws BadElementException, IOException {
if(image instanceof BufferedImage){
BufferedImage bi = (BufferedImage) image;
@ -811,97 +823,97 @@ public abstract class Image extends Rectangle {
return getInstance(new PdfContentByte(writer), awtImage, quality);
}
/**
* Gets an instance of a Image from a java.awt.Image.
* The image is added as a JPEG with a user defined quality.
*
* @param cb
* the <CODE>PdfContentByte</CODE> object to which the image will be added
* @param awtImage
* the <CODE>java.awt.Image</CODE> to convert
* @param quality
* a float value between 0 and 1
* @return an object of type <CODE>PdfTemplate</CODE>
* @throws BadElementException
* on error
* @throws IOException
*/
public static Image getInstance(PdfContentByte cb, java.awt.Image awtImage, float quality) throws BadElementException, IOException {
java.awt.image.PixelGrabber pg = new java.awt.image.PixelGrabber(awtImage,
0, 0, -1, -1, true);
try {
pg.grabPixels();
} catch (InterruptedException e) {
throw new IOException(
"java.awt.Image Interrupted waiting for pixels!");
}
if ((pg.getStatus() & java.awt.image.ImageObserver.ABORT) != 0) {
throw new IOException("java.awt.Image fetch aborted or errored");
}
int w = pg.getWidth();
int h = pg.getHeight();
PdfTemplate tp = cb.createTemplate(w, h);
Graphics2D g2d = tp.createGraphics(w, h, true, quality);
g2d.drawImage(awtImage, 0, 0, null);
g2d.dispose();
return getInstance(tp);
}
// image from indirect reference
/**
* Holds value of property directReference.
* An image is embedded into a PDF as an Image XObject.
* This object is referenced by a PdfIndirectReference object.
*/
private PdfIndirectReference directReference;
/**
* Getter for property directReference.
* @return Value of property directReference.
*/
public PdfIndirectReference getDirectReference() {
return this.directReference;
}
/**
* Setter for property directReference.
* @param directReference New value of property directReference.
*/
public void setDirectReference(PdfIndirectReference directReference) {
this.directReference = directReference;
}
/**
* Reuses an existing image.
* @param ref the reference to the image dictionary
* @throws BadElementException on error
* @return the image
*/
public static Image getInstance(PRIndirectReference ref) throws BadElementException {
PdfDictionary dic = (PdfDictionary)PdfReader.getPdfObjectRelease(ref);
int width = ((PdfNumber)PdfReader.getPdfObjectRelease(dic.get(PdfName.WIDTH))).intValue();
int height = ((PdfNumber)PdfReader.getPdfObjectRelease(dic.get(PdfName.HEIGHT))).intValue();
Image imask = null;
PdfObject obj = dic.get(PdfName.SMASK);
if (obj != null && obj.isIndirect()) {
imask = getInstance((PRIndirectReference)obj);
}
else {
obj = dic.get(PdfName.MASK);
if (obj != null && obj.isIndirect()) {
PdfObject obj2 = PdfReader.getPdfObjectRelease(obj);
if (obj2 instanceof PdfDictionary)
imask = getInstance((PRIndirectReference)obj);
}
}
Image img = new ImgRaw(width, height, 1, 1, null);
img.imageMask = imask;
img.directReference = ref;
return img;
}
// copy constructor
/**
* Gets an instance of a Image from a java.awt.Image.
* The image is added as a JPEG with a user defined quality.
*
* @param cb
* the <CODE>PdfContentByte</CODE> object to which the image will be added
* @param awtImage
* the <CODE>java.awt.Image</CODE> to convert
* @param quality
* a float value between 0 and 1
* @return an object of type <CODE>PdfTemplate</CODE>
* @throws BadElementException
* on error
* @throws IOException
*/
public static Image getInstance(PdfContentByte cb, java.awt.Image awtImage, float quality) throws BadElementException, IOException {
java.awt.image.PixelGrabber pg = new java.awt.image.PixelGrabber(awtImage,
0, 0, -1, -1, true);
try {
pg.grabPixels();
} catch (InterruptedException e) {
throw new IOException(
"java.awt.Image Interrupted waiting for pixels!");
}
if ((pg.getStatus() & java.awt.image.ImageObserver.ABORT) != 0) {
throw new IOException("java.awt.Image fetch aborted or errored");
}
int w = pg.getWidth();
int h = pg.getHeight();
PdfTemplate tp = cb.createTemplate(w, h);
Graphics2D g2d = tp.createGraphics(w, h, true, quality);
g2d.drawImage(awtImage, 0, 0, null);
g2d.dispose();
return getInstance(tp);
}
// image from indirect reference
/**
* Holds value of property directReference.
* An image is embedded into a PDF as an Image XObject.
* This object is referenced by a PdfIndirectReference object.
*/
private PdfIndirectReference directReference;
/**
* Getter for property directReference.
* @return Value of property directReference.
*/
public PdfIndirectReference getDirectReference() {
return this.directReference;
}
/**
* Setter for property directReference.
* @param directReference New value of property directReference.
*/
public void setDirectReference(PdfIndirectReference directReference) {
this.directReference = directReference;
}
/**
* Reuses an existing image.
* @param ref the reference to the image dictionary
* @throws BadElementException on error
* @return the image
*/
public static Image getInstance(PRIndirectReference ref) throws BadElementException {
PdfDictionary dic = (PdfDictionary)PdfReader.getPdfObjectRelease(ref);
int width = ((PdfNumber)PdfReader.getPdfObjectRelease(dic.get(PdfName.WIDTH))).intValue();
int height = ((PdfNumber)PdfReader.getPdfObjectRelease(dic.get(PdfName.HEIGHT))).intValue();
Image imask = null;
PdfObject obj = dic.get(PdfName.SMASK);
if (obj != null && obj.isIndirect()) {
imask = getInstance((PRIndirectReference)obj);
}
else {
obj = dic.get(PdfName.MASK);
if (obj != null && obj.isIndirect()) {
PdfObject obj2 = PdfReader.getPdfObjectRelease(obj);
if (obj2 instanceof PdfDictionary)
imask = getInstance((PRIndirectReference)obj);
}
}
Image img = new ImgRaw(width, height, 1, 1, null);
img.imageMask = imask;
img.directReference = ref;
return img;
}
// copy constructor
/**
* Constructs an <CODE>Image</CODE> -object, using an <VAR>url </VAR>.
@ -913,6 +925,7 @@ public abstract class Image extends Rectangle {
super(image);
this.type = image.type;
this.url = image.url;
this.srcString = image.srcString;
this.rawData = image.rawData;
this.bpc = image.bpc;
this.template = image.template;
@ -926,12 +939,12 @@ public abstract class Image extends Rectangle {
this.scaledHeight = image.scaledHeight;
this.mySerialId = image.mySerialId;
this.directReference = image.directReference;
this.directReference = image.directReference;
this.rotationRadians = image.rotationRadians;
this.initialRotation = image.initialRotation;
this.indentationLeft = image.indentationLeft;
this.indentationRight = image.indentationRight;
this.initialRotation = image.initialRotation;
this.indentationLeft = image.indentationLeft;
this.indentationRight = image.indentationRight;
this.spacingBefore = image.spacingBefore;
this.spacingAfter = image.spacingAfter;
@ -989,7 +1002,7 @@ public abstract class Image extends Rectangle {
}
/**
* @see com.fr.third.com.lowagie.text.Element#isNestable()
* @see Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
@ -1310,7 +1323,7 @@ public abstract class Image extends Rectangle {
* the height to fit
*/
public void scaleToFit(float fitWidth, float fitHeight) {
scalePercent(100);
scalePercent(100);
float percentX = (fitWidth * 100) / getScaledWidth();
float percentY = (fitHeight * 100) / getScaledHeight();
scalePercent(percentX < percentY ? percentX : percentY);
@ -1374,26 +1387,26 @@ public abstract class Image extends Rectangle {
return mySerialId;
}
// rotation, note that the superclass also has a rotation value.
// rotation, note that the superclass also has a rotation value.
/** This is the rotation of the image in radians. */
protected float rotationRadians;
/** Holds value of property initialRotation. */
private float initialRotation;
/** Holds value of property initialRotation. */
private float initialRotation;
/**
* Gets the current image rotation in radians.
* @return the current image rotation in radians
*/
public float getImageRotation() {
/**
* Gets the current image rotation in radians.
* @return the current image rotation in radians
*/
public float getImageRotation() {
double d = 2.0 * Math.PI;
float rot = (float) ((rotationRadians - initialRotation) % d);
if (rot < 0) {
rot += d;
}
return rot;
}
return rot;
}
/**
* Sets the rotation of the image in radians.
@ -1423,26 +1436,26 @@ public abstract class Image extends Rectangle {
setRotation(deg / 180 * (float) d);
}
/**
* Getter for property initialRotation.
* @return Value of property initialRotation.
*/
public float getInitialRotation() {
return this.initialRotation;
}
/**
* Getter for property initialRotation.
* @return Value of property initialRotation.
*/
public float getInitialRotation() {
return this.initialRotation;
}
/**
* Some image formats, like TIFF may present the images rotated that have
* to be compensated.
* @param initialRotation New value of property initialRotation.
*/
public void setInitialRotation(float initialRotation) {
float old_rot = rotationRadians - this.initialRotation;
this.initialRotation = initialRotation;
setRotation(old_rot);
}
/**
* Some image formats, like TIFF may present the images rotated that have
* to be compensated.
* @param initialRotation New value of property initialRotation.
*/
public void setInitialRotation(float initialRotation) {
float old_rot = rotationRadians - this.initialRotation;
this.initialRotation = initialRotation;
setRotation(old_rot);
}
// indentations
// indentations
/** the indentation to the left. */
protected float indentationLeft = 0;
@ -1532,7 +1545,7 @@ public abstract class Image extends Rectangle {
this.spacingAfter = spacing;
}
// widthpercentage (for the moment only used in ColumnText)
// widthpercentage (for the moment only used in ColumnText)
/**
* Holds value of property widthPercentage.
@ -1558,7 +1571,7 @@ public abstract class Image extends Rectangle {
this.widthPercentage = widthPercentage;
}
// annotation
// annotation
/** if the annotation is not null the image will be clickable. */
protected Annotation annotation = null;
@ -1582,9 +1595,9 @@ public abstract class Image extends Rectangle {
return annotation;
}
// Optional Content
// Optional Content
/** Optional Content layer to which we want this Image to belong. */
/** Optional Content layer to which we want this Image to belong. */
protected PdfOCG layer;
/**
@ -1861,48 +1874,48 @@ public abstract class Image extends Rectangle {
this.additional = additional;
}
/**
* Replaces CalRGB and CalGray colorspaces with DeviceRGB and DeviceGray.
*/
public void simplifyColorspace() {
if (additional == null)
return;
PdfArray value = additional.getAsArray(PdfName.COLORSPACE);
if (value == null)
return;
PdfObject cs = simplifyColorspace(value);
PdfObject newValue;
if (cs.isName())
newValue = cs;
else {
newValue = value;
PdfName first = value.getAsName(0);
if (PdfName.INDEXED.equals(first)) {
if (value.size() >= 2) {
PdfArray second = value.getAsArray(1);
if (second != null) {
value.set(1, simplifyColorspace(second));
}
}
}
}
additional.put(PdfName.COLORSPACE, newValue);
}
/**
* Replaces CalRGB and CalGray colorspaces with DeviceRGB and DeviceGray.
*/
public void simplifyColorspace() {
if (additional == null)
return;
PdfArray value = additional.getAsArray(PdfName.COLORSPACE);
if (value == null)
return;
PdfObject cs = simplifyColorspace(value);
PdfObject newValue;
if (cs.isName())
newValue = cs;
else {
newValue = value;
PdfName first = value.getAsName(0);
if (PdfName.INDEXED.equals(first)) {
if (value.size() >= 2) {
PdfArray second = value.getAsArray(1);
if (second != null) {
value.set(1, simplifyColorspace(second));
}
}
}
}
additional.put(PdfName.COLORSPACE, newValue);
}
/**
* Gets a PDF Name from an array or returns the object that was passed.
*/
private PdfObject simplifyColorspace(PdfArray obj) {
if (obj == null)
return obj;
PdfName first = obj.getAsName(0);
if (PdfName.CALGRAY.equals(first))
return PdfName.DEVICEGRAY;
else if (PdfName.CALRGB.equals(first))
return PdfName.DEVICERGB;
else
return obj;
}
private PdfObject simplifyColorspace(PdfArray obj) {
if (obj == null)
return obj;
PdfName first = obj.getAsName(0);
if (PdfName.CALGRAY.equals(first))
return PdfName.DEVICEGRAY;
else if (PdfName.CALRGB.equals(first))
return PdfName.DEVICERGB;
else
return obj;
}
/** Is this image a mask? */
protected boolean mask = false;
@ -2023,7 +2036,7 @@ public abstract class Image extends Rectangle {
/**
* Returns the compression level used for images written as a compressed stream.
* @return the compression level (0 = best speed, 9 = best compression, -1 is default)
* @since 2.1.3
* @since 2.1.3
*/
public int getCompressionLevel() {
return compressionLevel;
@ -2032,7 +2045,7 @@ public abstract class Image extends Rectangle {
/**
* Sets the compression level to be used if the image is written as a compressed stream.
* @param compressionLevel a value between 0 (best speed) and 9 (best compression)
* @since 2.1.3
* @since 2.1.3
*/
public void setCompressionLevel(int compressionLevel) {
if (compressionLevel < PdfStream.NO_COMPRESSION || compressionLevel > PdfStream.BEST_COMPRESSION)

323
fine-itext-old/src/com/fr/third/com/lowagie/text/List.java

@ -49,11 +49,11 @@
package com.fr.third.com.lowagie.text;
import com.fr.third.com.lowagie.text.factories.RomanAlphabetFactory;
import java.util.ArrayList;
import java.util.Iterator;
import com.fr.third.com.lowagie.text.factories.RomanAlphabetFactory;
/**
* A <CODE>List</CODE> contains several <CODE>ListItem</CODE>s.
* <P>
@ -103,22 +103,22 @@ public class List implements TextElementArray {
// constants
/** a possible value for the numbered parameter */
public static final boolean ORDERED = true;
/** a possible value for the numbered parameter */
public static final boolean UNORDERED = false;
/** a possible value for the lettered parameter */
public static final boolean NUMERICAL = false;
/** a possible value for the lettered parameter */
public static final boolean ALPHABETICAL = true;
/** a possible value for the lettered parameter */
public static final boolean UPPERCASE = false;
/** a possible value for the lettered parameter */
public static final boolean LOWERCASE = true;
/** a possible value for the numbered parameter */
public static final boolean ORDERED = true;
/** a possible value for the numbered parameter */
public static final boolean UNORDERED = false;
/** a possible value for the lettered parameter */
public static final boolean NUMERICAL = false;
/** a possible value for the lettered parameter */
public static final boolean ALPHABETICAL = true;
/** a possible value for the lettered parameter */
public static final boolean UPPERCASE = false;
/** a possible value for the lettered parameter */
public static final boolean LOWERCASE = true;
// member variables
/** This is the <CODE>ArrayList</CODE> containing the different <CODE>ListItem</CODE>s. */
/** This is the <CODE>ArrayList</CODE> containing the different <CODE>ListItem</CODE>s. */
protected ArrayList list = new ArrayList();
/** Indicates if the list has to be numbered. */
@ -127,6 +127,15 @@ public class List implements TextElementArray {
protected boolean lettered = false;
/** Indicates if the listsymbols are lowercase or uppercase. */
protected boolean lowercase = false;
public ArrayList getList() {
return list;
}
public void setList(ArrayList list) {
this.list = list;
}
/** Indicates if the indentation has to be set automatically. */
protected boolean autoindent = false;
/** Indicates if the indentation of all the items has to be aligned. */
@ -167,7 +176,7 @@ public class List implements TextElementArray {
* @since iText 2.0.8
*/
public List(float symbolIndent) {
this.symbolIndent = symbolIndent;
this.symbolIndent = symbolIndent;
}
/**
@ -175,7 +184,7 @@ public class List implements TextElementArray {
* @param numbered a boolean
*/
public List(boolean numbered) {
this(numbered, false);
this(numbered, false);
}
/**
@ -184,7 +193,7 @@ public class List implements TextElementArray {
* @param lettered has the list to be 'numbered' with letters
*/
public List(boolean numbered, boolean lettered) {
this.numbered = numbered;
this.numbered = numbered;
this.lettered = lettered;
this.autoindent = true;
this.alignindent = true;
@ -243,7 +252,7 @@ public class List implements TextElementArray {
* @return a type
*/
public int type() {
return Element.LIST;
return LIST;
}
/**
@ -287,8 +296,8 @@ public class List implements TextElementArray {
item.setIndentationRight(0);
return list.add(item);
}
else if (o instanceof List) {
List nested = (List) o;
else if (o instanceof com.fr.third.com.lowagie.text.List) {
com.fr.third.com.lowagie.text.List nested = (com.fr.third.com.lowagie.text.List) o;
nested.setIndentationLeft(nested.getIndentationLeft() + symbolIndent);
first--;
return list.add(nested);
@ -301,59 +310,59 @@ public class List implements TextElementArray {
// extra methods
/** Makes sure all the items in the list have the same indentation. */
/** Makes sure all the items in the list have the same indentation. */
public void normalizeIndentation() {
float max = 0;
Element o;
Element o;
for (Iterator i = list.iterator(); i.hasNext(); ) {
o = (Element)i.next();
o = (Element)i.next();
if (o instanceof ListItem) {
max = Math.max(max, ((ListItem)o).getIndentationLeft());
max = Math.max(max, ((ListItem)o).getIndentationLeft());
}
}
for (Iterator i = list.iterator(); i.hasNext(); ) {
o = (Element)i.next();
o = (Element)i.next();
if (o instanceof ListItem) {
((ListItem)o).setIndentationLeft(max);
((ListItem)o).setIndentationLeft(max);
}
}
}
// setters
/**
* @param numbered the numbered to set
*/
public void setNumbered(boolean numbered) {
this.numbered = numbered;
}
/**
* @param lettered the lettered to set
*/
public void setLettered(boolean lettered) {
this.lettered = lettered;
}
/**
* @param uppercase the uppercase to set
*/
public void setLowercase(boolean uppercase) {
this.lowercase = uppercase;
}
/**
* @param autoindent the autoindent to set
*/
public void setAutoindent(boolean autoindent) {
this.autoindent = autoindent;
}
/**
* @param alignindent the alignindent to set
*/
public void setAlignindent(boolean alignindent) {
this.alignindent = alignindent;
}
/**
* @param numbered the numbered to set
*/
public void setNumbered(boolean numbered) {
this.numbered = numbered;
}
/**
* @param lettered the lettered to set
*/
public void setLettered(boolean lettered) {
this.lettered = lettered;
}
/**
* @param uppercase the uppercase to set
*/
public void setLowercase(boolean uppercase) {
this.lowercase = uppercase;
}
/**
* @param autoindent the autoindent to set
*/
public void setAutoindent(boolean autoindent) {
this.autoindent = autoindent;
}
/**
* @param alignindent the alignindent to set
*/
public void setAlignindent(boolean alignindent) {
this.alignindent = alignindent;
}
/**
* Sets the number that has to come first in the list.
@ -402,12 +411,12 @@ public class List implements TextElementArray {
this.indentationRight = indentation;
}
/**
* @param symbolIndent the symbolIndent to set
*/
public void setSymbolIndent(float symbolIndent) {
this.symbolIndent = symbolIndent;
}
/**
* @param symbolIndent the symbolIndent to set
*/
public void setSymbolIndent(float symbolIndent) {
this.symbolIndent = symbolIndent;
}
// methods to retrieve information
@ -435,7 +444,7 @@ public class List implements TextElementArray {
* @return <CODE>true</CODE> if the list is empty
*/
public boolean isEmpty() {
return list.isEmpty();
return list.isEmpty();
}
/**
@ -480,109 +489,109 @@ public class List implements TextElementArray {
/**
* Checks if the indentation of list items is done automatically.
* @return the autoindent
*/
public boolean isAutoindent() {
return autoindent;
}
/**
* Checks if all the listitems should be aligned.
* @return the alignindent
*/
public boolean isAlignindent() {
return alignindent;
}
/**
* @return the autoindent
*/
public boolean isAutoindent() {
return autoindent;
}
/**
* Checks if all the listitems should be aligned.
* @return the alignindent
*/
public boolean isAlignindent() {
return alignindent;
}
/**
* Gets the first number .
* @return a number
*/
public int getFirst() {
return first;
}
*/
public int getFirst() {
return first;
}
/**
/**
* Gets the Chunk containing the symbol.
* @return a Chunk with a symbol
*/
public Chunk getSymbol() {
return symbol;
}
*/
public Chunk getSymbol() {
return symbol;
}
/**
/**
* Gets the indentation of this paragraph on the left side.
* @return the indentation
*/
public float getIndentationLeft() {
return indentationLeft;
}
*/
public float getIndentationLeft() {
return indentationLeft;
}
/**
/**
* Gets the indentation of this paragraph on the right side.
* @return the indentation
*/
public float getIndentationRight() {
return indentationRight;
}
*/
public float getIndentationRight() {
return indentationRight;
}
/**
/**
* Gets the symbol indentation.
* @return the symbol indentation
*/
public float getSymbolIndent() {
return symbolIndent;
}
/**
* @see com.fr.third.com.lowagie.text.Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return true;
}
/**
* @see com.fr.third.com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return true;
}
/**
* Returns the String that is after a number or letter in the list symbol.
* @return the String that is after a number or letter in the list symbol
* @since iText 2.1.1
*/
public String getPostSymbol() {
return postSymbol;
}
/**
* Sets the String that has to be added after a number or letter in the list symbol.
* @since iText 2.1.1
* @param postSymbol the String that has to be added after a number or letter in the list symbol.
*/
public void setPostSymbol(String postSymbol) {
this.postSymbol = postSymbol;
}
/**
* Returns the String that is before a number or letter in the list symbol.
* @return the String that is before a number or letter in the list symbol
* @since iText 2.1.1
*/
public String getPreSymbol() {
return preSymbol;
}
/**
* Sets the String that has to be added before a number or letter in the list symbol.
* @since iText 2.1.1
* @param preSymbol the String that has to be added before a number or letter in the list symbol.
*/
public void setPreSymbol(String preSymbol) {
this.preSymbol = preSymbol;
}
*/
public float getSymbolIndent() {
return symbolIndent;
}
/**
* @see Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return true;
}
/**
* @see Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return true;
}
/**
* Returns the String that is after a number or letter in the list symbol.
* @return the String that is after a number or letter in the list symbol
* @since iText 2.1.1
*/
public String getPostSymbol() {
return postSymbol;
}
/**
* Sets the String that has to be added after a number or letter in the list symbol.
* @since iText 2.1.1
* @param postSymbol the String that has to be added after a number or letter in the list symbol.
*/
public void setPostSymbol(String postSymbol) {
this.postSymbol = postSymbol;
}
/**
* Returns the String that is before a number or letter in the list symbol.
* @return the String that is before a number or letter in the list symbol
* @since iText 2.1.1
*/
public String getPreSymbol() {
return preSymbol;
}
/**
* Sets the String that has to be added before a number or letter in the list symbol.
* @since iText 2.1.1
* @param preSymbol the String that has to be added before a number or letter in the list symbol.
*/
public void setPreSymbol(String preSymbol) {
this.preSymbol = preSymbol;
}
}

44
fine-itext-old/src/com/fr/third/com/lowagie/text/Paragraph.java

@ -49,6 +49,8 @@
package com.fr.third.com.lowagie.text;
import java.util.HashMap;
/**
* A <CODE>Paragraph</CODE> is a series of <CODE>Chunk</CODE>s and/or <CODE>Phrases</CODE>.
* <P>
@ -78,7 +80,7 @@ public class Paragraph extends Phrase {
// membervariables
/** The alignment of the text. */
protected int alignment = Element.ALIGN_UNDEFINED;
protected int alignment = ALIGN_UNDEFINED;
/** The text leading that is multiplied by the biggest font size in the line. */
protected float multipliedLeading = 0;
@ -104,6 +106,24 @@ public class Paragraph extends Phrase {
/** Does the paragraph has to be kept together on 1 page. */
protected boolean keeptogether = false;
protected String background;
protected HashMap attributes = new HashMap();
public HashMap getAttributes() {
return attributes;
}
public void setAttributes(HashMap attributes) {
this.attributes = attributes;
}
public void setAttribute(String name, Object obj) {
if (attributes == null)
attributes = new HashMap();
attributes.put(name, obj);
}
// constructors
/**
@ -213,7 +233,7 @@ public class Paragraph extends Phrase {
* @return a type
*/
public int type() {
return Element.PARAGRAPH;
return PARAGRAPH;
}
// methods
@ -268,26 +288,26 @@ public class Paragraph extends Phrase {
*/
public void setAlignment(String alignment) {
if (ElementTags.ALIGN_CENTER.equalsIgnoreCase(alignment)) {
this.alignment = Element.ALIGN_CENTER;
this.alignment = ALIGN_CENTER;
return;
}
if (ElementTags.ALIGN_RIGHT.equalsIgnoreCase(alignment)) {
this.alignment = Element.ALIGN_RIGHT;
this.alignment = ALIGN_RIGHT;
return;
}
if (ElementTags.ALIGN_JUSTIFIED.equalsIgnoreCase(alignment)) {
this.alignment = Element.ALIGN_JUSTIFIED;
this.alignment = ALIGN_JUSTIFIED;
return;
}
if (ElementTags.ALIGN_JUSTIFIED_ALL.equalsIgnoreCase(alignment)) {
this.alignment = Element.ALIGN_JUSTIFIED_ALL;
this.alignment = ALIGN_JUSTIFIED_ALL;
return;
}
this.alignment = Element.ALIGN_LEFT;
this.alignment = ALIGN_LEFT;
}
/**
* @see com.fr.third.com.lowagie.text.Phrase#setLeading(float)
* @see Phrase#setLeading(float)
*/
public void setLeading(float fixedLeading) {
this.leading = fixedLeading;
@ -499,4 +519,12 @@ public class Paragraph extends Phrase {
return spacingAfter;
}
public void setBackground(String background){
this.background = background;
}
public String getBackground(){
return this.background;
}
}

2
fine-itext-old/src/com/fr/third/com/lowagie/text/factories/ElementFactory.java

@ -135,7 +135,7 @@ public class ElementFactory {
}
value = attributes.getProperty(ElementTags.BACKGROUNDCOLOR);
if (value != null) {
chunk.setBackground(Markup.decodeColor(value));
chunk.setBackground(value);
}
return chunk;
}

200
fine-itext-old/src/com/fr/third/com/lowagie/text/html/CSS.java

@ -0,0 +1,200 @@
package com.fr.third.com.lowagie.text.html;
/**
* @author kerry
* @date 2018/5/11
*/
public class CSS {
public final class Value {
private Value(){};
public static final String THIN = "thin";
public static final String MEDIUM = "medium";
public static final String THICK = "thick";
public static final String NONE = "none";
public static final String HIDDEN = "hidden";
public static final String DOTTED = "dotted";
public static final String DASHED = "dashed";
public static final String SOLID = "solid";
public static final String DOUBLE = "double";
public static final String GROOVE = "groove";
public static final String RIDGE = "ridge";
public static final String INSET = "inset";
public static final String OUTSET = "outset";
public static final String LEFT = "left";
public static final String CENTER = "center";
public static final String JUSTIFY = "justify";
public static final String BOTTOM = "bottom";
public static final String TOP = "top";
public static final String RIGHT = "right";
public static final String REPEAT = "repeat";
public static final String NO_REPEAT = "no-repeat";
public static final String REPEAT_X = "repeat-x";
public static final String REPEAT_Y = "repeat-y";
public static final String FIXED = "fixed";
public static final String SCROLL = "scroll";
public static final String DISC = "disc";
public static final String SQUARE = "square";
public static final String CIRCLE = "circle";
public static final String DECIMAL = "decimal";
public static final String LOWER_ROMAN = "lower-roman";
public static final String UPPER_ROMAN = "upper-roman";
public static final String LOWER_GREEK = "lower-greek";
public static final String UPPER_GREEK = "upper-greek";
public static final String LOWER_ALPHA = "lower-alpha";
public static final String UPPER_ALPHA = "upper-alpha";
public static final String LOWER_LATIN = "lower-latin";
public static final String UPPER_LATIN = "upper-latin";
public static final String INSIDE = "inside";
public static final String OUTSIDE = "outside";
public static final String INHERIT = "inherit";
public static final String UNDERLINE = "underline";
public static final String BOLD = "bold";
public static final String ITALIC = "italic";
public static final String OBLIQUE = "oblique";
public static final String SUPER = "super";
public static final String SUB = "sub";
public static final String TEXT_TOP = "text-top";
public static final String TEXT_BOTTOM = "text-bottom";
public static final String LINE_THROUGH = "line-through";
public static final String RELATIVE = "relative";
public static final String HIDE = "hide";
public static final String XX_SMALL = "xx-small";
public static final String X_SMALL = "x-small";
public static final String SMALL = "small";
public static final String LARGE = "large";
public static final String X_LARGE = "x-large";
public static final String XX_LARGE = "xx-large";
public static final String SMALLER = "smaller";
public static final String LARGER = "larger";
public static final String PX = "px";
public static final String IN = "in";
public static final String CM = "cm";
public static final String MM = "mm";
public static final String PT = "pt";
public static final String PC = "pc";
public static final String PERCENTAGE = "%";
public static final String EM = "em";
public static final String EX = "ex";
public static final String ALWAYS = "always";
public static final String AVOID = "avoid";
public static final String ABSOLUTE = "absolute";
public static final String AUTO = "auto";
public static final String INLINE = "inline";
public static final String BLOCK = "block";
public static final String SEPARATE = "separate";
public static final String COLLAPSE = "collapse";
public static final String RTL = "rtl";
public static final String LTR = "ltr";
public static final String INLINE_BLOCK = "inline-block";
public static final String INLINE_TABLE = "inline-table";
public static final String LIST_ITEM = "list-item";
public static final String RUN_IN = "run-in";
public static final String TABLE = "table";
public static final String TABLE_CAPTION = "table-caption";
public static final String TABLE_CELL = "table-cell";
public static final String TABLE_COLUMN_GROUP = "table-column-group";
public static final String TABLE_COLUMN = "table-column";
public static final String TABLE_FOOTER_GROUP = "table-footer-group";
public static final String TABLE_HEADER_GROUP = "table-header-group";
public static final String TABLE_ROW = "table-row";
public static final String TABLE_ROW_GROUP = "table-row-group";
}
public final class Property {
private Property() {};
public static final String BACKGROUND = "background";
public static final String BACKGROUND_IMAGE = "background-image";
public static final String BACKGROUND_REPEAT = "background-repeat";
public static final String BACKGROUND_ATTACHMENT = "background-attachment";
public static final String BACKGROUND_POSITION = "background-position";
public static final String BACKGROUND_COLOR = "background-color";
public static final String BACKGROUND_SIZE = "background-size";
public static final String LIST_STYLE = "list-style";
public static final String LIST_STYLE_TYPE = "list-style-type";
public static final String LIST_STYLE_POSITION = "list-style-position";
public static final String LIST_STYLE_IMAGE = "list-style-image";
public static final String MARGIN = "margin";
public static final String TOP = "top";
public static final String MARGIN_LEFT = "margin-left";
public static final String MARGIN_RIGHT = "margin-right";
public static final String MARGIN_TOP = "margin-top";
public static final String MARGIN_BOTTOM = "margin-bottom";
public static final String BORDER = "border";
public static final String BORDER_LEFT = "border-left";
public static final String BORDER_TOP = "border-top";
public static final String BORDER_RIGHT = "border-right";
public static final String BORDER_BOTTOM = "border-bottom";
public static final String BORDER_WIDTH = "border-width";
public static final String BORDER_STYLE = "border-style";
public static final String BORDER_COLOR = "border-color";
public static final String BORDER_COLLAPSE = "border-collapse";
public static final String BORDER_SPACING = "border-spacing";
public static final String BORDER_TOP_WIDTH = "border-top-width";
public static final String BORDER_BOTTOM_WIDTH = "border-bottom-width";
public static final String BORDER_LEFT_WIDTH = "border-left-width";
public static final String BORDER_RIGHT_WIDTH = "border-right-width";
public static final String BORDER_TOP_COLOR = "border-top-color";
public static final String BORDER_BOTTOM_COLOR = "border-bottom-color";
public static final String BORDER_LEFT_COLOR = "border-left-color";
public static final String BORDER_RIGHT_COLOR = "border-right-color";
public static final String BORDER_TOP_STYLE = "border-top-style";
public static final String BORDER_BOTTOM_STYLE = "border-bottom-style";
public static final String BORDER_LEFT_STYLE = "border-left-style";
public static final String BORDER_RIGHT_STYLE = "border-right-style";
public static final String PADDING = "padding";
public static final String PADDING_TOP = "padding-top";
public static final String PADDING_BOTTOM = "padding-bottom";
public static final String PADDING_LEFT = "padding-left";
public static final String PADDING_RIGHT = "padding-right";
public static final String FONT = "font";
public static final String FONT_WEIGHT = "font-weight";
public static final String FONT_SIZE = "font-size";
public static final String FONT_STYLE = "font-style";
public static final String FONT_FAMILY = "font-family";
public static final String TEXT_DECORATION = "text-decoration";
public static final String COLOR = "color";
public static final String TAB_INTERVAL = "tab-interval";
public static final String XFA_TAB_COUNT = "xfa-tab-count";
public static final String XFA_FONT_HORIZONTAL_SCALE = "xfa-font-horizontal-scale";
public static final String XFA_FONT_VERTICAL_SCALE = "xfa-font-vertical-scale";
public static final String BEFORE = "before";
public static final String AFTER = "after";
public static final String HEIGHT = "height";
public static final String WIDTH = "width";
public static final String LETTER_SPACING = "letter-spacing";
public static final String VERTICAL_ALIGN = "vertical-align";
public static final String LINE_HEIGHT = "line-height";
public static final String TEXT_ALIGN = "text-align";
public static final String TEXT_VALIGN = "text-valign";
public static final String TEXT_INDENT = "text-indent";
public static final String POSITION = "position";
public static final String EMPTY_CELLS = "empty-cells";
public static final String CELLPADDING = "cellpadding";
//deprecated
public static final String CELLPADDING_LEFT = "cellpadding-left";
public static final String CELLPADDING_TOP = "cellpadding-top";
public static final String CELLPADDING_RIGHT = "cellpadding-right";
public static final String CELLPADDING_BOTTOM = "cellpadding-bottom";
public static final String CAPTION_SIDE = "caption-side";
public static final String TAB_STOPS = "tab-stops";
public static final String XFA_TAB_STOPS = "xfa-tab-stops";
public static final String PAGE_BREAK_BEFORE = "page-break-before";
public static final String PAGE_BREAK_INSIDE = "page-break-inside";
public static final String PAGE_BREAK_AFTER = "page-break-after";
public static final String REPEAT_HEADER = "repeat-header";
public static final String REPEAT_FOOTER = "repeat-footer";
public static final String LEFT = "left";
public static final String DISPLAY = "display";
public static final String MIN_WIDTH = "min-width";
public static final String MAX_WIDTH = "max-width";
public static final String MIN_HEIGHT = "min-height";
public static final String MAX_HEIGHT = "max-height";
public static final String RIGHT = "right";
public static final String BOTTOM = "bottom";
public static final String FLOAT = "float";
public static final String DIRECTION = "direction";
}
}

105
fine-itext-old/src/com/fr/third/com/lowagie/text/html/CSSUtils.java

@ -0,0 +1,105 @@
package com.fr.third.com.lowagie.text.html;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author kerry
* @date 2018/4/9
*/
public class CSSUtils {
private static final Set<String> backgroundPositions = new HashSet<String>(
Arrays.asList(new String[] { CSS.Value.LEFT, CSS.Value.CENTER, CSS.Value.BOTTOM, CSS.Value.TOP, CSS.Value.RIGHT }));
public static Map<String, String> processBackground(final String background) {
Map<String, String> rules = new HashMap<String, String>();
String[] styles = splitComplexCssStyle(background);
for(String style : styles) {
if (style.contains("url(")) {
rules.put(CSS.Property.BACKGROUND_IMAGE, style);
} else if (style.equalsIgnoreCase(CSS.Value.REPEAT)
|| style.equalsIgnoreCase(CSS.Value.NO_REPEAT)
|| style.equalsIgnoreCase(CSS.Value.REPEAT_X)
|| style.equalsIgnoreCase(CSS.Value.REPEAT_Y)) {
rules.put(CSS.Property.BACKGROUND_REPEAT, style);
} else if (style.equalsIgnoreCase(CSS.Value.FIXED) || style.equalsIgnoreCase(CSS.Value.SCROLL)) {
rules.put(CSS.Property.BACKGROUND_ATTACHMENT, style);
} else if (backgroundPositions.contains(style)) {
if(rules.get(CSS.Property.BACKGROUND_POSITION) == null) {
rules.put(CSS.Property.BACKGROUND_POSITION, style);
} else {
style = style.concat(" "+rules.get(CSS.Property.BACKGROUND_POSITION));
rules.put(CSS.Property.BACKGROUND_POSITION, style);
}
} else if (isNumericValue(style) || isMetricValue(style) || isRelativeValue(style)) {
if(rules.get(CSS.Property.BACKGROUND_POSITION) == null) {
rules.put(CSS.Property.BACKGROUND_POSITION, style);
} else {
style = style.concat(" "+rules.get(CSS.Property.BACKGROUND_POSITION));
rules.put(CSS.Property.BACKGROUND_POSITION, style);
}
} else if(style.contains("rgb(") || style.contains("rgba(") || style.contains("#") || WebColors.NAMES.containsKey(style.toLowerCase())) {
rules.put(CSS.Property.BACKGROUND_COLOR, style);
}
}
return rules;
}
public static String[] splitComplexCssStyle(String s) {
s = s.replaceAll("\\s*,\\s*", ",") ;
return s.split("\\s");
}
public static boolean isMetricValue(final String value) {
return value.contains(CSS.Value.PX) || value.contains(CSS.Value.IN) || value.contains(CSS.Value.CM)
|| value.contains(CSS.Value.MM) || value.contains(CSS.Value.PC) || value.contains(CSS.Value.PT);
}
public static boolean isRelativeValue(final String value) {
return value.contains(CSS.Value.PERCENTAGE) || value.contains(CSS.Value.EM) || value.contains(CSS.Value.EX);
}
public static boolean isNumericValue(final String value) {
return value.matches("^-?\\d\\d*\\.\\d*$") || value.matches("^-?\\d\\d*$") || value.matches("^-?\\.\\d\\d*$");
}
public static String extractUrl(final String url) {
String str = null;
if (url.startsWith("url")) {
String urlString = url.substring(3).trim().replace("(", "").replace(")", "").trim();
if (urlString.startsWith("'") && urlString.endsWith("'")) {
str = urlString.substring(urlString.indexOf("'")+1, urlString.lastIndexOf("'"));
} else if ( urlString.startsWith("\"") && urlString.endsWith("\"") ) {
str = urlString.substring(urlString.indexOf('"')+1, urlString.lastIndexOf('"'));
} else {
str = urlString;
}
} else {
str = url;
}
return str;
}
public static Float parseFloat(String str){
float result = 0.0f;
try {
if(str.endsWith("px") || str.endsWith("pt")){
result = Float.parseFloat(str.substring(0, str.length() - 2));
}else{
result = Float.parseFloat(str);
}
}catch (NumberFormatException e){
}
return result;
}
}

55
fine-itext-old/src/com/fr/third/com/lowagie/text/html/IndentAttribute.java

@ -0,0 +1,55 @@
package com.fr.third.com.lowagie.text.html;
/**
* @author kerry
* @date 2018/5/9
*/
public class IndentAttribute {
private float top = 0.0f;
private float bottom = 0.0f;
private float left = 0.0f;
private float right = 0.0f;
public float getTop() {
return top;
}
public void setTop(float top) {
this.top = top;
}
public float getBottom() {
return bottom;
}
public void setBottom(float bottom) {
this.bottom = bottom;
}
public float getLeft() {
return left;
}
public void setLeft(float left) {
this.left = left;
}
public float getRight() {
return right;
}
public void setRight(float right) {
this.right = right;
}
public IndentAttribute(float top, float left, float bottom, float right){
this.top = top;
this.left = left;
this.bottom = bottom;
this.right = right;
}
public IndentAttribute(){
}
}

125
fine-itext-old/src/com/fr/third/com/lowagie/text/html/Markup.java

@ -54,7 +54,6 @@ package com.fr.third.com.lowagie.text.html;
import java.awt.Color;
import java.util.Properties;
import java.util.StringTokenizer;
/**
* A class that contains all the possible tagnames and their attributes.
@ -273,8 +272,8 @@ public class Markup {
public static final String CSS_VALUE_UNDERLINE = "underline";
/** a default value for font-size
* @since 2.1.3
*/
* @since 2.1.3
*/
public static final float DEFAULT_FONT_SIZE = 12f;
/**
@ -295,23 +294,23 @@ public class Markup {
boolean ok = true;
while (ok && pos < length) {
switch (string.charAt(pos)) {
case '+':
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
pos++;
break;
default:
ok = false;
case '+':
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
pos++;
break;
default:
ok = false;
}
}
if (pos == 0)
@ -353,23 +352,23 @@ public class Markup {
boolean ok = true;
while (ok && pos < length) {
switch (string.charAt(pos)) {
case '+':
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
pos++;
break;
default:
ok = false;
case '+':
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
pos++;
break;
default:
ok = false;
}
}
if (pos == 0)
@ -441,29 +440,45 @@ public class Markup {
Properties result = new Properties();
if (string == null)
return result;
StringTokenizer keyValuePairs = new StringTokenizer(string, ";");
StringTokenizer keyValuePair;
String key;
String value;
while (keyValuePairs.hasMoreTokens()) {
keyValuePair = new StringTokenizer(keyValuePairs.nextToken(), ":");
if (keyValuePair.hasMoreTokens())
key = keyValuePair.nextToken().trim();
else
continue;
if (keyValuePair.hasMoreTokens())
value = keyValuePair.nextToken().trim();
else
continue;
if (value.startsWith("\""))
value = value.substring(1);
if (value.endsWith("\""))
value = value.substring(0, value.length() - 1);
result.setProperty(key.toLowerCase(), value);
//换种方式解析,style中background里面也有可能会有;符号
String[] styles = string.split(";");
for (String s : styles) {
String[] part = s.split(":",2);
if (part.length == 2) {
key = stripDoubleSpacesAndTrim(part[0]).toLowerCase();
value = stripDoubleSpacesAndTrim(part[1]);
if (value.startsWith("\"") || value.startsWith("\'") )
value = value.substring(1);
if (value.endsWith("\"") || value.endsWith("\'"))
value = value.substring(0, value.length() - 1);
result.setProperty(key.toLowerCase(), value);
}
}
return result;
}
public static String stripDoubleSpacesAndTrim(final String str) {
char[] charArray = str.toCharArray();
if (str.contains(" ")) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < charArray.length; i++) {
char c = charArray[i];
if (c != ' ') {
builder.append(c);
} else {
if (i + 1 < charArray.length && charArray[i + 1] != ' ') {
builder.append(' ');
}
}
}
return builder.toString().trim();
} else {
return String.valueOf(charArray).trim();
}
}
/**
* Removes the comments sections of a String.
*
@ -476,7 +491,7 @@ public class Markup {
* @return the String stripped of its comment section
*/
public static String removeComment(String string, String startComment,
String endComment) {
String endComment) {
StringBuffer result = new StringBuffer();
int pos = 0;
int end = endComment.length();

84
fine-itext-old/src/com/fr/third/com/lowagie/text/html/ParseIndentAttrUtils.java

@ -0,0 +1,84 @@
package com.fr.third.com.lowagie.text.html;
import com.fr.third.com.lowagie.text.html.CSS;
import com.fr.third.com.lowagie.text.html.IndentAttribute;
import com.fr.third.com.lowagie.text.html.Markup;
import java.util.Iterator;
import java.util.Map;
/**
* @author kerry
* @date 2018/5/14
*/
public class ParseIndentAttrUtils {
public static IndentAttribute parseSpace(String indent){
String[] a = indent.split(" ");
if(a.length == 0){
return new IndentAttribute();
}
float indentTop = Markup.parseLength(a[0]);
if(a.length == 1){
return new IndentAttribute(indentTop, indentTop, indentTop, indentTop);
}
float indentLeft = Markup.parseLength(a[1]);
if(a.length == 2){
return new IndentAttribute(indentTop, indentLeft, indentTop, indentLeft);
}
float indentBottom = Markup.parseLength(a[2]);
if(a.length == 3){
return new IndentAttribute(indentTop, indentLeft, indentBottom, indentLeft);
}
float indentRight = Markup.parseLength(a[3]);
return new IndentAttribute(indentTop, indentLeft, indentBottom, indentRight);
}
public static IndentAttribute parsePaddingAttribute(Map map){
if (map == null){
return new IndentAttribute();
}
IndentAttribute indentAttribute = new IndentAttribute();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
if (CSS.Property.PADDING_LEFT.equals(key)) {
indentAttribute.setLeft(Markup.parseLength((String) entry.getValue()));
} else if (CSS.Property.PADDING_RIGHT.equals(key)) {
indentAttribute.setRight(Markup.parseLength((String) entry.getValue()));
} else if (CSS.Property.PADDING_TOP.equals(key)) {
indentAttribute.setTop(Markup.parseLength((String) entry.getValue()));
} else if (CSS.Property.PADDING_BOTTOM.equals(key)) {
indentAttribute.setBottom(Markup.parseLength((String) entry.getValue()));
}
}
return indentAttribute;
}
public static IndentAttribute parseMarginAttribute(Map map){
IndentAttribute indentAttribute = new IndentAttribute();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
float val = Markup.parseLength((String) entry.getValue());
if (CSS.Property.MARGIN_LEFT.equals(key)) {
indentAttribute.setLeft(val);
} else if (CSS.Property.MARGIN_RIGHT.equals(key)) {
indentAttribute.setRight(val);
} else if (CSS.Property.MARGIN_TOP.equals(key)) {
indentAttribute.setTop(val);
} else if (CSS.Property.MARGIN_BOTTOM.equals(key)) {
indentAttribute.setBottom(val);
}
}
return indentAttribute;
}
public static void createIndent(StringBuffer stringBuffer, String attr, IndentAttribute indentAttribute){
stringBuffer.append(attr).append("-").append("left").append(":").append(indentAttribute.getLeft()).append("px;")
.append(attr).append("-").append("right").append(":").append(indentAttribute.getRight()).append("px;")
.append(attr).append("-").append("top").append(":").append(indentAttribute.getTop()).append("px;")
.append(attr).append("-").append("bottom").append(":").append(indentAttribute.getBottom()).append("px;");
}
}

4
fine-itext-old/src/com/fr/third/com/lowagie/text/html/WebColors.java

@ -221,7 +221,7 @@ public class WebColors extends HashMap {
*/
public static Color getRGBColor(String name)
throws IllegalArgumentException {
int[] c = { 0, 0, 0, 0 };
int[] c = { 0, 0, 0, 255 };
if (name.startsWith("#")) {
if (name.length() == 4) {
c[0] = Integer.parseInt(name.substring(1, 2), 16) * 16;
@ -258,6 +258,6 @@ public class WebColors extends HashMap {
throw new IllegalArgumentException("Color '" + name
+ "' not found.");
c = (int[]) NAMES.get(name);
return new Color(c[0], c[1], c[2], c[3]);
return new Color(c[0], c[1], c[2], 255);
}
}

67
fine-itext-old/src/com/fr/third/com/lowagie/text/html/simpleparser/ChainedProperties.java

@ -75,6 +75,13 @@ public class ChainedProperties {
return null;
}
public String getLastChainProperty(String key){
Object obj[] = (Object[]) chain.get(chain.size()-1);
HashMap prop = (HashMap) obj[1];
return (String) prop.get(key);
}
public boolean hasProperty(String key) {
for (int k = chain.size() - 1; k >= 0; --k) {
Object obj[] = (Object[]) chain.get(k);
@ -85,6 +92,66 @@ public class ChainedProperties {
return false;
}
public String getPropertyFromChain (String tag, String key) {
//块级元素不继承行内元素属性
if(HtmlConstants.BLOCK_ELEMENTS.contains(tag)){
for (int k = chain.size() - 1; k >= 0; --k) {
Object obj[] = (Object[]) chain.get(k);
if(HtmlConstants.INLINE_ELEMENTS.contains(obj[0])){
continue;
}
HashMap prop = (HashMap) obj[1];
String ret = (String) prop.get(key);
if (ret != null)
return ret;
}
}else{
for (int k = chain.size() - 1; k >= 0; --k) {
Object obj[] = (Object[]) chain.get(k);
if(HtmlConstants.BLOCK_ELEMENTS.contains(obj[0])){
return null;
}
HashMap prop = (HashMap) obj[1];
String ret = (String) prop.get(key);
if (ret != null)
return ret;
}
}
return null;
}
public boolean hasPropertyInChain(String tag, String key) {
if (HtmlConstants.BLOCK_ELEMENTS.contains(tag)) {
for (int k = chain.size() - 1; k >= 0; --k) {
Object obj[] = (Object[]) chain.get(k);
if( HtmlConstants.INLINE_ELEMENTS.contains(obj[0])){
continue;
}
HashMap prop = (HashMap) obj[1];
if (prop.containsKey(key))
return true;
}
} else {
for (int k = chain.size() - 1; k >= 0; --k) {
Object obj[] = (Object[]) chain.get(k);
if( HtmlConstants.BLOCK_ELEMENTS.contains(obj[0])){
return false;
}
HashMap prop = (HashMap) obj[1];
if (prop.containsKey(key))
return true;
}
}
return false;
}
public void addToChain(String key, HashMap prop) {
// adjust the font size
String value = (String) prop.get(ElementTags.SIZE);

82
fine-itext-old/src/com/fr/third/com/lowagie/text/html/simpleparser/FactoryProperties.java

@ -50,12 +50,6 @@
package com.fr.third.com.lowagie.text.html.simpleparser;
import java.awt.Color;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import com.fr.third.com.lowagie.text.Chunk;
import com.fr.third.com.lowagie.text.Element;
import com.fr.third.com.lowagie.text.ElementTags;
@ -64,12 +58,19 @@ import com.fr.third.com.lowagie.text.FontFactory;
import com.fr.third.com.lowagie.text.FontFactoryImp;
import com.fr.third.com.lowagie.text.ListItem;
import com.fr.third.com.lowagie.text.Paragraph;
import com.fr.third.com.lowagie.text.html.Markup;
import com.fr.third.com.lowagie.text.html.HtmlTags;
import com.fr.third.com.lowagie.text.pdf.BaseFont;
import com.fr.third.com.lowagie.text.html.IndentAttribute;
import com.fr.third.com.lowagie.text.html.Markup;
import com.fr.third.com.lowagie.text.html.ParseIndentAttrUtils;
import com.fr.third.com.lowagie.text.pdf.HyphenationAuto;
import com.fr.third.com.lowagie.text.pdf.HyphenationEvent;
import java.awt.Color;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
/**
*
* @author psoares
@ -85,16 +86,24 @@ public class FactoryProperties {
public Chunk createChunk(String text, ChainedProperties props) {
Font font = getFont(props);
float size = font.getSize();
size /= 2;
size /= 3;
Chunk ck = new Chunk(text, font);
if (props.hasProperty("sub"))
ck.setTextRise(-size);
else if (props.hasProperty("sup"))
ck.setTextRise(size);
ck.setHyphenation(getHyphenation(props));
if(props.hasProperty("background")){
ck.setBackground(props.getProperty("background"));
}
for(String padding : HtmlConstants.PADDING){
if(props.hasPropertyInChain("span", padding)){
String ss = props.getPropertyFromChain("span", padding);
ck.setAttribute(padding, ss);
}
}
return ck;
}
private static void setParagraphLeading(Paragraph p, String leading) {
if (leading == null) {
p.setLeading(0, 1.5f);
@ -126,6 +135,34 @@ public class FactoryProperties {
else if (value.equalsIgnoreCase("justify"))
p.setAlignment(Element.ALIGN_JUSTIFIED);
}
if(props.hasPropertyInChain("div", "background")){
p.setBackground(props.getPropertyFromChain("div", "background"));
}
if(props.hasProperty("line-height")){
p.setAttribute("line-height", props.getProperty("line-height"));
}
for(String margin : HtmlConstants.MARGIN){
if(props.hasPropertyInChain("div", margin)){
String ss = props.getPropertyFromChain("div", margin);
p.setAttribute(margin, ss);
}
}
for(String padding : HtmlConstants.PADDING){
if(props.hasPropertyInChain("div", padding)){
String ss = props.getPropertyFromChain("div", padding);
p.setAttribute(padding, ss);
}
}
if(props.hasPropertyInChain("div", "text-indent")){
String ss = props.getPropertyFromChain("div", "text-indent");
p.setFirstLineIndent(Markup.parseLength(ss));
}
if(props.hasPropertyInChain("div", "width")){
String ss = props.getPropertyFromChain("div", "width");
p.setAttribute("width", ss);
}
p.setHyphenation(getHyphenation(props));
setParagraphLeading(p, props.getProperty("leading"));
value = props.getProperty("before");
@ -191,10 +228,7 @@ public class FactoryProperties {
if (value != null)
size = Float.parseFloat(value);
Color color = Markup.decodeColor(props.getProperty("color"));
String encoding = props.getProperty("encoding");
if (encoding == null)
encoding = BaseFont.WINANSI;
return fontImp.getFont(face, encoding, true, size, style, color);
return new Font(face, size, style, color);
}
/**
@ -309,13 +343,22 @@ public class FactoryProperties {
else {
h.put("leading", v + ",0");
}
} else if (key.equals(Markup.CSS_KEY_TEXTALIGN)) {
} else if (key.equals(Markup.CSS_KEY_PADDING)) {
String ss = prop.getProperty(key).trim().toLowerCase();
IndentAttribute indentAttribute = ParseIndentAttrUtils.parseSpace(ss);
h.put(Markup.CSS_KEY_PADDINGTOP, indentAttribute.getTop() + "px");
h.put(Markup.CSS_KEY_PADDINGLEFT, indentAttribute.getLeft() + "px");
h.put(Markup.CSS_KEY_PADDINGBOTTOM, indentAttribute.getBottom() + "px");
h.put(Markup.CSS_KEY_PADDINGRIGHT, indentAttribute.getRight() + "px");
}
else if (key.equals(Markup.CSS_KEY_TEXTALIGN)) {
String ss = prop.getProperty(key).trim().toLowerCase();
h.put("align", ss);
}
}
}
/**
* New method contributed by Lubos Strapko
* @param h
@ -380,12 +423,17 @@ public class FactoryProperties {
return;
}
h.put("leading", v + ",0");
h.put("line-height", ss);
} else if (key.equals(Markup.CSS_KEY_TEXTALIGN)) {
String ss = prop.getProperty(key).trim().toLowerCase();
h.put("align", ss);
} else if (key.equals(Markup.CSS_KEY_PADDINGLEFT)) {
} else if (key.equals(Markup.CSS_KEY_BGCOLOR)) {
String ss = prop.getProperty(key).trim().toLowerCase();
h.put("indent", Float.toString(Markup.parseLength(ss)));
h.put("background", ss);
}
else{
String ss = prop.getProperty(key).trim();
h.put(key, ss);
}
}
}

87
fine-itext-old/src/com/fr/third/com/lowagie/text/html/simpleparser/HTMLWorker.java

@ -50,16 +50,6 @@
package com.fr.third.com.lowagie.text.html.simpleparser;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Stack;
import java.util.StringTokenizer;
import com.fr.third.com.lowagie.text.html.HtmlTags;
import com.fr.third.com.lowagie.text.html.Markup;
import com.fr.third.com.lowagie.text.Chunk;
import com.fr.third.com.lowagie.text.DocListener;
import com.fr.third.com.lowagie.text.DocumentException;
@ -69,15 +59,32 @@ import com.fr.third.com.lowagie.text.ExceptionConverter;
import com.fr.third.com.lowagie.text.FontFactoryImp;
import com.fr.third.com.lowagie.text.HeaderFooter;
import com.fr.third.com.lowagie.text.Image;
import com.fr.third.com.lowagie.text.List;
import com.fr.third.com.lowagie.text.ListItem;
import com.fr.third.com.lowagie.text.Paragraph;
import com.fr.third.com.lowagie.text.Phrase;
import com.fr.third.com.lowagie.text.Rectangle;
import com.fr.third.com.lowagie.text.TextElementArray;
import com.fr.third.com.lowagie.text.html.CSSUtils;
import com.fr.third.com.lowagie.text.html.HtmlTags;
import com.fr.third.com.lowagie.text.html.Markup;
import com.fr.third.com.lowagie.text.pdf.PdfPTable;
import com.fr.third.com.lowagie.text.pdf.draw.LineSeparator;
import com.fr.third.com.lowagie.text.xml.simpleparser.SimpleXMLDocHandler;
import com.fr.third.com.lowagie.text.xml.simpleparser.SimpleXMLParser;
import sun.misc.BASE64Decoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Stack;
import java.util.StringTokenizer;
public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
@ -176,15 +183,23 @@ public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
cprops.addToChain("body", h);
}
public void startElement(String tag, HashMap h) {
if (!tagsSupported.containsKey(tag))
return;
try {
style.applyStyle(tag, h);
if(tag.equals("p")){
h.put(Markup.CSS_KEY_MARGINTOP, "16px");
h.put(Markup.CSS_KEY_MARGINBOTTOM, "16px");
}
String follow = (String) FactoryProperties.followTags.get(tag);
if (follow != null) {
HashMap prop = new HashMap();
prop.put(follow, null);
FactoryProperties.insertStyle(h, this.cprops);
prop.putAll(h);
cprops.addToChain(follow, prop);
return;
}
@ -285,6 +300,19 @@ public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
}
}
}
//处理base64编码图片
if(src.startsWith("data")){
BASE64Decoder decoder = new BASE64Decoder();
String[] srcArray = src.split(",");
String base64string = srcArray[srcArray.length -1];
byte[] bytes = decoder.decodeBuffer(base64string);
try {
img = Image.getInstance(bytes);
}catch (Exception e){
}
}
if (img == null) {
if (!src.startsWith("http")) {
String path = cprops.getProperty("image_path");
@ -294,6 +322,10 @@ public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
}
img = Image.getInstance(src);
}
if(img == null){
return;
}
img.setSrcString(src);
String align = (String) h.get("align");
String width = (String) h.get("width");
String height = (String) h.get("height");
@ -342,12 +374,22 @@ public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
document.add(img);
cprops.removeChain(tag);
} else {
Chunk ck = new Chunk(img, 0, 0);
if(cprops.hasPropertyInChain("img", "padding-left")){
String ss = cprops.getPropertyFromChain("img", "padding-left");
ck.setAttribute("padding-left", Float.toString(Markup.parseLength(ss)));
}
if(cprops.hasPropertyInChain("img", "padding-right")){
String ss = cprops.getPropertyFromChain("img", "padding-right");
ck.setAttribute("padding-right", Float.toString(Markup.parseLength(ss)));
}
cprops.removeChain(tag);
if (currentParagraph == null) {
currentParagraph = FactoryProperties
.createParagraph(cprops);
}
currentParagraph.add(new Chunk(img, 0, 0));
currentParagraph.add(ck);
}
return;
}
@ -366,7 +408,7 @@ public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
endElement(HtmlTags.LISTITEM);
skipText = true;
cprops.addToChain(tag, h);
com.fr.third.com.lowagie.text.List list = new com.fr.third.com.lowagie.text.List(false);
List list = new List(false);
try{
list.setIndentationLeft(new Float(cprops.getProperty("indent")).floatValue());
}catch (Exception e) {
@ -381,7 +423,7 @@ public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
endElement(HtmlTags.LISTITEM);
skipText = true;
cprops.addToChain(tag, h);
com.fr.third.com.lowagie.text.List list = new com.fr.third.com.lowagie.text.List(true);
List list = new List(true);
try{
list.setIndentationLeft(new Float(cprops.getProperty("indent")).floatValue());
}catch (Exception e) {
@ -443,6 +485,8 @@ public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
}
}
public void endElement(String tag) {
if (!tagsSupported.containsKey(tag))
return;
@ -510,7 +554,7 @@ public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
if (stack.empty())
return;
Object obj = stack.pop();
if (!(obj instanceof com.fr.third.com.lowagie.text.List)) {
if (!(obj instanceof List)) {
stack.push(obj);
return;
}
@ -536,12 +580,12 @@ public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
return;
}
Object list = stack.pop();
if (!(list instanceof com.fr.third.com.lowagie.text.List)) {
if (!(list instanceof List)) {
stack.push(list);
return;
}
ListItem item = (ListItem) obj;
((com.fr.third.com.lowagie.text.List) list).add(item);
((List) list).add(item);
ArrayList cks = item.getChunks();
if (!cks.isEmpty())
item.getListSymbol()
@ -588,6 +632,8 @@ public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
if (pendingTD)
endElement("td");
pendingTR = false;
String rowHeightPx = cprops.getLastChainProperty("height");
cprops.removeChain("tr");
ArrayList cells = new ArrayList();
IncTable table = null;
@ -601,8 +647,13 @@ public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
break;
}
}
float rowHeight = 0.0f;
if(rowHeightPx!=null){
rowHeight = CSSUtils.parseFloat(rowHeightPx);
}
table.addCols(cells);
table.endRow();
table.endRow(rowHeight);
stack.push(table);
skipText = true;
return;
@ -705,7 +756,7 @@ public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
}
/**
* @see com.fr.third.com.lowagie.text.DocListener#setMarginMirroring(boolean)
* @see DocListener#setMarginMirroring(boolean)
* @since 2.1.6
*/
public boolean setMarginMirroringTopBottom(boolean marginMirroring) {

45
fine-itext-old/src/com/fr/third/com/lowagie/text/html/simpleparser/HtmlConstants.java

@ -0,0 +1,45 @@
package com.fr.third.com.lowagie.text.html.simpleparser;
import com.fr.third.com.lowagie.text.html.HtmlTags;
import com.fr.third.com.lowagie.text.html.Markup;
import java.util.ArrayList;
import java.util.List;
/**
* @author kerry
* @date 2018/5/2
*/
public class HtmlConstants {
//块级元素集合
public static final List<String> BLOCK_ELEMENTS = new ArrayList<String>();
//行内元素集合
public static final List<String> INLINE_ELEMENTS = new ArrayList<String>();
//支持解析的属性
public static final List<String> PADDING = new ArrayList<String>();
public static final List<String> MARGIN = new ArrayList<String>();
static {
BLOCK_ELEMENTS.add(HtmlTags.DIV);
BLOCK_ELEMENTS.add(HtmlTags.UNORDEREDLIST);
BLOCK_ELEMENTS.add(HtmlTags.PARAGRAPH);
BLOCK_ELEMENTS.add(HtmlTags.ORDEREDLIST);
BLOCK_ELEMENTS.add(HtmlTags.TABLE);
INLINE_ELEMENTS.add(HtmlTags.SPAN);
INLINE_ELEMENTS.add(HtmlTags.IMAGE);
INLINE_ELEMENTS.add(HtmlTags.STRONG);
INLINE_ELEMENTS.add(HtmlTags.ANCHOR);
INLINE_ELEMENTS.add(HtmlTags.SUB);
INLINE_ELEMENTS.add(HtmlTags.SUP);
INLINE_ELEMENTS.add(HtmlTags.I);
INLINE_ELEMENTS.add(HtmlTags.U);
INLINE_ELEMENTS.add(HtmlTags.EM);
PADDING.add(Markup.CSS_KEY_PADDINGLEFT);
PADDING.add(Markup.CSS_KEY_PADDINGRIGHT);
PADDING.add(Markup.CSS_KEY_PADDINGTOP);
PADDING.add(Markup.CSS_KEY_PADDINGBOTTOM);
MARGIN.add(Markup.CSS_KEY_MARGINLEFT);
MARGIN.add(Markup.CSS_KEY_MARGINRIGHT);
MARGIN.add(Markup.CSS_KEY_MARGINTOP);
MARGIN.add(Markup.CSS_KEY_MARGINBOTTOM);
}
}

76
fine-itext-old/src/com/fr/third/com/lowagie/text/html/simpleparser/IncCell.java

@ -48,13 +48,17 @@
package com.fr.third.com.lowagie.text.html.simpleparser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.fr.third.com.lowagie.text.Element;
import com.fr.third.com.lowagie.text.ElementListener;
import com.fr.third.com.lowagie.text.Phrase;
import com.fr.third.com.lowagie.text.TextElementArray;
import com.fr.third.com.lowagie.text.html.CSSUtils;
import com.fr.third.com.lowagie.text.html.Markup;
import com.fr.third.com.lowagie.text.pdf.PdfPCell;
import com.fr.third.com.lowagie.text.Phrase;
/**
*
* @author psoares
@ -94,14 +98,52 @@ public class IncCell implements TextElementArray {
value = props.getProperty("border");
float border = 0;
if (value != null)
border = Float.parseFloat(value);
border = CSSUtils.parseFloat(value);
cell.setBorderWidth(border);
value = props.getProperty("cellpadding");
if (value != null)
cell.setPadding(Float.parseFloat(value));
cell.setPadding(CSSUtils.parseFloat(value));
cell.setUseDescender(true);
value = props.getProperty("bgcolor");
cell.setBackgroundColor(Markup.decodeColor(value));
//解析td上声明的width
value = props.getLastChainProperty("width");
if(value != null){
cell.setStyleWidth(CSSUtils.parseFloat(value));
}
//解析td上声明的height
value = props.getLastChainProperty("height");
if(value != null){
cell.setStyleHeight(CSSUtils.parseFloat(value));
}
//解析background相关属性并保存到cell对象
Map<String, String> backgroundRules = new HashMap<String, String>();
value = props.getLastChainProperty("background-size");
if(value!=null){
backgroundRules.put("background-size", value);
}
value = props.getLastChainProperty("background");
if(value!=null){
Map<String, String> backgroundStyles = CSSUtils.processBackground(value);
backgroundRules.putAll(backgroundStyles);
}
value = props.getLastChainProperty("background-color");
if(value!=null){
backgroundRules.put("background-color", value);
}
value = props.getLastChainProperty("background-position");
if(value!=null){
backgroundRules.put("background-position", value);
}
value = props.getLastChainProperty("background-repeat");
if(value!=null){
backgroundRules.put("background-repeat", value);
}
value = props.getLastChainProperty("background-image");
if(value!=null){
backgroundRules.put("background-image", value);
}
cell.setBackground(backgroundRules);
}
public boolean add(Object o) {
@ -127,19 +169,19 @@ public class IncCell implements TextElementArray {
return cell;
}
/**
* @see com.fr.third.com.lowagie.text.Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return true;
}
/**
* @see Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return true;
}
/**
* @see com.fr.third.com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return true;
}
/**
* @see Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return true;
}
}

100
fine-itext-old/src/com/fr/third/com/lowagie/text/html/simpleparser/IncTable.java

@ -51,8 +51,12 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import com.fr.third.com.lowagie.text.pdf.PdfPCell;
import com.fr.third.com.lowagie.text.html.CSSUtils;
import com.fr.third.com.lowagie.text.html.Markup;
import com.fr.third.com.lowagie.text.pdf.BorderStyle;
import com.fr.third.com.lowagie.text.pdf.PdfPTable;
import com.fr.third.com.lowagie.text.pdf.PdfPCell;
import com.fr.third.com.lowagie.text.pdf.TableProperties;
/**
*
@ -62,6 +66,8 @@ public class IncTable {
private HashMap props = new HashMap();
private ArrayList rows = new ArrayList();
private ArrayList cols;
private ArrayList<Float> rowHeights = new ArrayList<Float>();
/** Creates a new instance of IncTable */
public IncTable(HashMap props) {
this.props.putAll(props);
@ -80,7 +86,8 @@ public class IncTable {
cols.addAll(ncols);
}
public void endRow() {
public void endRow(float rowHeight) {
rowHeights.add(rowHeight);
if (cols != null) {
Collections.reverse(cols);
rows.add(cols);
@ -97,27 +104,88 @@ public class IncTable {
return new PdfPTable(1);
int ncol = 0;
ArrayList c0 = (ArrayList)rows.get(0);
ArrayList<Float> colWidths = new ArrayList<Float>();
for (int k = 0; k < c0.size(); ++k) {
ncol += ((PdfPCell)c0.get(k)).getColspan();
PdfPCell pCell = ((PdfPCell)c0.get(k));
int cellCols = pCell.getColspan();
ncol += cellCols;
if(cellCols > 1){
for(int a = 0; a < cellCols ; a++){
colWidths.add(pCell.getStyleWidth()/cellCols);
}
}else {
colWidths.add(pCell.getStyleWidth());
}
}
PdfPTable table = new PdfPTable(ncol);
String width = (String)props.get("width");
if (width == null)
table.setWidthPercentage(100);
else {
if (width.endsWith("%"))
table.setWidthPercentage(Float.parseFloat(width.substring(0, width.length() - 1)));
try {
TableProperties tableProperties = parseTableProperties();
table.setTableProperties(tableProperties);
String width = (String)props.get("width");
if (width == null)
table.setWidthPercentage(100);
else {
table.setTotalWidth(Float.parseFloat(width));
table.setLockedWidth(true);
if (width.endsWith("%"))
table.setWidthPercentage(CSSUtils.parseFloat(width));
else {
//解析单元格宽度
float totalWidth = CSSUtils.parseFloat(width);
float[] floats = new float[colWidths.size()];
for (int a = 0; a < colWidths.size(); a++){
floats[a] = colWidths.get(a);
}
//解析px数值
table.setTotalWidth(totalWidth);
try {
table.setWidths(floats);
}catch (Exception e){
e.printStackTrace();
}
table.setLockedWidth(true);
}
}
}
for (int row = 0; row < rows.size(); ++row) {
ArrayList col = (ArrayList)rows.get(row);
for (int k = 0; k < col.size(); ++k) {
table.addCell((PdfPCell)col.get(k));
for (int row = 0; row < rows.size(); ++row) {
ArrayList col = (ArrayList)rows.get(row);
for (int k = 0; k < col.size(); ++k) {
table.addCell((PdfPCell)col.get(k));
}
}
//调整行高
for(int a = 0; a < rowHeights.size(); a++){
table.getRow(a).setStyleHeight(rowHeights.get(a));
}
}catch (Exception e){
e.printStackTrace();
}
return table;
}
public TableProperties parseTableProperties(){
TableProperties tableProperties = new TableProperties();
BorderStyle borderStyle = new BorderStyle();
tableProperties.setBorderStyle(borderStyle);
String value = (String)props.get("border");
if(value != null){
borderStyle.setBorderWidth(CSSUtils.parseFloat(value));
}
value = (String)props.get("border-color");
if(value != null){
borderStyle.setBorderColor(Markup.decodeColor(value));
}
value = (String)props.get("border-collapse");
if(value != null){
tableProperties.setCollapse(value.equals("collapse"));
}
value = (String)props.get("cellspacing");
if(value != null){
tableProperties.setCellspacing(CSSUtils.parseFloat(value));
}
value = (String)props.get("cellpadding");
if(value != null){
tableProperties.setCellpadding(CSSUtils.parseFloat(value));
}
return tableProperties;
}
}

58
fine-itext-old/src/com/fr/third/com/lowagie/text/pdf/BorderStyle.java

@ -0,0 +1,58 @@
package com.fr.third.com.lowagie.text.pdf;
import com.fr.third.com.lowagie.text.DocumentException;
import com.fr.third.com.lowagie.text.html.CSSUtils;
import com.fr.third.com.lowagie.text.html.Markup;
import java.awt.Color;
public class BorderStyle {
private float borderWidth = 0.0f;
private Color borderColor = Color.black;
private String borderPattern = "solid";
public float getBorderWidth() {
return borderWidth;
}
public void setBorderWidth(float borderWidth) {
this.borderWidth = borderWidth;
}
public Color getBorderColor() {
return borderColor;
}
public void setBorderColor(Color borderColor) {
this.borderColor = borderColor;
}
public String getBorderPattern() {
return borderPattern;
}
public void setBorderPattern(String borderPattern) {
this.borderPattern = borderPattern;
}
public BorderStyle() {
}
public BorderStyle(int borderWidth, String borderPattern, Color borderColor) {
this.borderWidth = borderWidth;
this.borderPattern = borderPattern;
this.borderWidth = borderWidth;
}
public static BorderStyle parseBorderStyle(String borderString) throws DocumentException {
BorderStyle borderStyle = new BorderStyle();
String[] borderPros = borderString.split(" ");
borderStyle.setBorderWidth(CSSUtils.parseFloat(borderPros[0]));
borderStyle.setBorderPattern(borderPros[1]);
borderStyle.setBorderColor(Markup.decodeColor(borderPros[2]));
return borderStyle;
}
}

269
fine-itext-old/src/com/fr/third/com/lowagie/text/pdf/PdfPCell.java

@ -50,21 +50,53 @@
package com.fr.third.com.lowagie.text.pdf;
import java.util.List;
import java.util.Map;
import com.fr.Container;
import com.fr.third.com.lowagie.text.Chunk;
import com.fr.third.com.lowagie.text.DocumentException;
import com.fr.third.com.lowagie.text.Element;
import com.fr.third.com.lowagie.text.ExceptionConverter;
import com.fr.third.com.lowagie.text.Image;
import com.fr.third.com.lowagie.text.Phrase;
import com.fr.third.com.lowagie.text.Rectangle;
import com.fr.third.com.lowagie.text.pdf.events.PdfPCellEventForwarder;
import com.fr.third.com.lowagie.text.Phrase;
/**
* A cell in a PdfPTable.
*/
public class PdfPCell extends Rectangle{
public class PdfPCell extends Rectangle {
private float styleWidth = 0.0f;
private float styleHeight = 0.0f;
public float getStyleHeight() {
return styleHeight;
}
public void setStyleHeight(float styleHeight) {
this.styleHeight = styleHeight;
}
public float getStyleWidth() {
return styleWidth;
}
public Map<String, String> background ;
public Map<String, String> getBackground() {
return background;
}
public void setBackground(Map<String, String> background) {
this.background = background;
}
public void setStyleWidth(float styleWidth) {
this.styleWidth = styleWidth;
}
private ColumnText column = new ColumnText(null);
@ -212,21 +244,21 @@ public class PdfPCell extends Rectangle{
table.setExtendLastRow(true);
column.addElement(table);
if (style != null) {
cloneNonPositionParameters(style);
verticalAlignment = style.verticalAlignment;
paddingLeft = style.paddingLeft;
paddingRight = style.paddingRight;
paddingTop = style.paddingTop;
paddingBottom = style.paddingBottom;
colspan = style.colspan;
rowspan = style.rowspan;
cellEvent = style.cellEvent;
useDescender = style.useDescender;
useBorderPadding = style.useBorderPadding;
rotation = style.rotation;
cloneNonPositionParameters(style);
verticalAlignment = style.verticalAlignment;
paddingLeft = style.paddingLeft;
paddingRight = style.paddingRight;
paddingTop = style.paddingTop;
paddingBottom = style.paddingBottom;
colspan = style.colspan;
rowspan = style.rowspan;
cellEvent = style.cellEvent;
useDescender = style.useDescender;
useBorderPadding = style.useBorderPadding;
rotation = style.rotation;
}
else
setPadding(0);
setPadding(0);
}
/**
@ -256,6 +288,9 @@ public class PdfPCell extends Rectangle{
column = ColumnText.duplicate(cell.column);
useBorderPadding = cell.useBorderPadding;
rotation = cell.rotation;
background = cell.background;
styleWidth = cell.styleWidth;
styleHeight = cell.styleHeight;
}
/**
@ -339,11 +374,11 @@ public class PdfPCell extends Rectangle{
* @return effective value of property paddingLeft.
*/
public float getEffectivePaddingLeft() {
if (isUseBorderPadding()) {
float border = getBorderWidthLeft() / (isUseVariableBorders() ? 1f : 2f);
return paddingLeft + border;
}
return paddingLeft;
if (isUseBorderPadding()) {
float border = getBorderWidthLeft() / (isUseVariableBorders() ? 1f : 2f);
return paddingLeft + border;
}
return paddingLeft;
}
/**
@ -369,11 +404,11 @@ public class PdfPCell extends Rectangle{
* @return effective value of property paddingRight.
*/
public float getEffectivePaddingRight() {
if (isUseBorderPadding()) {
float border = getBorderWidthRight() / (isUseVariableBorders() ? 1f : 2f);
return paddingRight + border;
}
return paddingRight;
if (isUseBorderPadding()) {
float border = getBorderWidthRight() / (isUseVariableBorders() ? 1f : 2f);
return paddingRight + border;
}
return paddingRight;
}
/**
@ -401,10 +436,10 @@ public class PdfPCell extends Rectangle{
* @return effective value of property paddingTop.
*/
public float getEffectivePaddingTop() {
if (isUseBorderPadding()) {
float border = getBorderWidthTop()/(isUseVariableBorders()?1f:2f);
return paddingTop + border;
}
if (isUseBorderPadding()) {
float border = getBorderWidthTop()/(isUseVariableBorders()?1f:2f);
return paddingTop + border;
}
return paddingTop;
}
@ -434,10 +469,10 @@ public class PdfPCell extends Rectangle{
* @return effective value of property paddingBottom.
*/
public float getEffectivePaddingBottom() {
if (isUseBorderPadding()) {
float border = getBorderWidthBottom()/(isUseVariableBorders()?1f:2f);
return paddingBottom + border;
}
if (isUseBorderPadding()) {
float border = getBorderWidthBottom()/(isUseVariableBorders()?1f:2f);
return paddingBottom + border;
}
return paddingBottom;
}
@ -583,7 +618,7 @@ public class PdfPCell extends Rectangle{
* @since 2.1.5
*/
public boolean hasFixedHeight() {
return getFixedHeight() > 0;
return getFixedHeight() > 0;
}
/**
@ -613,7 +648,7 @@ public class PdfPCell extends Rectangle{
* @since 2.1.5
*/
public boolean hasMinimumHeight() {
return getMinimumHeight() > 0;
return getMinimumHeight() > 0;
}
/**
@ -808,18 +843,18 @@ public class PdfPCell extends Rectangle{
* @param cellEvent the cell event
*/
public void setCellEvent(PdfPCellEvent cellEvent) {
if (cellEvent == null)
this.cellEvent = null;
else if (this.cellEvent == null)
this.cellEvent = cellEvent;
else if (this.cellEvent instanceof PdfPCellEventForwarder)
((PdfPCellEventForwarder)this.cellEvent).addCellEvent(cellEvent);
else {
PdfPCellEventForwarder forward = new PdfPCellEventForwarder();
forward.addCellEvent(this.cellEvent);
forward.addCellEvent(cellEvent);
this.cellEvent = forward;
}
if (cellEvent == null)
this.cellEvent = null;
else if (this.cellEvent == null)
this.cellEvent = cellEvent;
else if (this.cellEvent instanceof PdfPCellEventForwarder)
((PdfPCellEventForwarder)this.cellEvent).addCellEvent(cellEvent);
else {
PdfPCellEventForwarder forward = new PdfPCellEventForwarder();
forward.addCellEvent(this.cellEvent);
forward.addCellEvent(cellEvent);
this.cellEvent = forward;
}
}
/**
@ -894,7 +929,7 @@ public class PdfPCell extends Rectangle{
* @since 2.1.1
*/
public List getCompositeElements() {
return getColumn().compositeElements;
return getColumn().compositeElements;
}
/**
@ -943,71 +978,81 @@ public class PdfPCell extends Rectangle{
column.setSimpleColumn(leftLimit, bry + 0.001f, rightLimit, 0);
}
else {
column.setSimpleColumn(0, leftLimit, bry + 0.001f, rightLimit);
column.setSimpleColumn(0, leftLimit, bry + 0.001f, rightLimit);
}
try {
column.go(true);
} catch (DocumentException e) {
// do nothing
}
}
/**
* Returns the height of the cell.
* @return the height of the cell
* @since 3.0.0
*/
public float getMaxHeight() {
boolean pivoted = (getRotation() == 90 || getRotation() == 270);
Image img = getImage();
if (img != null) {
img.scalePercent(100);
float refWidth = pivoted ? img.getScaledHeight() : img.getScaledWidth();
float scale = (getRight() - getEffectivePaddingRight()
column.go(true);
} catch (DocumentException e) {
// do nothing
}
}
/**
* Returns the height of the cell.
* @return the height of the cell
* @since 3.0.0
*/
public float getMaxHeight() {
boolean pivoted = (getRotation() == 90 || getRotation() == 270);
Image img = getImage();
if (img != null) {
img.scalePercent(100);
float refWidth = pivoted ? img.getScaledHeight() : img.getScaledWidth();
float scale = (getRight() - getEffectivePaddingRight()
- getEffectivePaddingLeft() - getLeft()) / refWidth;
img.scalePercent(scale * 100);
float refHeight = pivoted ? img.getScaledWidth() : img.getScaledHeight();
setBottom(getTop() - getEffectivePaddingTop() - getEffectivePaddingBottom() - refHeight);
}
else {
if (pivoted && hasFixedHeight())
setBottom(getTop() - getFixedHeight());
else {
ColumnText ct = ColumnText.duplicate(getColumn());
float right, top, left, bottom;
if (pivoted) {
right = PdfPRow.RIGHT_LIMIT;
top = getRight() - getEffectivePaddingRight();
left = 0;
bottom = getLeft() + getEffectivePaddingLeft();
}
else {
right = isNoWrap() ? PdfPRow.RIGHT_LIMIT : getRight() - getEffectivePaddingRight();
top = getTop() - getEffectivePaddingTop();
left = getLeft() + getEffectivePaddingLeft();
bottom = hasFixedHeight() ? top + getEffectivePaddingBottom() - getFixedHeight() : PdfPRow.BOTTOM_LIMIT;
}
PdfPRow.setColumn(ct, left, bottom, right, top);
try {
ct.go(true);
} catch (DocumentException e) {
throw new ExceptionConverter(e);
}
if (pivoted)
setBottom(getTop() - getEffectivePaddingTop() - getEffectivePaddingBottom() - ct.getFilledWidth());
else {
float yLine = ct.getYLine();
if (isUseDescender())
yLine += ct.getDescender();
setBottom(yLine - getEffectivePaddingBottom());
}
}
}
float height = getHeight();
if (height < getFixedHeight())
height = getFixedHeight();
else if (height < getMinimumHeight())
height = getMinimumHeight();
return height;
}
img.scalePercent(scale * 100);
float refHeight = pivoted ? img.getScaledWidth() : img.getScaledHeight();
setBottom(getTop() - getEffectivePaddingTop() - getEffectivePaddingBottom() - refHeight);
}
else {
if (pivoted && hasFixedHeight())
setBottom(getTop() - getFixedHeight());
else {
ColumnText ct = ColumnText.duplicate(getColumn());
float right, top, left, bottom;
if (pivoted) {
right = PdfPRow.RIGHT_LIMIT;
top = getRight() - getEffectivePaddingRight();
left = 0;
bottom = getLeft() + getEffectivePaddingLeft();
}
else {
right = isNoWrap() ? PdfPRow.RIGHT_LIMIT : getRight() - getEffectivePaddingRight();
top = getTop() - getEffectivePaddingTop();
left = getLeft() + getEffectivePaddingLeft();
bottom = hasFixedHeight() ? top + getEffectivePaddingBottom() - getFixedHeight() : PdfPRow.BOTTOM_LIMIT;
}
PdfPRow.setColumn(ct, left, bottom, right, top);
try {
ct.go(true);
} catch (DocumentException e) {
throw new ExceptionConverter(e);
}
if (pivoted)
setBottom(getTop() - getEffectivePaddingTop() - getEffectivePaddingBottom() - ct.getFilledWidth());
else {
float yLine = ct.getYLine();
if (isUseDescender())
yLine += ct.getDescender();
setBottom(yLine - getEffectivePaddingBottom());
}
}
}
float height = getHeight();
if (height < getFixedHeight())
height = getFixedHeight();
else if (height < getMinimumHeight())
height = getMinimumHeight();
return height;
}
private Container container;
public Container getContainer() {
return container;
}
public void addContent(Container container){
this.container = container;
}
}

432
fine-itext-old/src/com/fr/third/com/lowagie/text/pdf/PdfPRow.java

@ -51,9 +51,9 @@ package com.fr.third.com.lowagie.text.pdf;
import java.awt.Color;
import com.fr.third.com.lowagie.text.ExceptionConverter;
import com.fr.third.com.lowagie.text.DocumentException;
import com.fr.third.com.lowagie.text.Element;
import com.fr.third.com.lowagie.text.ExceptionConverter;
import com.fr.third.com.lowagie.text.Image;
import com.fr.third.com.lowagie.text.Rectangle;
@ -76,6 +76,16 @@ public class PdfPRow {
protected float widths[];
private float styleHeight;
public float getStyleHeight() {
return styleHeight;
}
public void setStyleHeight(float styleHeight) {
this.styleHeight = styleHeight;
}
/**
* extra heights that needs to be added to a cell because of rowspans.
* @since 2.1.6
@ -86,7 +96,7 @@ public class PdfPRow {
protected boolean calculated = false;
private int[] canvasesPos;
private int[] canvasesPos;
/**
* Constructs a new PdfPRow with the cells in the array that was passed
@ -179,37 +189,23 @@ public class PdfPRow {
*/
public float calculateHeights() {
maxHeight = 0;
// @change
int rowSpan = Integer.MAX_VALUE;
boolean hasAboveRowSpan = false;
float max_height = 0.0f;
for (int k = 0; k < cells.length;) {
for (int k = 0; k < cells.length; ++k) {
PdfPCell cell = cells[k];
float height = 0;
if (cell == null) {
hasAboveRowSpan = true;
k++;
continue;
}
else {
height = cell.getMaxHeight();
if (cell.getRowspan() == rowSpan && height > max_height) {
max_height = height;
} else if (cell.getRowspan() < rowSpan) {
rowSpan = cell.getRowspan();
max_height = height;
}
k += cell.getColspan();
height = cell.getStyleHeight() == 0 ? cell.getContainer().getHeight() : cell.getStyleHeight();
if ((height > maxHeight) && (cell.getRowspan() == 1))
maxHeight = height;
}
}
calculated = true;
// carl:假如有格子是从属于一个rowSpan的格子,而这个格子的主格不在这一行(当然这样的假设建立在格子是满的情况下。)
if (!hasAboveRowSpan || rowSpan == 1) {
maxHeight = max_height;
}
return maxHeight;
return maxHeight = Math.max(styleHeight, maxHeight);
}
/**
* Writes the border and background of one cell in the row.
*
@ -250,44 +246,44 @@ public class PdfPRow {
/**
* @since 2.1.6 private is now protected
*/
protected void saveAndRotateCanvases(PdfContentByte[] canvases, float a, float b, float c, float d, float e, float f) {
int last = PdfPTable.TEXTCANVAS + 1;
if (canvasesPos == null)
canvasesPos = new int[last * 2];
for (int k = 0; k < last; ++k) {
ByteBuffer bb = canvases[k].getInternalBuffer();
canvasesPos[k * 2] = bb.size();
canvases[k].saveState();
canvases[k].concatCTM(a, b, c, d, e, f);
canvasesPos[k * 2 + 1] = bb.size();
}
}
protected void saveAndRotateCanvases(PdfContentByte[] canvases, float a, float b, float c, float d, float e, float f) {
int last = PdfPTable.TEXTCANVAS + 1;
if (canvasesPos == null)
canvasesPos = new int[last * 2];
for (int k = 0; k < last; ++k) {
ByteBuffer bb = canvases[k].getInternalBuffer();
canvasesPos[k * 2] = bb.size();
canvases[k].saveState();
canvases[k].concatCTM(a, b, c, d, e, f);
canvasesPos[k * 2 + 1] = bb.size();
}
}
/**
* @since 2.1.6 private is now protected
*/
protected void restoreCanvases(PdfContentByte[] canvases) {
int last = PdfPTable.TEXTCANVAS + 1;
for (int k = 0; k < last; ++k) {
ByteBuffer bb = canvases[k].getInternalBuffer();
int p1 = bb.size();
canvases[k].restoreState();
if (p1 == canvasesPos[k * 2 + 1])
bb.setSize(canvasesPos[k * 2]);
}
}
protected void restoreCanvases(PdfContentByte[] canvases) {
int last = PdfPTable.TEXTCANVAS + 1;
for (int k = 0; k < last; ++k) {
ByteBuffer bb = canvases[k].getInternalBuffer();
int p1 = bb.size();
canvases[k].restoreState();
if (p1 == canvasesPos[k * 2 + 1])
bb.setSize(canvasesPos[k * 2]);
}
}
/**
* @since 3.0.0 protected is now public static
*/
public static float setColumn(ColumnText ct, float left, float bottom, float right, float top) {
if (left > right)
right = left;
if (bottom > top)
top = bottom;
ct.setSimpleColumn(left, bottom, right, top);
return top;
}
public static float setColumn(ColumnText ct, float left, float bottom, float right, float top) {
if (left > right)
right = left;
if (bottom > top)
top = bottom;
ct.setSimpleColumn(left, bottom, right, top);
return top;
}
/**
* Writes a number of cells (not necessarily all cells).
@ -338,23 +334,23 @@ public class PdfPRow {
float tly = cell.getTop() + yPos - cell.getEffectivePaddingTop();
if (cell.getHeight() <= currentMaxHeight) {
switch (cell.getVerticalAlignment()) {
case Element.ALIGN_BOTTOM:
tly = cell.getTop() + yPos - currentMaxHeight + cell.getHeight()
- cell.getEffectivePaddingTop();
break;
case Element.ALIGN_MIDDLE:
tly = cell.getTop() + yPos + (cell.getHeight() - currentMaxHeight) / 2
- cell.getEffectivePaddingTop();
break;
default:
break;
case Element.ALIGN_BOTTOM:
tly = cell.getTop() + yPos - currentMaxHeight + cell.getHeight()
- cell.getEffectivePaddingTop();
break;
case Element.ALIGN_MIDDLE:
tly = cell.getTop() + yPos + (cell.getHeight() - currentMaxHeight) / 2
- cell.getEffectivePaddingTop();
break;
default:
break;
}
}
if (img != null) {
if (cell.getRotation() != 0) {
img = Image.getInstance(img);
img.setRotation(img.getImageRotation() + (float)(cell.getRotation() * Math.PI / 180.0));
}
if (cell.getRotation() != 0) {
img = Image.getInstance(img);
img.setRotation(img.getImageRotation() + (float)(cell.getRotation() * Math.PI / 180.0));
}
boolean vf = false;
if (cell.getHeight() > currentMaxHeight) {
img.scalePercent(100);
@ -368,20 +364,20 @@ public class PdfPRow {
+ cell.getEffectivePaddingLeft();
if (vf) {
switch (cell.getHorizontalAlignment()) {
case Element.ALIGN_CENTER:
left = xPos
+ (cell.getLeft() + cell.getEffectivePaddingLeft()
+ cell.getRight()
- cell.getEffectivePaddingRight() - img
.getScaledWidth()) / 2;
break;
case Element.ALIGN_RIGHT:
left = xPos + cell.getRight()
- cell.getEffectivePaddingRight()
- img.getScaledWidth();
break;
default:
break;
case Element.ALIGN_CENTER:
left = xPos
+ (cell.getLeft() + cell.getEffectivePaddingLeft()
+ cell.getRight()
- cell.getEffectivePaddingRight() - img
.getScaledWidth()) / 2;
break;
case Element.ALIGN_RIGHT:
left = xPos + cell.getRight()
- cell.getEffectivePaddingRight()
- img.getScaledWidth();
break;
default:
break;
}
tly = cell.getTop() + yPos - cell.getEffectivePaddingTop();
}
@ -392,128 +388,128 @@ public class PdfPRow {
throw new ExceptionConverter(e);
}
} else {
// rotation sponsored by Connection GmbH
if (cell.getRotation() == 90 || cell.getRotation() == 270) {
float netWidth = currentMaxHeight - cell.getEffectivePaddingTop() - cell.getEffectivePaddingBottom();
float netHeight = cell.getWidth() - cell.getEffectivePaddingLeft() - cell.getEffectivePaddingRight();
ColumnText ct = ColumnText.duplicate(cell.getColumn());
ct.setCanvases(canvases);
ct.setSimpleColumn(0, 0, netWidth + 0.001f, -netHeight);
try {
ct.go(true);
} catch (DocumentException e) {
throw new ExceptionConverter(e);
}
float calcHeight = -ct.getYLine();
if (netWidth <= 0 || netHeight <= 0)
calcHeight = 0;
if (calcHeight > 0) {
if (cell.isUseDescender())
calcHeight -= ct.getDescender();
ct = ColumnText.duplicate(cell.getColumn());
ct.setCanvases(canvases);
ct.setSimpleColumn(-0.003f, -0.001f, netWidth + 0.003f, calcHeight);
float pivotX;
float pivotY;
if (cell.getRotation() == 90) {
pivotY = cell.getTop() + yPos - currentMaxHeight + cell.getEffectivePaddingBottom();
switch (cell.getVerticalAlignment()) {
case Element.ALIGN_BOTTOM:
pivotX = cell.getLeft() + xPos + cell.getWidth() - cell.getEffectivePaddingRight();
break;
case Element.ALIGN_MIDDLE:
pivotX = cell.getLeft() + xPos + (cell.getWidth() + cell.getEffectivePaddingLeft() - cell.getEffectivePaddingRight() + calcHeight) / 2;
break;
default: //top
pivotX = cell.getLeft() + xPos + cell.getEffectivePaddingLeft() + calcHeight;
break;
}
saveAndRotateCanvases(canvases, 0,1,-1,0,pivotX,pivotY);
}
else {
pivotY = cell.getTop() + yPos - cell.getEffectivePaddingTop();
switch (cell.getVerticalAlignment()) {
case Element.ALIGN_BOTTOM:
pivotX = cell.getLeft() + xPos + cell.getEffectivePaddingLeft();
break;
case Element.ALIGN_MIDDLE:
pivotX = cell.getLeft() + xPos + (cell.getWidth() + cell.getEffectivePaddingLeft() - cell.getEffectivePaddingRight() - calcHeight) / 2;
break;
default: //top
pivotX = cell.getLeft() + xPos + cell.getWidth() - cell.getEffectivePaddingRight() - calcHeight;
break;
}
saveAndRotateCanvases(canvases, 0,-1,1,0,pivotX,pivotY);
}
try {
ct.go();
} catch (DocumentException e) {
throw new ExceptionConverter(e);
} finally {
restoreCanvases(canvases);
}
}
}
else {
float fixedHeight = cell.getFixedHeight();
float rightLimit = cell.getRight() + xPos
- cell.getEffectivePaddingRight();
float leftLimit = cell.getLeft() + xPos
+ cell.getEffectivePaddingLeft();
if (cell.isNoWrap()) {
switch (cell.getHorizontalAlignment()) {
case Element.ALIGN_CENTER:
rightLimit += 10000;
leftLimit -= 10000;
break;
case Element.ALIGN_RIGHT:
if (cell.getRotation() == 180) {
rightLimit += RIGHT_LIMIT;
}
else {
leftLimit -= RIGHT_LIMIT;
}
break;
default:
if (cell.getRotation() == 180) {
leftLimit -= RIGHT_LIMIT;
}
else {
rightLimit += RIGHT_LIMIT;
}
break;
}
}
ColumnText ct = ColumnText.duplicate(cell.getColumn());
ct.setCanvases(canvases);
float bry = tly
- (currentMaxHeight
- cell.getEffectivePaddingTop() - cell.getEffectivePaddingBottom());
if (fixedHeight > 0) {
if (cell.getHeight() > currentMaxHeight) {
tly = cell.getTop() + yPos - cell.getEffectivePaddingTop();
bry = cell.getTop() + yPos - currentMaxHeight + cell.getEffectivePaddingBottom();
}
}
if ((tly > bry || ct.zeroHeightElement()) && leftLimit < rightLimit) {
ct.setSimpleColumn(leftLimit, bry - 0.001f, rightLimit, tly);
if (cell.getRotation() == 180) {
float shx = leftLimit + rightLimit;
float shy = yPos + yPos - currentMaxHeight + cell.getEffectivePaddingBottom() - cell.getEffectivePaddingTop();
saveAndRotateCanvases(canvases, -1,0,0,-1,shx,shy);
}
try {
ct.go();
} catch (DocumentException e) {
throw new ExceptionConverter(e);
} finally {
if (cell.getRotation() == 180) {
restoreCanvases(canvases);
}
}
}
}
}
// rotation sponsored by Connection GmbH
if (cell.getRotation() == 90 || cell.getRotation() == 270) {
float netWidth = currentMaxHeight - cell.getEffectivePaddingTop() - cell.getEffectivePaddingBottom();
float netHeight = cell.getWidth() - cell.getEffectivePaddingLeft() - cell.getEffectivePaddingRight();
ColumnText ct = ColumnText.duplicate(cell.getColumn());
ct.setCanvases(canvases);
ct.setSimpleColumn(0, 0, netWidth + 0.001f, -netHeight);
try {
ct.go(true);
} catch (DocumentException e) {
throw new ExceptionConverter(e);
}
float calcHeight = -ct.getYLine();
if (netWidth <= 0 || netHeight <= 0)
calcHeight = 0;
if (calcHeight > 0) {
if (cell.isUseDescender())
calcHeight -= ct.getDescender();
ct = ColumnText.duplicate(cell.getColumn());
ct.setCanvases(canvases);
ct.setSimpleColumn(-0.003f, -0.001f, netWidth + 0.003f, calcHeight);
float pivotX;
float pivotY;
if (cell.getRotation() == 90) {
pivotY = cell.getTop() + yPos - currentMaxHeight + cell.getEffectivePaddingBottom();
switch (cell.getVerticalAlignment()) {
case Element.ALIGN_BOTTOM:
pivotX = cell.getLeft() + xPos + cell.getWidth() - cell.getEffectivePaddingRight();
break;
case Element.ALIGN_MIDDLE:
pivotX = cell.getLeft() + xPos + (cell.getWidth() + cell.getEffectivePaddingLeft() - cell.getEffectivePaddingRight() + calcHeight) / 2;
break;
default: //top
pivotX = cell.getLeft() + xPos + cell.getEffectivePaddingLeft() + calcHeight;
break;
}
saveAndRotateCanvases(canvases, 0,1,-1,0,pivotX,pivotY);
}
else {
pivotY = cell.getTop() + yPos - cell.getEffectivePaddingTop();
switch (cell.getVerticalAlignment()) {
case Element.ALIGN_BOTTOM:
pivotX = cell.getLeft() + xPos + cell.getEffectivePaddingLeft();
break;
case Element.ALIGN_MIDDLE:
pivotX = cell.getLeft() + xPos + (cell.getWidth() + cell.getEffectivePaddingLeft() - cell.getEffectivePaddingRight() - calcHeight) / 2;
break;
default: //top
pivotX = cell.getLeft() + xPos + cell.getWidth() - cell.getEffectivePaddingRight() - calcHeight;
break;
}
saveAndRotateCanvases(canvases, 0,-1,1,0,pivotX,pivotY);
}
try {
ct.go();
} catch (DocumentException e) {
throw new ExceptionConverter(e);
} finally {
restoreCanvases(canvases);
}
}
}
else {
float fixedHeight = cell.getFixedHeight();
float rightLimit = cell.getRight() + xPos
- cell.getEffectivePaddingRight();
float leftLimit = cell.getLeft() + xPos
+ cell.getEffectivePaddingLeft();
if (cell.isNoWrap()) {
switch (cell.getHorizontalAlignment()) {
case Element.ALIGN_CENTER:
rightLimit += 10000;
leftLimit -= 10000;
break;
case Element.ALIGN_RIGHT:
if (cell.getRotation() == 180) {
rightLimit += RIGHT_LIMIT;
}
else {
leftLimit -= RIGHT_LIMIT;
}
break;
default:
if (cell.getRotation() == 180) {
leftLimit -= RIGHT_LIMIT;
}
else {
rightLimit += RIGHT_LIMIT;
}
break;
}
}
ColumnText ct = ColumnText.duplicate(cell.getColumn());
ct.setCanvases(canvases);
float bry = tly
- (currentMaxHeight
- cell.getEffectivePaddingTop() - cell.getEffectivePaddingBottom());
if (fixedHeight > 0) {
if (cell.getHeight() > currentMaxHeight) {
tly = cell.getTop() + yPos - cell.getEffectivePaddingTop();
bry = cell.getTop() + yPos - currentMaxHeight + cell.getEffectivePaddingBottom();
}
}
if ((tly > bry || ct.zeroHeightElement()) && leftLimit < rightLimit) {
ct.setSimpleColumn(leftLimit, bry - 0.001f, rightLimit, tly);
if (cell.getRotation() == 180) {
float shx = leftLimit + rightLimit;
float shy = yPos + yPos - currentMaxHeight + cell.getEffectivePaddingBottom() - cell.getEffectivePaddingTop();
saveAndRotateCanvases(canvases, -1,0,0,-1,shx,shy);
}
try {
ct.go();
} catch (DocumentException e) {
throw new ExceptionConverter(e);
} finally {
if (cell.getRotation() == 180) {
restoreCanvases(canvases);
}
}
}
}
}
PdfPCellEvent evt = cell.getCellEvent();
if (evt != null) {
Rectangle rect = new Rectangle(cell.getLeft() + xPos, cell.getTop()
@ -619,22 +615,22 @@ public class PdfPRow {
}
}
else {
float y;
float y;
ColumnText ct = ColumnText.duplicate(cell.getColumn());
float left = cell.getLeft() + cell.getEffectivePaddingLeft();
float bottom = cell.getTop() + cell.getEffectivePaddingBottom() - newHeight;
float right = cell.getRight() - cell.getEffectivePaddingRight();
float top = cell.getTop() - cell.getEffectivePaddingTop();
switch (cell.getRotation()) {
case 90:
case 270:
y = setColumn(ct, bottom, left, top, right);
break;
default:
y = setColumn(ct, left, bottom, cell.isNoWrap() ? RIGHT_LIMIT : right, top);
break;
}
int status;
float left = cell.getLeft() + cell.getEffectivePaddingLeft();
float bottom = cell.getTop() + cell.getEffectivePaddingBottom() - newHeight;
float right = cell.getRight() - cell.getEffectivePaddingRight();
float top = cell.getTop() - cell.getEffectivePaddingTop();
switch (cell.getRotation()) {
case 90:
case 270:
y = setColumn(ct, bottom, left, top, right);
break;
default:
y = setColumn(ct, left, bottom, cell.isNoWrap() ? RIGHT_LIMIT : right, top);
break;
}
int status;
try {
status = ct.go(true);
}
@ -648,7 +644,7 @@ public class PdfPRow {
}
else if ((status & ColumnText.NO_MORE_TEXT) == 0) {
newCell.setColumn(ct);
ct.setFilledWidth(0);
ct.setFilledWidth(0);
}
else
newCell.setPhrase(null);

642
fine-itext-old/src/com/fr/third/com/lowagie/text/pdf/PdfPTable.java

File diff suppressed because it is too large Load Diff

54
fine-itext-old/src/com/fr/third/com/lowagie/text/pdf/TableProperties.java

@ -0,0 +1,54 @@
package com.fr.third.com.lowagie.text.pdf;
import com.fr.third.com.lowagie.text.pdf.BorderStyle;
/**
* 描述table的属性类
* 包括cellspacingcellpaddingborder等
*/
public class TableProperties {
private BorderStyle borderStyle = new BorderStyle();
private float cellspacing = 2.0f;
private float cellpadding = 1.0f;
private boolean collapse = false;
public BorderStyle getBorderStyle() {
return borderStyle;
}
public void setBorderStyle(BorderStyle borderStyle) {
this.borderStyle = borderStyle;
}
public float getCellspacing() {
return isCollapse() ? 0 : cellspacing;
}
public void setCellspacing(float cellspacing) {
this.cellspacing = cellspacing;
}
public float getCellpadding() {
return cellpadding;
}
public void setCellpadding(float cellpadding) {
this.cellpadding = cellpadding;
}
public boolean isCollapse() {
return collapse;
}
public void setCollapse(boolean collapse) {
this.collapse = collapse;
}
public String toHtmlString(){
StringBuffer sb = new StringBuffer();
sb.append("cellspacing").append("=").append(cellspacing).append(" ");
sb.append("cellpadding").append("=").append(cellpadding).append(" ");
sb.append("border").append("=").append(borderStyle.getBorderWidth()).append(" ");
return sb.toString();
}
}

4
fine-itext-old/src/com/fr/third/com/lowagie/text/rtf/text/RtfChunk.java

@ -49,7 +49,6 @@
package com.fr.third.com.lowagie.text.rtf.text;
import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
@ -59,6 +58,7 @@ import com.fr.third.com.lowagie.text.rtf.RtfElement;
import com.fr.third.com.lowagie.text.rtf.document.RtfDocument;
import com.fr.third.com.lowagie.text.rtf.style.RtfColor;
import com.fr.third.com.lowagie.text.rtf.style.RtfFont;
import com.fr.third.com.lowagie.text.html.Markup;
/**
@ -126,7 +126,7 @@ public class RtfChunk extends RtfElement {
this.superSubScript = ((Float)chunk.getAttributes().get(Chunk.SUBSUPSCRIPT)).floatValue();
}
if(chunk.getAttributes() != null && chunk.getAttributes().get(Chunk.BACKGROUND) != null) {
this.background = new RtfColor(this.document, (Color) ((Object[]) chunk.getAttributes().get(Chunk.BACKGROUND))[0]);
this.background = new RtfColor(this.document, Markup.decodeColor((String)((Object[]) chunk.getAttributes().get(Chunk.BACKGROUND))[0]));
}
font = new RtfFont(doc, chunk.getFont());
content = chunk.getContent();

9
fine-itext/src/com/fr/third/v2/lowagie/text/html/simpleparser/HTMLWorker.java

@ -200,6 +200,8 @@ public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
if (follow != null) {
HashMap prop = new HashMap();
prop.put(follow, null);
FactoryProperties.insertStyle(h, this.cprops);
prop.putAll(h);
cprops.addToChain(follow, prop);
return;
}
@ -306,7 +308,12 @@ public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
String[] srcArray = src.split(",");
String base64string = srcArray[srcArray.length -1];
byte[] bytes = decoder.decodeBuffer(base64string);
img = Image.getInstance(bytes);
try {
img = Image.getInstance(bytes);
}catch (Exception e){
}
}
if (img == null) {
if (!src.startsWith("http")) {

BIN
fine-sense4/lib/jna-3.2.2.jar

Binary file not shown.

63
fine-sense4/src/Sense4/Elite4.java

@ -0,0 +1,63 @@
package Sense4;
/**
* @author Lanlan
* @date 2018/11/25
*/
public class Elite4 {
public static byte[] readElite4Serial() {
EliteLockIO eliteLockIO = LockUtils.getEliteLockIOInstance();
eliteLockIO.initS4(false);
byte[] serial = eliteLockIO.readEliteSerial();
eliteLockIO.closeS4();
return serial;
}
/*
* Write byte[] to elite4
*/
public static boolean writeBytes2ToElite4(byte[] bytes) {
EliteLockIO eliteLockIO = LockUtils.getEliteLockIOInstance();
eliteLockIO.initS4(true);
byte[] write_len_bytes = LockUtils.intToByteArray1(bytes.length + 4);
if (!eliteLockIO.write_internal_file(0, 4, write_len_bytes)) {
eliteLockIO.closeS4();
return false;
}
if (!eliteLockIO.write_internal_file(4, bytes.length, bytes)) {
eliteLockIO.closeS4();
return false;
}
eliteLockIO.closeS4();
return true;
}
/*
* Read byte[] from elite4
*/
public static byte[] readBytesFromElitee4() {
EliteLockIO eliteLockIO = LockUtils.getEliteLockIOInstance();
eliteLockIO.initS4(true);
byte[] len_out = eliteLockIO.read_internal_file(0, 4);
int read_len = LockUtils.byteArray2Int(len_out) - 4;
if (read_len < 0) {
eliteLockIO.closeS4();
return new byte[0];
}
byte read_bytes[] = eliteLockIO.read_internal_file(4, read_len);
eliteLockIO.closeS4();
return read_bytes;
}
public static String toHexString(byte[] b) {
return LockUtils.toHexString(b);
}
}

20
fine-sense4/src/Sense4/EliteLockIO.java

@ -0,0 +1,20 @@
package Sense4;
/**
* @author Lanlan
* @date 2018/11/25
*/
public interface EliteLockIO {
void initS4(boolean changeDir);
void closeS4();
boolean write_internal_file(int offset, int write_len, byte[] write_bytes);
byte[] read_internal_file(int offset, int read_len);
boolean uploadHexExeFile();
byte[] readEliteSerial();
}

277
fine-sense4/src/Sense4/EliteLockIO32.java

@ -0,0 +1,277 @@
package Sense4;
import java.io.File;
import java.io.FileInputStream;
import Sense4.Sense32.S4CREATEDIRINFO;
import Sense4.Sense32.S4OPENINFO;
import Sense4.Sense32.SENSE4_CONTEXT;
import com.sun.jna.ptr.IntByReference;
/**
* @author Lanlan
* @date 2018/11/25
*/
public class EliteLockIO32 implements EliteLockIO {
public static final int MAX_BUFF_SIZE = 0xf0;
public static final byte WRITE = 0;
public static final byte READ = 1;
public SENSE4_CONTEXT ctx= new SENSE4_CONTEXT();//[] = new Sense4.SENSE4_CONTEXT[2];
public Sense32 lib = Sense32.instance;
public EliteLockIO32() {}
public void initS4(boolean changeDir) {
IntByReference pSize = new IntByReference(0);
int ret = lib.S4Enum(ctx, pSize);
ret = lib.S4Enum(ctx, pSize);
if(ret!=0)
{
System.out.println("列举设备失败!");
}
ret = lib.S4Open(ctx);
if(ret!=0)
{
System.out.println("打开设备失败!");
}
if (changeDir) {
ret = lib.S4ChangeDir(ctx, "\\");
if(ret!=0)
{
System.out.println("切换目录失败!");
lib.S4Close(ctx);
}
ret = lib.S4VerifyPin(ctx, "12345678", 8, lib.S4_USER_PIN);
if(ret!=0)
{
System.out.println("校验用户pin失败!");
lib.S4Close(ctx);
}
}
}
public void closeS4() {
int ret = lib.S4Close(ctx);
if(ret!=0)
{
System.out.println("关闭设备失败!");
}
}
public boolean write_internal_file(int offset, int write_len, byte[] write_bytes) {
int write_offset = offset;
int old_offset = write_offset;
byte inBuffer[]=new byte[0xf8];
byte outBuffer[]=new byte[0xf8];
IntByReference pdwByteOut = new IntByReference(0);
inBuffer[0]=WRITE;
while (write_len > 0) {
old_offset = write_offset;
inBuffer[2]=(byte)((write_offset >> 8) & 0xFF);
inBuffer[3]=(byte)(write_offset & 0xFF);
if (write_len <= MAX_BUFF_SIZE) {
System.arraycopy(write_bytes, old_offset - offset, inBuffer, 4, write_len);
inBuffer[1] = (byte)(write_len & 0xFF);
write_len = 0;
write_offset += write_len;
} else {
System.arraycopy(write_bytes, old_offset - offset, inBuffer, 4, MAX_BUFF_SIZE);
inBuffer[1] = (byte)MAX_BUFF_SIZE;
write_len -= MAX_BUFF_SIZE;
write_offset += MAX_BUFF_SIZE;
}
int ret = lib.S4Execute(ctx,"ef21",inBuffer,0xf8,outBuffer,0xf8, pdwByteOut);
if(ret!=0)
{
System.out.println("执行锁内程序失败!");
lib.S4Close(ctx);
return false;
}
}
return true;
}
public byte[] read_internal_file(int offset, int read_len) {
if (read_len < 0) {
throw new IllegalArgumentException();
}
int read_offset = offset;
int old_offset = read_offset;
byte[] out = new byte[read_len];
IntByReference pdwByteOut = new IntByReference(0);
byte inBuffer[]=new byte[0xf8];
byte outBuffer[]=new byte[0xf8];
inBuffer[0]=READ;
while (read_len > 0) {
old_offset = read_offset;
// big-edian
inBuffer[2]=(byte)((read_offset >> 8) & 0xFF);
inBuffer[3]=(byte)(read_offset & 0xFF);
if (read_len <= MAX_BUFF_SIZE) {
inBuffer[1] = (byte)read_len;
read_len = 0;
read_offset += read_len;
} else {
inBuffer[1] = (byte)MAX_BUFF_SIZE;
read_len -= MAX_BUFF_SIZE;
read_offset += MAX_BUFF_SIZE;
}
int ret = lib.S4Execute(ctx, "ef21",inBuffer,0xf8,outBuffer,0xf8,pdwByteOut);
if(ret!=0 || pdwByteOut.getValue() < inBuffer[1])
{
System.out.println("执行锁内程序失败!");
lib.S4Close(ctx);
} else {
System.arraycopy(outBuffer, 0, out, old_offset - offset, pdwByteOut.getValue());
}
}
return out;
}
public boolean uploadHexExeFile() {
Sense32 lib = Sense32.instance;
IntByReference pSize = new IntByReference(0);
int ret = 0;
long errorCount = 0;
IntByReference lpBytesReturned = new IntByReference(0);
SENSE4_CONTEXT[] s4_context = new SENSE4_CONTEXT[0];
ret = lib.S4Enum(null, pSize);
s4_context = new SENSE4_CONTEXT[pSize.getValue() / 92];
for (int i = 0;i< pSize.getValue() / 92; i++){
s4_context[i] = new SENSE4_CONTEXT();
}
ret = lib.S4Enum(s4_context[0], pSize);
checkS4ExceptionResult(ret, "Enumerate Sense4");
errorCount += ret;
S4OPENINFO s4_OpenInfo = new S4OPENINFO();
s4_OpenInfo.dwS4OpenInfoSize = 8;
s4_OpenInfo.dwShareMode = lib.S4_EXCLUSIZE_MODE;
ret = lib.S4OpenEx(s4_context[0], s4_OpenInfo);
checkS4ExceptionResult(ret, "Open Sense4");
errorCount += ret;
byte [] frequency = {0x04};
ret = lib.S4Control(s4_context[0], lib.S4_LED_WINK, frequency, 1, null, 0, lpBytesReturned);
checkS4ExceptionResult(ret, "Sense4 LED wink");
errorCount += ret;
ret = lib.S4ChangeDir (s4_context[0], "\\");
checkS4ExceptionResult(ret, "Change Dir");
errorCount += ret;
ret = lib.S4VerifyPin(s4_context[0], "123456781234567812345678", 24, lib.S4_DEV_PIN);
checkS4ExceptionResult(ret, "Verify dev pin");
errorCount += ret;
ret = lib.S4EraseDir(s4_context[0], null);
checkS4ExceptionResult(ret, "Erase MF");
errorCount += ret;
S4CREATEDIRINFO s4_CreateDirInfo = new S4CREATEDIRINFO();
s4_CreateDirInfo.dwS4CreateDirInfoSize = 12;
s4_CreateDirInfo.szAtr[0] = (byte)0xFF;
s4_CreateDirInfo.szAtr[1] = (byte)0xFF;
s4_CreateDirInfo.szAtr[2] = (byte)0xFF;
s4_CreateDirInfo.szAtr[3] = (byte)0xFF;
s4_CreateDirInfo.szAtr[4] = (byte)0xFF;
s4_CreateDirInfo.szAtr[5] = (byte)0xFF;
s4_CreateDirInfo.szAtr[6] = (byte)0xFF;
s4_CreateDirInfo.szAtr[7] = (byte)0xFF;
ret = lib.S4CreateDirEx(s4_context[0], "\\", 0, lib.S4_CREATE_ROOT_DIR,s4_CreateDirInfo);
checkS4ExceptionResult(ret, "Create MF");
errorCount += ret;
ret = lib.S4VerifyPin (s4_context[0], "123456781234567812345678", 24, lib.S4_DEV_PIN );
checkS4ExceptionResult(ret, "Verify Dev Pin");
errorCount += ret;
// write bin file ef21
File demofile = new File("ReadData.bin");
long contentsize = demofile.length ();
byte [] content = new byte[1];
try
{
FileInputStream is = new FileInputStream (demofile);
content = new byte[(int)contentsize];
is.read(content, 0, (int)contentsize);
is.close();
}
catch(Exception e)
{
System.out.println("error: read hex bing file ");
}
ret = lib.S4WriteFile (s4_context[0], "ef21", 0, content, (int)contentsize, (int)contentsize + 20, lpBytesReturned,
lib.S4_CREATE_NEW , lib.S4_EXE_FILE );
checkS4ExceptionResult(ret, "Write hex bin file");
errorCount += ret;
// write data file bf21
byte[] data_file = new byte[0x6000];
ret = lib.S4WriteFile (s4_context[0], "bf21", 0, data_file, (int)data_file.length, (int)data_file.length + 20, lpBytesReturned,
lib.S4_CREATE_NEW , lib.S4_DATA_FILE );
checkS4ExceptionResult(ret, "Write data file");
errorCount += ret;
ret = lib.S4Control (s4_context[0], lib.S4_LED_DOWN, null, 0, null, 0, lpBytesReturned);
checkS4ExceptionResult(ret, "LED Down");
errorCount += ret;
ret = lib.S4Close(s4_context[0]);
checkS4ExceptionResult(ret, "Close Sense4");
errorCount += ret;
return errorCount == 0;
}
public byte[] readEliteSerial() {
byte[] serial = new byte[8];
int ret = lib.S4Control(ctx, lib.S4_GET_SERIAL_NUMBER, null, 0, serial, 8, null);
if (ret != 0) {
System.out.println("S4_GET_SERIAL_NUMBER: " + ret);
}
return serial;
}
private static void checkS4ExceptionResult(int ret, String info) {
if (ret != 0) {
System.out.println("Error Code: " + ret + " Info:" + info);
} else {
System.out.println("Success: " + info);
}
}
}

274
fine-sense4/src/Sense4/EliteLockIO64.java

@ -0,0 +1,274 @@
package Sense4;
import java.io.File;
import java.io.FileInputStream;
import Sense4.Sense64.S4CREATEDIRINFO;
import Sense4.Sense64.S4OPENINFO;
import Sense4.Sense64.SENSE4_CONTEXT;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.LongByReference;
/**
* @author Lanlan
* @date 2018/11/25
*/
public class EliteLockIO64 implements EliteLockIO {
public static final int MAX_BUFF_SIZE = 0xf0;
public static final byte WRITE = 0;
public static final byte READ = 1;
public SENSE4_CONTEXT ctx= new SENSE4_CONTEXT();//[] = new Sense4.SENSE4_CONTEXT[2];
public Sense64 lib = Sense64.instance;
public EliteLockIO64() {}
public void initS4(boolean changeDir) {
LongByReference pSize = new LongByReference(0);
long ret = lib.S4Enum(ctx, pSize);
ret = lib.S4Enum(ctx, pSize);
if(ret!=0)
{
System.out.println("List列举设备失败!" + ret);
}
ret = lib.S4Open(ctx);
if(ret!=0)
{
System.out.println("Open打开设备失败!" + ret);
}
if (changeDir) {
ret = lib.S4ChangeDir(ctx, "\\");
if(ret!=0)
{
System.out.println("Change切换目录失败!" + ret);
lib.S4Close(ctx);
}
ret = lib.S4VerifyPin(ctx, "12345678", 8, lib.S4_USER_PIN);
if(ret!=0)
{
System.out.println("Verify校验用户pin失败!" + ret);
lib.S4Close(ctx);
}
}
}
public void closeS4() {
long ret = lib.S4Close(ctx);
if(ret!=0)
{
System.out.println("Close关闭设备失败!" + ret);
}
}
public boolean write_internal_file(int offset, int write_len, byte[] write_bytes) {
int write_offset = offset;
int old_offset = write_offset;
byte inBuffer[]=new byte[0xf8];
byte outBuffer[]=new byte[0xf8];
IntByReference pdwByteOut = new IntByReference(0);
inBuffer[0]=WRITE;
while (write_len > 0) {
old_offset = write_offset;
inBuffer[2]=(byte)((write_offset >> 8) & 0xFF);
inBuffer[3]=(byte)(write_offset & 0xFF);
if (write_len <= MAX_BUFF_SIZE) {
System.arraycopy(write_bytes, old_offset - offset, inBuffer, 4, write_len);
inBuffer[1] = (byte)(write_len & 0xFF);
write_len = 0;
write_offset += write_len;
} else {
System.arraycopy(write_bytes, old_offset - offset, inBuffer, 4, MAX_BUFF_SIZE);
inBuffer[1] = (byte)MAX_BUFF_SIZE;
write_len -= MAX_BUFF_SIZE;
write_offset += MAX_BUFF_SIZE;
}
int ret = lib.S4Execute(ctx,"ef21",inBuffer,0xf8,outBuffer,0xf8, pdwByteOut);
if(ret!=0)
{
System.out.println("执行锁内程序失败!");
lib.S4Close(ctx);
return false;
}
}
return true;
}
public byte[] read_internal_file(int offset, int read_len) {
int read_offset = offset;
int old_offset = read_offset;
byte[] out = new byte[read_len];
IntByReference pdwByteOut = new IntByReference(0);
byte inBuffer[]=new byte[0xf8];
byte outBuffer[]=new byte[0xf8];
inBuffer[0]=READ;
while (read_len > 0) {
old_offset = read_offset;
inBuffer[2]=(byte)((read_offset >> 8) & 0xFF);
inBuffer[3]=(byte)(read_offset & 0xFF);
if (read_len <= MAX_BUFF_SIZE) {
inBuffer[1] = (byte)read_len;
read_len = 0;
read_offset += read_len;
} else {
inBuffer[1] = (byte)MAX_BUFF_SIZE;
read_len -= MAX_BUFF_SIZE;
read_offset += MAX_BUFF_SIZE;
}
long ret = lib.S4Execute(ctx, "ef21",inBuffer,0xf8,outBuffer,0xf8,pdwByteOut);
if(ret!=0 || pdwByteOut.getValue() < inBuffer[1])
{
System.out.println("执行锁内程序失败!");
lib.S4Close(ctx);
} else {
System.arraycopy(outBuffer, 0, out, old_offset - offset, (int)pdwByteOut.getValue());
}
}
return out;
}
public boolean uploadHexExeFile() {
Sense64 lib = Sense64.instance;
LongByReference pSize = new LongByReference(0);
long ret = 0;
long errorCount = 0;
LongByReference lpBytesReturned = new LongByReference(0);
SENSE4_CONTEXT[] s4_context = new SENSE4_CONTEXT[0];
ret = lib.S4Enum(null, pSize);
s4_context = new SENSE4_CONTEXT[(int)pSize.getValue() / 92];
for (int i = 0;i< pSize.getValue() / 92; i++){
s4_context[i] = new SENSE4_CONTEXT();
}
ret = lib.S4Enum(s4_context[0], pSize);
checkS4ExceptionResult(ret, "Enumerate Sense4");
errorCount += ret;
S4OPENINFO s4_OpenInfo = new S4OPENINFO();
s4_OpenInfo.dwS4OpenInfoSize = 8;
s4_OpenInfo.dwShareMode = lib.S4_EXCLUSIZE_MODE;
ret = lib.S4OpenEx(s4_context[0], s4_OpenInfo);
checkS4ExceptionResult(ret, "Open Sense4");
errorCount += ret;
byte [] frequency = {0x04};
ret = lib.S4Control(s4_context[0], lib.S4_LED_WINK, frequency, 1, null, 0, lpBytesReturned);
checkS4ExceptionResult(ret, "Sense4 LED wink");
errorCount += ret;
ret = lib.S4ChangeDir (s4_context[0], "\\");
checkS4ExceptionResult(ret, "Change Dir");
errorCount += ret;
ret = lib.S4VerifyPin(s4_context[0], "123456781234567812345678", 24, lib.S4_DEV_PIN);
checkS4ExceptionResult(ret, "Verify dev pin");
errorCount += ret;
ret = lib.S4EraseDir(s4_context[0], null);
checkS4ExceptionResult(ret, "Erase MF");
errorCount += ret;
S4CREATEDIRINFO s4_CreateDirInfo = new S4CREATEDIRINFO();
s4_CreateDirInfo.dwS4CreateDirInfoSize = 12;
s4_CreateDirInfo.szAtr[0] = (byte)0xFF;
s4_CreateDirInfo.szAtr[1] = (byte)0xFF;
s4_CreateDirInfo.szAtr[2] = (byte)0xFF;
s4_CreateDirInfo.szAtr[3] = (byte)0xFF;
s4_CreateDirInfo.szAtr[4] = (byte)0xFF;
s4_CreateDirInfo.szAtr[5] = (byte)0xFF;
s4_CreateDirInfo.szAtr[6] = (byte)0xFF;
s4_CreateDirInfo.szAtr[7] = (byte)0xFF;
ret = lib.S4CreateDirEx(s4_context[0], "\\", 0, lib.S4_CREATE_ROOT_DIR,s4_CreateDirInfo);
checkS4ExceptionResult(ret, "Create MF");
errorCount += ret;
ret = lib.S4VerifyPin (s4_context[0], "123456781234567812345678", 24, lib.S4_DEV_PIN );
checkS4ExceptionResult(ret, "Verify Dev Pin");
errorCount += ret;
// write bin file ef21
File demofile = new File("ReadData.bin");
long contentsize = demofile.length ();
byte [] content = new byte[1];
try
{
FileInputStream is = new FileInputStream (demofile);
content = new byte[(int)contentsize];
is.read(content, 0, (int)contentsize);
is.close();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("error: read hex bing file ");
}
ret = lib.S4WriteFile (s4_context[0], "ef21", 0, content, (int)contentsize, (int)contentsize + 20, lpBytesReturned,
lib.S4_CREATE_NEW , lib.S4_EXE_FILE );
checkS4ExceptionResult(ret, "Write hex bin file");
errorCount += ret;
// write data file bf21
byte[] data_file = new byte[0x6000];
ret = lib.S4WriteFile (s4_context[0], "bf21", 0, data_file, (int)data_file.length, (int)data_file.length + 20, lpBytesReturned,
lib.S4_CREATE_NEW , lib.S4_DATA_FILE );
checkS4ExceptionResult(ret, "Write data file");
errorCount += ret;
ret = lib.S4Control (s4_context[0], lib.S4_LED_DOWN, null, 0, null, 0, lpBytesReturned);
checkS4ExceptionResult(ret, "LED Down");
errorCount += ret;
ret = lib.S4Close(s4_context[0]);
checkS4ExceptionResult(ret, "Close Sense4");
errorCount += ret;
return errorCount == 0;
}
private static void checkS4ExceptionResult(long ret, String info) {
if (ret != 0) {
System.out.println("Error Code: " + ret + " Info:" + info);
} else {
System.out.println("Success: " + info);
}
}
public byte[] readEliteSerial() {
byte[] serial = new byte[8];
long ret = lib.S4Control(ctx, lib.S4_GET_SERIAL_NUMBER, null, 0, serial, 8, null);
if (ret != 0) {
System.out.println("S4_GET_SERIAL_NUMBER: " + ret);
}
return serial;
}
}

65
fine-sense4/src/Sense4/LockUtils.java

@ -0,0 +1,65 @@
package Sense4;
/**
* @author Lanlan
* @date 2018/11/25
*/
public abstract class LockUtils {
private static EliteLockIO intance;
public static boolean isJVMSystem32() {
String arch_model = System.getProperty("sun.arch.data.model");
return "32".equals(arch_model);
}
// big-endian
public static byte[] intToByteArray1(int i) {
byte[] result = new byte[4];
result[0] = (byte)((i >> 24) & 0xFF);
result[1] = (byte)((i >> 16) & 0xFF);
result[2] = (byte)((i >> 8) & 0xFF);
result[3] = (byte)(i & 0xFF);
return result;
}
// big-endian
public static int byteArray2Int(byte[] bytes) {
int res = 0;
res += (bytes[0] & 0xff) << 24;
res += (bytes[1] & 0xff) << 16;
res += (bytes[2] & 0xff)<< 8;
res += bytes[3] & 0xff;
return res;
}
public static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = "0" + hex;
}
sb.append(hex);
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println("System is 32-bit: " + isJVMSystem32());
}
public static EliteLockIO getEliteLockIOInstance() {
if (intance == null) {
if (isJVMSystem32()) {
intance = new EliteLockIO32();
} else {
intance = new EliteLockIO64();
}
}
return intance;
}
}

218
fine-sense4/src/Sense4/Sense32.java

@ -0,0 +1,218 @@
package Sense4;
import com.sun.jna.Native;
import com.sun.jna.Structure;
import com.sun.jna.ptr.IntByReference;
import java.util.ArrayList;
import java.util.List;
public interface Sense32 extends com.sun.jna.Library
{
Sense32 instance = (Sense32) Native.loadLibrary("EL", Sense32.class);
public static final int S4_USER_PIN = 0x000000a1;
public static final int S4_DEV_PIN = 0x000000a2;
public static final int S4_AUTHEN_PIN = 0x000000a3;
public static final int S4_CREATE_NEW = 0x000000a5;
public static final int S4_UPDATE_FILE = 0x000000a6;
// #define S4_EXE_FILE 0x00000008 /** executable file of virtual machine*/
public static final byte S4_EXE_FILE = 0x00000008;
public static final byte S4_DATA_FILE = 0x00000009;
public static final int S4_FILE_EXIST = 0x00006a80;
// #define S4_LED_DOWN 0x00000008 /** LED down*/
public static final int S4_LED_DOWN = 0x00000008;
// #define S4_LED_WINK 0x00000028 /** LED wink*/
public static final int S4_LED_WINK = 0x00000028;
public static final int S4_GET_SERIAL_NUMBER = 0x00000026;
// #define S4_EXCLUSIZE_MODE 0 /** exclusive mode*/
// #define S4_SHARE_MODE 1 /** sharable mode*/
public static final int S4_EXCLUSIZE_MODE = 0x00000000;
public static final int S4_SHARE_MODE = 0x00000001;
// #define S4_CREATE_ROOT_DIR 0x000000ab /** create root directory*/
public static final int S4_CREATE_ROOT_DIR = 0x000000ab;
public static class RTC_TIME_T extends Structure
{
public byte second; /* second (0-59) */
public byte minute; /* minute (0-59) */
public byte hour; /* hour (0-23) */
public byte day; /* day of month (1-31) */
public byte week; /* day of week (0-6, sunday is 0) */
public byte month; /* month (0-11) */
public short year; /* year (0- 138, 1900 - 2038) */
protected List<String> getFieldOrder() {
List<String> list = new ArrayList<String>();
list.add("second");
list.add("minute");
list.add("hour");
list.add("day");
list.add("week");
list.add("month");
list.add("year");
return list;
}
}
public static class SENSE4_CONTEXT extends Structure {
public int dwIndex; /** device index; index begins at zero*/
public int dwVersion; /** device version*/
public int hLock; /** device handle*/
public byte[] reserve = new byte[12*2]; /** reserved*/
public byte[] bAtr = new byte[56]; /** ATR*/
public byte[] bID = new byte[8]; /** device ID*/
public int dwAtrLen; /** ATR length*/
protected List<String> getFieldOrder() {
List<String> list = new ArrayList<String>();
list.add("dwIndex");
list.add("dwVersion");
list.add("hLock");
list.add("reserve");
list.add("bAtr");
list.add("bID");
list.add("dwAtrLen");
return list;
}
}
/** Netlock Module infomation definition*/
// typedef struct _S4MODULEINFO {
// WORD wModuleID; /* Module ID*/
// WORD wLicenseCount; /* License Count */
// } S4MODULEINFO;
public static class S4MODULEINFO extends Structure {
public short wModuleID;
public short wLicenseCount;
protected List<String> getFieldOrder() {
List<String> list = new ArrayList<String>();
list.add("wModuleID");
list.add("wLicenseCount");
return list;
}
}
// typedef struct _S4NETCONFIG {
// DWORD dwLicenseMode; /* License Mode */
// DWORD dwModuleCount; /* Module Count */
// S4MODULEINFO ModuleInfo[16]; /* Module detail infomation */
// } S4NETCONFIG;
public static class S4NETCONFIG extends Structure {
public int dwLicenseMode;
public int dwModuleCount;
public S4MODULEINFO[] ModuleInfo = new S4MODULEINFO[16];
protected List<String> getFieldOrder() {
List<String> list = new ArrayList<String>();
list.add("dwLicenseMode");
list.add("dwModuleCount");
list.add("ModuleInfo");
return list;
}
}
// S4CREATEDIRINFO structure definition
// typedef struct _S4CREATEDIRINFO {
// DWORD dwS4CreateDirInfoSize; /* size of the structure*/
// BYTE szAtr[8]; /* ATR information */
// S4NETCONFIG NetConfig; /* netlock config infomation */
// } S4CREATEDIRINFO;
public static class S4CREATEDIRINFO extends Structure {
public int dwS4CreateDirInfoSize;
public byte[] szAtr = new byte[8];
public S4NETCONFIG NetConfig;
protected List<String> getFieldOrder() {
List<String> list = new ArrayList<String>();
list.add("dwS4CreateDirInfoSize");
list.add("szAtr");
list.add("NetConfig");
return list;
}
}
// typedef struct _S4OPENINFO {
// DWORD dwS4OpenInfoSize; /* size of the structure*/
// DWORD dwShareMode; /* share mode*/
// } S4OPENINFO;
public static class S4OPENINFO extends Structure {
public int dwS4OpenInfoSize;
public int dwShareMode;
protected List<String> getFieldOrder() {
List<String> list = new ArrayList<String>();
list.add("dwS4OpenInfoSize");
list.add("dwShareMode");
return list;
}
}
public int S4Enum(SENSE4_CONTEXT ctx, IntByReference pSize);
public int S4Open(SENSE4_CONTEXT ctx);
// DWORD WINAPI S4Control(
// IN SENSE4_CONTEXT *pS4Ctx,
// IN DWORD dwCtlCode,
// IN VOID *pInBuffer,
// IN DWORD dwInBufferLen,
// OUT VOID *pOutBuffer,
// IN DWORD dwOutBufferLen,
// OUT DWORD *pdwBytesReturned
// );
public int S4Control(
SENSE4_CONTEXT ctx,
int dwCtlCode,
byte[] pInBuffer,
int dwInBufferLen,
byte[] pOutBuffer,
int dwOutBufferLen,
IntByReference pdwBytesReturned
);
public int S4ChangeDir(SENSE4_CONTEXT ctx, String dir);
//
public int S4EraseDir(SENSE4_CONTEXT ctx, String dir);
public int S4VerifyPin(SENSE4_CONTEXT ctx, String passwd, int passwdLen, int type);
public int S4WriteFile(SENSE4_CONTEXT ctx,
String lpszFileID,
int dwOffset,
byte lpBuffer[],
int dwBufferSize,
int dwFileSize,
IntByReference pdwBytesWritten,
int dwFlags,
byte bFileType);
public int S4Execute(SENSE4_CONTEXT ctx, String fileID, byte[] inputBuf, int inputSize, byte[] outputBuf, int outputSize, IntByReference pSize);
public int S4Close(SENSE4_CONTEXT ctx);
// DWORD WINAPI S4CreateDirEx(
// IN SENSE4_CONTEXT *pS4Ctx,
// IN LPCSTR lpszDirID,
// IN DWORD dwDirSize,
// IN DWORD dwFlags,
// IN S4CREATEDIRINFO *pCreateDirInfo
// );
public int S4CreateDirEx(
SENSE4_CONTEXT ctx,
String lpszDirID,
int dwDirSize,
int dwFlags,
S4CREATEDIRINFO pCreateDirInfo
);
// DWORD WINAPI S4OpenEx(
// IN OUT SENSE4_CONTEXT *pS4Ctx,
// IN S4OPENINFO *pS4OpenInfo
// );
public int S4OpenEx(SENSE4_CONTEXT ctx, S4OPENINFO pS4OpenInfo);
}

219
fine-sense4/src/Sense4/Sense64.java

@ -0,0 +1,219 @@
package Sense4;
import com.sun.jna.Native;
import com.sun.jna.Structure;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.LongByReference;
import java.util.ArrayList;
import java.util.List;
public interface Sense64 extends com.sun.jna.Library
{
Sense64 instance = (Sense64) Native.loadLibrary("EL", Sense64.class);
public static final long S4_USER_PIN = 0x000000a1;
public static final long S4_DEV_PIN = 0x000000a2;
public static final long S4_AUTHEN_PIN = 0x000000a3;
public static final long S4_CREATE_NEW = 0x000000a5;
public static final long S4_UPDATE_FILE = 0x000000a6;
// #define S4_EXE_FILE 0x00000008 /** executable file of virtual machine*/
public static final byte S4_EXE_FILE = 0x00000008;
public static final byte S4_DATA_FILE = 0x00000009;
public static final long S4_FILE_EXIST = 0x00006a80;
// #define S4_LED_DOWN 0x00000008 /** LED down*/
public static final long S4_LED_DOWN = 0x00000008;
// #define S4_LED_WINK 0x00000028 /** LED wink*/
public static final long S4_LED_WINK = 0x00000028;
public static final long S4_GET_SERIAL_NUMBER = 0x00000026;
// #define S4_EXCLUSIZE_MODE 0 /** exclusive mode*/
// #define S4_SHARE_MODE 1 /** sharable mode*/
public static final long S4_EXCLUSIZE_MODE = 0x00000000;
public static final long S4_SHARE_MODE = 0x00000001;
// #define S4_CREATE_ROOT_DIR 0x000000ab /** create root directory*/
public static final long S4_CREATE_ROOT_DIR = 0x000000ab;
public static class RTC_TIME_T extends Structure
{
public byte second; /* second (0-59) */
public byte minute; /* minute (0-59) */
public byte hour; /* hour (0-23) */
public byte day; /* day of month (1-31) */
public byte week; /* day of week (0-6, sunday is 0) */
public byte month; /* month (0-11) */
public short year; /* year (0- 138, 1900 - 2038) */
protected List<String> getFieldOrder() {
List<String> list = new ArrayList<String>();
list.add("second");
list.add("minute");
list.add("hour");
list.add("day");
list.add("week");
list.add("month");
list.add("year");
return list;
}
}
public static class SENSE4_CONTEXT extends Structure {
public long dwIndex; /** device index; index begins at zero*/
public long dwVersion; /** device version*/
public long hLock; /** device handle*/
public byte[] reserve = new byte[12*2]; /** reserved*/
public byte[] bAtr = new byte[56]; /** ATR*/
public byte[] bID = new byte[8]; /** device ID*/
public long dwAtrLen; /** ATR length*/
protected List<String> getFieldOrder() {
List<String> list = new ArrayList<String>();
list.add("dwIndex");
list.add("dwVersion");
list.add("hLock");
list.add("reserve");
list.add("bAtr");
list.add("bID");
list.add("dwAtrLen");
return list;
}
}
/** Netlock Module infomation definition*/
// typedef struct _S4MODULEINFO {
// WORD wModuleID; /* Module ID*/
// WORD wLicenseCount; /* License Count */
// } S4MODULEINFO;
public static class S4MODULEINFO extends Structure {
public int wModuleID;
public int wLicenseCount;
protected List<String> getFieldOrder() {
List<String> list = new ArrayList<String>();
list.add("wModuleID");
list.add("wLicenseCount");
return list;
}
}
// typedef struct _S4NETCONFIG {
// DWORD dwLicenseMode; /* License Mode */
// DWORD dwModuleCount; /* Module Count */
// S4MODULEINFO ModuleInfo[16]; /* Module detail infomation */
// } S4NETCONFIG;
public static class S4NETCONFIG extends Structure {
public long dwLicenseMode;
public long dwModuleCount;
public S4MODULEINFO[] ModuleInfo = new S4MODULEINFO[16];
protected List<String> getFieldOrder() {
List<String> list = new ArrayList<String>();
list.add("dwLicenseMode");
list.add("dwModuleCount");
list.add("ModuleInfo");
return list;
}
}
// S4CREATEDIRINFO structure definition
// typedef struct _S4CREATEDIRINFO {
// DWORD dwS4CreateDirInfoSize; /* size of the structure*/
// BYTE szAtr[8]; /* ATR information */
// S4NETCONFIG NetConfig; /* netlock config infomation */
// } S4CREATEDIRINFO;
public static class S4CREATEDIRINFO extends Structure {
public long dwS4CreateDirInfoSize;
public byte[] szAtr = new byte[8];
public S4NETCONFIG NetConfig;
protected List<String> getFieldOrder() {
List<String> list = new ArrayList<String>();
list.add("dwS4CreateDirInfoSize");
list.add("szAtr");
list.add("NetConfig");
return list;
}
}
// typedef struct _S4OPENINFO {
// DWORD dwS4OpenInfoSize; /* size of the structure*/
// DWORD dwShareMode; /* share mode*/
// } S4OPENINFO;
public static class S4OPENINFO extends Structure {
public long dwS4OpenInfoSize;
public long dwShareMode;
protected List<String> getFieldOrder() {
List<String> list = new ArrayList<String>();
list.add("dwS4OpenInfoSize");
list.add("dwShareMode");
return list;
}
}
public long S4Enum(SENSE4_CONTEXT ctx, LongByReference pSize);
public long S4Open(SENSE4_CONTEXT ctx);
// DWORD WINAPI S4Control(
// IN SENSE4_CONTEXT *pS4Ctx,
// IN DWORD dwCtlCode,
// IN VOID *pInBuffer,
// IN DWORD dwInBufferLen,
// OUT VOID *pOutBuffer,
// IN DWORD dwOutBufferLen,
// OUT DWORD *pdwBytesReturned
// );
public long S4Control(
SENSE4_CONTEXT ctx,
long dwCtlCode,
byte[] pInBuffer,
long dwInBufferLen,
byte[] pOutBuffer,
long dwOutBufferLen,
LongByReference pdwBytesReturned
);
public long S4ChangeDir(SENSE4_CONTEXT ctx, String dir);
//
public long S4EraseDir(SENSE4_CONTEXT ctx, String dir);
public long S4VerifyPin(SENSE4_CONTEXT ctx, String passwd, long passwdLen, long type);
public long S4WriteFile(SENSE4_CONTEXT ctx,
String lpszFileID,
long dwOffset,
byte lpBuffer[],
long dwBufferSize,
long dwFileSize,
LongByReference pdwBytesWritten,
long dwFlags,
byte bFileType);
public int S4Execute(Sense64.SENSE4_CONTEXT ctx, String fileID, byte[] inputBuf, int inputSize, byte[] outputBuf, int outputSize, IntByReference pSize);
public long S4Close(SENSE4_CONTEXT ctx);
// DWORD WINAPI S4CreateDirEx(
// IN SENSE4_CONTEXT *pS4Ctx,
// IN LPCSTR lpszDirID,
// IN DWORD dwDirSize,
// IN DWORD dwFlags,
// IN S4CREATEDIRINFO *pCreateDirInfo
// );
public long S4CreateDirEx(
SENSE4_CONTEXT ctx,
String lpszDirID,
long dwDirSize,
long dwFlags,
S4CREATEDIRINFO pCreateDirInfo
);
// DWORD WINAPI S4OpenEx(
// IN OUT SENSE4_CONTEXT *pS4Ctx,
// IN S4OPENINFO *pS4OpenInfo
// );
public long S4OpenEx(SENSE4_CONTEXT ctx, S4OPENINFO pS4OpenInfo);
}

690
fine-sense4/src/Sense4/sense4.h

@ -0,0 +1,690 @@
/**************************************************************************************
* Copyright (c) 2008, Senselock Software Technology Co., Ltd
* All rights reserved.
*
* filename: sense4.h
*
* briefs: EliteIV library interface declaration, return value and some constant definition.
*
* date: 2008.04.08
* version: 3.1
*******************************************************************************************/
#ifndef __SENSE4_H__
#define __SENSE4_H__
#ifdef _MSC_VER
#pragma comment(linker, "/defaultlib:setupapi.lib")
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if defined WIN32 || defined _WIN32 || defined _WIN64
#include <windows.h>
typedef HANDLE S4HANDLE;
#elif defined __MACH__
typedef io_connect_t S4HANDLE;
#else
typedef void* S4HANDLE;
#endif /* defined WIN32 || defined _WIN32 || defined _WIN64 */
#ifndef IN
#define IN
#endif
#ifndef OUT
#define OUT
#endif
#if !defined _WINDOWS_
#define WINAPI
#define CONST const
typedef unsigned char UCHAR;
typedef unsigned short USHORT;
typedef unsigned int UINT;
typedef unsigned long ULONG;
typedef char CHAR;
typedef char TCHAR;
typedef void VOID;
#ifndef _BYTE_DEFINED
#define _BYTE_DEFINED
typedef unsigned char BYTE;
#endif
#ifndef _WORD_DEFINED
#define _WORD_DEFINED
typedef unsigned short WORD;
#endif
#ifndef _DWORD_DEFINED
#define _DWORD_DEFINED
typedef unsigned long DWORD;
#endif
typedef VOID* LPVOID;
typedef CHAR* LPSTR;
typedef CONST CHAR* LPCSTR;
typedef CONST TCHAR* LPCTSTR;
typedef BYTE* LPBYTE;
typedef WORD* LPWORD;
typedef DWORD* LPDWORD;
#endif /* !defined _WINDOWS */
//@{
/**
device share mode definition
*/
#define S4_EXCLUSIZE_MODE 0 /** exclusive mode*/
#define S4_SHARE_MODE 1 /** sharable mode*/
//@}
//@{
/**
the control code value definition
*/
#define S4_LED_UP 0x00000004 /** LED up*/
#define S4_LED_DOWN 0x00000008 /** LED down*/
#define S4_LED_WINK 0x00000028 /** LED wink*/
#define S4_GET_DEVICE_TYPE 0x00000025 /** get the device type*/
#define S4_GET_SERIAL_NUMBER 0X00000026 /** get the device serial number*/
#define S4_GET_VM_TYPE 0X00000027 /** get the virtual machine type*/
#define S4_GET_DEVICE_USABLE_SPACE 0x00000029 /** get the total space of the device*/
#define S4_SET_DEVICE_ID 0x0000002a /** set the device ID*/
#define S4_RESET_DEVICE 0x00000002 /** reset the device*/
#define S4_DF_AVAILABLE_SPACE 0x00000031 /** get the free space of current directory*/
#define S4_EF_INFO 0x00000032 /** get specified file information in current directory*/
#define S4_SET_USB_MODE 0x00000041 /** set the device as a normal usb device*/
#define S4_SET_HID_MODE 0x00000042 /** set the device as a HID device*/
#define S4_GET_CUSTOMER_NAME 0x0000002b /** get the customer number*/
#define S4_GET_MANUFACTURE_DATE 0x0000002c /** get the manufacture date of the device*/
#define S4_GET_CURRENT_TIME 0x0000002d /** get the current time of the clock device*/
#define S4_SET_NET_CONFIG 0x00000030 /** set netlock config */
//@}
//@}
//@{
/**
device type definition
*/
#define S4_LOCAL_DEVICE 0x00 /** local device*/
#define S4_MASTER_DEVICE 0x01 /** net master device*/
#define S4_SLAVE_DEVICE 0x02 /** net slave device*/
//@}
//@{
/**
virtual machine type definition
*/
#define S4_VM_51 0x00 /** inter 51*/
#define S4_VM_251_BINARY 0x01 /** inter 251, binary mode*/
#define S4_VM_251_SOURCE 0X02 /** inter 251, source mode*/
//@}
//@{
/**
NetLock license mode
*/
#define S4_MODULE_MODE 0x00000000 /** Module mode*/
#define S4_IP_MODE 0x00000001 /** IP mode*/
//@}
//@{
/**
PIN and key type definition
*/
#define S4_USER_PIN 0x000000a1 /** user PIN*/
#define S4_DEV_PIN 0x000000a2 /** developer PIN*/
#define S4_AUTHEN_PIN 0x000000a3 /** authentication key of net device*/
//@}
//@{
/**
file type definition
*/
#define S4_RSA_PUBLIC_FILE 0x00000006 /** RSA public key file*/
#define S4_RSA_PRIVATE_FILE 0x00000007 /** RSA private key file*/
#define S4_EXE_FILE 0x00000008 /** executable file of virtual machine*/
#define S4_DATA_FILE 0x00000009 /** data file*/
#define S4_XA_EXE_FILE 0x0000000b /** executable file of XA User mode*/
//@}
//@{
/**
flag value definition
*/
#define S4_CREATE_NEW 0x000000a5 /** create a new file*/
#define S4_UPDATE_FILE 0x000000a6 /** write data to the specified file*/
#define S4_KEY_GEN_RSA_FILE 0x000000a7 /** generate RSA key pair files*/
#define S4_SET_LICENCES 0x000000a8 /** set the max license number of the current module for the net device*/
#define S4_CREATE_ROOT_DIR 0x000000ab /** create root directory*/
#define S4_CREATE_SUB_DIR 0x000000ac /** create child directory for current directory*/
#define S4_CREATE_MODULE 0x000000ad /** create a module directory for the net device */
/** the following three flags can only be used when creating a new executable file */
#define S4_FILE_READ_WRITE 0x00000000 /** the new executable file can be read and written by executable file */
#define S4_FILE_EXECUTE_ONLY 0x00000100 /** the new executable file can't be read or written by executable file*/
#define S4_CREATE_PEDDING_FILE 0x00002000 /** create a padding file*/
//@}
//@{
/**
execuable file executing mode definition
*/
#define S4_VM_EXE 0x00000000 /** executing on virtual machine*/
#define S4_XA_EXE 0x00000001 /** executing on XA User mode */
//@}
//@{
/**
return value definition
*/
#define S4_SUCCESS 0x00000000 /** success*/
#define S4_UNPOWERED 0x00000001 /** the device has been powered off*/
#define S4_INVALID_PARAMETER 0x00000002 /** invalid parameter*/
#define S4_COMM_ERROR 0x00000003 /** communication error*/
#define S4_PROTOCOL_ERROR 0x00000004 /** communication protocol error*/
#define S4_DEVICE_BUSY 0x00000005 /** the device is busy*/
#define S4_KEY_REMOVED 0x00000006 /** the device has been removed */
#define S4_INSUFFICIENT_BUFFER 0x00000011 /** the input buffer is insufficient*/
#define S4_NO_LIST 0x00000012 /** find no device*/
#define S4_GENERAL_ERROR 0x00000013 /** general error, commonly indicates not enough memory*/
#define S4_UNSUPPORTED 0x00000014 /** the function isn't supported*/
#define S4_DEVICE_TYPE_MISMATCH 0x00000020 /** the device type doesn't match*/
#define S4_FILE_SIZE_CROSS_7FFF 0x00000021 /** the execuable file crosses address 0x7FFF*/
#define S4_CURRENT_DF_ISNOT_MF 0x00000201 /** a net module must be child directory of the root directory*/
#define S4_INVAILABLE_MODULE_DF 0x00000202 /** the current directory is not a module*/
#define S4_FILE_SIZE_TOO_LARGE 0x00000203 /** the file size is beyond address 0x7FFF*/
#define S4_DF_SIZE 0x00000204 /** the specified directory size is too small*/
#define S4_DEVICE_UNSUPPORTED 0x00006a81 /** the request can't be supported by the device*/
#define S4_FILE_NOT_FOUND 0x00006a82 /** the specified file or directory can't be found */
#define S4_INSUFFICIENT_SECU_STATE 0x00006982 /** the security state doesn't match*/
#define S4_DIRECTORY_EXIST 0x00006901 /** the specified directory has already existed*/
#define S4_FILE_EXIST 0x00006a80 /** the specified file or directory has already existed*/
#define S4_INSUFFICIENT_SPACE 0x00006a84 /** the space is insufficient*/
#define S4_OFFSET_BEYOND 0x00006B00 /** the offset is beyond the file size*/
#define S4_PIN_BLOCK 0x00006983 /** the specified pin or key has been locked*/
#define S4_FILE_TYPE_MISMATCH 0x00006981 /** the file type doesn't match*/
#define S4_CRYPTO_KEY_NOT_FOUND 0x00009403 /** the specified pin or key cann't be found*/
#define S4_APPLICATION_TEMP_BLOCK 0x00006985 /** the directory has been temporarily locked*/
#define S4_APPLICATION_PERM_BLOCK 0x00009303 /** the directory has been locked*/
#define S4_DATA_BUFFER_LENGTH_ERROR 0x00006700 /** invalid data length*/
#define S4_CODE_RANGE 0x00010000 /** the PC register of the virtual machine is out of range*/
#define S4_CODE_RESERVED_INST 0x00020000 /** invalid instruction*/
#define S4_CODE_RAM_RANGE 0x00040000 /** internal ram address is out of range*/
#define S4_CODE_BIT_RANGE 0x00080000 /** bit address is out of range*/
#define S4_CODE_SFR_RANGE 0x00100000 /** SFR address is out of range*/
#define S4_CODE_XRAM_RANGE 0x00200000 /** external ram address is out of range*/
#define S4_ERROR_UNKNOWN 0xffffffff /** unknown error*/
//@}
#define MAX_ATR_LEN 56 /** max ATR length */
#define MAX_ID_LEN 8 /** max device ID length */
#define S4_RSA_MODULUS_LEN 128 /** RSA key modules length,in bytes */
#define S4_RSA_PRIME_LEN 64 /** RSA key prime length,in bytes*/
//@{
/**
structure definition
*/
/* file information definition*/
typedef struct{
WORD EfID; /* file ID*/
BYTE EfType; /* file type*/
WORD EfSize; /* file size*/
}EFINFO,*PEFINFO;
/* device production date structure definition*/
typedef struct {
WORD wYear; /* year*/
BYTE byMonth; /* month*/
BYTE byDay; /* the day of the month */
}S4_MANUFACTURE_DATE;
/* current time structure definition*/
#ifndef _TM_DEFINED
typedef struct {
int tm_sec; /* seconds after the minute - [0,59] */
int tm_min; /* minutes after the hour - [0,59] */
int tm_hour; /* hours since midnight - [0,23] */
int tm_mday; /* day of the month - [1,31] */
int tm_mon; /* months since January - [0,11] */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday - [0,6] */
int tm_yday; /* days since January 1 - [0,365] */
int tm_isdst; /* daylight savings time flag */
} TM;
#define _TM_DEFINED
#endif
/**
device version definition
*/
typedef enum{
SENSE4_CARD_TYPE_V2_00 = 0x00020000, /** version 2.00*/
SENSE4_CARD_TYPE_V2_01 = 0x00020001, /** version 2.10*/
SENSE4_CARD_TYPE_V2_02 = 0x00020002, /** version 2.20*/
SENSE4_CARD_TYPE_V2_05 = 0x00020005, /** version 2.05*/
SENSE4_CARD_TYPE_V2_30 = 0x00020300 /** version 2.30*/
}CARD_VERSION;
/**
device information structure definition
*/
typedef struct {
DWORD dwIndex; /** device index; index begins at zero*/
DWORD dwVersion; /** device version*/
S4HANDLE hLock; /** device handle*/
BYTE reserve[12]; /** reserved*/
BYTE bAtr[MAX_ATR_LEN]; /** ATR*/
BYTE bID[MAX_ID_LEN]; /** device ID*/
DWORD dwAtrLen; /** ATR length*/
}SENSE4_CONTEXT,*PSENSE4_CONTEXT;
/** RSA public key structure*/
typedef struct {
unsigned char modulus[S4_RSA_MODULUS_LEN]; /* modulus*/
unsigned char exponent[S4_RSA_MODULUS_LEN]; /* public exponent*/
} S4_RSA_PUBLIC_KEY;
/** RSA private key structure*/
typedef struct {
unsigned char modulus[S4_RSA_MODULUS_LEN]; /* modulus*/
unsigned char publicExponent[S4_RSA_MODULUS_LEN]; /* public exponent*/
unsigned char exponent[S4_RSA_MODULUS_LEN]; /* private exponent*/
unsigned char prime[2][S4_RSA_PRIME_LEN]; /* prime factors*/
unsigned char primeExponent[2][S4_RSA_PRIME_LEN]; /* exponents for CRT*/
unsigned char coefficient[S4_RSA_PRIME_LEN]; /* CRT coefficient*/
} S4_RSA_PRIVATE_KEY;
/** Netlock Module infomation definition*/
typedef struct _S4MODULEINFO {
WORD wModuleID; /* Module ID*/
WORD wLicenseCount; /* License Count */
} S4MODULEINFO;
typedef struct _S4NETCONFIG {
DWORD dwLicenseMode; /* License Mode */
DWORD dwModuleCount; /* Module Count */
S4MODULEINFO ModuleInfo[16]; /* Module detail infomation */
} S4NETCONFIG;
/** S4CREATEDIRINFO structure definition*/
typedef struct _S4CREATEDIRINFO {
DWORD dwS4CreateDirInfoSize; /* size of the structure*/
BYTE szAtr[8]; /* ATR information */
S4NETCONFIG NetConfig; /* netlock config infomation */
} S4CREATEDIRINFO;
/** S4OPENINFO structure definition*/
typedef struct _S4OPENINFO {
DWORD dwS4OpenInfoSize; /* size of the structure*/
DWORD dwShareMode; /* share mode*/
} S4OPENINFO;
//@}
//@{
/**
@function interface
*/
/*
reserved
*/
unsigned long WINAPI S4Startup(
VOID
);
/*
reserved
*/
unsigned long WINAPI S4Cleanup(
VOID
);
/**
enumerate all EliteIV devices plugged in the computer.
if pS4CtxList is NULL, the pdwCtxListSize will return the required buffer size
@paramter pS4CtxList [out] return the device list
@paramter pdwCtxListSize [in][out] return the amount of storage of device list, in bytes.
@return value
if the function succeeds,the return vlaue is S4_SUCCESS, otherwise return other defined return value.
*/
DWORD WINAPI S4Enum(
OUT SENSE4_CONTEXT *pS4CtxList,
IN OUT DWORD *pdwCtxListSize
);
/**
open the EliteIV device with sharable mode
@paramter pS4Ctx [in][out] the context pointer of the device
@return value
if the function succeeds,the return vlaue is S4_SUCCESS, otherwise return other defined return value.
*/
DWORD WINAPI S4Open(
IN OUT SENSE4_CONTEXT *pS4Ctx
);
/**
close the EliteIV device
@parameter pS4Ctx [in] the context pointer of the device
@return value
if the function succeeds,the return vlaue is S4_SUCCESS, otherwise return other defined return value.
*/
DWORD WINAPI S4Close(
IN SENSE4_CONTEXT *pS4Ctx
);
/**
Send control command to device
@parameter pS4Ctx [in] the context pointer of the device, the device must has been opened
@parameter dwCtlCode [in] control code
@parameter pInBuffer [in] input buffer
@parameter dwInBufferLen [in] the length of input data,in bytes
@parameter pOutBuffer [out] return output data
@parameter dwOutBufferLen [in] output buffer size, in bytes
@parameter pdwBytesReturned [out] the length of output data, cannot be NULL
@return value
if the function succeeds,the return vlaue is S4_SUCCESS, otherwise return other defined return value.
*/
DWORD WINAPI S4Control(
IN SENSE4_CONTEXT *pS4Ctx,
IN DWORD dwCtlCode,
IN VOID *pInBuffer,
IN DWORD dwInBufferLen,
OUT VOID *pOutBuffer,
IN DWORD dwOutBufferLen,
OUT DWORD *pdwBytesReturned
);
/**
create a new child directory for the current directory, and set current directory to the new directory
@parameter pS4Ctx [in] the context pointer of the device, the device must has been opened
@parameter lpszDirID [in] ID of the new directory
@parameter dwDirSize [in] size of the new directory
@parameter dwFlags [in] flag
@return value
if the function succeeds,the return vlaue is S4_SUCCESS, otherwise return other defined return value.
*/
DWORD WINAPI S4CreateDir(
IN SENSE4_CONTEXT *pS4Ctx,
IN LPCSTR lpszDirID,
IN DWORD dwDirSize,
IN DWORD dwFlags
);
/**
set the current directory
@parameter pS4Ctx [in] the context pointer of the device, the device must has been opened
@parameter lpszPath [in] ID of the specified directory
@return value
if the function succeeds,the return vlaue is S4_SUCCESS, otherwise return other defined return value.
*/
DWORD WINAPI S4ChangeDir(
IN SENSE4_CONTEXT *pS4Ctx,
IN LPCSTR lpszPath
);
/**
erase the root and empty the device if the specified direcotry is the device root,
otherwise erase all files or child direcotries of the specified directory.
@parameter pS4Ctx [in] the context pointer of the device, the device must has been opened
@parameter lpszDirID [in] reserved, must be NULL
@return value
if the function succeeds,the return vlaue is S4_SUCCESS, otherwise return other defined return value.
*/
DWORD WINAPI S4EraseDir(
IN SENSE4_CONTEXT *pS4Ctx,
IN LPCTSTR lpszDirID
);
/**
verify the pin, to reach a security status before call S4CreateDir,S4EraseDir,S4Execute,S4WriteFile.
@parameter pS4Ctx [in] the context pointer of the device, the device must has been opened
@parameter pbPin [in] PIN value
@parameter dwPinLen [in] the PIN value length, the length of User PIN is 8 bytesthe length of developer PIN is 24 bytes
@parameter dwPinType [in] PIN type
@return value
if the function succeeds,the return vlaue is S4_SUCCESS, otherwise return other defined return value.
*/
DWORD WINAPI S4VerifyPin(
IN SENSE4_CONTEXT *pS4Ctx,
IN BYTE *pbPin,
IN DWORD dwPinLen,
IN DWORD dwPinType
);
/**
change PIN or key value
@parameter pS4Ctx [in] the context pointer of the device, the device must has been opened
@parameter pbOldPin [in] old PIN or key value
@parameter dwOldPinLen [in] the length of old PIN or key value
@parameter pbNewPin [in] new PIN or key value
@parameter dwNewPinLen [in] the legnth of new PIN or key value
@parameter dwPinType [in] PIN or key type
@return value
if the function succeeds,the return vlaue is S4_SUCCESS, otherwise return other defined return value.
*/
DWORD WINAPI S4ChangePin(
IN SENSE4_CONTEXT *pS4Ctx,
IN BYTE *pbOldPin,
IN DWORD dwOldPinLen,
IN BYTE *pbNewPin,
IN DWORD dwNewPinLen,
IN DWORD dwPinType
);
/**
create a new file or update file data
@parameter pS4Ctx [in] the context pointer of the device, the device must has been opened
@parameter lpszFileID [in] ID of the specified file
@parameter dwOffset [in] offset to write the file
@parameter pBuffer [in] input data buffer
@parameter dwBufferSize [in] input data length
@parameter dwFileSize [in] file size
@parameter pdwBytesWritten [out] return the length of data written into the file
@parameter dwFlags [in] flag
@parameter bFileType [in] file type
@return value
if the function succeeds,the return vlaue is S4_SUCCESS, otherwise return other defined return value.
*/
DWORD WINAPI S4WriteFile(
IN SENSE4_CONTEXT *pS4Ctx,
IN LPCSTR lpszFileID,
IN DWORD dwOffset,
IN VOID *pBuffer,
IN DWORD dwBufferSize,
IN DWORD dwFileSize,
OUT DWORD *pdwBytesWritten,
IN DWORD dwFlags,
IN BYTE bFileType
);
/**
execute the specified executable file of current directory on virtual machine
@parameter pS4Ctx [in] the context pointer of the device, the device must has been opened
@parameter lpszFileID [in] ID of the executable file
@parameter pInBuffer [in] input data buffer
@parameter dwInbufferSize [in] input data length
@parameter pOutBuffer [out] output data buffer
@parameter dwOutBufferSize [in] output data buffer size
@parameter pdwBytesReturned [out] output data length
@return value
if the function succeeds,the return vlaue is S4_SUCCESS, otherwise return other defined return value.
*/
DWORD WINAPI S4Execute(
IN SENSE4_CONTEXT *pS4Ctx,
IN LPCSTR lpszFileID,
IN VOID *pInBuffer,
IN DWORD dwInbufferSize,
OUT VOID *pOutBuffer,
IN DWORD dwOutBufferSize,
OUT DWORD *pdwBytesReturned
);
/**
execute the specified executable file of current directory on virtual machine
or on XA User mode
@parameter pS4Ctx [in] the context pointer of the device, the device must has been opened
@parameter lpszFileID [in] ID of the executable file
@parameter dwFlag [in] executing mode
@parameter pInBuffer [in] input data buffer
@parameter dwInbufferSize [in] input data length
@parameter pOutBuffer [out] output data buffer
@parameter dwOutBufferSize [in] output data buffer size
@parameter pdwBytesReturned [out] output data length
@return value
if the function succeeds,the return vlaue is S4_SUCCESS, otherwise return other defined return value.
*/
DWORD WINAPI S4ExecuteEx(
IN SENSE4_CONTEXT *pS4Ctx,
IN LPCSTR lpszFileID,
IN DWORD dwFlag,
IN VOID *pInBuffer,
IN DWORD dwInbufferSize,
OUT VOID *pOutBuffer,
IN DWORD dwOutBufferSize,
OUT DWORD *pdwBytesReturned
);
/**
create a new child directory for the current directory, and set the new
directory to current directory. if creating the root directory, the function
will create a ATR file at the same time.
@parameter pS4Ctx [in] the context pointer of the device, the device must has been opened
@parameter lpszDirID [in] ID of the new directory
@parameter dwDirSize [in] size of the new directory
@parameter dwFlags [in] flag
@parameter pCreateDirInfo [in] S4CREATEDIRINFO structure pointer
@return value
if the function succeeds,the return vlaue is S4_SUCCESS, otherwise return other defined return value.
*/
DWORD WINAPI S4CreateDirEx(
IN SENSE4_CONTEXT *pS4Ctx,
IN LPCSTR lpszDirID,
IN DWORD dwDirSize,
IN DWORD dwFlags,
IN S4CREATEDIRINFO *pCreateDirInfo
);
/**
open the EliteIV device using specific mode
@paramter pS4Ctx [in][out] the context pointer of the device
@paramter pS4OpenInfo [in] S4OPENINFO structure pointer
@return value
if the function succeeds,the return vlaue is S4_SUCCESS, otherwise return other defined return value.
*/
DWORD WINAPI S4OpenEx(
IN OUT SENSE4_CONTEXT *pS4Ctx,
IN S4OPENINFO *pS4OpenInfo
);
//@}
#ifdef __cplusplus
}
#endif
#endif //__SENSE4_H__
Loading…
Cancel
Save