Spire.PDF for Java支持在PDF中创建Codebar、Code11、Code128A、Code128B、Code32、Code39、Code39 Extended 、Code93和Code93 Extended条形码,本教程选择了其中的Codebar、Code128A和Code39进行展示。
import com.spire.pdf.barcode.*;
import com.spire.pdf.graphics.*;
import static com.spire.pdf.graphics.PdfFontStyle.Bold;
import java.awt.*;
import java.awt.geom.Point2D;
import java.util.EnumSet;
public class DrawBarcode {
public static void main(String[] args) {
//创建PdfDocument对象
PdfDocument doc = new PdfDocument();
//添加一页
PdfPageBase page = doc.getPages().add();
//初始化y变量
double y = 15;
//创建字体
PdfFont font= new PdfFont(PdfFontFamily.Helvetica, 12, EnumSet.of(Bold));
// 绘制文本“Codebar:”到PDF
PdfTextWidget text = new PdfTextWidget();
text.setFont(font);
text.setText("Codebar:");
PdfLayoutResult result = text.draw(page, 0, y);
y =(float)(result.getBounds().getY()+ result.getBounds().getHeight() + 2);
//绘制Codebar条码到PDF
PdfCodabarBarcode codebar= new PdfCodabarBarcode("00:12-3456/7890");
codebar.setBarcodeToTextGapHeight(1f);
codebar.setBarHeight(50f);
codebar.setEnableCheckDigit(true);
codebar.setShowCheckDigit(true);
codebar.setTextDisplayLocation(TextLocation.Bottom);
PdfRGBColor blue = new PdfRGBColor(Color.blue);
codebar.setTextColor(blue);
Point2D.Float point = new Point2D.Float();
point.setLocation(0,y);
codebar.draw(page,point);
y = codebar.getBounds().getY()+ codebar.getBounds().getHeight() + 5;
//绘制文本“Code128-A:”到PDF
text.setText("Code128-A:");
result = text.draw(page, 0, y);
page = result.getPage();
y =result.getBounds().getY()+ result.getBounds().getHeight() + 2;
//绘制Code128A条码到PDF
PdfCode128ABarcode code128 = new PdfCode128ABarcode("HELLO 00-123");
code128.setBarcodeToTextGapHeight(1f);
code128.setBarHeight(50f);
code128.setTextDisplayLocation(TextLocation.Bottom);
code128.setTextColor(blue);
point.setLocation(point.x,y);
code128.draw(page, point);
y =code128.getBounds().getY()+ code128.getBounds().getHeight() + 5;
//绘制文本“Code39”到PDF
text.setText("Code39:");
result = text.draw(page, 0, y);
page = result.getPage();
y =result.getBounds().getY()+ result.getBounds().getHeight() + 2;
//绘制Code39条形码到PDF
PdfCode39Barcode code39 = new PdfCode39Barcode("16-273849");
code39.setBarcodeToTextGapHeight(1f);
code39.setBarHeight(50f);
code39.setTextDisplayLocation(TextLocation.Bottom);
code39.setTextColor(blue);
point.setLocation(point.x,y);
code39.draw(page, point);
//保存PDF文档
doc.saveToFile("DrawBarcode.pdf");
}
}