How to remove margin of QRCode generated with zxing? - java

I am using com.google.zxing version 3.3.2 to generate QRCode using jasper report.
The generated QRCode is having spaces and margin. How can I avoid those spaces.
I found solutions to add EncodeHintType.MARGIN, -1 but how to add this in image expression in jasper report.
Below is the image expression as of now I am using.
com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage(
new com.google.zxing.qrcode.QRCodeWriter().encode(
$F{Code},com.google.zxing.BarcodeFormat.QR_CODE, 300, 300))

Adding EncodeHintType.MARGIN is correct but you need to put 0 (otherwise it will throw an error)
To add this you can use the second constructor of QRCodeWriter
public BitMatrix encode(String contents,BarcodeFormat format,
int width,int height,Map<EncodeHintType,?> hints)
throws WriterException
This means that you need to pass a Map which is initialize with the key and value. One way of creating and initializing maps is to use use Guava and it's ImmutableMap
com.google.common.collect.ImmutableMap.of(com.google.zxing.EncodeHintType.MARGIN,0)
Hence the resulting expression would be
com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage(
new com.google.zxing.qrcode.QRCodeWriter().encode(
$F{Code},com.google.zxing.BarcodeFormat.QR_CODE, 300, 300,
com.google.common.collect.ImmutableMap.of(com.google.zxing.EncodeHintType.MARGIN,0)))
Example (I have put a border around to demonstrate margin 0)
jrxml
<?xml version="1.0" encoding="UTF-8"?>
<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="QRCode" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="ee443473-56d0-44df-b5d4-ac3fe82fd9bc">
<queryString>
<![CDATA[]]>
</queryString>
<title>
<band height="200" splitType="Stretch">
<image>
<reportElement x="0" y="0" width="200" height="200" uuid="9236a226-c581-4d35-88d3-c65181090d03"/>
<box>
<pen lineWidth="0.25"/>
<topPen lineWidth="0.25" lineStyle="Solid" lineColor="#000000"/>
<leftPen lineWidth="0.25" lineStyle="Solid" lineColor="#000000"/>
<bottomPen lineWidth="0.25" lineStyle="Solid" lineColor="#000000"/>
<rightPen lineWidth="0.25" lineStyle="Solid" lineColor="#000000"/>
</box>
<imageExpression><![CDATA[com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage(
new com.google.zxing.qrcode.QRCodeWriter().encode(
"Hello world",com.google.zxing.BarcodeFormat.QR_CODE, 300, 300,com.google.common.collect.ImmutableMap.of(com.google.zxing.EncodeHintType.MARGIN,0)))]]></imageExpression>
</image>
</band>
</title>
</jasperReport>
Result

Related

How to print/display MathML expressions?

Currently I'm trying to use a textField with markup="html" but it's not working.
Example
<textField isStretchWithOverflow="true" isBlankWhenNull="true">
<reportElement positionType="Float" stretchType="RelativeToTallestObject" x="100" y="0" width="450" height="25" isPrintWhenDetailOverflows="true" uuid="1aeaa5e9-4136-4239-a301-2733598340d9">
<property name="com.jaspersoft.studio.unit.height" value="pixel"/>
<property name="com.jaspersoft.studio.unit.width" value="pixel"/>
</reportElement>
<textElement verticalAlignment="Middle" markup="html">
<paragraph lineSpacing="Single" leftIndent="5" rightIndent="3"/>
</textElement>
<textFieldExpression><![CDATA[$F{question}]]></textFieldExpression>
$F{question} contain:
"<p id="id"><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>A</mi><mo>+</mo><mo> </mo><mi>B</mi><mo> </mo><mo> </mo><msqrt><mi>c</mi><mfenced><mrow><mi>d</mi><mfenced open="[" close="]"><mi>r</mi></mfenced></mrow></mfenced></msqrt><mo> </mo><mi>δ</mi><mo> </mo><mo>∞</mo><mi mathvariant="normal">π</mi><mo> </mo></math></p>"
Expected Result :
Result which I get :
The textField does not support MathML, it only support very basic html nor can you use the html component since the JEditorPane on which it's built neither does support MathML
You will need an external library as for example jeuclid, once that you have this library in classpath you can render the xml to a BufferedImage using Converter.render and then display it in jasper report.
This can be done without a java helper class as in this example, hence writting all the code directly in the jrxml on 1 line (using the builder pattern below), but for clarity of example I'm will use external helper class.
Example
java
public class MathML {
public static BufferedImage getImage(String xml, float size) throws IOException, SAXException, ParserConfigurationException {
// Load the string to a node
Element node = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)))
.getDocumentElement();
//Generate the layout parameter
MutableLayoutContext params = new LayoutContextImpl(
LayoutContextImpl.getDefaultLayoutContext());
params.setParameter(Parameter.MATHSIZE, size);
//Render the xml to a BufferedImage
return Converter.getInstance().render(node, params);
}
}
jrxml
<?xml version="1.0" encoding="UTF-8"?>
<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="Blank_A4_12" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="8deaea2e-3739-4c4e-b2b5-8c58773ab1a0">
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
<queryString>
<![CDATA[]]>
</queryString>
<title>
<band height="50" splitType="Stretch">
<image>
<reportElement x="0" y="0" width="100" height="50" uuid="9ee17167-a91e-4725-b36e-a4bba5e24acb">
</reportElement>
<imageExpression><![CDATA[it.jdd.MathML.getImage("<math xmlns='http://www.w3.org/1998/Math/MathML'><mi>A</mi><mo>+</mo><mo> </mo><mi>B</mi><mo> </mo><mo> </mo><msqrt><mi>c</mi><mfenced><mrow><mi>d</mi><mfenced open='[' close=']'><mi>r</mi></mfenced></mrow></mfenced></msqrt><mo> </mo><mi>δ</mi><mo> </mo><mo>∞</mo><mi mathvariant='normal'>π</mi><mo> </mo></math>",70f)]]></imageExpression>
</image>
</band>
</title>
</jasperReport>
Output (export to pdf)

