Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@leoleozhu
Created August 19, 2019 03:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leoleozhu/5ebe9628f79e9d35a96e3369dc3f882e to your computer and use it in GitHub Desktop.
Save leoleozhu/5ebe9628f79e9d35a96e3369dc3f882e to your computer and use it in GitHub Desktop.
Draw transparent text with iText 7
class TextBox {
private UUID uuid;
private float x;
private float y;
private float width;
private float height;
private double angle;
private PdfFont font;
private float fontSize;
private float characterSpacing;
private float lineHeight;
private int r,g,b,a;
}
class PdfGenerator {
private static void applyText(PdfPage page, TextBox box, UserText userText) {
AffineTransform at = AffineTransform.getTranslateInstance(box.getX(), box.getY());
at.concatenate(AffineTransform.getTranslateInstance(0, box.getHeight()));
at.concatenate(AffineTransform.getRotateInstance(box.getAngle()));
float[] matrix = new float[6];
at.getMatrix(matrix);
PdfCanvas canvas = new PdfCanvas(page);
canvas.beginText()
.setFontAndSize(box.getFont(), box.getFontSize())
.setCharacterSpacing(box.getCharacterSpacing())
.setLineWidth(box.getLineHeight())
.setLeading(box.getFontSize()*box.getLineHeight())
.setTextMatrix(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
// color
canvas.setFillColorRgb(box.getR()/255f, box.getG()/255f, box.getB()/255f);
PdfExtGState gs1 = new PdfExtGState();
gs1.setFillOpacity(box.getA()/255f);
canvas.setExtGState(gs1);
for(String s: userText.getContent().split("[\\r\\n]+")) {
if(box.getFont().getWidth(s, box.getFontSize()) + s.length() * box.getCharacterSpacing() <= box.getWidth()) {
canvas.newlineShowText(s);
} else {
StringBuilder sb = new StringBuilder();
float width = 0;
for(char character: s.toCharArray()) {
float charWidth = box.getFont().getWidth(Character.toString(character), box.getFontSize());
if (width + charWidth + box.getCharacterSpacing() > box.getWidth()) { // overflow...
// add the current string and reset
canvas.newlineShowText(sb.toString());
sb = new StringBuilder();
width = 0;
}
if(sb.length() > 0) {
width += box.getCharacterSpacing();
}
width += charWidth;
sb.append(character);
}
if(width > 0) {
canvas.newlineShowText(sb.toString());
}
}
}
canvas.endText();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment