Example usage for com.itextpdf.text.pdf PdfContentByte getPdfWriter

List of usage examples for com.itextpdf.text.pdf PdfContentByte getPdfWriter

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfContentByte getPdfWriter.

Prototype

public PdfWriter getPdfWriter() 

Source Link

Document

Gets the PdfWriter in use by this object.

Usage

From source file:bouttime.report.bracketsheet.BracketSheetReport.java

License:Open Source License

public static boolean generateReport(Dao dao, List<Group> list, String outputFile, boolean doBoutNumbers,
        boolean doTimestamp) {

    if (list.isEmpty()) {
        return false;
    }//from w w w.  j a  v a2 s .  c  om

    // step 1: creation of a document-object
    Document document = new Document();

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile(outputFile);
        if (fos == null) {
            return false;
        }
        PdfWriter writer = PdfWriter.getInstance(document, fos);

        // step 3: we open the document
        document.open();

        // step 4: we grab the ContentByte and do some stuff with it
        PdfContentByte cb = writer.getDirectContent();

        String timestamp = "";
        if (doTimestamp) {
            timestamp = DateFormat.getInstance().format(new Date());
        }

        int rv;
        int i = 0;
        int size = list.size();
        for (Group g : list) {
            rv = addBracket(cb, dao, g, doBoutNumbers);
            if (rv != PAGE_ERROR) {
                // Print the watermark, if necessary
                boolean doWatermark = false;
                String gClass = g.getClassification();
                String wmValues = dao.getBracketsheetWatermarkValues();
                if ((wmValues != null) && !wmValues.isEmpty()) {
                    String[] tokens = wmValues.split(",");
                    for (String s : tokens) {
                        if (s.trim().equalsIgnoreCase(gClass)) {
                            doWatermark = true;
                            break;
                        }
                    }
                }

                int rotation = (rv == PAGE_ROUNDROBIN) ? 45 : 135;

                if (doWatermark) {
                    PdfContentByte ucb = writer.getDirectContentUnder();
                    BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
                    ucb.saveState();
                    ucb.setColorFill(BaseColor.LIGHT_GRAY);
                    ucb.beginText();
                    ucb.setFontAndSize(helv, 86);
                    ucb.showTextAligned(Element.ALIGN_CENTER, gClass, document.getPageSize().getWidth() / 2,
                            document.getPageSize().getHeight() / 2, rotation);
                    ucb.endText();
                    ucb.restoreState();
                }

                if (doTimestamp) {
                    rotation -= 45;
                    float width = cb.getPdfWriter().getPageSize().getWidth();
                    int x = (rv == PAGE_ROUNDROBIN) ? 15 : (int) (width - 15);
                    int y = 15;
                    BracketSheetUtil.drawTimestamp(cb, null, x, y, 10, timestamp, rotation);
                }

                // If not doing bout numbers, this is an 'award' type of
                // bracket.  So print an image/logo, if configured.
                if (!doBoutNumbers && (dao.getBracketsheetAwardImage() != null)
                        && !dao.getBracketsheetAwardImage().isEmpty()) {
                    Image image = Image.getInstance(Image.getInstance(dao.getBracketsheetAwardImage()));
                    image.setRotationDegrees((rv == PAGE_ROUNDROBIN) ? 0 : 90);
                    PositionOnPage positionOnPage = dao.getBracketsheetAwardImagePosition();
                    if (PositionOnPage.UPPER_RIGHT == positionOnPage) {
                        float x = (rv == PAGE_ROUNDROBIN)
                                ? document.getPageSize().getWidth() - 10 - image.getWidth()
                                : 10;
                        float y = document.getPageSize().getHeight() - 10 - image.getHeight();
                        image.setAbsolutePosition(x, y);
                        cb.addImage(image);
                    } else if (PositionOnPage.CENTER == positionOnPage) {
                        // put the image in the background, in the middle of the page
                        PdfContentByte ucb = writer.getDirectContentUnder();
                        float pageX = document.getPageSize().getWidth() / 2;
                        float pageY = document.getPageSize().getHeight() / 2;
                        float imageX = image.getWidth() / 2;
                        float imageY = image.getHeight() / 2;
                        image.setAbsolutePosition(pageX - imageX, pageY - imageY);
                        ucb.addImage(image);
                    }
                }

                if (++i < size) {
                    document.newPage();
                }
            }
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    } catch (IOException ioe) {
        logger.error("IO Exception", ioe);
        return false;
    }

    // step 5: we close the document
    document.close();

    return true;
}

