Java StyledText, appending text with different font? - java

I am new to Java and would like to know how to set the font and font color to be used for the next text to be added to a SWT StyledText box.
So for example I have an application that defines "command" and "data" text and each is to be displayed in a different font/color. So let's say I've just added some "command" text. Now how do I set things up so that the next text which will be "data" text is displayed in a different font and color?
I've done a lot of googling, but nothing seems to be helping me.
P.S.: This can't be the most efficient way to do it:
int a = st.getCharCount();
Font font = new Font(shlProtruleModifier.getDisplay(), "Courier", 10, SWT.NORMAL);
StyleRange[] sr = new StyleRange[1];
sr[0] = new StyleRange();
st.append("\r\nWhat the heck?");
sr[0].start = a;
sr[0].length = st.getCharCount() - a;
sr[0].font = font;
sr[0].foreground = SWTResourceManager.getColor(SWT.COLOR_BLACK);
st.replaceStyleRanges(sr[0].start, sr[0].length, sr);

So all I've been able to come up with the following technique that does work,
int a = st.getCharCount();
Font font = new Font(shlProtruleModifier.getDisplay(), "Courier", 10, SWT.NORMAL);
StyleRange[] sr = new StyleRange[1];
sr[0] = new StyleRange();
st.append("\r\nWhat the heck?");
sr[0].start = a;
sr[0].length = st.getCharCount() - a;
sr[0].font = font;
sr[0].foreground = SWTResourceManager.getColor(SWT.COLOR_BLACK);
st.replaceStyleRanges(sr[0].start, sr[0].length, sr);

Related

Can java use pdfbox to turn the red stamp into black

