Java com.itextpdf.text.pdf.PdfContentByte 代码实例

・25 分钟阅读

以下是展示如何使用com.itextpdf.text.pdf.PdfContentByte的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public void addWahlzettel(Document document,PdfWriter writer, HSSFSheet worksheet, int spaltenindex) throws Exception{
                BallotCard bc= readDataSet(worksheet, spaltenindex);
                IBallotCardImageCreator bcic= new BallotCardImageCreatorNewDesign(595*3 , 842*3 , bc);
                ImageIcon ic= bcic.createImage(Color.WHITE);
                //ic.setImage(ic.getImage().getScaledInstance(595,842,java.awt.Image.SCALE_DEFAULT ));
                PdfContentByte cb = writer.getDirectContent();
//              PdfTemplate tp = cb.createTemplate(400,400);
//        Graphics2D g2 = tp.createGraphics(400,400);
        // Create the graphics as shapes
        cb.saveState();
        float breite = document.getPageSize().getWidth();
        float hoehe = document.getPageSize().getHeight();
        Graphics2D g2 = cb.createGraphics(breite, hoehe);//  createGraphicsShapes(breite,hoehe);
        //Shape oldClip = g2.getClip();
        //g2.clipRect(0, 0, (int)breite, (int)hoehe);
        g2.scale(1.0 / 3, 1.0 / 3);
        g2.drawImage(ic.getImage(), 0,0, ic.getIconWidth(),ic.getIconHeight(),null);
       //Druckt eine Id auf jeden Wahlzettel um ihn zuordnen zu knnen!!!!
        g2.setFont(new Font("Sans Sarif", Font.PLAIN,12));
        g2.drawString(((spaltenindex-3)/2)+"", breite*3-150,(120));
        g2.dispose();
                cb.restoreState();
                document.newPage();
        }
 

实例 2


/**
 * Gets an instance of a Image from a java.awt.Image.
 * The image is added as a JPEG with a user defined quality.
 *
 * @param cb
 *            the <CODE>PdfContentByte</CODE> object to which the image will be added
 * @param awtImage
 *            the <CODE>java.awt.Image</CODE> to convert
 * @param quality
 *            a float value between 0 and 1
 * @return an object of type <CODE>PdfTemplate</CODE>
 * @throws BadElementException
 *             on error
 * @throws IOException
 */
public static Image getInstance(PdfContentByte cb, java.awt.Image awtImage, float quality) throws BadElementException, IOException {
    java.awt.image.PixelGrabber pg = new java.awt.image.PixelGrabber(awtImage,
            0, 0, -1, -1, true);
    try {
        pg.grabPixels();
    } catch (InterruptedException e) {
        throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels"));
    }
    if ((pg.getStatus() & java.awt.image.ImageObserver.ABORT) != 0) {
        throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.fetch.aborted.or.errored"));
    }
    int w = pg.getWidth();
    int h = pg.getHeight();
    PdfTemplate tp = cb.createTemplate(w, h);
    Graphics2D g2d = tp.createGraphics(w, h, true, quality);
    g2d.drawImage(awtImage, 0, 0, null);
    g2d.dispose();
    return getInstance(tp);
}
 

实例 3


private byte[] createPdfWithCornerText() throws Exception{
    final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    final Document document = new Document(PageSize.LETTER);
    PdfWriter writer = PdfWriter.getInstance(document, byteStream);
    document.open();
    PdfContentByte canvas = writer.getDirectContent();
    canvas.beginText();
    canvas.setFontAndSize(BaseFont.createFont(), 12);
    canvas.showTextAligned(PdfContentByte.ALIGN_LEFT, "Upper Left", 10, document.getPageSize().getHeight() - 10 - 12, 0);
    canvas.showTextAligned(PdfContentByte.ALIGN_RIGHT, "Upper Right", document.getPageSize().getWidth() - 10, document.getPageSize().getHeight() - 10 - 12, 0);
    canvas.showTextAligned(PdfContentByte.ALIGN_LEFT, "Lower Left", 10, 10, 0);
    canvas.showTextAligned(PdfContentByte.ALIGN_RIGHT, "Lower Right", document.getPageSize().getWidth() - 10, 10, 0);
    canvas.endText();
    document.close();
    final byte[] pdfBytes = byteStream.toByteArray();
    return pdfBytes;
}
 

