How to create a xls file using open office sdk? Please give Java example source code. Also needed to create word and power point files. I’m not able to get any examples
Below is the code I tried. It tries to open in Open office App, that I don't want. I want to generate the .ods file in the WebSphere App Server under AIX environment, using Java. I'm using it to generate a report and download it to front end (web app).
import ooo.connector.BootstrapSocketConnector;
import com.sun.star.beans.PropertyValue;
import com.sun.star.comp.helper.BootstrapException;
import com.sun.star.container.XIndexAccess;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.sheet.XSpreadsheet;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XSpreadsheets;
import com.sun.star.table.XCell;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
XComponentContext xContext = null;
// get the remote office component context
try {
String folder = "C:\\Program Files (x86)\\OpenOffice 4\\program";
xContext = BootstrapSocketConnector.bootstrap(folder);
} catch (BootstrapException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
XSpreadsheetDocument myDoc = null;
System.out.println("Opening an empty Calc document");
myDoc = openCalc(xContext);
XSpreadsheet xSheet = null;
try {
System.out.println("Getting spreadsheet");
XSpreadsheets xSheets = myDoc.getSheets();
XIndexAccess oIndexSheets = (XIndexAccess) UnoRuntime
.queryInterface(XIndexAccess.class, xSheets);
xSheet = (XSpreadsheet) UnoRuntime.queryInterface(
XSpreadsheet.class, oIndexSheets.getByIndex(0));
} catch (Exception e) {
System.out.println("Couldn't get Sheet " + e);
e.printStackTrace(System.err);
}
System.out.println("Creating the Header") ;
insertIntoCell(1,0,"JAN",xSheet,"");
insertIntoCell(2,0,"FEB",xSheet,"");
insertIntoCell(3,0,"MAR",xSheet,"");
insertIntoCell(4,0,"APR",xSheet,"");
insertIntoCell(5,0,"MAI",xSheet,"");
insertIntoCell(6,0,"JUN",xSheet,"");
insertIntoCell(7,0,"JUL",xSheet,"");
insertIntoCell(8,0,"AUG",xSheet,"");
insertIntoCell(9,0,"SEP",xSheet,"");
insertIntoCell(10,0,"OCT",xSheet,"");
insertIntoCell(11,0,"NOV",xSheet,"");
insertIntoCell(12,0,"DEC",xSheet,"");
insertIntoCell(13,0,"SUM",xSheet,"");
System.out.println("Fill the lines");
insertIntoCell(0,1,"Smith",xSheet,"");
insertIntoCell(1,1,"42",xSheet,"V");
insertIntoCell(2,1,"58.9",xSheet,"V");
insertIntoCell(3,1,"-66.5",xSheet,"V");
insertIntoCell(4,1,"43.4",xSheet,"V");
insertIntoCell(5,1,"44.5",xSheet,"V");
insertIntoCell(6,1,"45.3",xSheet,"V");
insertIntoCell(7,1,"-67.3",xSheet,"V");
insertIntoCell(8,1,"30.5",xSheet,"V");
insertIntoCell(9,1,"23.2",xSheet,"V");
insertIntoCell(10,1,"-97.3",xSheet,"V");
insertIntoCell(11,1,"22.4",xSheet,"V");
insertIntoCell(12,1,"23.5",xSheet,"V");
insertIntoCell(13,1,"=SUM(B2:M2)",xSheet,"");
insertIntoCell(0,2,"Jones",xSheet,"");
insertIntoCell(1,2,"21",xSheet,"V");
insertIntoCell(2,2,"40.9",xSheet,"V");
insertIntoCell(3,2,"-57.5",xSheet,"V");
insertIntoCell(4,2,"-23.4",xSheet,"V");
insertIntoCell(5,2,"34.5",xSheet,"V");
insertIntoCell(6,2,"59.3",xSheet,"V");
insertIntoCell(7,2,"27.3",xSheet,"V");
insertIntoCell(8,2,"-38.5",xSheet,"V");
insertIntoCell(9,2,"43.2",xSheet,"V");
insertIntoCell(10,2,"57.3",xSheet,"V");
insertIntoCell(11,2,"25.4",xSheet,"V");
insertIntoCell(12,2,"28.5",xSheet,"V");
insertIntoCell(13,2,"=SUM(B3:M3)",xSheet,"");
insertIntoCell(0,3,"Brown",xSheet,"");
insertIntoCell(1,3,"31.45",xSheet,"V");
insertIntoCell(2,3,"-20.9",xSheet,"V");
insertIntoCell(3,3,"-117.5",xSheet,"V");
insertIntoCell(4,3,"23.4",xSheet,"V");
insertIntoCell(5,3,"-114.5",xSheet,"V");
insertIntoCell(6,3,"115.3",xSheet,"V");
insertIntoCell(7,3,"-171.3",xSheet,"V");
insertIntoCell(8,3,"89.5",xSheet,"V");
insertIntoCell(9,3,"41.2",xSheet,"V");
insertIntoCell(10,3,"71.3",xSheet,"V");
insertIntoCell(11,3,"25.4",xSheet,"V");
insertIntoCell(12,3,"38.5",xSheet,"V");
insertIntoCell(13,3,"=SUM(A4:L4)",xSheet,"");
}
public static void insertIntoCell(int CellX, int CellY, String theValue,
XSpreadsheet TT1, String flag) {
XCell xCell = null;
try {
xCell = TT1.getCellByPosition(CellX, CellY);
} catch (com.sun.star.lang.IndexOutOfBoundsException ex) {
System.err.println("Could not get Cell");
ex.printStackTrace(System.err);
}
if (flag.equals("V")) {
xCell.setValue((new Float(theValue)).floatValue());
} else {
xCell.setFormula(theValue);
}
}
public static XSpreadsheetDocument openCalc(XComponentContext xContext) {
// define variables
XMultiComponentFactory xMCF = null;
XComponentLoader xCLoader;
XSpreadsheetDocument xSpreadSheetDoc = null;
XComponent xComp = null;
try {
// get the servie manager rom the office
xMCF = xContext.getServiceManager();
// create a new instance of the the desktop
Object oDesktop = xMCF.createInstanceWithContext(
"com.sun.star.frame.Desktop", xContext);
// query the desktop object for the XComponentLoader
xCLoader = (XComponentLoader) UnoRuntime.queryInterface(
XComponentLoader.class, oDesktop);
PropertyValue[] szEmptyArgs = new PropertyValue[0];
String strDoc = "private:factory/scalc";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0,
szEmptyArgs);
xSpreadSheetDoc = (XSpreadsheetDocument) UnoRuntime.queryInterface(
XSpreadsheetDocument.class, xComp);
} catch (Exception e) {
System.err.println(" Exception " + e);
e.printStackTrace(System.err);
}
return xSpreadSheetDoc;
}
}
I have a situation that need to print order bill in cash counter and packing area(warehouse ).
Technically, how to print javafx.print.PrinterJob by saying printer name.
1) Sample print
public static void PrintSample() {
Label lbl = new Label("This is sample \n\n\n\n\n\nprint");
PrinterJob job = PrinterJob.createPrinterJob();
if (job != null ) {
boolean success = job.printPage(lbl);
if (success) {
job.endJob();
}
}
}
2) Get list of printers
public static void GetListOfPrinters() {
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
System.out.println("Number of print services: " + printServices.length);
for (PrintService printer : printServices) {
System.out.println("Printer: " + printer.getName());
}
}
The answer is too late but any one need the answer for the same question:
you can use this class to print file(not node)....
public static void print(String imageName, PagesManager pagesManager) {
Printer printer = Printer.getDefaultPrinter();
PageLayout pageLayout
= printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.HARDWARE_MINIMUM);
PrinterAttributes attr = printer.getPrinterAttributes();
PrinterJob job = PrinterJob.createPrinterJob();
if (job.showPrintDialog(pagesManager.getScene().getWindow())) {
String selectedPrinter = job.getPrinter().getName();
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.GIF, pras);
if (pss.length == 0) {
throw new RuntimeException("No printer services available.");
}
int i = 0;
for (i = 0; i < pss.length; i++) {
if (pss[i].getName().equals(selectedPrinter)) {
break;
}
}
PrintService ps = pss[i];
System.out.println("Printing to " + ps);
DocPrintJob docPrintJob = ps.createPrintJob();
FileInputStream fin = null;
try {
fin = new FileInputStream(imageName);
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.GIF, null);
try {
docPrintJob.print(doc, pras);
} catch (PrintException ex) {
System.out.println(ex);
}
try {
fin.close();
} catch (IOException ex) {
System.out.println(ex);
}
}
}
The method 'createPrinterJob' with no-args creates a printer job for the default printer. You can use the other version of the method 'createPrinterJob(Printer printer)' to create a printer job for the specified printer.
First get instance of printer like below:
Printer myPrinter;
ObservableSet<Printer> printers = Printer.getAllPrinters();
for(Printer printer : printers){
if(printer.getName().matches("spefic printer name")){
myPrinter = printer;
}
}
Now Create a printer job for 'myPrinter' like this:
PrinterJob job = PrinterJob.createPrinterJob(myPrinter);
PrinterJob job = PrinterJob.createPrinterJob(myPrinter);
this line is not working give error The method createPrinterJob(Printer) is undefined for the type PrinterJob
I developed a Java desktop program that uses a thermal printer with the following code:
/**
* printableObject extends Printable
*/
public static boolean print(Object printableObject, String printer_name) throws InterruptedException {
InputStream printerTest = new ByteArrayInputStream("".getBytes());
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc myDoc = new SimpleDoc(printableObject, DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
Doc docTest = new SimpleDoc(printerTest, flavor, null);
HashPrintServiceAttributeSet aset = new HashPrintServiceAttributeSet();
PrintRequestAttributeSet rset = new HashPrintRequestAttributeSet();
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
PrinterName printer = new PrinterName(printer_name, null);
rset.add(OrientationRequested.PORTRAIT);
rset.add(MediaSizeName.INVOICE);
aset.add(printer);
services = PrintServiceLookup.lookupPrintServices(null, aset);
if (!priterIsReady(services[0], 5)) {
return false;
}
if (services != null) {
try {
DocPrintJob docPrintJobTest = services[0].createPrintJob();
docPrintJobTest.print(docTest, rset);
if (!priterIsReady(services[0], 5)) {
return false;
}
DocPrintJob job = services[0].createPrintJob();
job.print(myDoc, rset);
Thread.sleep(300);
if (priterIsReady(services[0], 5)) {
DocPrintJob job2 = services[0].createPrintJob();
job2.print(docTest, rset);
return priterIsReady(services[0], 5);
} else {
return false;
}
} catch (ArrayIndexOutOfBoundsException ex) {
ex.printStackTrace();
} catch (PrintException pe) {
pe.printStackTrace();
}
}
return false;
}
public static boolean priterIsReady(PrintService printer, int max) throws InterruptedException {
int count = 0;
while (count < max) {
AttributeSet att = printer.getAttributes();
for (Attribute a : att.toArray()) {
String attributeName;
String attributeValue;
attributeName = a.getName();
attributeValue = att.get(a.getClass()).toString();
if (attributeName.equals("queued-job-count")) {
if (Integer.valueOf(attributeValue) == 0) {
return true;
} else {
System.err.println(">>> queued-job-count: " + Integer.valueOf(attributeValue));
}
}
}
Thread.sleep(600 + 600 / 5 * count);
count = count + 1;
}
return false;
}
The code works perfectly in my IDE or using the jar (java 1.8.0_73). The printing is fast. But using another notebook with similar configuration (i7, 8GB, Windows10) I have problem: the printing takes more than 10 seconds to start. The same JAR and the same printer, but java 1.8.0_101. In this period the document is in the print queue.
I used another notebook (i5, 8GB, Windows10) and I had the same delay.
I changed the above code and I tried to print without check if the printer is ready or print test, but the problem persists.
Has someone gone through this problem?
Is there another way that I can print a Printable Object?
I'm trying to print from differents printer trays using javax.print with no luck, I have a printer HP Officejet Pro X476dw with 2 paper trays numbered 1 and 2.
My code is this:
public class ImprimeSide{
public static void main (String [] args) {
try {
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(null, null);
//Acquire Printer
PrintService printer = null;
for(PrintService serv: pservices){
if(serv.getName().contains("HP Officejet")){
printer = serv;
}
}
if(printer != null){
//Open File
FileInputStream fis = new FileInputStream("Documento2.pdf");
//Create Doc out of file, autosense filetype
Doc pdfDoc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
//Create job for printer
DocPrintJob printJob = printer.createPrintJob();
//Create AttributeSet
PrintRequestAttributeSet pset = new HashPrintRequestAttributeSet();
//Add MediaTray to AttributeSet
pset.add(MediaTray.SIDE);
//Print using Doc and Attributes
printJob.print(pdfDoc, pset);
//Close File
fis.close();
}
}catch (Throwable t) {
t.printStackTrace();
}
}
}
Changing the line pset.add(MediaTray.SIDE) for every constant in the class MediaTray (TOP, BOTTOM, MANUAL.. etc) doesn't change anything, it will print taking paper from the default tray.
Any sugestion will be appreciated.
you must declare a MediaTray after mapping all media in a hashmap
DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
for (PrintService service : services)
{
System.out.println(service);
// we retrieve all the supported attributes of type Media
// we can receive MediaTray, MediaSizeName, ...
Object o = service.getSupportedAttributeValues(Media.class, flavor, null);
if (o != null && o.getClass().isArray())
{
for (Media media : (Media[]) o)
{
// we collect the MediaTray available
if (media instanceof MediaTray)
{
System.out.println(media.getValue() + " : " + media + " - " + media.getClass().getName());
trayMap.put(media.getValue(), media);
}
}
}
}
MediaTray selectedTray = (MediaTray) trayMap.get(Integer.valueOf(mediaId));
and after you add it to the PrintRequestAttributeSet
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
attributes.add(selectedTray);
And when you print you use this PrintRequestAttributeSet
DocPrintJob job = services[0].createPrintJob();
job.print(doc, attributes);
Jorge