I tried to use the following code to convert the stamp color, but it didn't work
PDFDocumentSignature signature = signatures.get(i);
PDPageContentStream contents2 = new PDPageContentStream(pdDocument, pages,PDPageContentStream.AppendMode.APPEND, false, false);
PDExtendedGraphicsState r01 = new PDExtendedGraphicsState();
r01.setBlendMode(BlendMode.SATURATION);
contents2.setGraphicsStateParameters(r01);
contents2.setNonStrokingColor(Color.DARK_GRAY);
contents2.addRect(signature.getX(), signature.getY(), signature.getHeight(), signature.getHeight());
contents2.fill();
contents2.close();`
As it turned out in the comments to the question, the red stamp in question is a signature form field widget.
This explains why the OP's code could not de-saturate the stamp: That code de-saturates a portion of the static page content. Widgets (and annotations in general), though, are not part of the static page content but are rendered on top of it.
Thus, we have to manipulate the content stream of the widget annotation in question or another annotation over it.
You can manipulate the signature appearance like this:
PDDocument pdf = ...;
PDAcroForm acroForm = pdf.getDocumentCatalog().getAcroForm();
PDTerminalField acroField = (PDTerminalField) acroForm.getField("Signature1");
PDAnnotationWidget widget = acroField.getWidgets().get(0);
PDAppearanceStream appearance = widget.getAppearance().getNormalAppearance().getAppearanceStream();
byte[] originalBytes;
try ( InputStream oldContent = appearance.getContents() ) {
originalBytes = IOUtils.toByteArray(oldContent);
}
try ( PDPageContentStream canvas = new PDPageContentStream(pdf, appearance) ) {
canvas.appendRawCommands(originalBytes);
PDExtendedGraphicsState r01 = new PDExtendedGraphicsState();
r01.setBlendMode(BlendMode.SATURATION);
canvas.setGraphicsStateParameters(r01);
canvas.setNonStrokingColor(Color.DARK_GRAY);
PDRectangle bbox = appearance.getBBox();
canvas.addRect(bbox.getLowerLeftX(), bbox.getLowerLeftY(), bbox.getWidth(), bbox.getHeight());
canvas.fill();
}
pdf.save(RESULT);
(ChangeAppearance test testRemoveAppearanceSaturation)
before
after

Low Resolution, Blurry TrueType font in LibGDX

I'm programming a game in LibGDX, but when I try to display some text on the screen with a TrueType font (.ttf), it comes out somewhat blurry.
Why is this happening?
This is how I'm using the text in my code, implemented from this thread How to draw smooth text in libgdx?:
stage = new Stage(viewport, game.batch);
table = new Table();
table.center();
table.setFillParent(true);
generator = new FreeTypeFontGenerator(Gdx.files.internal("Lato-Bold.ttf"));
parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = 30;
parameter.color = Color.WHITE;
parameter.characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
font = generator.generateFont(parameter);
generator.dispose();
Label.LabelStyle labelStyle = new Label.LabelStyle(font, font.getColor());
touchToStartLabel = new Label("Touch To Start", labelStyle);
table.add(touchToStartLabel);
stage.addActor(table);
Any ideas on how I can get a better rendered text? It's been bugging me for a while.
EDIT: I tried to use trilinear filtering by changing the code to this (and I'm using a FitViewport in case that's important):
generator = new FreeTypeFontGenerator(Gdx.files.internal("Lato-Bold.ttf"));
parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = 30;
parameter.color = Color.WHITE;
parameter.minFilter = Texture.TextureFilter.MipMapLinearLinear;
parameter.magFilter = Texture.TextureFilter.Linear;
parameter.characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
font = generator.generateFont(parameter);
font.setUseIntegerPositions(false);
All I got was this (at least the squares are sharp):

LibGDX - How to save generated FreeType fonts

I have problem with fonts lin LibGDX. I have three different fonts and parameters:
parameter_score = new FreeTypeFontGenerator.FreeTypeFontParameter();
//Some parameters..
font_score = generator.generateFont(parameter_score);
parameter_Big = new FreeTypeFontGenerator.FreeTypeFontParameter();
//Some parameters..
font_Big = generator.generateFont(parameter_Big);
parameter_Small = new FreeTypeFontGenerator.FreeTypeFontParameter();
//Some parameters..
font_Small = generator.generateFont(parameter_Small);
and it is very slow to generate fonts. When the app starts, i see black screen for about 3 seconds. I heard about method, when I generate fonts only first time, then I save it to some file, and when I lunch app next time, it will get generated fonts from file. But i dont know how to save, and load generated fonts. Do anyone know?
BitmapFontWriter
BitmapFontWriter is a class in gdx-tools which can write BMFont files from a BitmapFontData instance. This allows a font to be generated using FreeTypeFontGenerator, then written to a font file and PNG files. BitmapFontWriter has the benefit that it can be more easily run from scripts and can make use of FreeTypeFontGenerator's shadows and borders. Otherwise, the output is very similar to Hiero, though Hiero avoids writing a glyph image multiple times if different character codes render the same glyph.
Usage can look like this:
new LwjglApplication(new ApplicationAdapter() {
public void create () {
FontInfo info = new FontInfo();
info.padding = new Padding(1, 1, 1, 1);
FreeTypeFontParameter param = new FreeTypeFontParameter();
param.size = 13;
param.gamma = 2f;
param.shadowOffsetY = 1;
param.renderCount = 3;
param.shadowColor = new Color(0, 0, 0, 0.45f);
param.characters = Hiero.EXTENDED_CHARS;
param.packer = new PixmapPacker(512, 512, Format.RGBA8888, 2, false, new SkylineStrategy());
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.absolute("some-font.ttf"));
FreeTypeBitmapFontData data = generator.generateData(param);
BitmapFontWriter.writeFont(data, new String[] {"font.png"},
Gdx.files.absolute("font.fnt"), info, 512, 512);
BitmapFontWriter.writePixmaps(param.packer.getPages(), Gdx.files.absolute("imageDir"), name);
System.exit(0);
}
});
https://github.com/libgdx/libgdx/wiki/Hiero#bitmapfontwriter

iText create PDF/A_1A with images

I am trying to create a pdf/a 1a document with iText 5.5.2
I can create a simple pdf/a with hello world but I am not able to add an image in the document without the error:
com.itextpdf.text.pdf.PdfAConformanceException: Alt entry should specify alternate description for /Figure element.
Below is my code tryout. I don't know how to add Alt entry Figure for the image. I tried with the PdfDictionary but it does not work. I am out of idea's. Does anyone have a tip for me?
final float MARGIN_OF_ONE_CM = 28.8f;
final com.itextpdf.text.Document document = new com.itextpdf.text.Document(PageSize.A4
, MARGIN_OF_ONE_CM
, MARGIN_OF_ONE_CM
, MARGIN_OF_ONE_CM
, MARGIN_OF_ONE_CM);
ByteArrayOutputStream pdfAsStream = new ByteArrayOutputStream();
PdfAWriter writer = PdfAWriter.getInstance(document,
new FileOutputStream("D:\\tmp\\pdf\\test.pdf"), PdfAConformanceLevel.PDF_A_1A);
document.addAuthor("Author");
document.addSubject("Subject");
document.addLanguage("nl-nl");
document.addCreationDate();
document.addCreator("Creator");
document.addTitle("title");
writer.setPdfVersion(PdfName.VERSION);
writer.setTagged();
writer.createXmpMetadata();
document.open();
final String FONT = "./src/main/resources/fonts/arial.ttf";
Font font = FontFactory.getFont(FONT, BaseFont.CP1252, BaseFont.EMBEDDED);
final Paragraph element = new Paragraph("Hello World", font);
document.add(element);
final InputStream logo = this.getClass().getResourceAsStream("/logos/logo.jpg");
final byte[] bytes = IOUtils.toByteArray(logo);
Image logoImage = Image.getInstance(bytes);
document.add(logoImage);
final String colorProfile = "/color/sRGB Color Space Profile.icm";
final InputStream resourceAsStream = this.getClass().getResourceAsStream(colorProfile);
ICC_Profile icc = ICC_Profile.getInstance(resourceAsStream);
writer.setOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
document.close();
Normally, you need to add the alternate description like this:
logoImage.setAccessibleAttribute(PdfName.ALT, new PdfString("Logo"));
This works for PDF/A2-A and PDF/A3-A, but not for PDF/A1-A. I have tested this and I see that you have discovered a bug. This bug has now been fixed. The fix will be in the next release.

Unable to change font of Vector element in blackberry

I am using Vector to add elements in a table in a blackberry project. The font does not seem to change programmatically. I have tested it in different screen blackberry phones. In BOLD & CURVE it seems fine, but in large screen phones like 9810 torch, 9790 BOLD, it takes some default font which is very big. Even if I change the font of the phone through setup, it changes the font of LabelFields and TextFields but applying FontFamily font does not reflect on Vector elements.
I am attaching the screenshots from 9800 & 9810...In 9800 it appears fine, in 9810, it looks big
Try this
for (int x = 0; x < vector.size(); x++) {
FriendListObject b = (FriendListObject) vector.elementAt(x);
name_ = b.getf_name().toString();
}
TableRowManager row = new TableRowManager() {
public void paint(Graphics g) {
g.setBackgroundColor(0xa2b8c3);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(0xe5e7e7);
g.clear();
super.paint(g);
}
};
LabelField name= new LabelField(name_+" :", DrawStyle.ELLIPSIS);
name.setFont(Font.getDefault().derive(Font.PLAIN));
row.add(name);
same situation I am also faced then,I customised fontfamily for each resolution.for example
if (Display.getWidth()==480 && Display.getHeight()==360) {
_custHeadNews = new CustTextField(_newsHead,30,0x05235b,TextField.FOCUSABLE);
_custMainNews = new CustTextField(_newsMain,25,0x666666, RichTextField.FOCUSABLE);
_custMetadata = new CustTextField(_metaData,15,0x666666,TextField.FOCUSABLE);
}
else if (Display.getWidth()==320 && Display.getHeight()==240) {
_custHeadNews = new CustTextField(_newsHead,25,0x05235b,TextField.FOCUSABLE);
_custMainNews = new CustTextField(_newsMain,15,0x666666, RichTextField.FOCUSABLE);
_custMetadata = new CustTextField(_metaData,10,0x666666,TextField.FOCUSABLE);
}
bolded font size for different resolutions.
This issue was solved by making changes in RegionStyles. Initially we had given Font parameter as null. After changing it to appFont1 instead of null, the app font stopped overriding and works fine now.
RegionStyles style = new RegionStyles(BorderFactory.createSimpleBorder(new XYEdges(5,0,0,0), Border.STYLE_TRANSPARENT), appFont1, null,null, RegionStyles.ALIGN_LEFT, RegionStyles.ALIGN_MIDDLE);

Categories

Resources