我成功地將條形碼使用PDFBox的和燒烤的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;
}
}
然而,這不是免費的:它需要iText的,將要求在商業許可我的情況。 – topchef
這是GPL3。除非你需要表揚,否則它不需要商業許可證。 –