Hot questions for Using JasperReports in printing

Question:

All I want, is to print a JasperReport without user selecting a printer. I searched for it but there is no good solution that works. This is the relevat part of my code:

//compile to .jasper
String report = JasperCompileManager.compileReportToFile(sourceFileName);

//fill the report
JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameter, dataSource);

//print the report      
JasperPrintManager.printReport(jasperPrint, true);

Instead of simple printReport i want to select a printer. is there any way to do this?


Answer:

This is how it's supposed to be:

try {

    String report = JasperCompileManager.compileReportToFile(sourceFileName);

    JasperPrint jasperPrint = JasperFillManager.fillReport(report, para, ds);

    PrinterJob printerJob = PrinterJob.getPrinterJob();

    PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage();
    printerJob.defaultPage(pageFormat);

    int selectedService = 0;

    AttributeSet attributeSet = new HashPrintServiceAttributeSet(new PrinterName(printerNameShort, null));

    PrintService[] printService = PrintServiceLookup.lookupPrintServices(null, attributeSet);

    try {
        printerJob.setPrintService(printService[selectedService]);

    } catch (Exception e) {

        System.out.println(e);
    }
    JRPrintServiceExporter exporter;
    PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
    printRequestAttributeSet.add(MediaSizeName.NA_LETTER);
    printRequestAttributeSet.add(new Copies(1));

    // these are deprecated
    exporter = new JRPrintServiceExporter();
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, printService[selectedService]);
    exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, printService[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();

} catch (JRException e) {
    e.printStackTrace();
}

Question:

I am developping a Spring MVC - Angularjs application. I need to print reports, I chose JasperReport to do that.

Before I move on, I want to know if I can generate a report, then directly print it on the default printer set up on the client computer (printer which can change according to users) without displaying it on screen. I have been looking for answers on this specific need, but couldn't find any.

If anyone knows about it....

Source to generate report and print it:

HashMap<String, Object> params = new HashMap<String, Object>(); 
params.put("Title", "My Report");

InputStream reportStream = this.getClass().getResourceAsStream(TEMPLATE); 
JasperDesign jd = JRXmlLoader.load(reportStream);
JasperReport jr = JasperCompileManager.compileReport(jd);
JasperPrint jp = JasperFillManager.fillReport(jr, params, datasource.getDataSource());

JasperPrintManager.printReport(jp, false);

Answer:

You can create an object in HTML page which hold PDF & then print it using print() method or use java.awt.print.PrinterJob. See below examples.

Hope this helps you

Question:

We are experiencing a strange problem trying to print barcodes from the Mac. Everything works fine on Windows, however, on the Mac:

  • Jasper Preview shows barcode fine
  • Saving PDF via jasper shows barcode fine and pdf prints correctly
  • Printing report excludes barcode
  • Saving PDF via Mac Printer dialog excludes barcodes

This report also includes a second image directly from a field, which prints fine on the Mac. The barcode is generated via zxing and written to a ByteArrayOutputStream as a png. This is added to the report as an image object. I've also tried other image formats without success.

This issue has been reproduced across different printers and on the latest jasper library (6.4.1). There are no error message reported in the log. I've also tried generating the barcode slightly smaller than the bounding region to ensure it doesn't get clipped.

My Mac is currently running 10.12.6 with java 8.

Thanks.

Test case below (BarcodeTest.java):

public class BarcodeTest
{
    public static java.io.ByteArrayInputStream createBarcode(String aBarcodeStr, int aAlignmentX, int rotate, int sizeX, int sizeY)
        throws IOException, WriterException, NotFoundException
    {
        Code39Writer c39 = new Code39Writer();
        BitMatrix bm = c39.encode(aBarcodeStr.trim(), BarcodeFormat.CODE_39, sizeX, sizeY);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bm, "PNG", out);
        return new java.io.ByteArrayInputStream(out.toByteArray());
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(() ->
        {
            String thisFile = "BarcodeTest.jrxml";
            try
            {
                JasperReport jasperReport = JasperCompileManager.compileReport(thisFile);
                HashMap hm = new HashMap();
                JasperPrint jasperPrint = JasperFillManager.fillReport(
                    jasperReport,
                    hm,
                    new JREmptyDataSource());

                JRViewer jrv = new JRViewer(jasperPrint);
                JFrame jf = new JFrame("Barcode test");
                jf.setSize(800, 600);
                jf.add(jrv);
                jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                jf.getContentPane().add(jrv);
                jf.setLocationRelativeTo(null);
                jf.setVisible(true);
            }
            catch(HeadlessException | JRException e)
            {
                e.printStackTrace();
            }
        });
    }
}