From source file:com.automaster.autoview.server.servlet.TextStateOperators.java

/**
 * Creates a PDF document.// w  ww  . ja v a  2  s  . co m
 * @param filename the path to the new PDF document
 * @throws DocumentException 
 * @throws IOException
 */
public void createPdf(String filename) throws IOException, DocumentException {
    // step 1
    Rectangle rect = new Rectangle(595, 842);
    Document document = new Document(rect, 30, 30, 30, 30);
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    document.open();
    // step 4
    //PdfAcroForm canva = writer.getAcroForm();

    BaseFont bf = BaseFont.createFont();

    //canva.addMultiLineTextField("txtTeste", "texto de teste vamos ver se le quebra a linha", bf, 15, 300, 800, 100, 100);

    PdfContentByte canvas = writer.getDirectContent();
    String text = "AWAY again";
    String text1 = "TESTE Rua alameda luis de sousa santos, N 52, castanhal, CEP: 68742-783, ao lado do posto adriano";
    canvas.beginText();
    // line 1
    canvas.setFontAndSize(bf, 16);
    canvas.moveText(36, 800);
    canvas.moveTextWithLeading(0, -24);
    canvas.setTextRise(10);
    canvas.showText(text);
    // line 2
    canvas.setWordSpacing(20);
    canvas.newlineShowText(text);
    // line 3
    canvas.setCharacterSpacing(10);
    canvas.newlineShowText(text);
    canvas.setWordSpacing(0);
    canvas.setCharacterSpacing(0);
    // line 4
    canvas.setHorizontalScaling(50);
    canvas.newlineShowText(text);
    canvas.setHorizontalScaling(100);
    // line 5
    canvas.newlineShowText(text);
    canvas.setTextRise(15);
    canvas.setFontAndSize(bf, 12);
    canvas.setColorFill(BaseColor.RED);
    canvas.showText("2");
    canvas.setColorFill(GrayColor.GRAYBLACK);
    // line 6
    canvas.setLeading(56);
    canvas.setMiterLimit(5);
    canvas.newlineShowText(
            "Rua alameda luis de sousa santos, N 52, castanhal, CEP: 68742-783, ao lado do posto" + text);
    canvas.setLeading(24);
    canvas.newlineText();
    Paragraph paragraph = new Paragraph("teste");
    PdfWriter pdfWriter = canvas.getPdfWriter();
    PdfAcroForm pdfAcroForm = pdfWriter.getAcroForm();
    //pdfAcroForm.addMultiLineTextField("txtTeste", "Changing the adriano leading: Rua alameda luis de sousa santos, N 52, castanhal, CEP: 68742-783, ao lado do posto", bf, 12, 30, 650, 550, 750);
    //pdfAcroForm.addHiddenField("txtTeste", text); 
    PdfFormField pdfFormField = new PdfFormField(pdfWriter, 30, 650, 550, 750, null);
    pdfFormField.setFieldName("txtTeste");
    pdfFormField.setValueAsString(text1);
    //TextField textField = new TextField(canvas.getPdfWriter(), new Rectangle(30, 650, 550, 750), "txtTest");
    //textField.setText(text);
    pdfAcroForm.addFormField(pdfFormField);
    // line 7
    PdfTextArray array = new PdfTextArray("A");
    array.add(120);
    array.add("W");
    array.add(120);
    array.add("A");
    array.add(95);
    array.add("Y again");
    canvas.showText(array);
    canvas.endText();

    canvas.setColorFill(BaseColor.BLUE);
    canvas.beginText();
    canvas.setTextMatrix(360, 770);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();

    canvas.beginText();
    canvas.setTextMatrix(360, 730);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();

    canvas.beginText();
    canvas.setTextMatrix(360, 690);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();

    canvas.beginText();
    canvas.setTextMatrix(360, 650);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();

    PdfTemplate template = canvas.createTemplate(200, 36);
    template.setLineWidth(2);
    for (int i = 0; i < 6; i++) {
        template.moveTo(0, i * 6);
        template.lineTo(200, i * 6);
    }
    template.stroke();

    canvas.saveState();
    canvas.beginText();
    canvas.setTextMatrix(360, 610);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_CLIP);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();
    canvas.addTemplate(template, 360, 610);
    canvas.restoreState();

    canvas.saveState();
    canvas.beginText();
    canvas.setTextMatrix(360, 570);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE_CLIP);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();
    canvas.addTemplate(template, 360, 570);
    canvas.restoreState();

    canvas.saveState();
    canvas.beginText();
    canvas.setTextMatrix(360, 530);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE_CLIP);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();
    canvas.addTemplate(template, 360, 530);
    canvas.restoreState();

    canvas.saveState();
    canvas.beginText();
    canvas.setTextMatrix(360, 490);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_CLIP);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();
    canvas.addTemplate(template, 360, 490);
    canvas.restoreState();

    // step 5
    //document.add((Element) pdfAcroForm);
    document.close();
}