实例 4


/**
 * Transfers the pdf content from the reader to the writer.
 */
private void transferPdfContent(final Document document, final PdfReader reader, final PdfWriter writer) {
        final float scale = (float) getConverterPreferenceController().getImageSize().intValue() / 100f;
        final int pageCount = reader.getNumberOfPages();
        PdfContentByte directContent = null;            
        for(int i = 0; i < pageCount; i++) {
                Rectangle pageSize = reader.getPageSizeWithRotation(i +1);
                pageSize.setTop(pageSize.getTop() * scale);
                pageSize.setRight(pageSize.getRight() * scale);
                document.setPageSize(pageSize);         
                if(i == 0) {
                        document.open();
                        directContent = writer.getDirectContent();
                } else {                                
                        document.newPage();
                }
                PdfImportedPage page = writer.getImportedPage(reader, i + 1);
                directContent.addTemplate(page, scale, 0, 0, scale, 0, 0);
        }
}
 

实例 5


/**
 * Draws a horizontal line.
 * @param canvas        the canvas to draw on
 * @param leftX         the left x coordinate
 * @param rightX        the right x coordindate
 * @param y                     the y coordinate
 */
public void drawLine(PdfContentByte canvas, float leftX, float rightX, float y) {
        float w;
    if (getPercentage() < 0)
        w = -getPercentage();
    else
        w = (rightX - leftX) * getPercentage() / 100.0f;
    float s;
    switch (getAlignment()) {
        case Element.ALIGN_LEFT:
            s = 0;
            break;
        case Element.ALIGN_RIGHT:
            s = rightX - leftX - w;
            break;
        default:
            s = (rightX - leftX - w) / 2;
            break;
    }
    canvas.setLineWidth(getLineWidth());
    if (getLineColor() != null)
        canvas.setColorStroke(getLineColor());
    canvas.moveTo(s + leftX, y + offset);
    canvas.lineTo(s + w + leftX, y + offset);
    canvas.stroke();
}
 

实例 6


/**
 * Adds the header and the footer.
 * 
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
 */
@Override
public void onEndPage(PdfWriter writer,Document document){
        if (writer.getPageNumber() == 1) return;
        if (isIndex()) {
        } else {
                PdfContentByte cb = writer.getDirectContent();
                cb.saveState();
                cb.setLineWidth(1);
                /** ----------------------HEADER-------------------- */
                cb.moveTo(MARGIN_LEFT, PageSize.A4.getHeight() - HEADER_HEIGHT - 2);
                cb.lineTo(PageSize.A4.getWidth() - MARGIN_RIGHT, PageSize.A4.getHeight() - HEADER_HEIGHT - 2);
                cb.stroke();
                //ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_CENTER, header,PageSize.A4.getWidth()/2,PageSize.A4.getHeight()-HEADER_HEIGHT, 0);
                /** ----------------------FOOTER-------------------- */
                cb.moveTo(MARGIN_LEFT, FOOTER_HEIGHT);
                cb.lineTo(PageSize.A4.getWidth() - MARGIN_RIGHT, FOOTER_HEIGHT);
                cb.stroke();
                footerImage.setAbsolutePosition((PageSize.A4.getWidth() - footerImage.getPlainWidth()) / 2, FOOTER_HEIGHT - footerImage.getPlainHeight() - 5);
                try {
                        cb.addImage(footerImage);
                } catch (DocumentException e) {
                        e.printStackTrace();
                }
                Phrase p = rcf.getPageNumberPhrase(pagenumber);
                ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT, p, PageSize.A4.getWidth() - MARGIN_RIGHT, FOOTER_HEIGHT - p.getFont().getSize() - 2, 0);
                cb.restoreState();
        }
        if (SHOW_AREA) {
                PdfContentByte under = writer.getDirectContentUnder();
                under.saveState();
                under.setRGBColorFill(0xFF, 0xD7, 0x00);
                under.rectangle(MARGIN_LEFT, MARGIN_DOWN, PageSize.A4.getWidth() - MARGIN_RIGHT - MARGIN_LEFT, PageSize.A4.getHeight() - MARGIN_UP - MARGIN_DOWN);
                under.fill();
                under.restoreState();
                under.saveState();
                under.setRGBColorFill(0x99, 0xcc, 0xff);
                under.rectangle(MARGIN_LEFT, PageSize.A4.getHeight() - HEADER_HEIGHT, PageSize.A4.getWidth() - MARGIN_RIGHT - MARGIN_LEFT, HEADER_HEIGHT);
                under.fill();
                under.restoreState();
                under.saveState();
                under.setRGBColorFill(0x99, 0xcc, 0xff);
                under.rectangle(MARGIN_LEFT, 0, PageSize.A4.getWidth() - MARGIN_RIGHT - MARGIN_LEFT, FOOTER_HEIGHT);
                under.fill();
                under.restoreState();
        }
}
 

