jxl.WritableCellFormat definition - java

Is it possible to create one jxl.WritableCellFormat attribute which contains Font, NumberFormat, BackgroundColor and Border?
This works:
public static final NumberFormat numberformatter = new NumberFormat("#,###0.00");
public static final WritableFont defaultfont = new WritableFont(WritableFont.TAHOMA, 10);
public static final WritableCellFormat numberCellFormat = new WritableCellFormat(defaultfont, numberformatter); '
but I can't get borders and colors, thought same kind of cell is needed many times when creating sheets.

You can set the border and background via the WritableCellFormat.setBorder() and WritableCellFormat.setBackground() methods after having instanciated your cell.
You can see the API there.
If you have to do that a lot, you can make a helper function like this :
public static makeCell(NumberFormat format, WritableFont font, Color backgrd, Border border){
final WritableCellFormat result = new WritableCellFormat(defaultfont, numberformatter);
result.setBorder(border);
result.setBackground(backgrd);
return result;
}

You Can do this by 2 steps
Create a WritableFont
Create a WritableCellFormat with WritableFont,NumberFormats as a parameter
Attaching the code snippet
int fontSize = 8;
WritableFont wfontStatus = new WritableFont(WritableFont.ARIAL, fontSize);
wfontStatus.setColour(Colour.BLACK);
wfontStatus.setBoldStyle(WritableFont.BOLD);
WritableCellFormat fCellstatus = new WritableCellFormat(wfontStatus, NumberFormats.TEXT); // You can use any NumberFormats I have used TEXT for my requirement
try {
fCellstatus.setWrap(true);
fCellstatus.setBorder(Border.ALL,BorderLineStyle.THIN);
fCellstatus.setAlignment(Alignment.CENTRE);
fCellstatus.setBackground(Colour.YELLOW);
}
catch (WriteException e) {
e.printStackTrace();
}

Related

Issue with Adding TextField to PdfPCell

I'm using itext to generate editable Calendar pdf.
Im trying to add TextField to the PdfPCell using this code,
//To create PdfPCell for a specific day
public PdfPCell getDayCell(Calendar calendar, Locale locale) {
PdfPCell cell = new PdfPCell();
cell.setPadding(3);
// set the background color, based on the type of day
if (isSunday(calendar))
cell.setBackgroundColor(BaseColor.GRAY);
else if (isSpecialDay(calendar))
cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
else
cell.setBackgroundColor(BaseColor.WHITE);
// set the content in the language of the locale
Chunk chunk = new Chunk(String.format(locale, "%1$ta", calendar), small);
chunk.setTextRise(5);
// a paragraph with the day
Paragraph p = new Paragraph(chunk);
// a separator
p.add(new Chunk(new VerticalPositionMark()));
// and the number of the day
p.add(new Chunk(String.format(locale, "%1$te", calendar), normal));
cell.addElement(p);
cell.setCellEvent(new MyCellField(locale+""+calendar));
cell.setFixedHeight(80);
return cell;
}
// Adding TextField to the cellEvent
class MyCellField implements PdfPCellEvent {
protected String fieldname;
public MyCellField(String fieldname) {
this.fieldname = fieldname;
}
public void cellLayout(PdfPCell cell, Rectangle rectangle, PdfContentByte[] canvases) {
final PdfWriter writer = canvases[0].getPdfWriter();
final TextField textField = new TextField(writer, rectangle, fieldname);
textField.setAlignment(Element.ALIGN_TOP);
textField.setOptions(TextField.MULTILINE);
try {
final PdfFormField field = textField.getTextField();
writer.addAnnotation(field);
} catch (final IOException ioe) {
throw new ExceptionConverter(ioe);
} catch (final DocumentException de) {
throw new ExceptionConverter(de);
}
}
}
When I render the calendar pdf, the Cell focus is vertical not horizontal.
Kindly help me to find out what I'm missing.
NOTE: Please don't negative vote, I really want to figure out how to solve this. I referred other links like ITextSharp - text field in PdfPCell which where not helpful.
I tried adding
float textboxheight = 12f;
Rectangle rect = rectangle;
rect.Bottom = rect.Top - textboxheight;
rect.Bottom is showing error "The final field Rectangle.BOTTOM cannot be assigned".
Im using iText5
I think it's odd, because the behavior you describe isn't supposed to happen in the official iText version. (That makes me wonder: where did you get your version?)
However, you could try replacing this line:
Document document = new Document(PageSize.A4);
With this line:
Document document = new Document(new Rectangle(842, 595));

Font displays in text field very small