How to check if the value of BigDecimal field is negative in JasperReports

I am getting some strange negative values in my report, which could be from the database. I want to format fields to display zero when the values are negative in the expression editor. How can this be done?
You should use the BigDecimal.signum() method for check the sign of BigDecimal.
The expression will be:
<textFieldExpression><![CDATA[$P{bigDecimalValue}.signum() == -1 ? "0" : "Not negative big decimal"]]></textFieldExpression>
The expression for Double is simpler:
<textFieldExpression><![CDATA[$P{doubleValue} < 0 ? "0" : "Non negative double"]]></textFieldExpression>
The sample:
<?xml version="1.0" encoding="UTF-8"?>
<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="BigDecimal check" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
<parameter name="doubleValue" class="java.lang.Double" isForPrompting="false">
<defaultValueExpression><![CDATA[1234.567]]></defaultValueExpression>
</parameter>
<parameter name="bigDecimalValue" class="java.math.BigDecimal" isForPrompting="false">
<defaultValueExpression><![CDATA[new BigDecimal(-9.8)]]></defaultValueExpression>
</parameter>
<title>
<band height="70">
<textField>
<reportElement x="10" y="10" width="300" height="15"/>
<textFieldExpression><![CDATA[$P{doubleValue} < 0.0 ? "0" : "Non negative double"]]></textFieldExpression>
</textField>
<textField>
<reportElement x="10" y="25" width="300" height="15"/>
<textFieldExpression><![CDATA[$P{bigDecimalValue}.signum() == -1 ? "0" : "Not negative big decimal"]]></textFieldExpression>
</textField>
</band>
</title>
</jasperReport>
The output result generated in Jaspersoft Studio will be:

Some currency Symbol in Jasper report is not coming

I have created a jasper report template using jaspersoft studio and I am populating the template using java code. I have some data in the report which needs to be localize and for that I am seeting the "locale" by below code in java.
Locale locale = new Locale("zh", "CN");
templateParameters.put("REPORT_LOCALE", locale); //A map to pass to report
I have also tried -
Locale locale = java.util.Locale.CHINA;
In populated report "Number formatting" is there but currecny symbol is missing(only dollar, pound, euro symbols are coming)
Below is the code I have used in jasper report to populate the text field -
NumberFormat.getCurrencyInstance($P{REPORT_LOCALE}).format($P{Param_Name})
I would be very thankful if someone could pointout the mistake or provide some suggestion.
I believe that your issue related with font supporting.
We should use Font Extensions in case using JRPdfExporter.
I tried to use font with Chinese support and in this case everything is OK.I don't know why using a ton of another fonts is not helping
Example
Java code
Map<String, Object> params = new HashMap<>();
params.put(JRParameter.REPORT_LOCALE, Locale.CHINA);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, new JREmptyDataSource());
Report template
There are 4 textFields in jrxml file: two using font with Chinese support and another 2 - without it.
<?xml version="1.0" encoding="UTF-8"?>
<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="Show currency" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
<parameter name="value" class="java.lang.Double" isForPrompting="false">
<defaultValueExpression><![CDATA[1234.567]]></defaultValueExpression>
</parameter>
<title>
<band height="70">
<textField>
<reportElement x="10" y="10" width="300" height="15"/>
<textElement>
<font fontName="Sharp Dawn"/>
</textElement>
<textFieldExpression><![CDATA[NumberFormat.getCurrencyInstance(new Locale("zh", "CN")).format($P{value})]]></textFieldExpression>
</textField>
<textField>
<reportElement x="10" y="25" width="300" height="15"/>
<textElement>
<font fontName="Sharp Dawn"/>
</textElement>
<textFieldExpression><![CDATA[NumberFormat.getCurrencyInstance($P{REPORT_LOCALE}).format($P{value})]]></textFieldExpression>
</textField>
<textField>
<reportElement x="3" y="40" width="300" height="15"/>
<textFieldExpression><![CDATA[NumberFormat.getCurrencyInstance($P{REPORT_LOCALE}).format($P{value})]]></textFieldExpression>
</textField>
<textField>
<reportElement x="3" y="55" width="300" height="15"/>
<textFieldExpression><![CDATA[NumberFormat.getCurrencyInstance(new Locale("zh", "CN")).format($P{value})]]></textFieldExpression>
</textField>
</band>
</title>
</jasperReport>
Output result
The pdf file generated with help of JRPdfExporter looks like
The Yuan symbol is showing only for first group.

