Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add zxing object drawer for barcode generation #533

Merged
merged 1 commit into from
Aug 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ enum LogMessageId2Param implements LogMessageId {
"algorithm for break-word! Start-substring=[{}], end={}"),
GENERAL_EXPECTING_BOX_CHILDREN_OF_TYPE_BUT_GOT(XRLog.GENERAL, "Expecting box children to be of type ({}) but got ({})."),
GENERAL_PDF_FOUND_ELEMENT_WITHOUT_ATTRIBUTE_NAME(XRLog.GENERAL, "found a <{} {}> element without attribute name, the element will not work without this attribute"),
GENERAL_UNABLE_TO_PARSE_VALUE_AS(XRLog.GENERAL, "Unable to parse value '{}' as {}"),

EXCEPTION_CANT_OPEN_STREAM_FOR_URI(XRLog.EXCEPTION, "Can't open stream for URI '{}': {}"),
EXCEPTION_SVG_EXTERNAL_RESOURCE_NOT_ALLOWED(XRLog.EXCEPTION, "Tried to fetch external resource from SVG. Refusing. Details: {}, {}"),
Expand Down
5 changes: 5 additions & 0 deletions openhtmltopdf-examples/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@
<artifactId>jfreechart</artifactId>
<version>1.5.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<html>
<head>
<title>a</title>
<style>
@page {
size: 100px 80px;
margin: 0;
}
</style>
</head>
<body>
before
<object type="image/barcode" style="width:50px;height:20px;"
value="123"
format="CODE_39"
on-color="0xFF0000FF"
off-color="0xFFFFFFFF">
</object>
after
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<html>
<head>
<title>a</title>
<style>
@page {
size: 120px 60px;
margin: 0;
}
</style>
</head>
<body>
<object type="image/barcode" style="width:100px;height:40px;border:1px solid red;" format="DATA_MATRIX" value="hello world">
<encode-hint name="DATA_MATRIX_SHAPE" value="FORCE_RECTANGLE"></encode-hint>
</object>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<html>
<head>
<title>a</title>
<style>
@page {
size: 80px 80px;
margin: 0;
}
</style>
</head>
<body>
<object type="image/barcode" style="width:60px;height:60px;border:1px solid red;" value="hello world">
</object>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import java.util.Collections;

import com.openhtmltopdf.extend.FSStream;
import com.openhtmltopdf.objects.zxing.ZXingObjectDrawer;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
Expand Down Expand Up @@ -1216,6 +1217,21 @@ public void testIssue474NpeImageDecoding() throws IOException {
assertTrue(vt.runTest("issue-474-npe-image-decoding"));
}

@Test
public void testBarcode() throws IOException {

VisualTester.BuilderConfig c = builder -> {
DefaultObjectDrawerFactory factory = new DefaultObjectDrawerFactory();
factory.registerDrawer("image/barcode", new ZXingObjectDrawer());
builder.useObjectDrawerFactory(factory);
};

assertTrue(vt.runTest("zxing-qrcode-default", c));
assertTrue(vt.runTest("zxing-barcode-custom-color", c));
assertTrue(vt.runTest("zxing-datamatrix-encode-hint", c));

}

// TODO:
// + Elements that appear just on generated overflow pages.
// + content property (page counters, etc)
Expand Down
6 changes: 6 additions & 0 deletions openhtmltopdf-objects/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@
<version>1.5.0</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
<optional>true</optional>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package com.openhtmltopdf.objects.zxing;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.datamatrix.encoder.SymbolShapeHint;
import com.google.zxing.pdf417.encoder.Dimensions;
import com.openhtmltopdf.extend.FSObjectDrawer;
import com.openhtmltopdf.extend.OutputDevice;
import com.openhtmltopdf.render.RenderingContext;
import com.openhtmltopdf.util.LogMessageId;
import com.openhtmltopdf.util.XRLog;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.awt.*;
import java.util.*;
import java.util.logging.Level;

