Skip to content

Plugins: 1D 2D Barcode with ZXing

Sylvain Jermini edited this page Aug 17, 2020 · 5 revisions

The ZXing plugin provide an easy way to embed 1D/2D barcode into your document.

Example

You will need to define a size (width/height) for your object:

<html>
  <body>
    <h1>Default barcode: qrcode</h1>
    <object type="image/barcode" style="width:60px;height:60px;" value="hello world"></object>
    <h1>Select barcode type:</h1>
    <object type="image/barcode" style="width:50px;height:20px;" value="123" format="CODE_39"></object>
    <h1>Encode hint</h1>
    <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>
  	<dependency>
  		<!-- Objects support plugin. -->
  		<groupId>com.openhtmltopdf</groupId>
  		<artifactId>openhtmltopdf-objects</artifactId>
  		<version>${openhtml.version}</version>
  	</dependency>
	<dependency>
  		<groupId>com.google.zxing</groupId>
  		<artifactId>javase</artifactId>
  		<version>3.4.0</version>
	</dependency>
public static void main(String... args) throws Exception { 
        try (OutputStream os = new FileOutputStream("barcode.pdf")) {
            PdfRendererBuilder builder = new PdfRendererBuilder();
            builder.withUri("barcode.html");
            builder.useFastMode();
            builder.toStream(os);
            
            DefaultObjectDrawerFactory factory = new DefaultObjectDrawerFactory();
            factory.registerDrawer("image/barcode", new ZXingObjectDrawer());
            builder.useObjectDrawerFactory(factory);

            builder.run();
        }
}

Result

barcode-result

Parameters

Format:

The format attribute is used for selecting the barcode format. You can choose the values from the BarcodeFormat enum

On and off color

You can define the "on" and "off" color of your barcode by using the on-color and off-color attributes. As defined in the MatrixToImageConfig constructor, it's specified as an ARGB value.

For example: on-color="0xFF0000FF" off-color="0xFFFFFFFF"

Encode hints

You can pass rendering hints by using <encode-hint name="NAME" value="VALUE"></encode-hint> elements.

The accepted name/value are defined in the EncodeHintType enum.