实例 7


private static byte[] createPdfWithRotatedText(String text1, String text2, float rotation, boolean moveTextToNextLine, float moveTextDelta) throws Exception {
        final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        final Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, byteStream);
        document.setPageSize(PageSize.LETTER);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        BaseFont font = BaseFont.createFont();
        float x = document.getPageSize().getWidth()/2;
        float y = document.getPageSize().getHeight()/2;
        cb.transform(AffineTransform.getTranslateInstance(x, y));
        cb.moveTo(-10, 0);
        cb.lineTo(10, 0);
        cb.moveTo(0, -10);
        cb.lineTo(0, 10);
        cb.stroke();
        cb.beginText();
        cb.setFontAndSize(font, 12);
        cb.transform(AffineTransform.getRotateInstance(rotation/180f*Math.PI));
        cb.showText(text1);
        if (moveTextToNextLine)
            cb.moveText(0, moveTextDelta);
        else
            cb.transform(AffineTransform.getTranslateInstance(moveTextDelta, 0));
        cb.showText(text2);
        cb.endText();
        document.close();
        final byte[] pdfBytes = byteStream.toByteArray();
        return pdfBytes;
    }
 

实例 8


private void setStrokeDiff(Stroke newStroke, Stroke oldStroke) {
    PdfContentByte cb = _currentPage;
    if (newStroke == oldStroke)
        return;
    if (!(newStroke instanceof BasicStroke))
        return;
    BasicStroke nStroke = (BasicStroke) newStroke;
    boolean oldOk = (oldStroke instanceof BasicStroke);
    BasicStroke oStroke = null;
    if (oldOk)
        oStroke = (BasicStroke) oldStroke;
    if (!oldOk || nStroke.getLineWidth() != oStroke.getLineWidth())
        cb.setLineWidth(nStroke.getLineWidth());
    if (!oldOk || nStroke.getEndCap() != oStroke.getEndCap()) {
        switch (nStroke.getEndCap()) {
        case BasicStroke.CAP_BUTT:
            cb.setLineCap(0);
            break;
        case BasicStroke.CAP_SQUARE:
            cb.setLineCap(2);
            break;
        default:
            cb.setLineCap(1);
        }
    }
    if (!oldOk || nStroke.getLineJoin() != oStroke.getLineJoin()) {
        switch (nStroke.getLineJoin()) {
        case BasicStroke.JOIN_MITER:
            cb.setLineJoin(0);
            break;
        case BasicStroke.JOIN_BEVEL:
            cb.setLineJoin(2);
            break;
        default:
            cb.setLineJoin(1);
        }
    }
    if (!oldOk || nStroke.getMiterLimit() != oStroke.getMiterLimit())
        cb.setMiterLimit(nStroke.getMiterLimit());
    boolean makeDash;
    if (oldOk) {
        if (nStroke.getDashArray() != null) {
            if (nStroke.getDashPhase() != oStroke.getDashPhase()) {
                makeDash = true;
            } else if (!java.util.Arrays.equals(nStroke.getDashArray(), oStroke.getDashArray())) {
                makeDash = true;
            } else
                makeDash = false;
        } else if (oStroke.getDashArray() != null) {
            makeDash = true;
        } else
            makeDash = false;
    } else {
        makeDash = true;
    }
    if (makeDash) {
        float dash[] = nStroke.getDashArray();
        if (dash == null)
            cb.setLiteral("[]0 dn");
        else {
            cb.setLiteral('[');
            int lim = dash.length;
            for (int k = 0; k < lim; ++k) {
                cb.setLiteral(dash[k]);
                cb.setLiteral(' ');
            }
            cb.setLiteral(']');
            cb.setLiteral(nStroke.getDashPhase());
            cb.setLiteral(" dn");
        }
    }
}
 

