用什么来生成包含动态生成的条形码(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;
    }

}
上一篇:php – 如何在Codeigniter中生成条形码图像?


下一篇:android – Mobile Vision API BarcodeDetector仅在屏幕*检测到