I am using JasperReports API to print from my Java application. I am printing a report like this:
public void prints(String billNo, String fileName, String outFileName, String perameterName) {
HashMap hm = new HashMap();
hm.put(perameterName, billNo);
//Here parameterName is the parameter in JasperReport.
// billNo is the value from my java application.
try {
conn = new connection().db();
PrinterJob job = PrinterJob.getPrinterJob();
/* Create an array of PrintServices */
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
PrintService default_service = PrintServiceLookup.lookupDefaultPrintService();
int selectedService = 0;
/* Scan found services to see if anyone suits our needs */
for (int i = 0; i < services.length; i++) {
if (services[i].getName().toUpperCase().equals(default_service.getName().toUpperCase())) {
selectedService = i;
}
}
job.setPrintService(services[selectedService]);
PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
printRequestAttributeSet.add(MediaSizeName.ISO_A4);
printRequestAttributeSet.add(new Copies(1));
JRPrintServiceExporter exporter;
exporter = new JRPrintServiceExporter();
JasperPrint print = JasperFillManager.fillReport(fileName, hm, conn);
JRExporter exporterr = new JRPdfExporter();
exporterr.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, outFileName);
exporterr.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, services[selectedService]);
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, services[selectedService].getAttributes());
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET, printRequestAttributeSet);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.FALSE);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.FALSE);
exporter.exportReport();
exporterr.exportReport();
} catch (JRException e) {
JOptionPane.showMessageDialog(null, e);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Printer not connected. Check power cable.");
}
}
I use to invoke this method in other classes.
But how can I pass multiple Parameters and multiple values to report?
for example query:
"select * from table1 where date>"+thisDate+" and date<"+thatDate+" "
How can I send thisDate and thatDate from my Java application?
Since you are using a HashMap you can store there many values. You can do it like:
HashMap hm = new HashMap();
hm.put(perameterName, billNo);
hm.put("thisDate", thisDate);
hm.put("theDate", theDate);
hm.put("anotherParam", paramValue);
If you don't want your method to pass so many keys and values as arguments, you can simply pass the "hm" object to your method:
public void prints( String fileName, String outFileName, HashMap hm){
Related
I'm new to Geotools. Now I want to insert a custom area (Polygon) in a Shapefile of Austria.
My code:
public static void main(String[] args) throws IOException {
File file = new File("src/main/java/org/geotools/austria.shp");
Map<String, Object> map = new HashMap<>();
map.put("url", file.toURI().toURL());
DataStore dataStore = DataStoreFinder.getDataStore(map);
String typeName = dataStore.getTypeNames()[0];
FeatureSource<SimpleFeatureType, SimpleFeature> source =
dataStore.getFeatureSource(typeName);
MapContent showmap = new MapContent();
showmap.setTitle("Austria");
Style style = SLD.createSimpleStyle(source.getSchema());
Layer layer = new FeatureLayer(source, style);
showmap.addLayer(layer);
// display the map
JMapFrame.showMap(showmap);
}
My current result:
This image shows my current output. I drew a red hexagon to show what I want to have in future.
How can I insert and display this Polygon into a Shapefile?
First you need to create a new Shapefile (you could overwrite the old one but it is easy to lose your data that way).
SimpleFeatureType TYPE = dataStore.getSchema(typeName);
File newFile = new File("output.shp");
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map<String, Serializable> params = new HashMap<String, Serializable>();
params.put("url", URLs.fileToURL(newFile));
params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
newDataStore.createSchema(TYPE);
Then you need to copy the existing polygons to the new file (I'm assuming they are in a SimpleFeatureCollection called collection) followed by the new feature(s):
Transaction transaction = new DefaultTransaction("create");
String typeName = newDataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
featureStore.setTransaction(transaction);
try {
featureStore.addFeatures(collection);
// Now add the hexagon
featureStore.addFeatures(DataUtilities.collection(hexagon));
transaction.commit();
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
System.exit(-1);
} finally {
transaction.close();
}
} else {
System.out.println(typeName + " does not support read/write access");
System.exit(1);
}
i am using a report in iReports, but I would want to print this with something changes in configuration for example: Copies, Orientation, Sides and others things; but it is not possible for me.
The fragment code is that:
InitialContext initialContext = new InitialContext();
DataSource dataSource = (DataSource) initialContext.lookup("java:/ds");
Connection connection = dataSource.getConnection();
String report = JasperCompileManager.compileReportToFile("report.jrxml");
JasperPrint jasperPrint = JasperFillManager.fillReport(report, new HashMap<String, Object>(), connection);
String defaultPrinter = PrintServiceLookup.lookupDefaultPrintService().getName().toLowerCase();
PrinterJob printerJob = PrinterJob.getPrinterJob();
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
PrintService selectedService = null;
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(Sides.DUPLEX);
for (PrintService service : services) {
String existingPrinter = service.getName().toLowerCase();
if (existingPrinter.equals(defaultPrinter)) {
selectedService = service;
break;
}
}
if (selectedService != null) {
printerJob.setPrintService(selectedService);
boolean printSucceed = JasperPrintManager.printReport(jasperPrint, false);
}
I am using java language, help me please.
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
I need to print to an Epson TM-T70 printer (Ethernet version) with Java. I can't found documentation about this. Which is the simplest way? Maybe using JavaPOS? Is there some example?
Thanks.
for our pos, I was able to do:
/* (non-Javadoc)
* #see be.intoit.pos.epsonagent.commands.Command#execute()
*/
public void execute() throws Exception {
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
StringBuilder builder = new StringBuilder();
builder.append(toPrint);
builder.append(EscapeCodeUtil.createEscapeCode(10));
PrintRequestAttributeSet aset= new HashPrintRequestAttributeSet();
aset.add(new MediaPrintableArea(100,400,210,160,Size2DSyntax.MM));
InputStream is = new ByteArrayInputStream(builder.toString().getBytes("UTF-8"));
Doc mydoc = new SimpleDoc(is, flavor, null);
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
//print using default
DocPrintJob
job = defaultService.createPrintJob();
job.print(mydoc, aset);
}
Where The util class was:
public class EscapeCodeUtil {
public static String createEscapeCode(int ... codes)
{
StringBuilder sb = new StringBuilder();
for(int code : codes)
sb.append((char) code);
return sb.toString();
}
}
This cut the paper
Socket sock = new Socket(IP_printer, 9100);
PrintWriter oStream = new PrintWriter(sock.getOutputStream());
oStream.print(""+(char)29+(char)86+(char)0);
I'm trying to write a Java program that will run an OpenOffice Macro. I'm getting this error:
java.lang.RuntimeException:
com.sun.star.script.provider.ScriptFrameworkErrorException: Incorrect
format for Script URI: vnd.sun.star.script:Name of macro
I believe it has something to do with the way that I'm calling the macro (String cmd)
I've searched high and low but can't seem to find any information on this. There are a few posts on the OO forums but none of them seemed to help. Here is some of the code:
public static void main(String[] args) throws BootstrapException {
if(args.length == 0)
{
System.out.println("Must enter a filename");
System.exit(1);
}
try
{
String param = args[0];
//String cmd = "Standard.Conversion.ConvertHTMLToWord?langauge=Basic&location=application";
String cmd = "Name.Of.Macro?langauge=Basic&location=Document";
System.out.println("Running macro on " + param);
Macro macObj = new Macro();
macObj.executeMacro(cmd, new Object[]{param}]);
System.out.println("Completed");
}
catch(Exception e)
{
System.out.println(e.toString());
//e.printStackTrace();
}
Macro Class:
class Macro {
private static final String ooExecPath = "C:/Program Files/OpenOffice.org 3/program";
public Object executeMacro(String strMacroName, Object[] aParams) throws BootstrapException
{
try
{
com.sun.star.uno.XComponentContext xContext;
System.out.println("Connecting to OpenOffice");
xContext = BootstrapSocketConnector.bootstrap(ooExecPath);
System.out.println("Connected to a running instance of OpenOffice");
System.out.println("Trying to execute macro...");
com.sun.star.text.XTextDocument mxDoc = openWriter(xContext);
XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, mxDoc);
XScriptProvider xScriptProvider = xScriptPS.getScriptProvider();
XScript xScript = xScriptProvider.getScript("vnd.sun.star.script:"+strMacroName);
short[][] aOutParamIndex = new short[1][1];
Object[][] aOutParam = new Object[1][1];
return xScript.invoke(aParams, aOutParamIndex, aOutParam);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static com.sun.star.text.XTextDocument openWriter(com.sun.star.uno.XComponentContext xContext)
{
com.sun.star.frame.XComponentLoader xCLoader;
com.sun.star.text.XTextDocument xDoc = null;
com.sun.star.lang.XComponent xComp = null;
try {
// get the remote office service manager
com.sun.star.lang.XMultiComponentFactory xMCF =
xContext.getServiceManager();
Object oDesktop = xMCF.createInstanceWithContext(
"com.sun.star.frame.Desktop", xContext);
xCLoader = (com.sun.star.frame.XComponentLoader)
UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class,
oDesktop);
com.sun.star.beans.PropertyValue [] szEmptyArgs =
new com.sun.star.beans.PropertyValue [0];
/*
ArrayList<PropertyValue> props = new ArrayList<PropertyValue>();
PropertyValue p = new PropertyValue();
p.Name = "Hidden";
p.Value = new Boolean(true);
props.add(p);
PropertyValue[] properties = new PropertyValue[props.size()];
props.toArray(properties);
String strDoc = "private:factory/swriter";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, properties);
*/
String strDoc = "private:factory/swriter";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, szEmptyArgs);
xDoc = (com.sun.star.text.XTextDocument)
UnoRuntime.queryInterface(com.sun.star.text.XTextDocument.class,
xComp);
} catch(Exception e){
System.err.println(" Exception " + e);
e.printStackTrace(System.err);
}
return xDoc;
}
}
I suppose your problem is in the "Name.Of.Macro": it must be: Library.Module.NameOfMacro.
"langauge=Basic" of course sets the language name, and "location=application" means the macro library should be searched in the opened document, and not in global OO libraries.
As far as parameters are involved, I use:
XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, xComponent);
XScriptProvider xScriptProvider = xScriptPS.getScriptProvider();
XScript xScript = xScriptProvider.getScript("vnd.sun.star.script:"+macroName);
short[][] aOutParamIndex = new short[1][1];
Object[][] aOutParam = new Object[1][1];
Object[] aParams = new String[2];
aParams[0] = myFirstParameterName;
aParams[1] = mySecondParameterName;
#SuppressWarnings("unused")
Object result = xScript.invoke(aParams, aOutParamIndex, aOutParam);
System.out.println("xScript invoke macro " + macroName);
Hope it can be useful, after such long time... :-(
XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, xComponent);
What is xComponent in the above code?
Compare: ?langauge=Basic&location=Document"
to: ?language=Basic&location=Document"
wring is: "langauge" :D, swap "au" to "ua". :)