实例 9


public void renderPDF(Item item, PDFTarget target, PreviewProperties properties) {
    Float x = item.getData(NodeItem.X);
    Float y = item.getData(NodeItem.Y);
    Float size = item.getData(NodeItem.SIZE);
    size /= 2f;
    Color color = item.getData(NodeItem.COLOR);
    Color borderColor = ((DependantColor) properties.getValue(PreviewProperty.NODE_BORDER_COLOR)).getColor(color);
    float borderSize = properties.getFloatValue(PreviewProperty.NODE_BORDER_WIDTH);
    float alpha = properties.getIntValue(PreviewProperty.NODE_OPACITY) / 100f;
    PdfContentByte cb = target.getContentByte();
    cb.setRGBColorStroke(borderColor.getRed(), borderColor.getGreen(), borderColor.getBlue());
    cb.setLineWidth(borderSize);
    cb.setRGBColorFill(color.getRed(), color.getGreen(), color.getBlue());
    if (alpha < 1f) {
        cb.saveState();
        PdfGState gState = new PdfGState();
        gState.setFillOpacity(alpha);
        gState.setStrokeOpacity(alpha);
        cb.setGState(gState);
    }
    cb.circle(x, -y, size);
    if (borderSize > 0) {
        cb.fillStroke();
    } else {
        cb.fill();
    }
    if (alpha < 1f) {
        cb.restoreState();
    }
}
 

实例 10


private void followPath(Shape s, int drawType) {
    PdfContentByte cb = _currentPage;
    if (s == null)
        return;
    if (drawType == STROKE) {
        if (!(_stroke instanceof BasicStroke)) {
            s = _stroke.createStrokedShape(s);
            followPath(s, FILL);
            return;
        }
    }
    if (drawType == STROKE) {
        setStrokeDiff(_stroke, _oldStroke);
        _oldStroke = _stroke;
        ensureStrokeColor();
    } else if (drawType == FILL) {
        ensureFillColor();
    }
    PathIterator points;
    if (drawType == CLIP) {
        points = s.getPathIterator(IDENTITY);
    } else {
        points = s.getPathIterator(_transform);
    }
    float[] coords = new float[6];
    int traces = 0;
    while (!points.isDone()) {
        ++traces;
        int segtype = points.currentSegment(coords);
        normalizeY(coords);
        switch (segtype) {
        case PathIterator.SEG_CLOSE:
            cb.closePath();
            break;
        case PathIterator.SEG_CUBICTO:
            cb.curveTo(coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]);
            break;
        case PathIterator.SEG_LINETO:
            cb.lineTo(coords[0], coords[1]);
            break;
        case PathIterator.SEG_MOVETO:
            cb.moveTo(coords[0], coords[1]);
            break;
        case PathIterator.SEG_QUADTO:
            cb.curveTo(coords[0], coords[1], coords[2], coords[3]);
            break;
        }
        points.next();
    }
    switch (drawType) {
    case FILL:
        if (traces > 0) {
            if (points.getWindingRule() == PathIterator.WIND_EVEN_ODD)
                cb.eoFill();
            else
                cb.fill();
        }
        break;
    case STROKE:
        if (traces > 0)
            cb.stroke();
        break;
    default: // drawType==CLIP
        if (traces == 0)
            cb.rectangle(0, 0, 0, 0);
        if (points.getWindingRule() == PathIterator.WIND_EVEN_ODD)
            cb.eoClip();
        else
            cb.clip();
        cb.newPath();
    }
}
 

实例 11


