The apache POI project explains how to read a shape from a powerpoint slide http://poi.apache.org/slideshow/xslf-cookbook.html#GetShapes
However, I can't find any doc on how to add a shape to a powerpoint slide using this part of the library. If I use an old powerpoint format (ppt as opposed to pptx), I can just use the hslf part of the libaray and do:
SlideShow ppt = new SlideShow();
//add first slide
Slide s1 = ppt.createSlide();
// create shapes./
java.awt.geom.GeneralPath path = new java.awt.geom.GeneralPath();
path.moveTo(100, 100);
path.lineTo(200, 100);
path.curveTo(50, 45, 134, 22, 78, 133);
path.curveTo(10, 45, 134, 56, 78, 100);
path.lineTo(100, 200);
path.closePath();
Freeform shape = new Freeform();
shape.setPath(path);
s1.addShape(shape);
//save changes in a file
FileOutputStream out;
try {
out = new FileOutputStream("slideshow.ppt");
ppt.write(out);
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException ex) {
e.printStakTrace();
}
How would I do something similar using xlsf part of the library and thus generate a pptx?
Thanks
It's actually quite similar ...
XMLSlideShow ppt = new XMLSlideShow();
XSLFSlide s1 = ppt.createSlide();
// create shapes
java.awt.geom.Path2D.Double path = new java.awt.geom.Path2D.Double();
path.moveTo(100, 100);
path.lineTo(200, 100);
path.curveTo(50, 45, 134, 22, 78, 133);
path.curveTo(10, 45, 134, 56, 78, 100);
path.lineTo(100, 200);
path.closePath();
XSLFFreeformShape shape = s1.createFreeform();
shape.setPath(path);
shape.setLineWidth(1);
shape.setLineColor(Color.BLACK);
//save changes in a file
FileOutputStream out;
try {
out = new FileOutputStream("slideshow.pptx");
ppt.write(out);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
For more examples and Graphics2D context you can paint on, have a look on my PptxGraphics2D class.
Related
Hello im trying to output an excel file generated from a template xls using jxls library but I dont find the way to do so.
My code look like this:
ServletContext contexto = request.getServletContext();
String path = contexto.getRealPath("/lib/xlsx/plantilla.xlsx");
Conexion conexion = new Conexion();
List<Conexion> conexiones = new ArrayList<Conexion>();
ResultSet rs = CargarConsultas.ejecutarConsulta("CONS_GET_TABLA_CONEXION");
try {
while(rs.next()) {
conexion.setIp(rs.getString("ori_ip"));
conexion.setMac(rs.getString("ori_mac"));
conexion.setUrl_destino(rs.getString("url_dest"));
conexion.setSolicitud(rs.getString("time_stamp_solicitud"));
conexion.setUser_id(rs.getString("user_id"));
conexion.setSubida(rs.getString("icoming"));
conexion.setBajada(rs.getString("outgoing"));
conexion.setAutorizacion(rs.getString("time_stamp_autorizacion"));
conexion.setRenovacion(rs.getString("time_stamp_renovacion"));
conexion.setFin_sesion(rs.getString("time_stamp_fin_sesion"));
conexion.setGw_adress(rs.getString("gw_address"));
conexion.setGw_port(rs.getString("gw_port"));
conexiones.add(conexion);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
File salida = new File(path);
InputStream is = new FileInputStream(salida);
try (FileOutputStream os = new FileOutputStream("salida.xlsx")) {
Context context = new Context();
context.putVar("conexiones", conexiones);
JxlsHelper.getInstance().processTemplate(is, os, context);
} catch (Exception e) {
e.printStackTrace();
}
Please let me knoew if you know how to output it and no save it to server disk.The code works fine. Thanks alot
Good morning!
I'm using the iText library to create a pdf template and Primefaces to display the content on a web application.
When I ran the first test to see if all the libraries were all set, it was displayed normally. But then I made some changes, and it seems that something is caching my first test in memory and it is the only thing displayed, no matter what changes I make it keeps the same first content. I´ve already cleaned up my netbeans project, closed the IDE and also restarted the computer.
Thats is my tag on the jsf page:
<p:media value="#{atividadeController.pdfContent}" player="pdf" width="100%" height="700px"/>
And here is my method in the managed bean, which is a SessionScoped:
public String preparePdf()
{
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
Font fontHeader = new Font(Font.FontFamily.HELVETICA, 20, Font.BOLD);
Font fontLine = new Font(Font.FontFamily.TIMES_ROMAN, 14);
Font fontLineBold = new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD);
Document document = new Document();
PdfWriter.getInstance(document, output);
document.open();
//Writing document
Chunk preface = new Chunk("GERAL", fontHeader);
document.add(preface);
Calendar cal = Calendar.getInstance();
cal.setTime(current.getData());
int year = cal.get(Calendar.YEAR);
int month = 1 + cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
String dateStr = day+"/"+month+"/"+year;
Paragraph dataAndHour = new Paragraph(dateStr, fontLine);
document.add(dataAndHour);
document.close();
pdfContent = new DefaultStreamedContent(new ByteArrayInputStream(output.toByteArray()), "application/pdf");
} catch (Exception e) {
e.printStackTrace();
}
return "/views/view_atividade_pdf";
}
There is no exception on the server log.
I really aprecciate any help. Thanks in advance
I am working on a Webapp using PrimeFaces. I am very close to a solution, but am stuck with trying to update the chart as new data is calculated.
I have 3 tabs: Inputs, Outputs & Charts.
On the Inputs Tab, I have textboxes and a Submit button.
On the Outputs Tab, I have a datachart to display the data that is calculated after inputs are entered and submit is clicked. I have verified that data is populated correctly.
On the Charts Tab, I have a chart (will be multiple later) that is to display data from the calculation as well.
Here is my relevant code:
public void createNewChart() {
FileInputStream fis = null;
try {
//Graphic Text
BufferedImage bufferedImg = new BufferedImage(100, 25, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufferedImg.createGraphics();
g2.drawString("This is a text", 0, 10);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedImg, "png", os);
graphicText = new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()), "image/png");
//Chart
File chartFile = new File("C:\\Desktop\\Temp", "Chart" + Math.round(Math.random() * 1000000) + ".png");
chartData = calculateValuesServlet.getChartData();
calculateDataSets();
XYSeriesCollection xyDataset = new XYSeriesCollection();
xyDataset.addSeries(minumumLine);
xyDataset.addSeries(maximumLine);
xyDataset.addSeries(optimumLine);
xyDataset.addSeries(ratingPoint);
chart = ChartFactory.createXYLineChart("Chart Title", xAxis.getAxisLabel(), yAxis.getAxisLabel(), xyDataset, PlotOrientation.VERTICAL, true, false, false);
fixRenderings();
ChartUtilities.saveChartAsPNG(chartFile, chart, 375, 300);
fis = new FileInputStream(chartFile);
chartContent = new DefaultStreamedContent(fis, "image/png");
calculateValuesServlet.setNewChartNeeded(false);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException ex) {
Logger.getLogger(DataChart.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Also, in my index.html:
<p:tab title="Charts">
<h:panelGrid columns="2" cellpadding="10">
<p:graphicImage id="outputChart1" value="#{dataChart.chartContent}" />
</h:panelGrid>
</p:tab>
And for completeness, this is from DataChart.java:
public StreamedContent getChartContent() {
if (chartData != null && !chartData.isEmpty() && calculateValuesServlet.isNewChartNeeded()) {
createNewChart();
}
return chartContent;
}
I have started saving the charts to Desktop\Temp so that I can view the charts. The ones that are created in my Temp folder are correct, but the one that appears on the webapp is not. I also tried setting cache="FALSE" in the graphicImage, but then I get a broken image icon instead of the graph.
I realize this tells me that the webapp is not getting that latest image, but why?
I'm facing problem on image not refresh too.
Try to change the scope to #RequestScoped and add in cache="false" on p:graphicImage
after reading the question it looks like I have asked the question which was already asked but believe me I have tried the possible solutions where in I didn't get the desired output....
First of all What I want to achieve ?
To achieve the AntiAliasing , I have tried some of the way like
new Scene(,,,,SceneAntialiasing.BALANCED);
shape[object].setSmooth(true);
System.setProperty("prism.lcdtext", "false"); from the link
How to force anti-aliasing in JavaFX fonts?
I have tried to use SubScene as well , but it was somewhat improper way to go...
But none of the above solutions works for me ... So Now, I am posting the
SSCVE ...
Please help me on this ...
Thanks in advance...
SSCVE
the CreateScene method in UI class which extends JFXPanel looks like ....
private Scene createScene()
{
Group rootNode = new Group();
//System.setProperty("prism.lcdtext", "false");
double StrokeWidth = 1.0;
double yPosition = 20.0;
//textFontsize = textFontsize + 0.7 ;
// straight Vertical Lines
rootNode.getChildren().add(createLines(35.0, yPosition+20, 35.0, yPosition+150, StrokeWidth,"GREEN"));
rootNode.getChildren().add(createLines(25.0, yPosition+20, 25, yPosition+150, StrokeWidth,"BLACK"));
rootNode.getChildren().add(createLines(30.0, yPosition+20, 30, yPosition+150, StrokeWidth,"BLUE"));
// straight horizontal lines
rootNode.getChildren().add(createLines(80.0, yPosition+30, 240, yPosition+30, StrokeWidth,"RED"));
rootNode.getChildren().add(createLines(80.0, yPosition+40, 240, yPosition+40, StrokeWidth,"GREEN"));
rootNode.getChildren().add(createLines(80.0, yPosition+50, 240, yPosition+50, StrokeWidth,"BLACK"));
// create slope lines
rootNode.getChildren().add(createLines(420.0, yPosition+20, 470, yPosition+150, StrokeWidth,"BLACK"));
rootNode.getChildren().add(createLines(430.0, yPosition+20, 480, yPosition+150, StrokeWidth,"RED"));
rootNode.getChildren().add(createLines(440.0, yPosition+20, 490, yPosition+150, StrokeWidth,"BLUE"));
rootNode.getChildren().add(createLines(450.0, yPosition+20, 500, yPosition+150, StrokeWidth,"GREEN"));
double textFontsize = 12.0;
String fontColor = "RED";
String font ="Arial";
int count = 5;
String newLine = null;
if(count == 5)
{
newLine = "\n\n\n\n\n";
}
rootNode.getChildren().add(createText(50,yPosition+230,font,textFontsize, newLine+"15352465 \n"
+ "Circle is "+StrokeWidth+" . "+"Font name is "+font+" . Minimum visible font size is 0.7 ."
+ "\n The Font size for text is "+textFontsize+". ",fontColor, StrokeWidth));
ScrollPane scroll = new ScrollPane();
scroll.setHbarPolicy(ScrollBarPolicy.ALWAYS);
scroll.setVbarPolicy(ScrollBarPolicy.NEVER);
scroll.setContent(rootNode);
//iv.setClip(new Rectangle(0,20,250,200));
Scene sc = new Scene(scroll, 500,500,false,SceneAntialiasing.BALANCED);
SceneAntialiasing value = sc.getAntiAliasing();
return sc;
}
public Line createLines(double startX, double startY, double endX, double endY, double strokeWidth, String strokeColor)
{
Line line = new Line(startX-0.5, startY-0.5, endX-0.5, endY-0.5);
if(strokeColor.equals("BLUE"))
{
line.setStroke(javafx.scene.paint.Color.BLUE);
}
else if(strokeColor.equals("RED"))
{
line.setStroke(javafx.scene.paint.Color.RED);
}
else if(strokeColor.equals("GREEN"))
{
line.setStroke(javafx.scene.paint.Color.GREEN);
}
else if(strokeColor.equals("BLACK"))
{
line.setStroke(javafx.scene.paint.Color.BLACK);
}
line.setStrokeWidth(strokeWidth);
//line.setSmooth(true);
return line;
}
public Text createText(double xParam, double yParam, String fontType, double fontSize, String text, String strokeColor, double StrokeWidth)
{
Text txt = new Text(text);
txt.setX(xParam);
txt.setY(yParam);
if(fontType.equals("Comic Sans MS"))
{
txt.setFont(Font.font(fontType,FontWeight.BOLD, fontSize));
}
else
{
txt.setFont(Font.font(fontType, fontSize));
}
//txt.setStrokeWidth(StrokeWidth);
if(strokeColor.equals("BLUE"))
{
txt.setFill(Color.BLUE);
}
else if(strokeColor.equals("RED"))
{
txt.setFill(javafx.scene.paint.Color.RED);
}
else if(strokeColor.equals("GREEN"))
{
txt.setFill(javafx.scene.paint.Color.GREEN);
}
else if(strokeColor.equals("BLACK"))
{
txt.setFill(javafx.scene.paint.Color.BLACK);
}
else if(strokeColor.equals("BROWN"))
{
txt.setFill(javafx.scene.paint.Color.BROWN);
}
// txt.setFontSmoothingType(FontSmoothingType.LCD);
// txt.setStrokeType(StrokeType.INSIDE);
return txt;
}
So I have the following code:
public class Minesweeper extends MIDlet implements CommandListener {
public static String error = "";
public void startApp() throws MIDletStateChangeException {
Display display = Display.getDisplay(this);
canvas = new MCanvas();
canvas.addCommand(exitCommand);
canvas.addCommand(okCommand);
canvas.addCommand(newCommand);
canvas.setCommandListener(this);
try{
display.setCurrent(canvas);
} catch (Exception e) {
error = e.toString();
}
}
}
When I leave display.setCurrent(canvas); outside of the try block, the app fails with a NullPointerException. When I comment out that line, the app works (although obviously no canvas is added). So the error is caused by that line, or something that that line causes.
So I suround that line with try/catch. Although the error is caused by that line, the error still happens when the line is surrounded by try/catch. How can I catch the error? (I've tried this using Throwable as well, and it is still not caught.
MCanvas:
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
public class MCanvas extends Canvas {
protected void paint(Graphics g){
//Minesweeper.p("repaint");
Space[] data = Minesweeper.topaint;
for(int x=0; x<data.length; x++){
data[x].print();
int r = data[x].row * 10;
int c = data[x].col * 10;
int v = data[x].value;
String s = "";
//System.out.println("r:"+Integer.toString(r)+" c:"+Integer.toString(c)+" s:"+Integer.toString(v));
g.setColor(250, 0, 0);
//Minesweeper.p("if");
if(data[x].open){
switch(v){
case 0:
g.setColor(50, 50, 50);
break;
case 1:
g.setColor(100, 50, 50);
s = "1";
break;
case 2:
g.setColor(150, 50, 50);
s = "2";
break;
case 3:
g.setColor(200, 50, 50);
s = "3";
break;
case 4:
g.setColor(250, 50, 50);
s = "4";
break;
case 5:
g.setColor(250, 100, 100);
s = "5";
break;
case 6:
g.setColor(250, 125, 125);
s = "6";
break;
case 7:
g.setColor(250, 150, 150);
s = "7";
break;
case 8:
g.setColor(250, 175, 175);
s = "8";
break;
case 9:
g.setColor(250, 200, 200);
break;
default:
g.setColor(250, 100, 100);
}
} else {
g.setColor(0,0,0);
}
g.fillRect(c, r, 10, 10);
g.setColor(250, 250, 250);
Font font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL);
g.setFont(font);
g.drawString(s, c+5, r+8, Graphics.HCENTER | Graphics.BASELINE);
if(data[x].hover){
g.setColor(250, 250, 250);
g.drawLine(c, r, c, r+9);
g.drawLine(c, r, c+9, r);
g.drawLine(c+9, r, c+9, r+9);
g.drawLine(c, r+9, c+9, r+9);
}
//Minesweeper.p("here?");
}
//Minesweeper.p("here");
//Minesweeper.p(Minesweeper.error);
if(Minesweeper.error != null){
g.drawString(Minesweeper.error, 10, 10, Graphics.HCENTER | Graphics.BASELINE);
}
Minesweeper.p("msg:"+Minesweeper.message);
g.setColor(0, 0, 0);
Font font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_LARGE);
g.setFont(font);
g.drawString(Minesweeper.message, this.getWidth()/2, this.getHeight()-10, Graphics.HCENTER | Graphics.BASELINE);
Font fontsm = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL);
g.setFont(fontsm);
}
protected void keyPressed(int keyCode) {
int gameaction = getGameAction(keyCode);
int c = Minesweeper.selected.col;
int r = Minesweeper.selected.row;
switch (gameaction) {
case UP:
Minesweeper.p("UP");
if(r>0){
Minesweeper.selected.leavehere();
Minesweeper.getSpace(Minesweeper.selected.row - 1, Minesweeper.selected.col).gohere();
}
break;
case DOWN:
Minesweeper.p("DOWN");
if(r<Minesweeper.height-1){
Minesweeper.selected.leavehere();
Minesweeper.getSpace(Minesweeper.selected.row + 1, Minesweeper.selected.col).gohere();
}
break;
case LEFT:
Minesweeper.p("LEFT");
if(c>0){
Minesweeper.selected.leavehere();
Minesweeper.getSpace(Minesweeper.selected.row, Minesweeper.selected.col - 1).gohere();
}
break;
case RIGHT:
Minesweeper.p("RIGHT");
if(c<Minesweeper.length-1){
Minesweeper.selected.leavehere();
Minesweeper.getSpace(Minesweeper.selected.row, Minesweeper.selected.col + 1).gohere();
}
break;
}
repaint();
}
}
As explained in Display.setCurrent API javadocs,
...The setCurrent() method returns immediately, without waiting for the change to take place...
Because of above, exceptions that may occur in calls triggered by setCurrent may (and most likely will) slip through your try-catch.
To be able to catch and report such exceptions, one should study what calls are triggered by setCurrent (in your case, these are explained in API javadocs for Canvas, Event Delivery section), cover these by try-catch blocks where appropriate and design the appropriate way to report exceptions if these occur.
In your case, try-catch could likely surround code in MCanvas.paint (this is where NPE likely occurs) and exceptions could be reported for example by showing appropriate screen with error message (eg Alert) by invoking setCurrent for that screen from catch block.
If I were you I would continue to insert try/catch blocks in the MCanvas class.
It is difficult for anyone to figure out where your NullPointerException occurs without seeing more of the code.
The only question I can come up with, from the code you pasted so far, is:
Does your Minesweeper class contain a static array of object Space called topaint? Did you declare it but maybe forgot to fill it with data?
Space[] topaint = new Space[20]; // Declared, but nothing in it yet.
Trying to access Minesweeper.topaint[0] will give a NullPointerException, unless you also do
topaint[0] = new Space();