I have this class, and I am trying to display a custom font in a text field, but but when I run it the font is super tiny like 2px tiny. If i just run font = new Font("sans-serif", Font.PLAIN, 24); it displays just fine at the right font size.
Here is what it looks like:
Here is what it looks like when I only use font = new Font("sans-serif", Font.PLAIN, 24);
What is causing the small text box with a custom font?
public class Search extends JTextField{
public Search(int width){
super(width);
Font font;
String filename = "/media/fonts/SourceCodePro-Light.ttf";
try{
InputStream is = this.getClass().getResourceAsStream(filename);
font = Font.createFont(Font.TRUETYPE_FONT, is);
font = font.deriveFont(24);
}catch(FontFormatException | IOException ex){
font = new Font("sans-serif", Font.PLAIN, 24);
}
this.setFont(font);
}
}
font.deriveFont has two overloaded forms that can be quite similar. The one taking int sets the font style, the one taking float sets the font size. YOu are invoking the int version instead of the float version. Change 24 to 24.0f, and it will work

Itext New Font with Bold and Underline

I am trying to add new font to my pdf which I need to make it bold and underlined..
I can add the new Font, but cannot make it bold and underlined at same time.
I tried the following way..
public class PdfGenerator {
private static final String BASE_FONT = "Trebuchet MS";
private static final String BASE_FONT_BOLDITALIC = "Trebuchet MS BI";
private static final String BASE_FONT_BOLD = "Trebuchet MS B";
private static final Font titlefontSmall = FontFactory.getFont(
BASE_FONT_BOLD, 10, Font.UNDERLINE);
static {
String filePath = "..my font directory";
String fontPath = filePath + "\\" + "trebuc.ttf";
String fontPathB = filePath + "\\" + "TREBUCBD.TTF";
String fontPathBI = filePath + "\\" + "TREBUCBI.TTF";
FontFactory.register(fontPath, BASE_FONT);
FontFactory.register(fontPathB, BASE_FONT_BOLD);
FontFactory.register(fontPathBI, BASE_FONT_BOLDITALIC);
}
public void genMyPdf(String filePath) {
try {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(filePath));
document.open();
Paragraph p = new Paragraph("This should be bold & underline",
titlefontSmall);
document.add(p);
document.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
What am I doing wrong ?
you can define a font object with both styles :
private static final Font SUBFONT = new Font(Font.getFamily("TIMES_ROMAN"), 12, Font.BOLD|Font.UNDERLINE);
Read up on HERE since you are using the IText library.
Basically use chunks then add those chunks to the document.
Chunk underline = new Chunk("Underline. ");
underline.setUnderline(0.1f, -2f); //0.1 thick, -2 y-location
document.add(underline);
I haven't tried it myself so I don't know how it turns out yet. Further reading up on the iText documentation, it seems that you have to define a bold font first and then implement it. THIS TUTORIAL shows an example of bold font usage with iText and making a pdf with bold text. From there, I'm sure you can implement the code above to the bold text and walah!, bold-underlined text :D
You can define your FONT in your class as such:
public final static Font CUSTOM_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD | Font.UNDERLINE);
and then use it as :
paragraph.add(new Phrase( " YOUR TEXT HERE ",PDFCreator.CUSTOM_FONT));
try it
Font fontbold = FontFactory.getFont("Times-Roman", 12, Font.BOLD);
document.add(new Paragraph("Times-Roman, Bold", fontbold));
and Font.UNDERLINE for undeline
You can just use the following to get both bold and underline:-
Chunk buyerOrder = new Chunk("Buyer's Order Number", FontFactory.getFont(FontConstants.TIMES_ROMAN,8,Font.BOLD));
buyerOrder.setUnderline(0.1f, -2f);
Hope it helps! Thanks

iText - Get Font size and family of a text segment

I'm currently trying to automatically extract important keywords from a PDF file. I am able to get the text information out of the PDF document. But now I need to know, which font size and font family these keywords have.
The following code I already have:
Main
public static void main(String[] args) throws IOException {
String src = "SEM_081145.pdf";
PdfReader reader = new PdfReader(src);
SemTextExtractionStrategy semTextExtractionStrategy = new SemTextExtractionStrategy();
PrintWriter out = new PrintWriter(new FileOutputStream(src + ".txt"));
Rectangle rect = new Rectangle(70, 80, 490, 580);
RenderFilter filter = new RegionTextRenderFilter(rect);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
// strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), filter);
out.println(PdfTextExtractor.getTextFromPage(reader, i, semTextExtractionStrategy));
}
out.flush();
out.close();
}
And I have implemented the TextExtraction Strategy SemTextExtractionStrategy which looks like this:
public class SemTextExtractionStrategy implements TextExtractionStrategy {
private String text;
#Override
public void beginTextBlock() {
}
#Override
public void renderText(TextRenderInfo renderInfo) {
text = renderInfo.getText();
System.out.println(renderInfo.getFont().getFontType());
System.out.print(text);
}
#Override
public void endTextBlock() {
}
#Override
public void renderImage(ImageRenderInfo renderInfo) {
}
#Override
public String getResultantText() {
return text;
}
}
I can get the FontType but there is no method to get the font size. Is there another way or how can I get the font size of the current text segment?
Or are there any other libraries which can fetch out the font size from TextSegments? I already had a look into PDFBox, and PDFTextStream. The PDF Shareware Library from Aspose would perfectly do the job. But it's very expensive and I need to use an open source project.
Thanks to Alexis I could convert his C# solution into Java code:
text = renderInfo.getText();
Vector curBaseline = renderInfo.getBaseline().getStartPoint();
Vector topRight = renderInfo.getAscentLine().getEndPoint();
Rectangle rect = new Rectangle(curBaseline.get(0), curBaseline.get(1), topRight.get(0), topRight.get(1));
float curFontSize = rect.getHeight();
I had some trouble using Alexis' and Prine's solution, since it doesn't deal with rotated text correctly. So this is what I do (sorry, in Scala):
val x0 = info.getAscentLine.getEndPoint
val x1 = info.getBaseline.getStartPoint
val x2 = info.getBaseline.getEndPoint
val length1 = (x2.subtract(x1)).cross((x1.subtract(x0))).lengthSquared
val length2 = x2.subtract(x1).lengthSquared
(length1, length2) match {
case (0, 0) => 0
case _ => length1 / length2
}
You can adapt the code provided in this answer, in particular this code snippet:
Vector curBaseline = renderInfo.GetBaseline().GetStartPoint();
Vector topRight = renderInfo.GetAscentLine().GetEndPoint();
iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(curBaseline[Vector.I1], curBaseline[Vector.I2], topRight[Vector.I1], topRight[Vector.I2]);
Single curFontSize = rect.Height;
This answer is in C#, but the API is so similar that the conversion to Java should be straightforward.
If you want the exact fontsize, use the following code in your renderText:
float fontsize = renderInfo.getAscentLine().getStartPoint().get(1)
- renderInfo.getDescentLine().getStartPoint().get(1);
Modify this as indicated in the other answers for rorated text.