protected void addImage(java.awt.Image awtImage, String printName)
                throws DocumentException, IOException {
        if (! isFirst) {
                if (singleImage) {
                        document.newPage();
                } else {
                        document.add(new Paragraph("n"));
                        float vertPos = writer.getVerticalPosition(true);
                        PdfContentByte cb = writer.getDirectContent();
                        cb.setLineWidth(1f);
                        if (isLetter) {
                                cb.moveTo(PageSize.LETTER.getLeft(50), vertPos);
                                cb.lineTo(PageSize.LETTER.getRight(50), vertPos);
                        } else {
                                cb.moveTo(PageSize.A4.getLeft(50), vertPos);
                                cb.lineTo(PageSize.A4.getRight(50), vertPos);
                        }
                        cb.stroke();
                }
        }
        if (showName) {
                paragraph = new Paragraph(printName);
                paragraph.setAlignment(Element.ALIGN_CENTER);
                document.add(paragraph);
                //spcNm = 40;
        }
        if (showSize) {
                paragraph = new Paragraph(awtImage.getWidth(null)+" x "+ awtImage.getHeight(null));
                paragraph.setAlignment(Element.ALIGN_CENTER);
                document.add(paragraph);
                //spcSz = 40;
        }
        if (singleImage) {
                if (showName) spcNm = 40;
                if (showSize) spcSz = 40;
        }
        image = Image.getInstance(awtImage, null);
        //                              if (scaleToFit && (awtImage.getWidth(null) > 520) || (awtImage.getHeight(null) > 720))
        if (scaleToFit) {
                if (isLetter)
                        image.scaleToFit(PageSize.LETTER.getRight(50+spcNm+spcSz), PageSize.LETTER.getTop(50+spcNm+spcSz));
                else
                        image.scaleToFit(PageSize.A4.getRight(50+spcNm+spcSz), PageSize.A4.getTop(50+spcNm+spcSz));
        }
        image.setAlignment(Element.ALIGN_CENTER);
        document.add(image);
        isFirst = false;
}
 

实例 12


public void _prepareStyle(PdfContentByte cb, float x0, float y0, int k, BaseColor color, float h) {
        int style = k;
        while(style>6) style-=7;
        switch(style){
                case 0:
                        cb.setColorFill(color);
                        cb.circle(x0,y0,2);
                        cb.fill();
                        break;
                case 1:
                        cb.setColorFill(color);
                cb.moveTo(x0-2,y0-2);
                cb.lineTo(x0-2,y0+2);
                cb.lineTo(x0+2,y0+2);
                cb.lineTo(x0+2,y0-2);
                        cb.fill();
                        break;
                case 2:
                        cb.setColorFill(color);
                cb.moveTo(x0,y0-2);
                cb.lineTo(x0-2,y0);
                cb.lineTo(x0,y0+2);
                cb.lineTo(x0+2,y0);
                        cb.fill();
                        break;
                case 3:
                        cb.setColorFill(color);
                cb.moveTo(x0,y0+2);
                cb.lineTo(x0-2,y0-2);
                cb.lineTo(x0+2,y0-2);
                        cb.fill();
                        break;
                case 4:
                        cb.setColorFill(color);
                cb.moveTo(x0,y0+2);
                cb.lineTo(x0,y0-2);
                cb.fill();
                cb.moveTo(x0+2,y0);
                cb.lineTo(x0-2,y0);
                        cb.fill();
                        break;
                case 5:
                        cb.setColorFill(color);
                cb.moveTo(x0+2,y0+2);
                cb.lineTo(x0-2,y0-2);
                cb.fill();
                cb.moveTo(x0+2,y0-2);
                cb.lineTo(x0-2,y0+2);
                        cb.fill();
                        break;
                case 6:
                        cb.setColorFill(color);
                cb.moveTo(x0+2,y0+2);
                cb.lineTo(x0-2,y0-2);
                cb.fill();
                cb.moveTo(x0+2,y0-2);
                cb.lineTo(x0-2,y0+2);
                        cb.fill();
                cb.moveTo(x0,y0+2);
                cb.lineTo(x0,y0-2);
                cb.fill();
                        break;
        }
}
 
讨论
淘淘あ西西 profile image