Skip to content

Instantly share code, notes, and snippets.

@halyph
Created May 14, 2013 16:02
Show Gist options
  • Save halyph/5577135 to your computer and use it in GitHub Desktop.
Save halyph/5577135 to your computer and use it in GitHub Desktop.
Generate DataMatrix, inline it in PDF and read generate DataMatrix
package org.halyph.barcode;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Map;
import javax.imageio.ImageIO;
import org.krysalis.barcode4j.impl.datamatrix.DataMatrixBean;
import org.krysalis.barcode4j.impl.datamatrix.SymbolShapeHint;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.output.bitmap.BitmapEncoder;
import org.krysalis.barcode4j.output.bitmap.BitmapEncoderRegistry;
import org.krysalis.barcode4j.tools.UnitConv;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfWriter;
public class App {
private void generate(File outputFile) throws IOException, DocumentException {
String msg = "TTT OIOrest Ivasiv 50e8400-e29b-41d4-a716-446655440000|4-550e8400-e29b-41d4-a716-446655440000 tralalala";
//Create the barcode bean
DataMatrixBean bean = new DataMatrixBean();
final int dpi = 300;
//Configure the barcode generator
bean.setModuleWidth(UnitConv.in2mm(5f / dpi)); //makes a dot/module exactly eight pixels
bean.doQuietZone(true);
bean.setShape(SymbolShapeHint.FORCE_SQUARE);
boolean antiAlias = false;
int orientation = 0;
//Set up the canvas provider to create a monochrome bitmap
BitmapCanvasProvider canvas = new BitmapCanvasProvider(
dpi, BufferedImage.TYPE_BYTE_BINARY, antiAlias, orientation);
//Generate the barcode
bean.generateBarcode(canvas, msg);
//Signal end of generation
canvas.finish();
//Get generated bitmap
BufferedImage symbol = canvas.getBufferedImage();
int width = symbol.getWidth();
int height = symbol.getHeight();
//Add padding
int padding = 10;
width += 2 * padding;
height += 3 * padding;
BufferedImage bitmap = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g2d = bitmap.createGraphics();
g2d.setBackground(Color.white);
g2d.setColor(Color.black);
g2d.clearRect(0, 0, bitmap.getWidth(), bitmap.getHeight());
//Place the barcode symbol
AffineTransform symbolPlacement = new AffineTransform();
symbolPlacement.translate(padding, padding);
g2d.drawRenderedImage(symbol, symbolPlacement);
createPdf(bitmap);
//Encode bitmap as file
String mime = "image/png";
OutputStream out = new FileOutputStream(outputFile);
try {
final BitmapEncoder encoder = BitmapEncoderRegistry.getInstance(mime);
encoder.encode(bitmap, out, mime, dpi);
} finally {
out.close();
}
}
public void readDataMatrix(File file) {
Map<DecodeHintType,Object> hints = new EnumMap<DecodeHintType,Object>(DecodeHintType.class);
hints.put(DecodeHintType.POSSIBLE_FORMATS, Arrays.asList(BarcodeFormat.DATA_MATRIX));
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
try {
String data = readCode(file, hints);
System.out.println(data);
} catch (Exception e) {
e.printStackTrace();
}
}
public String readCode(File file,
Map<DecodeHintType,?> hints)
throws FileNotFoundException, IOException, NotFoundException {
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
new BufferedImageLuminanceSource(
ImageIO.read(file))));
Result result = new MultiFormatReader().decode(binaryBitmap, hints);
return result.getText();
}
private static File createTempFile(String fileName) throws IOException {
File file = File.createTempFile("DataMatrix", ".png");
return file;
}
public void createPdf(BufferedImage bitmap) throws IOException, DocumentException {
// step 1
Document document = new Document(PageSize.POSTCARD, 30, 30, 30, 30);
File pdfFile = File.createTempFile("DataMatrix", ".pdf");
System.out.println("PDF = " + pdfFile);
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(pdfFile));
writer.setCompressionLevel(0);
// step 3
document.open();
Image img= Image.getInstance(bitmap, null);
img.setAbsolutePosition(
(PageSize.POSTCARD.getWidth() - img.getScaledWidth()) / 2,
(PageSize.POSTCARD.getHeight() - img.getScaledHeight()) / 2);
writer.getDirectContent().addImage(img, true);
// step 5
document.close();
}
/**
* Command-line program.
* @param args the command-line arguments
*/
public static void main(String[] args) {
try {
App app = new App();
String fileName = "code.png";
File file = createTempFile(fileName);
System.out.println("printing to " + file.getAbsolutePath());
app.generate(file);
app.readDataMatrix(file);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment