`
log_cd
  • 浏览: 1098654 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

integrate Barcode4J in a Java application

阅读更多
   Barcode4J资源地址:http://barcode4j.sourceforge.net/index.html
一、using the JavaBean API
	public static void generateCode128Barcode(File file, String code) {
		Code128Bean bean = new Code128Bean();
		final int dpi = 150;
		
		//barcode
		bean.setModuleWidth(0.21);
		bean.setHeight(15);
		bean.doQuietZone(true);
		bean.setQuietZone(2);//两边空白区
		//human-readable
		bean.setFontName("Helvetica");
		bean.setFontSize(3);
		bean.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM);
		
		OutputStream out = null;

		try {
			out = new FileOutputStream(file);

			BitmapCanvasProvider canvas = new BitmapCanvasProvider(out,
					"image/jpeg", dpi, BufferedImage.TYPE_BYTE_BINARY, true, 0);
			bean.generateBarcode(canvas, code);
			canvas.finish();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public static void generateCode39Barcode(int mode, File file, String code) {
		Code39Bean bean = new Code39Bean();
		// Dot Per Inch每英寸所打印的点数或线数,用来表示打印机打印分辨率。
		final int dpi = 150;
		// bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi));
		bean.setModuleWidth(0.2);
		bean.setHeight(15);

		bean.setWideFactor(3);
		bean.doQuietZone(true);

		OutputStream out = null;

		try {
			out = new FileOutputStream(file);

			if (mode == 0) {
				BitmapCanvasProvider canvas = new BitmapCanvasProvider(out,
						"image/jpeg", dpi, BufferedImage.TYPE_BYTE_GRAY, false,
						0);

				bean.generateBarcode(canvas, code);

				canvas.finish();

			} else {
				BitmapCanvasProvider canvas = new BitmapCanvasProvider(dpi,
						BufferedImage.TYPE_BYTE_GRAY, true, 0);
				bean.generateBarcode(canvas, code);
				canvas.finish();
				BufferedImage barcodeImage = canvas.getBufferedImage();

				ImageIO.write(barcodeImage, "jpg", out);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

二、use XML API
1.code39.xml
<?xml version="1.0" encoding="UTF-8"?>
<barcode>
  <code39>
      <height>15mm</height>
      <module-width>0.19mm</module-width>
      <wide-factor>2.5</wide-factor>
      <interchar-gap-width>1mw</interchar-gap-width>
      <quiet-zone enabled="true">10mw</quiet-zone>
      <checksum>ignore</checksum>
      <human-readable>
        <placement>bottom</placement>
        <font-name>Helvetica</font-name>
        <font-size>8pt</font-size>
        <display-start-stop>false</display-start-stop>
        <display-checksum>false</display-checksum>
      </human-readable>
  </code39>
</barcode>

2.java
	/**
	 * 不同的类型,其属性定义有所有同,最好是加载xml文件的方式来配置
	 */
	public static Configuration buildCfg(String barcode_type) {
		DefaultConfiguration cfg = new DefaultConfiguration("barcode");
		DefaultConfiguration barcodeType = new DefaultConfiguration(barcode_type);

		/** *********属性设置************* */
		addChild(barcodeType,"bar-height",15);
		addChild(barcodeType,"module-width","0.19");
		addChild(barcodeType,"quiet-zone",10);
		addChild(barcodeType,"wide-factor","2.5");
		addChild(barcodeType,"interchar-gap-width",1);
		
		DefaultConfiguration humanReadable = new DefaultConfiguration("human-readable");
		addChild(humanReadable,"placement","bottom");
		addChild(humanReadable,"font-name","Helvetica");
		addChild(humanReadable,"font-size","3mm");
		
		barcodeType.addChild(humanReadable);
		cfg.addChild(barcodeType);

		return cfg;
	}

	/**
	 * 添加子节点
	 * @param parent
	 * @param attrName
	 * @param attrValue
	 */
	public static void addChild(DefaultConfiguration parent,String attrName,Object attrValue){
		DefaultConfiguration attr;
		attr = new DefaultConfiguration(attrName);
		if(attrValue instanceof String) {
			attr.setValue((String)attrValue);
		}else{
			attr.setValue((Integer)attrValue);
		}
		parent.addChild(attr);
	}

	/**
	 * 加载xml配置的条形码属性文件
	 * @param file
	 * @return
	 */
	public static Configuration buildCfgFromFile(File file) {
		DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
		Configuration cfg = null;
		try {
			cfg = builder.buildFromFile(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cfg;
	}

	/**
	 * 生成条形码
	 * @param barcodeType
	 * @param code
	 * @param file
	 */
	public static void generateBarcode(String barcodeType, String code,
			File file) {
		byte[] data;
		ByteArrayOutputStream baos = null;
		BitmapCanvasProvider bitmap = null;
		String FORMAT = MimeTypes.MIME_JPEG;
		int RESOLUTION = 150;
		int ORIENTATION = 0;
		try {
			//加载文件方式
			//Configuration cfg = buildCfgFromFile(getResourceFile(barcodeType.concat(".xml")));
			
			Configuration cfg = buildCfg(barcodeType);//程序中的配置属性
			BarcodeUtil util = BarcodeUtil.getInstance();
			BarcodeGenerator gen = util.createBarcodeGenerator(cfg);

			baos = new ByteArrayOutputStream();

			bitmap = new BitmapCanvasProvider(baos, FORMAT, RESOLUTION,
					BufferedImage.TYPE_BYTE_GRAY, true, ORIENTATION);

			gen.generateBarcode(bitmap, code);
			bitmap.finish();

			data = baos.toByteArray();
			FileOutputStream out = new FileOutputStream(file);
			out.write(data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.close();
				}
				bitmap = null;
			} catch (Exception e) {
			}
		}

	}

	/**
	 * 取资源文件
	 * @param fileName
	 * @return
	 */
	public static File getResourceFile(String fileName) {
		String path = ClassLoader.getSystemResource("").getPath().substring(1) + fileName;
		return new File(path);
	}

3.测试
	public static void main(String[] args) {
		String code = "ISN8859-52036";
		generateCode39Barcode(0, new File("d:/barcode/code39_0.jpg"), code);
		generateCode39Barcode(1, new File("d:/barcode/code39_1.jpg"), code);
		generateCode128Barcode(new File("d:/barcode/code128.jpg"), code);

		generateBarcode("code39", code, new File("d:/barcode/code39.jpg"));
	}
分享到:
评论

相关推荐

    exe4j 4.0.3

    exe4j is a Java exe maker that helps you integrate your Java applications into the Windows operating environment, whether they are service, GUI or command line applications. If you want your own ...

    Secure Java: For Web Application Development

    Secure Java: For Web Application Development covers secure programming, risk assessment, and threat modeling—explaining how to integrate these practices into a secure software development life cycle...

    Java.EE.and.HTML5.Enterprise.Application.Development

    Title: Java EE and HTML5 Enterprise Application Development Author: Arun Gupta, Geertjan Wielenga, John Brock Length: 176 pages Edition: 1 Language: English Publisher: McGraw-Hill Osborne Media ...

    dom4j api 参考手册

    org.dom4j Defines the XML Document Object Model in Java interfaces together with some helper classes. org.dom4j.bean An implementation of the dom4j API which allows JavaBeans to be used to store and ...

    英文原版-Instant Messaging in Java 1st Edition

    This book describes how to create Instant Messaging applications in Java and covers the Jabber IM protocols. If you want to create new IM systems, integrate them with your existing software, or wish ...

    Integrate image scanning within a C# application-Part VI

    在本系列教程的第六部分,我们将深入探讨如何在C#应用程序中集成图像扫描功能。这一技术对于开发桌面应用,特别是那些处理文档管理、图像处理或需要用户上传实物照片的应用至关重要。我们将关注Scanner.cs和Button...

    Packt.Hands-On.Spring.Security.5.for.Reactive.Applications

    You will also understand how to achieve authorization in a Spring WebFlux application using Spring Security.You will be able to explore the security confgurations required to achieve OAuth2 for ...

    Mastering Java for Data Science

    First, we will revise the most important things when starting a Data Science application, and then brush up the basics of Java and Machine Learning before diving into more advanced topics.We start ...

    源代码+书Java EE 8 High Performance

    What you will learnIdentify performance bottlenecks in an applicationLocate application hotspots using performance toolsUnderstand the work done under the hood by EE containers and its impact on ...

    Integrate_E2E_in_MICROSAR.pdf

    4. 变体处理 Maximilian Hempe在后续的更新中,详细阐述了使用Groovy脚本进行变体管理以配合E2E Protection Wrapper的策略,这为适应不同环境和配置需求提供了灵活性。 5. 参考文档 为了帮助读者深入理解,文档引用...

    ActiveMQ in Action pdf英文版+源代码

    With the basics well in hand, you move into interesting examples of ActiveMQ at work, following a running Stock Portfolio application. You'll integrate ActiveMQ with containers like Geronimo and ...

    Using java swing components in MATLAB

    JCONTROL provides an easy way to integrate a full range of java GUIs from the java.awt and javax.swing libraries into MATLAB. Example: obj=JCONTROL(Parent, Style); obj=JCONTROL(Parent, Style,... ...

    Java EE 8 High Performance

    What you will learnIdentify performance bottlenecks in an applicationLocate application hotspots using performance toolsUnderstand the work done under the hood by EE containers and its impact on ...

    Tkinter GUI Application Development HOTSHOT(PACKT,2013)

    Starting with a high level overview of Tkinter that covers the most important concepts involved in writing a GUI application, the book then takes you through a series of real world projects of ...

    Learning.Reactive.Programming.With.Java.8

    The book starts with an explanation of what reactive programming is, why it is so appealing, and how we can integrate it in to Java. It continues by introducing the new Java 8 syntax features, such as...

    Natural.Language.Processing.with.Java.178439179

    Natural Language Processing (NLP) is an important area of application development and its relevance in addressing contemporary problems will only increase in the future. There has been a significant ...

    Java - J2EE Job Interview Companion.pdf

    In conclusion, Log4j is a powerful tool for logging within Java applications. Its hierarchical logger architecture, multiple output formats, and performance optimizations make it a preferred choice ...

Global site tag (gtag.js) - Google Analytics