with this jrxml (BarcodeTest.jrxml):

<?xml version="1.0" encoding="Cp1252"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="AdvancedReports" columnCount="3" printOrder="Horizontal" pageWidth="595" pageHeight="842" columnWidth="185" columnSpacing="9" leftMargin="9" rightMargin="9" topMargin="62" bottomMargin="6" uuid="7c881f22-0368-4f79-8e3f-8ca0a36dfe37">
    <pageHeader>
        <band height="72">
            <textField isBlankWhenNull="true">
                <reportElement positionType="Float" x="4" y="35" width="176" height="30" forecolor="#000000" backcolor="#FFFFFF" uuid="1a38a9fe-2887-498f-be6f-758397d57175"/>
                <textElement textAlignment="Left" verticalAlignment="Middle" rotation="None"/>
                <textFieldExpression><![CDATA["123456"]]></textFieldExpression>
            </textField>
            <image hAlign="Left">
                <reportElement x="4" y="4" width="176" height="30" uuid="508b033d-e71c-419d-843f-c23255294533"/>
                <imageExpression><![CDATA[BarcodeTest.createBarcode("123456",2,0,176,30)]]></imageExpression>
            </image>
        </band>
    </pageHeader>
</jasperReport>

Answer:

I ran your report and got an error message that looks just like the one from JDK-8038142. So chances are the problem that you are experiencing is caused by the same Java bug (which should be fixed in the latest version, but for some reason it still didn't work for me).

One simple way to workaround the JDK problem is to change your createBarcode method to return a BufferedImage instead of PNG image data. All you need for that is

return MatrixToImageWriter.toBufferedImage(bm);

Question:

I'm having trouble printing following kind of structure with JasperReports Studio/DynamicJasper:

Date (1.1.2015)
-action1 (text)
-action2
.
.
.
-actionN

-image1      (image-file)
-image1 text (text)
-image2
-image2 text
.
.
.
-imageN
-imageN text

Date (2.1.2015)
-action1 (text)
-action2
.
.
.
-actionN

-image1      (image-file)
-image1 text (text)
-image2
-image2 text
 .
 .
 .
-imageN
-imageN text

So the original idea is to print all the actions and images attached to one day, and then do the same for the next day until there are no days in the database.Basically all of this data should be printed as one report all of the described content going to detail band(s) one day after another.

Basically there can be any amount of days, and then any amount of actions and images related to each day. It would be preferred that all of this content would be printed like there was only one column: first the list of actions and then the list of images just below the actions list.

At first I was trying to implement this Jasper Studio as that was the tool I have used so far for all the other reports I have created.

Soon I realized that, this kind of structure seems not the be possible to be created with Studio, at least as far as I see it.

Problem basically is that there seems to be no way of adding dynamic amount of tables to the report created with Studio.

So that's why I started to investigate DynamicJasper.

Feel free to correct me if I'm wrong, but could this kind of structure be implemented with DynamicJasper by using DynamicJasper's subreporting capabilities?

It looks like I definitely need at least two subreport definitions if I want data to be presented like it would look like #being printed on just one column".

This is because there will be two totally different kind of datatypes printed on these columns: actions are texts and images are image files.

So basically in my DynamicJasper code I would just iterate all of my dates coming from database and create 2 subreports for each day so i would end up creating 2*(the amount of days) subreports and concatenate all of these to my reportbuilder. Does this sound like something that could work?

To be exact, I think I would print the description texts of the images on adjacent column next to images just to make things easier....


Answer:

In general the solution is this: "in order to print report element(s) in a loop any amount of times in one report, place the element(s) to the detail band of the report and jasper will automatically print this set of elements as many times as there are beans in the collection passed for the report as main datasource/dataAdapter."

Question:

I wrote this app that manages clients, I am generating reports with DynamicReports.

I have created an option in my app that generates a report for each client in a press of a button.

For Example: if I have 5 clients, I press "generate reports" and 5 reports are opened, 1 for each client.

Is there a way to automatically send the report to a printer once it's loaded?

Now, I have to press print manually 5 times, once for each report.


Answer:

Add

report.print();

to every report which is being created.

Question:

I would like to print an A2 size report on jasper on an A4 size printer. i want to print it in four landscape prints so page 1 and 2 make the top of the A2 and pages 3 and 4 make the bottom part of the A2.

.______________________________. |                             |                             | |              1             |              2             | |                             |                             | |-----------..------------+--.--------------------| |                             |                             | |              3             |              4             | |.______________|______________.|

normally printing only prints the left part page 1 and 3. how can I print all the four parts of the page, each on its own page


Answer:

Actually I was able to do it by (Not the best quality, but works for me at the moment):

  • first converting the jasper report an image,
  • then cropping the image into pieces of the printer paper size before sending them to the printer.
  • and sending the image to the printer one by one

JasperPrint jp = the_jasper_print_to_be_printed; // 
int i = 1; // Page Number to print
float zoom = 1f;

BufferedImage image = (BufferedImage) JasperPrintManager.printPageToImage(jp, i, zoom);
PrinterJob printJob = PrinterJob.getPrinterJob();
PageFormat pf = printJob.getPageFormat(null);
int paperWidth = Functions.StringToInt(pf.getImageableWidth());
int paperHeight = Functions.StringToInt(pf.getImageableHeight());
int x = 0, y = 0;
while (y < image.getHeight()) {
    x = 0;
    while (x < image.getWidth()) {
        Rectangle rect = new Rectangle(x, y, paperWidth, paperHeight);
        printImage(Functions.cropImage(image, rect), printJob);
        x += paperWidth;
    }
    y += paperHeight;
}

Function to crop image

public static BufferedImage cropImage(BufferedImage src, Rectangle rect) {
    int w = (rect.x + rect.width > src.getWidth()) ? src.getWidth() - rect.x : rect.width;
    int h = (rect.y + rect.height > src.getHeight()) ? src.getHeight()- rect.y : rect.height;
    BufferedImage dest = src.getSubimage(rect.x, rect.y, w, h);
    return dest;
}

Function to send cropped image to printer

private static void printImage(BufferedImage image, PrinterJob printJob) {
    printJob.setPrintable(new Printable() {
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
            if (pageIndex != 0) {
                return NO_SUCH_PAGE;
            }
            graphics.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            return PAGE_EXISTS;
        }
    });
    try {
        printJob.print();
    } catch (PrinterException e1) {
        e1.printStackTrace();
    }
}