public class ZXingObjectDrawer implements FSObjectDrawer {


private static Object handleValueForHint(EncodeHintType type, String value) {
switch (type) {
case DATA_MATRIX_SHAPE:
return safeSymbolShapeHint(value);
case PDF417_DIMENSIONS: {
try {
int[] dim = Arrays.stream(value.trim().split(",")).mapToInt(Integer::parseInt).toArray();
if (dim.length == 4) {
return new Dimensions(dim[0], dim[1], dim[2], dim[3]);
}
} catch (NumberFormatException nfe) {
}
XRLog.log(Level.WARNING, LogMessageId.LogMessageId2Param.GENERAL_UNABLE_TO_PARSE_VALUE_AS, value, Dimensions.class.getCanonicalName());
return null;
}
default:
return value;
}
}

private static SymbolShapeHint safeSymbolShapeHint(String value) {
try {
return SymbolShapeHint.valueOf(value);
} catch (IllegalArgumentException e) {
XRLog.log(Level.WARNING, LogMessageId.LogMessageId2Param.GENERAL_UNABLE_TO_PARSE_VALUE_AS, value, SymbolShapeHint.class.getCanonicalName(), e);
return null;
}
}

private static EncodeHintType safeEncodeHintTypeValueOf(String value) {
try {
return EncodeHintType.valueOf(value);
} catch (IllegalArgumentException e) {
XRLog.log(Level.WARNING, LogMessageId.LogMessageId2Param.GENERAL_UNABLE_TO_PARSE_VALUE_AS, value, EncodeHintType.class.getCanonicalName(), e);
return null;
}
}

private static int parseInt(String value, int defaultColor) {
try {
return Long.decode(value.toLowerCase(Locale.ROOT)).intValue();
} catch (NumberFormatException nfe) {
XRLog.log(Level.WARNING, LogMessageId.LogMessageId2Param.GENERAL_UNABLE_TO_PARSE_VALUE_AS, value, "integer", nfe);
return defaultColor;
}
}

@Override
public Map<Shape, String> drawObject(Element e, double x, double y, double width, double height, OutputDevice outputDevice, RenderingContext ctx, int dotsPerPixel) {
MultiFormatWriter mfw = new MultiFormatWriter();
int onColor = e.hasAttribute("on-color") ? parseInt(e.getAttribute("on-color"), MatrixToImageConfig.BLACK) : MatrixToImageConfig.BLACK;
int offColor = e.hasAttribute("off-color") ? parseInt(e.getAttribute("off-color"), MatrixToImageConfig.WHITE) : MatrixToImageConfig.WHITE;

Map<EncodeHintType, Object> encodeHints = new EnumMap<>(EncodeHintType.class);
encodeHints.put(EncodeHintType.MARGIN, 0); // default
NodeList childNodes = e.getChildNodes();
int childNodesCount = childNodes.getLength();
for (int i = 0; i < childNodesCount; i++) {
Node n = childNodes.item(i);
if (!(n instanceof Element))
continue;
Element eChild = (Element) n;
if (!"encode-hint".equals(eChild.getTagName())) {
continue;
}
EncodeHintType encodeHintType = safeEncodeHintTypeValueOf(eChild.getAttribute("name"));
Object value = encodeHintType != null ? handleValueForHint(encodeHintType, eChild.getAttribute("value")) : null;
if (encodeHintType != null && value != null) {
encodeHints.put(encodeHintType, value);
}
}

String value = e.getAttribute("value");
BarcodeFormat barcodeFormat = e.hasAttribute("format") ? BarcodeFormat.valueOf(e.getAttribute("format")) : BarcodeFormat.QR_CODE;

int finalWidth = (int) (width/dotsPerPixel);
int finalHeight = (int) (height/dotsPerPixel);
try {
BitMatrix bitMatrix = mfw.encode(value, barcodeFormat, finalWidth, finalHeight, encodeHints);

outputDevice.drawWithGraphics((float) x, (float) y, (float) width, (float) height, graphics2D -> {
//generating a vector from the bitmatrix don't seems to be straightforward, thus a bitmap image...
graphics2D.drawImage(MatrixToImageWriter.toBufferedImage(bitMatrix, new MatrixToImageConfig(onColor, offColor)), 0, 0, finalWidth, finalHeight, null);
});
} catch (WriterException we) {
XRLog.log(Level.WARNING, LogMessageId.LogMessageId1Param.GENERAL_MESSAGE, "Error while generating the barcode", we);
}
return null;
}
}