PDF generated from JAVA is damaged using Jasper Reports

I am using iReport Designer 4.7 to create .jrxml. Its a very simle .jrxml which displays parameters passsed
from JAVA. The test pdf gets generated from iReport Designer and I can view it using Adobe Reader.
Now, Here is the java code
I am calling createReport(String reportName, Map params) from Servlet.
The parameters are set from Servlet. There will be always parameters passed.
public void generateReport(String fileName, String outFileName, Map paramerterMap,
String reportFormat) throws JRException{
String reportSource = "C:\\jrxml\\" + fileName;
String outFile = null;
downloadPath = "C:\\pdfs\\";
outFile = downloadPath + outFileName;
JRExporter exporter = new JRPdfExporter();
JasperPrint jasperPrint = JasperFillManager.fillReport(reportSource, paramerterMap);
exporter.setParameter(JRXlsExporterParameter.CHARACTER_ENCODING,"UTF-8");
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, outFile);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.exportReport();
}
public Boolean createReport(String reportName, Map params) {
try {
String jrFile = reportName + ".jasper";
String outFileName = String.valueOf(7884);
outFileName += "_" + reportName + ".pdf";
generateReport(jrFile, outFileName, params, ".pdf");
return true;
} catch (JRException e) {
e.printStackTrace();
log.error("ReportManager--generateReport--JRException: " + e);
return false;
} catch (Exception e) {
e.printStackTrace();
log.error("ReportManager--generateReport--Exception: " + e);
return false;
}
}
I am using same set of .jar which iReport Designer used.
(In fact I have copied .jar files from iReport installation directory)
Problem: The pdf generated using JAVA code is broken.
When I try to open PDF at created location, The Adobe reader says :
Adobe Reader could not open 'test.pdf' because it is either not a
supported file type or because the file has been damaged (for example,
it was sent as an email attachment and wasn't correctly decoded).
EDIT: I do not get any exception and the generated file size is around 5 KB.
EDIT2: Adding JRXML
<?xml version="1.0" encoding="UTF-8"?>
<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="Certificate" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="7367a6fb-f8da-4ba3-b90d-319807f92789">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<property name="ireport.scriptlethandling" value="0"/>
<property name="ireport.encoding" value="UTF-8"/>
<import value="net.sf.jasperreports.engine.*"/>
<import value="java.util.*"/>
<import value="net.sf.jasperreports.engine.data.*"/>
<parameter name="name" class="java.lang.String"/>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="27" splitType="Stretch">
<textField pattern="MMMMM dd, yyyy" isBlankWhenNull="false">
<reportElement uuid="b72c0bad-3935-40ba-8d6d-3993cb5122d2" key="textField" x="413" y="0" width="140" height="20"/>
<box>
<topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
</box>
<textElement>
<font size="12"/>
</textElement>
<textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
</textField>
</band>
</title>
<pageHeader>
<band height="21" splitType="Stretch"/>
</pageHeader>
<columnHeader>
<band height="22" splitType="Stretch"/>
</columnHeader>
<detail>
<band height="141" splitType="Stretch">
<textField isStretchWithOverflow="true" isBlankWhenNull="true">
<reportElement uuid="cbaae0d4-53da-420e-8efa-7f4fcc6900f0" key="name" x="0" y="10" width="530" height="20"/>
<box>
<topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
</box>
<textElement textAlignment="Left" verticalAlignment="Middle">
<font fontName="Arial" size="11" isBold="true"/>
</textElement>
<textFieldExpression><![CDATA[$P{name}]]></textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band splitType="Stretch"/>
</columnFooter>
<pageFooter>
<band height="20" splitType="Stretch"/>
</pageFooter>
<summary>
<band splitType="Stretch"/>
</summary>
</jasperReport>
Hardik,
I see 2-3 things over here
1) Your outfile name in generateReport always comes as "c:\pdfs"+ NULL.
( I wonder why test.pdf is still created )
2) What does gujarati object contains parameters for reports??
EDIT
3) Just asking why keep two seperate function for report generation?
In my opinion you could achieve the objective with single function createReport.!
EDIT : 2
I think this link might offer some help : http://jasperforge.org/uploads/publish/jasperreportswebsite/trunk/faq.html?group_id=252#FAQ29