From source file:com.vectorprint.report.itext.debug.DebugHelper.java

License:Open Source License

public static void debugBackground(PdfContentByte canvas, Rectangle rect, BaseColor color, String prefix,
        EnhancedMap settings, LayerManager layerAware) {
    canvas = canvas.getPdfWriter().getDirectContentUnder();
    int rgb = color.getRed() + color.getBlue() + color.getGreen();
    rect.setBackgroundColor(color);//from  www . jav  a 2s  .  c  o  m
    canvas.rectangle(rect);
    layerAware.startLayerInGroup(DEBUG, canvas);
    debugFont(canvas, settings);
    BaseColor txtColor = (rgb < 150) ? color.brighter().brighter() : color.darker().darker();
    canvas.setColorFill(txtColor);
    canvas.setColorStroke(txtColor);
    canvas.beginText();
    canvas.showTextAligned(Element.ALIGN_LEFT, prefix + color.toString().replace(Color.class.getName(), ""),
            rect.getLeft() + rect.getWidth() / 2, rect.getTop() - rect.getHeight() / 2, 0);
    canvas.endText();
    canvas.endLayer();
}

From source file:com.vectorprint.report.itext.DefaultElementProducer.java

License:Open Source License

@Override
public PdfLayer startLayerInGroup(String groupId, PdfContentByte canvas) {
    PdfLayer pl;/*from   ww  w.  ja va2 s.  c om*/
    try {
        pl = new PdfLayer(groupId + CHILD_LAYERSUFFIX, canvas.getPdfWriter());
    } catch (IOException ex) {
        throw new VectorPrintRuntimeException(ex);
    }
    initLayerGroup(groupId, canvas).addChild(pl);
    canvas.beginLayer(pl);
    return pl;
}

From source file:com.vectorprint.report.itext.DefaultElementProducer.java

License:Open Source License

@Override
public PdfLayer initLayerGroup(String layerId, PdfContentByte canvas) {
    if (!layerGroups.containsKey(layerId)) {
        PdfLayer parent;//from  w  ww .j  a v a 2s.c  om
        try {
            parent = new PdfLayer(layerId, canvas.getPdfWriter());
        } catch (IOException ex) {
            throw new VectorPrintRuntimeException(ex);
        }
        layerGroups.put(layerId, parent);
        canvas.beginLayer(parent);
        canvas.endLayer();
    }
    return layerGroups.get(layerId);
}

From source file:mkl.testarea.itext5.pdfcleanup.PdfCleanUpContentOperator.java

License:Open Source License

