JAVA生成有动态章的PDF_用什么来生成包含动态生成的条形码(Java)的pdf文档?

我的要求要求生成包含任意文本和条形码的pdf文档.我有相关的question,它涉及pdf生成部分,但在这里我想知道如何在Java中将条形码合并到pdf中.

到目前为止,我已经找到了关于barcode4j如何使用Apache FOP:Instructions for the Apache FOP extension的明确解释

但看起来XSL-FO不是我的要求的主要选项,因为我更喜欢使用pdf表格(使用iText或PDFBox或类似).同样,这还不是最终的.

您是否在pdf中使用图像或字体作为条形码?除了pdf API之外还应该有什么依赖(字体,库)?

解决方法:

我成功地使用PDFBox和Barbecue将条形码添加到PDF.烧烤提供输出界面自己绘制条形码.我以这样的方式实现了这个接口,即drawBar()转换为对PDPageContentStream.fillRect()的调用.

现在,向PDF添加条形码可归结为:

Barcode barcode = BarcodeFactory.createCode128(text);

barcode.output(new PDFBoxOutput(pageContentStream, startX, startY, height));

PDFBoxOutput类如下所示:

import java.awt.Color;

import java.io.IOException;

import net.sourceforge.barbecue.output.LabelLayout;

import net.sourceforge.barbecue.output.Output;

import net.sourceforge.barbecue.output.OutputException;

import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;

public class PDFBoxOutput implements Output {

/** The widths and heights from Barbecue are multipplied with this scalar to get the widths and heights for PDFBox. */

public final static float SCALAR = 0.5f;

private final PDPageContentStream stream;

private final float startX;

private final float startY;

private final float height;

private boolean toggleDrawingColor;

PDFBoxOutput(PDPageContentStream stream, float startX, float startY, float height) {

this.stream = stream;

this.startX = startX;

this.startY = startY;

this.height = height;

}

@Override

public void beginDraw() throws OutputException {}

@Override

public int drawBar(int x, int y, int width, int height, boolean paintWithForegroundColor) throws OutputException {

if (paintWithForegroundColor == !toggleDrawingColor) {

try {

stream.setLineWidth(0.0f);

stream.setStrokingColor(Color.BLACK);

stream.fillRect(startX + SCALAR * x, startY - SCALAR * y, SCALAR * width, this.height);

stream.stroke();

} catch (IOException e) {

throw new OutputException(e);

}

}

return width;

}

@Override

public int drawText(String text, LabelLayout layout) throws OutputException {

return 0;

}

@Override

public void endDraw(int width, int height) throws OutputException {}

@Override

public void paintBackground(int x, int y, int width, int height) {}

@Override

public void toggleDrawingColor() {

toggleDrawingColor = !toggleDrawingColor;

}

}

标签:java,pdf,pdf-generation,barcode

来源: https://codeday.me/bug/20190723/1515677.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值