Need to know to code printer name in Java - java

I have use jasper report to create a report in Java and most of the time i tried to setup the printer name by using code, but I couldn't do that. Please help me how to give printer name to print without using print manager
try {
String comname = "";
comname = "Stars Bombay Sweet (Pvt) Ltd.";
JRTableModelDataSource dts = new JRTableModelDataSource(jTable1.getModel());
String path = "D:\\Aster Soft\\Stars Reports\\posh_print\\report1.jrxml";
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", comname);
params.put("para1", InvNo.getText());
params.put("para2", dat);
params.put("para3", Customer.getText());
params.put("credit", jComboBox1.getSelectedItem());
params.put("Qty", GrossQty.getText());
params.put("TotAmont", TotalAmount.getText());
params.put("Discount", Discount.getText());
params.put("GrossAmont", DisAmount.getText());
JasperReport report = JasperCompileManager.compileReport(path);
JasperPrint print = JasperFillManager.fillReport(report, params, dts);
JasperViewer.viewReport(print, false);
JasperPrintManager.printReport(print, true);
} catch (Exception e) {
e.printStackTrace();
}

JasperPrint print = JasperFillManager.fillReport(this.class.getResource("/classpath/yourReport.jasper").getPath(),
new HashMap(), new yourReportDataSource());
PrinterJob job = PrinterJob.getPrinterJob();
/* Create an array of PrintServices */
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
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().contains("Your printer's name")){
/*If the service is named as what we are querying we select it */
selectedService = i;
}
}
job.setPrintService(services[selectedService]);
I think below blog link will help you
http://blog.marcnuri.com/choosing-a-printer-programmatically-in-jasper-reports/

Related

Java Printing with ZPL prints ZPL as text

I am trying to use a Zebra label printer using Java, and I'm having some issues:
I am trying the following code, which contains code taken from here: https://github.com/w3blogfr/zebra-zpl
public static void printZpl(String zpl, String printerName) throws ZebraPrintException {
try {
PrintService psZebra = null;
String sPrinterName = null;
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
for (int i = 0; i < services.length; i++) {
PrintServiceAttribute attr = services[i].getAttribute(PrinterName.class);
sPrinterName = ((PrinterName) attr).getValue();
if (sPrinterName.toLowerCase().indexOf(printerName.toLowerCase()) >= 0) {
psZebra = services[i];
break;
}
}
if (psZebra == null) {
throw new ZebraPrintNotFoundException("Zebra printer not found : " + printerName);
}
DocPrintJob job = psZebra.createPrintJob();
byte[] by = zpl.getBytes();
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
Doc doc = new SimpleDoc(by, flavor, null);
job.print(doc, null);
} catch (PrintException e) {
throw new ZebraPrintException("Cannot print label on this printer : " + printerName, e);
}
}
The string I am trying to print is this one:
^XA
^MMT
^FT0,110^FH\^FDTestString^FS
^XZ
The problem is that although I am able to connect to the printer and print something, the output is printed as plain text, it's as if the printer does not recognize that a ZDL command has been given.
The printer is a Zebra ZD220, and I have connected it to my Mac as a generic label printer, and selected the Zebra ZDL as the software to use it with.
Is there something I miss?
Note that I have been able to do this using NodeJS (so I know that this is working) using node-printer, so I know that it should work, but with Java, I cannot seem to make the printer understand that I am giving ZPL commands to it, and it prints plain characters.
I got this working by creating a socket connection with ZPL printer and writing ZPL content to output stream. Refer https://github.com/khpraful/ZPLPrint/blob/master/src/ZebraPrinter.java for more details. I tried with locally installed ZPL print emulator.

Java merge two Jasper Report