public void invoke(PdfContentStreamProcessor pdfContentStreamProcessor, PdfLiteral operator,
        ArrayList<PdfObject> operands) throws Exception {
    String operatorStr = operator.toString();
    PdfContentByte canvas = cleanUpStrategy.getContext().getCanvas();
    PRStream xFormStream = null;//from   www .java  2 s. c  o m
    boolean disableOutput = pathConstructionOperators.contains(operatorStr)
            || pathPaintingOperators.contains(operatorStr) || clippingPathOperators.contains(operatorStr);
    GraphicsState gs = pdfContentStreamProcessor.gs();

    // key - number of a string in the TJ operator, value - number following the string; the first number without string (if it's presented) is stored under 0.
    // BE AWARE: zero-length strings are ignored!!!
    Map<Integer, Float> structuredTJoperands = null;

    if ("Do".equals(operatorStr)) {
        if (operands.size() == 2 && operands.get(0).isName()) {
            PdfDictionary xObjResources = cleanUpStrategy.getContext().getResources()
                    .getAsDict(PdfName.XOBJECT);

            if (xObjResources != null) {
                PdfStream xObj = xObjResources.getAsStream((PdfName) operands.get(0));

                if (xObj instanceof PRStream && xObj.getAsName(PdfName.SUBTYPE) != null
                        && xObj.getAsName(PdfName.SUBTYPE).compareTo(PdfName.FORM) == 0) {
                    xFormStream = (PRStream) xObj;
                    cleanUpStrategy.registerNewContext(xObj.getAsDict(PdfName.RESOURCES), null);
                }
            }
        }
    }

    originalContentOperator.invoke(pdfContentStreamProcessor, operator, operands);
    List<PdfCleanUpContentChunk> chunks = cleanUpStrategy.getChunks();

    if (xFormStream != null) {
        xFormStream.setData(cleanUpStrategy.getContext().getCanvas()
                .toPdf(cleanUpStrategy.getContext().getCanvas().getPdfWriter()));
        cleanUpStrategy.popContext();
        canvas = cleanUpStrategy.getContext().getCanvas();
    }

    if ("Do".equals(operatorStr)) {
        if (chunks.size() > 0 && chunks.get(0) instanceof PdfCleanUpContentChunk.Image) {
            PdfCleanUpContentChunk.Image chunk = (PdfCleanUpContentChunk.Image) chunks.get(0);

            if (chunk.isVisible()) {
                PdfDictionary xObjResources = cleanUpStrategy.getContext().getResources()
                        .getAsDict(PdfName.XOBJECT);
                PRStream imageStream = (PRStream) xObjResources.getAsStream((PdfName) operands.get(0));
                updateImageStream(imageStream, chunk.getNewImageData());
            } else {
                disableOutput = true;
            }
        }
    } else if (lineStyleOperators.contains(operatorStr)) {
        disableOutput = true;
    } else if (textShowingOperators.contains(operatorStr)
            && !allChunksAreVisible(cleanUpStrategy.getChunks())) {
        disableOutput = true;

        if ("'".equals(operatorStr)) {
            canvas.getInternalBuffer().append(TStar);
        } else if ("\"".equals(operatorStr)) {
            operands.get(0).toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());
            canvas.getInternalBuffer().append(Tw);

            operands.get(1).toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());
            canvas.getInternalBuffer().append(TcTStar);
        } else if ("TJ".equals(operatorStr)) {
            structuredTJoperands = structureTJarray((PdfArray) operands.get(0));
        }

        writeTextChunks(structuredTJoperands, chunks, canvas, gs.getCharacterSpacing(), gs.getWordSpacing(),
                gs.getFontSize(), gs.getHorizontalScaling());
    } else if (pathPaintingOperators.contains(operatorStr)) {
        writePath(operatorStr, canvas, gs.getColorSpaceStroke());
    } else if (strokeColorOperators.contains(operatorStr)) {
        // Replace current color with the new one.
        cleanUpStrategy.getContext().popStrokeColor();
        cleanUpStrategy.getContext().pushStrokeColor(operands);
    } else if ("q".equals(operatorStr)) {
        cleanUpStrategy.getContext().pushStrokeColor(cleanUpStrategy.getContext().peekStrokeColor());
    } else if ("Q".equals(operatorStr)) {
        cleanUpStrategy.getContext().popStrokeColor();
    }

    if (!disableOutput) {
        writeOperands(canvas, operands);
    }

    cleanUpStrategy.clearChunks();
}

From source file:mkl.testarea.itext5.pdfcleanup.PdfCleanUpContentOperator.java

License:Open Source License

private void writeOperands(PdfContentByte canvas, List<PdfObject> operands) throws IOException {
    int index = 0;

    for (PdfObject o : operands) {
        toPdf(o, canvas.getPdfWriter(), canvas.getInternalBuffer());
        canvas.getInternalBuffer().append(operands.size() > ++index ? (byte) ' ' : (byte) '\n');
    }/*w  w  w . j a  v a  2s.  c  om*/
}

