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");
}
}