I have created two report jrxml with jasper report. In my java program I merge the two report into one PDF with iText.
The problem is that the pdf contains only one report plus a blank page.
I have also done this proof:
in my java program creation report one creation report two, merge and I see pdf containig only report one plus blank page
in my java program creation report two and then creation report one, merge and I see pdf containing only report two plus blank page
I have to obtain the pdf with both reports
Does someone help me to solve the problem?
Thanks in advance
Attach the code of my java program:
#Name("pdfFactory")
public class PdfScalareFactory {
private static final String JASPER_FILE_MOVIMENTI = "scalarePdf/pdf_movimenti.jrxml";
private static final String JASPER_FILE_SCALARE = "scalarePdf/pdf_scalare.jrxml";
#SuppressWarnings("rawtypes")
public byte[] rawPdf(BeScalare beScalare, String codTabulato, String output) throws JRException, IOException {
JRBeanArrayDataSource dataSource = new JRBeanArrayDataSource(new Object[]{beScalare});
//report's list
List<byte[]> pdfFilesAsByteArray = new ArrayList<byte[]>();
//Report one
Class cScalare = this.getClass();
ClassLoader clScalare = cScalare.getClassLoader();
InputStream isScalare = clScalare.getResourceAsStream(JASPER_FILE_SCALARE);
JasperDesign jasDesignScalare = JRXmlLoader.load(isScalare);
//compile report one
JasperReport reportScalare = JasperCompileManager.compileReport(jasDesignScalare);
//parameters report one
Map<String, Object> paramScalare = new HashMap<String, Object>();
JRBeanCollectionDataSource itemsScalareSaldiPerValuta = new JRBeanCollectionDataSource(beScalare.getLstBeScalareSaldiPerValuta());
paramScalare.put("scalareSaldiPerValuta", itemsScalareSaldiPerValuta);
//fill report one
JasperPrint jasperPrintScalare = JasperFillManager.fillReport(reportScalare, paramScalare, dataSource);
pdfFilesAsByteArray.add(JasperExportManager.exportReportToPdf(jasperPrintScalare));
//Report two
Class c = this.getClass();
ClassLoader cl = c.getClassLoader();
InputStream is = cl.getResourceAsStream(JASPER_FILE_MOVIMENTI);
JasperDesign jasDesign = JRXmlLoader.load(is);
//compile report two
JasperReport reportMovimenti = JasperCompileManager.compileReport(jasDesign);
//parameters report two
Map<String, Object> paramMovimenti = new HashMap<String, Object>();
BufferedImage imgNumeroVerde = ImageIO.read(getClass().getResource("/scalarePdf/headphones.png"));
paramMovimenti.put("numeroVerde", imgNumeroVerde);
BufferedImage imgInternet = ImageIO.read(getClass().getResource("/scalarePdf/internet.png"));
paramMovimenti.put("internet", imgInternet);
JRBeanCollectionDataSource itemsScalareMovimenti = new JRBeanCollectionDataSource(beScalare.getLstBeScalareMovimenti());
paramMovimenti.put("scalareMovimenti", itemsScalareMovimenti);
//fill report two
JasperPrint jasperPrintMovimenti = JasperFillManager.fillReport(reportMovimenti, paramMovimenti, dataSource);
pdfFilesAsByteArray.add(JasperExportManager.exportReportToPdf(jasperPrintMovimenti));
//merge the two reports in one
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
Document document = null;
PdfCopy writer = null;
for (byte[] pdfByteArray : pdfFilesAsByteArray) {
try {
PdfReader reader = new PdfReader(pdfByteArray);
int numberOfPages = reader.getNumberOfPages();
if (document == null) {
document = new Document(reader.getPageSizeWithRotation(1));
writer = new PdfCopy(document, outStream); // new
document.open();
}
PdfImportedPage page;
for (int i = 0; i < numberOfPages;) {
++i;
page = writer.getImportedPage(reader, i);
writer.addPage(page);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
document.close();
outStream.close();
return outStream.toByteArray();
}
}
Problem is in the data source and not in merging. You create one data source for both reports but the first report will consume it and then the second report has data source with pointer at the end.
You use JRBeanArrayDataSource which implements JRRewindableDataSource so you can call the moveFirst() method to return data source pointer on the first position:
//Report two
dataSource.moveFirst();
Or you can create the data source again for the second report:
//Report two
dataSource = new JRBeanArrayDataSource(new Object[]{beScalare});
Note: But as Amongalen mentioned in the comment it is easier to merge two and more Jasper reports using JRPdfExporter and List<JasperPrint> instance as an input.

Print ".pdf" file - PrinterJob

I'm having problems when trying to print a ".pdf". I printed Strings with this code without problems, but the pdf will not.
My program receives a byte[] with pdf and print it, I thought of recording a tempfile to print from InputStream, but also failed.
Follows the code I'm using to print:
    FileChannel fc = null;
    ByteBuffer bb = ByteBuffer.wrap(pdf);
    FileOutputStream fos = null;
    RandomAccessFile fis = null;
    try {
        File Tempfile = File.createTempFile("portfolios-temp", ".pdf");
        fos = new FileOutputStream(tempfile);
        fos.write(pdf);
        fos.close();
        FileInputStream psStream = new FileInputStream(tempfile);
        DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
        MyDoc doc = new SimpleDoc(psStream, psInFormat, null);
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        aset.add (new Copies (1));
        aset.add (OrientationRequested.PORTRAIT);
        aset.add (Sides.ONE_SIDED);
        aset.add (MediaSizeName.ISO_A4);
        DocPrintJob job printService.createPrintJob =();
        try {
            job.print (myDoc, aset);
        } Catch (Exception pe) {
            pe.printStackTrace ();
        }
    } [...]
I get the Print Service this way:
PrintService printService = null;
for(PrintService printServiceCurrent : PrinterJob.lookupPrintServices()) {
if(printServiceCurrent.getName().equals(PRINTER_NAME)) {
printService = printServiceCurrent;
break;
}
}
He send a command to the printer, but comes like have no content. I checked the temporary file and it is being generated perfectly.
Any idea?
Thanks in advance.
First of all, instead of
PrintRequestAttributeSet aset HashPrintRequestAttributeSet = new();
it should be
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
Second you're not checking the printers that can print the format according to the instructions in the attribute set.
Check this link for more detailed information:
Java Print Service API

How to insert an image in to an openoffice writer document with java?

I'm trying to create an openoffice writer document from a template.
I can replace text parts of report with this code
private static void searchAndReplace(final String search,
final String replace, final XTextDocument mxDoc) {
XReplaceable xReplaceable = (XReplaceable) UnoRuntime.queryInterface(
XReplaceable.class, mxDoc);
XReplaceDescriptor xRepDesc = xReplaceable.createReplaceDescriptor();
xRepDesc.setSearchString(search);
xRepDesc.setReplaceString(replace);
xReplaceable.replaceAll(xRepDesc);
}
I found some sample code from here to link or embed an image into an xTextDocument.
But, I can't insert into an xTextDocument. Is there any other way to do this with Java?
Openoffice version is 3.1.0.
Any answer?
I found this here: https://svn.apache.org/repos/asf/openoffice/ooo-site/trunk/content/api/Examples/Snippets/Writer/Writer.EmbedAGraphicIntoATextdocument.snip
private void embedGraphic(GraphicInfo grProps,
XMultiServiceFactory xMSF, XTextCursor xCursor) {
XNameContainer xBitmapContainer = null;
XText xText = xCursor.getText();
XTextContent xImage = null;
String internalURL = null;
try {
xBitmapContainer = (XNameContainer) UnoRuntime.queryInterface(
XNameContainer.class, xMSF.createInstance(
"com.sun.star.drawing.BitmapTable"));
xImage = (XTextContent) UnoRuntime.queryInterface(
XTextContent.class, xMSF.createInstance(
"com.sun.star.text.TextGraphicObject"));
XPropertySet xProps = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, xImage);
// helper-stuff to let OOo create an internal name of the graphic
// that can be used later (internal name consists of various checksums)
xBitmapContainer.insertByName("someID", grProps.unoURL);
internalURL = AnyConverter.toString(xBitmapContainer
.getByName("someID"));
xProps.setPropertyValue("AnchorType",
com.sun.star.text.TextContentAnchorType.AS_CHARACTER);
xProps.setPropertyValue("GraphicURL", internalURL);
xProps.setPropertyValue("Width", (int) grProps.widthOfGraphic);
xProps.setPropertyValue("Height", (int) grProps.heightOfGraphic);
// inser the graphic at the cursor position
xText.insertTextContent(xCursor, xImage, false);
// remove the helper-entry
xBitmapContainer.removeByName("someID");
} catch (Exception e) {
System.out.println("Failed to insert Graphic");
}
}

Problem using Java with ireport

try {
//providing path of jrxml to java
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ReportTemplates/WeeklyReportForCurrentWeek.jrxml");
JasperDesign jdesign = JasperManager.loadXmlDesign(inputStream);
String imgPath = "C:/Users/Sorathiya.Deven/";
//Compile managaer
JasperReport jreport = JasperManager.compileReport(jdesign);
//Run time Report parameters
Map param = new HashMap();
param.put("CurrWeek", new java.math.BigDecimal(week));
param.put("CurrYear", new java.math.BigDecimal(year));
param.put("imgPath", imgPath);
//Fatch Database
Connection con = CreateConnection.makeConnection();
//compile report
JasperPrint jprint=JasperFillManager.fillReport(jreport, param, con);
JRPdfExporter exporterPDF = new JRPdfExporter();
exporterPDF.setParameter(JRExporterParameter.JASPER_PRINT, jprint);
exporterPDF.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "C:/Users/Sorathiya.Deven/WeeklyReportForCurrentWeek.pdf");
exporterPDF.exportReport();
CreateConnection.closeConnection(con);
} catch (Exception e) {
e.printStackTrace();
}
Hello friends i am using above given code for showing my report containing sub report but when i run this i get report containing blank page does any one tell me whats the actual problem
Your connection is empty.
Please parse sql query then create the report.

Categories