Using iTextSharp, I create a pdf writing some text into it.
What I need is to draw a line to delimiter the text every 25 words, like the following image:
Basically, I need to do that: draw a line every 25 words, just like the image.
I'm aware there's a way of finding the position of a word on a page, but considering I'm writing the text to the pdf file, I guess there could be a way of calculating this without really having to find the text position, right?
Please take a look at the Every25Words examples. In that example, I read a text file into a String with the readFile() method. I then split the text into words based on the occurrence of spaces, and I add each word one by one:
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
writer.setPageEvent(new WordCounter());
writer.setInitialLeading(16);
document.open();
String[] words = readFile().split("\\s+");
Chunk chunk = null;
for (String word : words) {
if (chunk != null) {
document.add(new Chunk(" "));
}
chunk = new Chunk(word);
chunk.setGenericTag("");
document.add(chunk);
}
document.close();
}
The magic happens in this line:
writer.setPageEvent(new WordCounter());
chunk.setGenericTag("");
First we declare an instance of the WordCounter event. You may choose a better name for that class, as not only does it count words, it also draws a dashed line:
public class WordCounter extends PdfPageEventHelper {
public int count = 0;
#Override
public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) {
count++;
if (count % 25 == 0) {
PdfContentByte canvas = writer.getDirectContent();
canvas.saveState();
canvas.setLineDash(5, 5);
canvas.moveTo(document.left(), rect.getBottom());
canvas.lineTo(rect.getRight(), rect.getBottom());
canvas.lineTo(rect.getRight(), rect.getTop());
canvas.lineTo(document.right(), rect.getTop());
canvas.stroke();
canvas.restoreState();
}
}
}
Do you see what we do between the saveState() and restoreState() method? We define a dash pattern, we move to the left of the page, we construct a path to the right of the word, then we draw a short upwards line, to finish the path with a line to the right. Once the path is constructed, we stroke the line.
This onGenericTag() method will be triggered every time a Chunk is added on which we used the setGenericTag method.
This is what the result looks like every25words.pdf:
Related
I need to search a String in a text file that the content in the text file will always be appended(in other method). For example String "abcdefg" need to be search exactly same in the file.
ArrayList<String> List = new ArrayList<String>();
FileReader filereader = new FileReader(file);
BufferedReader bufferreader = new BufferedReader(filereader);
String linetxt;
while((linetxt = bufferreader.readLine())!=null)
{
List.add(linetxt);
List.add("\r\n");
}
System.out.println("Please enter a string: ");
String usern = input.next();
System.out.println(List);
if ((List.contains(usern.substring(0,usern.length()))));
{
System.out.println("String existed.");
}
bufferreader.close();
The Test File current content (will always be added new content):
abcde12345
This is my code, but it occurs a problem that I will always get "String existed" no matter what I input(the String I input is not in the text file but it still printing that the String existed).
How can I modify my code to make that if my input is contained in the ArrayList, it will return "String existed"?
Is it any other ways to search a String in a text file(the content of text file will be appended in other method)?
Thanks.............. Hope everyone safe.
import java.util.ArrayList;
public class DataBase {
public ArrayList<String> nameList = new ArrayList<>();
public void nameAdd(String s, int i) {
if (i < nameList.size()){
nameList.add(i, s);
//string not adding to arrayList, ive probably done it wrong.
}
System.out.println(s);
System.out.println("nameList.size = " + nameList.size());
System.out.println("arrayList number = " + i);
}
}
I've been coding for about a month now so please excuse my noobieness but i'm trying to basically take a string from a GUI i've built, cut it up to get a name, and add that name to a "database" when the user clicks another button to add it to it. Ive already been able to increment the i which is supposed to set an index for the string within the arrayList but the arrayList isnt increasing in size and I get a whole bunch of errors thus the if statement ive added to stop it from trying to add to an index that isnt yet in the arrayList.
In your code I see your array nameList always empty.
Because you have this line:
public ArrayList<String> nameList = new ArrayList<>();
In this moment you create your array (empty), but in your nameAdd method if you pass this at the first time:
nameAdd('ADDFIRSTELEMENT', 0)
Your if statemnt is always false
if (i < nameList.size()){
nameList.add(i, s);
//string not adding to arrayList, ive probably done it wrong.
}
You must to change your check as follow:
if (i <= nameList.size())
Because if your index is the same of the size, you can add your element in the array.
If you want you can use the contains method of your nameList ArrayList object so you can see if your string is present in your array
I have a class with a TextField as a property. This text field is added to the stage and has a digit as a value of the text property. I also have a method, that must change this digit:
public function decrementCooldown()
{
cdText.text = (--cd.value != 0)? cd.value : "";
}
However, it changes nothing. I've modified the code that way:
public function decrementCooldown()
{
cdText.text = (--cd.value != 0)? cd.value : "";
cdText.x -= 100;
}
This caused my text field to move to the left, but its text remained the same.
Then, I've tried to trace the text before and after modifying it. The second line of the output contained the digit that I wanted to appear on screen, it was 1 less than the digit on the first line.
I wonder how to solve my problem.
Ok, this seems really strange to me, but the problem was with DropShadowFilter I had on the TextField.
I've fixed this problem by adding two lines that clear the filters array before modifying the text, then adding a DropShadowFilter again after that:
public function decrementCooldown()
{
cdText.filters = [];
cdText.text = (--cd.value != 0)? cd.value : "";
cdText.filters = [new DropShadowFilter()];
}
Seems like a bug though.
My app requires the Y-axis to have strings like 'Charging', 'Discharging' and 'Charging Failed'. Is it possible to plot a graph with this and have the parameter in question depicted in accordance with these strings on Android Plot?
I'm still not 100% sure I'm understanding the desired visualization but here are the basic steps I would suggest:
To start, you're going to need to convert your CSV data in to XYSeries data. To accomplish this, you'll need to map your current X/Y string values to numbers. I'd suggest creating a method that looks something like this:
// parses a CSV string into an XYSeries
// for example, DISCHARGE = 1, MPPT = 2
public XYSeries convertCSVToXYSeries(String csvContent) {...}
Next, setup your Plot etc. pretty much the same way you would for any other XYPlot as shown in the Androidplot Quickstart Tutorial.
When you add the XYSeries you get back from convertCSVToXYSeries to your plot, use an XYStepFormatter:
StepFormatter stepFormatter = new StepFormatter(Color.BLUE, Color.BLUE);
stepFormatter.setVertexPaint(null); // don't draw individual points
plot.addSeries(series, stepFormatter);
Finally, add a custom range value formatter to print your status strings instead of the int values they've been mapped to:
// create a custom getFormatter to draw our state names as range tick labels:
plot.setRangeValueFormat(new Format() {
#Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
Number num = (Number) obj;
switch(num.intValue()) {
case 1:
toAppendTo.append("DISCHARGE");
break;
case 2:
toAppendTo.append("MPPT");
break;
default:
toAppendTo.append("Unknown");
break;
}
return toAppendTo;
}
#Override
public Object parseObject(String source, ParsePosition pos) {
return null;
}
});
I want to program some kind of game where the player has to name loacations shown on a map. I am using the slick library.
My problem is that I need some way to get the keyboard input from the player. I tried it with InputDialog from JOptionPane but I do not really like it. I would rather have the string appear on some part of the screen. But I do not have any idea how I can read from the keyboard directly into a variable that should be drawn on the screen. I thought that it would be possible to use streams but if I try to get some examples, they are always about reading from files and I do not know how to use that for reading from keyboard.
String answer;
public void render(GameContainer gameContainer, StateBasedGame sbGame, Graphics g){
g.drawString(answer, 50, 50);
}
public void update(GameContainer gameContainer, StateBasedGame sbGame, int delta){
//user types something which I now call "inputFromUser"
//it does not appear anywhere before the string is drawn on the screen.
answer = inputFromUser;
}
Something like a Scanner does not work for me because the user has to type that into the console, and I want him to type it "directly into the game" like it works with a textfield. (But I do not want to use a textfield.)
I have one way to accomplish that but it's fairly resource intensive. First create a global variable to keep track of the current letters. now create a new method that runs through all of the keys to check if they are down
private String totalString;
private void handelUserInput(Input input){
if(input.isKeyDown(Input.KEY_BACK)){
totalString = totalString.substring(0, totalString.length() - 1);
}
if(input.isKeyDown(Input.KEY_A)){
totalString += "a";
}
if(input.isKeyDown(Input.KEY_B)){
totalString += "b";
}
...etc
}
next create an input handler in the update loop to pass into the handle input method.
public void update(GameContainer gc, StateBasedGame sbg, int delta)throws SlickException {
Input input = gc.getInput();
handelUserInput(input);
}
and then print the string somewhere on your window in the render loop. by the way the Input class is built into slick.