From source file:mkl.testarea.itext5.pdfcleanup.PdfCleanUpContentOperator.java

License:Open Source License

/**
 * Renders parts of text which are visible.
 *//*www  .  ja  v a 2s.  c o  m*/
private void writeTextChunks(Map<Integer, Float> structuredTJoperands, List<PdfCleanUpContentChunk> chunks,
        PdfContentByte canvas, float characterSpacing, float wordSpacing, float fontSize,
        float horizontalScaling) throws IOException {
    canvas.setCharacterSpacing(0);
    canvas.setWordSpacing(0);
    canvas.getInternalBuffer().append((byte) '[');

    float convertedCharacterSpacing = -characterSpacing * 1000f / fontSize;
    float convertedWordSpacing = -wordSpacing * 1000f / fontSize;

    float shift = structuredTJoperands != null ? structuredTJoperands.get(0) : 0;
    PdfCleanUpContentChunk.Text prevChunk = null;

    for (PdfCleanUpContentChunk chunk : chunks) {
        PdfCleanUpContentChunk.Text textChunk = (PdfCleanUpContentChunk.Text) chunk;

        if (prevChunk != null && prevChunk.getNumOfStrTextBelongsTo() != textChunk.getNumOfStrTextBelongsTo()
                && structuredTJoperands != null) {
            shift += structuredTJoperands.get(prevChunk.getNumOfStrTextBelongsTo());
        }

        if (textChunk.isVisible()) {
            if (Float.compare(shift, 0.0f) != 0 && Float.compare(shift, -0.0f) != 0) {
                canvas.getInternalBuffer().append(shift).append(' ');
            }

            textChunk.getText().toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());
            canvas.getInternalBuffer().append(' ');

            shift = convertedCharacterSpacing + (isSpace(textChunk) ? convertedWordSpacing : 0);
        } else {
            shift += getUnscaledTextChunkWidth(textChunk, characterSpacing, wordSpacing, fontSize,
                    horizontalScaling);
        }

        prevChunk = textChunk;
    }

    if (Float.compare(shift, 0.0f) != 0 && Float.compare(shift, -0.0f) != 0) {
        canvas.getInternalBuffer().append(shift);
    }

    canvas.getInternalBuffer().append(TJ);

    if (Float.compare(characterSpacing, 0.0f) != 0 && Float.compare(characterSpacing, -0.0f) != 0) {
        new PdfNumber(characterSpacing).toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());
        canvas.getInternalBuffer().append(Tc);
    }

    if (Float.compare(wordSpacing, 0.0f) != 0 && Float.compare(wordSpacing, -0.0f) != 0) {
        new PdfNumber(wordSpacing).toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());
        canvas.getInternalBuffer().append(Tw);
    }
}

From source file:mkl.testarea.itext5.pdfcleanup.PdfCleanUpContentOperator.java

License:Open Source License

private void writeMoveTo(Point2D destinationPoint, PdfContentByte canvas) throws IOException {
    new PdfNumber(destinationPoint.getX()).toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());
    canvas.getInternalBuffer().append(' ');
    new PdfNumber(destinationPoint.getY()).toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());
    canvas.getInternalBuffer().append(m);
}

From source file:mkl.testarea.itext5.pdfcleanup.PdfCleanUpContentOperator.java

License:Open Source License

private void writeBezierCurve(BezierCurve curve, PdfContentByte canvas) throws IOException {
    List<Point2D> basePoints = curve.getBasePoints();
    Point2D p2 = basePoints.get(1);
    Point2D p3 = basePoints.get(2);
    Point2D p4 = basePoints.get(3);

    new PdfNumber(p2.getX()).toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());
    canvas.getInternalBuffer().append(' ');

    new PdfNumber(p2.getY()).toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());
    canvas.getInternalBuffer().append(' ');

    new PdfNumber(p3.getX()).toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());
    canvas.getInternalBuffer().append(' ');

    new PdfNumber(p3.getY()).toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());
    canvas.getInternalBuffer().append(' ');

    new PdfNumber(p4.getX()).toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());
    canvas.getInternalBuffer().append(' ');

    new PdfNumber(p4.getY()).toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer());
    canvas.getInternalBuffer().append(c);
}