使用jar :barcode4j.jar
代码如下:
package com.test;
import java.io.File;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.svg.SVGCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;
import org.w3c.dom.DocumentFragment;
public class BarcodeTest {
public static void main(String[] args) throws Exception {
Double moduleWidth = Double.valueOf(1.0D);
double dpi = 150;
Double width = 11d;
Code128Bean bean = new Code128Bean();
String barcode = "test123zxc";
Integer barcodeLength = Integer.valueOf(barcode.length());
if (barcodeLength.intValue() < 8)
{
moduleWidth = Double.valueOf(2.0D * width.doubleValue());
}
else if (barcodeLength.intValue() < 16)
{
moduleWidth = width;
}
if (moduleWidth.doubleValue() < 1.0D)
{
moduleWidth = Double.valueOf(1.0D);
}
bean.setModuleWidth(UnitConv.in2mm(moduleWidth.doubleValue() / dpi));
SVGCanvasProvider canvas = new SVGCanvasProvider(false, 0);
bean.generateBarcode(canvas, barcode);
DocumentFragment frag = canvas.getDOMFragment();
TransformerFactory factory = TransformerFactory.newInstance();
Transformer trans = factory.newTransformer();
Source src = new DOMSource(frag);
Result res = new StreamResult(new File("D://barcode" + File.separator + 1 + ".svg"));
trans.transform(src, res);
}
}