Question:

I am using DynamicReports and struggling with getting the corrent printout, when i call .show() everything is perfect, but when i print it, either to an image using image printer or to PDF using Foxit Printer or even to my LaserJet Printer, result is same as shown in the picture below. I have tried making .jar using this link here

And i checked my PDF it has embedded font whihc i am using "Nafees Noori Nastaleeq" and their is certainly no issue in the font but the issue that my charaters are being distorted i dont know why... ...

Any help will be appreciated, i got not much time limit to do this. ... [img]http://s17.postimg.org/j7lywrpr3/report_issue.png[/img]

UPDATE: I tried exporting to PDF directly from the program and in that PDF i cannot see any unicode characters, i also installed iReport to check the issue and this issue was same(no unicode in directly exported PDF and missing and distorted unicode characters in printing form any pdf printer or physical printer.) So i suspect the issue is not with my DynamicReport configuration its with Font or some genric settings which are not working.


Answer:

Alright, no answer so better answer my own question. The issue was that this font i am using and many other fonts (about 80% of my collection of urdu fonts) are behaving same. Where some other fonts are working good, i have created a list of fonts which worked for me. Pasting it here so that others may get some help if they need. Urdu Nastaliq Unicode Al_Qalam Tehreeri

****LIST****

Arial Arial Unicode MS

Attari_Sulus Attari_Abbas

Microsoft Sans Serif Microsoft Uighur//issue bit

Nafees Web Naskh

UL Sajid Heading//issues in date Urdu Najd v3//same issue

//downloaded and installed for chekcing Adobe Arabic AlFars 7 Kodak Bold// AlFars 18 Aban AlFars 6 Kamran Bold

AlQalam Nabeel

Dubai Unicode Zohar Unicode

AA Sameer Zikran AA Sameer Armaa Unicode

......................

This is a great repository of urdu fonts if anyone need this. http://font.urduweb.org/ ... Lastly i would like to know how can i check any font file for such corruptions and if the font is 100% ok and will work in all scenarios, is there a generic way to check all fonts against any language?