Blank PDF even with the simplest Jasperreport jrxml

i have a EJB site with glassfish 3.1 + JSF for jasperreport 4.0.1. the site has no problem on streaming pdf, but it products blank PDF while printing PDF with runReportToPdfStream, below is the code snippet:
EJB
public class BookEJB {
public void printReport() throws ClassNotFoundException, IOException, JRException {
Map parameterMap = new HashMap();
FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
InputStream reportStream = ctx.getExternalContext().getResourceAsStream("/reports/test.jasper");
ServletOutputStream servletOutputStream = response.getOutputStream();
servletOutputStream.flush();
response.setContentType("application/pdf");
JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parameterMap);
servletOutputStream.flush();
servletOutputStream.close();
ctx.responseComplete();
}}
test.jrxml - a simple report without SQL connection
<?xml version="1.0" encoding="UTF-8"?>
<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="test" pageWidth="800" pageHeight="1200" columnWidth="555" leftMargin="25" rightMargin="25" topMargin="30" bottomMargin="30">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<queryString>
<![CDATA[]]>
</queryString>
<pageHeader>
<band height="100">
<staticText>
<reportElement x="0" y="0" width="285" height="36"/>
<textElement>
<font size="24" isBold="true"/>
</textElement>
<text><![CDATA[Report of Testing]]></text>
</staticText>
</band>
</pageHeader>
<detail>
<band height="200">
<staticText>
<reportElement x="0" y="0" width="374" height="48"/>
<textElement>
<font size="18"/>
</textElement>
<text><![CDATA[If you don't see this, it didn't work blah blah blah.... ]]></text>
</staticText>
</band>
</detail>
<pageFooter>
<band height="100"/>
</pageFooter>
</jasperReport>
no error log in glassfish when generating this report on JSF, but only blank PDF has been shown. Please help, let me know if you need further info for the analysis.
Steven
After all, JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parameterMap, new JREmptyDataSource()); solved the problem.
Quote from Sanda of Jasperreport:
By default, when no datasource info is present in a report, JR generates no pages. Another option (which can be set in the report's whenNoDataType attribute) would be to print all report sections, excepting the <detail>.
This report contains a detail section, but only with some static data. To ensure this section will be printed too, the simplest way is to provide an empty data source, containing a single empty record.
Source: https://community.jaspersoft.com/questions/537650/blank-pdf-even-simplest-jrxml
When you are not using the details band, just static values, you can do the following:
Right click in the iReport project, then select 'Properties', search for the property 'When no Data', and select 'All Sections, No Detail'
It works for me, using iReport 4.0
In addition to what Mythox said, I'll show the best way to fake a data source in jasper and if you need also on JasperServer.
1) Define an Empty Data Adapter (a simple .xml file), and deploy it in Server or put it in reports folder:
<?xml version="1.0" encoding="UTF-8" ?><emptyDataAdapter class="net.sf.jasperreports.data.empty.EmptyDataAdapterImpl"><name>Nuovo Data Adapter 1</name><recordCount>1</recordCount></emptyDataAdapter>
2) Link it into the main report:
<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="repor" language="javascript" pageWidth="612" pageHeight="792" whenNoDataType="NoDataSection" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" isFloatColumnFooter="true" uuid="c0eee90e-1b1a-4f34-ad99-1112847752de">
<property name="net.sf.jasperreports.data.adapter" value="EmptyDataAdapter.xml"/>
prefix "repo:" to the value of the property for the data adapter, if the xml is deployed on jasper server.
The attribute "whenNoDataType" will be ignored.
Other details here.

Categories

Resources