Multiline JLabels - Java [duplicate]

This question already has answers here:
Multiline text in JLabel
(11 answers)
Closed 8 years ago.
I want JLabel text in multiline format otherwise text will be too long. How can we do this in Java?
If you don't mind wrapping your label text in an html tag, the JLabel will automatically word wrap it when its container's width is too narrow to hold it all. For example try adding this to a GUI and then resize the GUI to be too narrow - it will wrap:
new JLabel("<html>This is a really long line that I want to wrap around.</html>");
I recommend creating your own custom component that emulates the JLabel style while wrapping:
import javax.swing.JTextArea;
public class TextNote extends JTextArea {
public TextNote(String text) {
super(text);
setBackground(null);
setEditable(false);
setBorder(null);
setLineWrap(true);
setWrapStyleWord(true);
setFocusable(false);
}
}
Then you just have to call:
new TextNote("Here is multiline content.");
Make sure that you set the amount of rows (textNote.setRows(2)) if you want to pack() to calculate the height of the parent component correctly.
I suggest to use a JTextArea instead of a JLabel
and on your JTextArea you can use the method .setWrapStyleWord(true) to change line at the end of a word.
It is possible to use (basic) CSS in the HTML.
MultiLine Label with auto adjust height.
Wrap text in Label
private void wrapLabelText(JLabel label, String text) {
FontMetrics fm = label.getFontMetrics(label.getFont());
PlainDocument doc = new PlainDocument();
Segment segment = new Segment();
try {
doc.insertString(0, text, null);
} catch (BadLocationException e) {
}
StringBuffer sb = new StringBuffer("<html>");
int noOfLine = 0;
for (int i = 0; i < text.length();) {
try {
doc.getText(i, text.length() - i, segment);
} catch (BadLocationException e) {
throw new Error("Can't get line text");
}
int breakpoint = Utilities.getBreakLocation(segment, fm, 0, this.width - pointerSignWidth - insets.left - insets.right, null, 0);
sb.append(text.substring(i, i + breakpoint));
sb.append("<br/>");
i += breakpoint;
noOfLine++;
}
sb.append("</html>");
label.setText(sb.toString());
labelHeight = noOfLine * fm.getHeight();
setSize();
}
Thanks,
Jignesh Gothadiya

Categories