Example usage for com.lowagie.text.pdf PdfContentByte moveTo

List of usage examples for com.lowagie.text.pdf PdfContentByte moveTo

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfContentByte moveTo.

Prototype


public void moveTo(float x, float y) 

Source Link

Document

Move the current point (x, y), omitting any connecting line segment.

Usage

From source file:com.estate.pdf.Page.java

protected void drawSpacingGrid(Rectangle rct, float spacing, Color color) {
    PdfContentByte cb = writer.getDirectContentUnder();

    cb.setLineWidth(.25f);// ww  w . j ava  2  s . c  o  m
    cb.setColorStroke(color);
    for (float x = 0; x < rct.getRight(); x += spacing) {
        cb.moveTo(x, 0);
        cb.lineTo(x, rct.getTop());
    }

    for (float y = 0; y < rct.getTop(); y += spacing) {
        cb.moveTo(0, y);
        cb.lineTo(rct.getRight(), y);
    }

    cb.stroke();

}

From source file:com.estate.pdf.PageBorder.java

public void draw(Document doc, int iconNum, String pageNum, String toolName) {
    try {/*from   w w w . j  av a 2  s.c  o  m*/
        PdfContentByte cb = writer.getDirectContentUnder();
        BaseFont fontBold = BaseFont.createFont(Locations.getFontLocation() + "timesbd.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);
        BaseFont font = BaseFont.createFont(Locations.getFontLocation() + "times.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);
        Rectangle rct = new Rectangle(doc.getPageSize());
        float iconBase = (1.25f * 72); // This is the base of the icons on
        // the page
        Image icon = Image.getInstance(Locations.getImageLocation() + icons[iconNum]);
        // Image box = Image.getInstance(Locations.ImageLocation() +
        // "blueBOX.png");
        icon.scalePercent(23);
        float scale = .23f;
        float iconLeft = (icon.getWidth() / 2) * scale;
        float boxSize = (.1875f * 72);

        // Adjust the top
        rct.setTop(rct.getTop() - (.5f * 72));

        // Place the Icon
        icon.setAbsolutePosition((1.25f * 72) - iconLeft, rct.getTop() - iconBase);
        doc.add(icon);

        // Set our line color
        cb.setRGBColorStroke(0, 72, 117);

        cb.setLineWidth(.75f);

        // do the bottom line
        cb.moveTo(1.25f * 72, (.5f * 72));
        cb.lineTo(rct.getRight() - (.5f * 72), (.5f * 72));

        cb.moveTo(1.25f * 72, (.5f * 72));
        cb.lineTo(1.25f * 72, rct.getTop());

        // stroke the lines
        cb.stroke();

        // Do the lower left box
        cb.rectangle((1.25f - 0.09375f) * 72, (.5f - 0.09375f) * 72, boxSize, boxSize);
        cb.setRGBColorFill(0, 72, 117);
        cb.closePathFillStroke();

        // Do the lower right box
        Rectangle pnRect = new Rectangle(0, 0);
        pnRect.setLeft(rct.getRight() - ((.5f + 0.09375f) * 72));
        pnRect.setTop((.5f - 0.09375f) * 72);
        pnRect.setRight(pnRect.getLeft() + boxSize);
        pnRect.setBottom(pnRect.getTop() - boxSize);

        // cb.rectangle(rct.getRight() - ((.5f + 0.09375f) * 72), (.5f -
        // 0.09375f) * 72, (.1875f * 72), (.1875f * 72));
        cb.rectangle(pnRect.getLeft(), pnRect.getTop(), boxSize, boxSize);
        cb.setRGBColorFill(0, 72, 117);
        cb.closePathFillStroke();

        // Now we do the page number if one is supplied.
        if (pageNum.length() > 0) {
            float pnHeight = fontBold.getAscentPoint(pageNum, 9) - fontBold.getDescentPoint(pageNum, 9);
            float pnWidth = fontBold.getWidthPoint(pageNum, 9);

            float l = pnRect.getLeft() + ((boxSize - pnWidth) / 2);
            float b = pnRect.getTop() + ((boxSize - pnHeight) / 2);

            cb.beginText();
            cb.setFontAndSize(fontBold, 9);
            cb.setRGBColorFill(255, 255, 255);
            cb.setTextMatrix(l, b);
            cb.showText(pageNum);
            cb.endText();

        }

        // Display the copyright
        SimpleDateFormat df = new SimpleDateFormat("yyyy");
        char cs = 0x00a9; // Unicode for the copyright symbol
        String copyRight = com.estate.constants.StringConstants.copyRight + cs + " " + df.format(new Date());
        float crWidth;
        float crLeft;

        crWidth = font.getWidthPoint(copyRight, 8);
        cb.beginText();

        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(0, 0, 0);

        crLeft = (doc.getPageSize().getRight() - crWidth) / 2;
        cb.setTextMatrix(crLeft, .375f * 72); // Place the base of the
        // copyright at 3/8" up from
        // the bottom
        cb.showText(copyRight);
        cb.endText();

        if (toolName.length() > 0) {
            cb.beginText();

            cb.setFontAndSize(font, 8);
            cb.setRGBColorFill(0, 0, 0);

            cb.setTextMatrix((1.25f * 72) + boxSize, .375f * 72);
            cb.showText(toolName);
            cb.endText();
        }

        // Fix a licensee at left
        cb.beginText();
        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(0, 0, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, " Licensee: " + getLicense(), (10.2f * 72), .375f * 72,
                0);
        cb.endText();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.qcadoo.report.api.pdf.PdfPageNumbering.java

License:Open Source License

private void buildFooter(final PdfWriter writer, final Document document) {
    PdfContentByte cb = writer.getDirectContent();

    cb.saveState();/*from w  w  w  .  jav  a2  s. com*/

    String text = footer.getPage() + " " + writer.getPageNumber() + " " + footer.getIn() + " ";

    float textBase = document.bottom() - 25;
    float textSize = FontUtils.getDejavu().getWidthPoint(text, 7);

    cb.setColorFill(ColorUtils.getLightColor());
    cb.setColorStroke(ColorUtils.getLightColor());
    cb.setLineWidth(1);
    cb.setLineDash(2, 2, 1);
    cb.moveTo(document.left(), document.bottom() - 10);
    cb.lineTo(document.right(), document.bottom() - 10);
    cb.stroke();
    cb.beginText();
    cb.setFontAndSize(FontUtils.getDejavu(), 7);

    float adjust = FontUtils.getDejavu().getWidthPoint("0", 7);

    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);

    textSize = FontUtils.getDejavu().getWidthPoint(footer.getGeneratedBy(), 7);

    cb.setTextMatrix(document.right() - textSize, textBase - 10);
    cb.showText(footer.getGeneratedBy());

    textSize = FontUtils.getDejavu().getWidthPoint(generationDate, 7);

    cb.setTextMatrix(document.right() - textSize, textBase - 20);
    cb.showText(generationDate);
    cb.endText();

    try {
        textSize = FontUtils.getDejavu().getWidthPoint(footer.getAdditionalText(), 7);

        ColumnText ct = new ColumnText(cb);

        ct.setSimpleColumn(new Phrase(footer.getAdditionalText(), FontUtils.getDejavuRegular7Light()),
                document.left() + 240, textBase + 10, document.left() + 390, textBase - 25, 10,
                Element.ALIGN_LEFT);
        ct.go();
    } catch (DocumentException e) {
        LOG.warn("Problem with additional text generation in report footer.");
    }

    try {
        ColumnText ct = new ColumnText(cb);

        ct.setSimpleColumn(document.left(), textBase + 10, document.left() + 230, textBase - 25, 10,
                Element.ALIGN_LEFT);
        ct.addText(new Phrase(footer.getCompanyName() + "\n", FontUtils.getDejavuRegular7Light()));

        if (!"".equals(footer.getAddress())) {
            ct.addText(new Phrase(footer.getAddress() + "\n", FontUtils.getDejavuRegular7Light()));
        }
        if (!"".equals(footer.getPhoneEmail())) {
            ct.addText(new Phrase(footer.getPhoneEmail(), FontUtils.getDejavuRegular7Light()));
        }

        ct.go();
    } catch (DocumentException e) {
        LOG.warn("Problem with company text generation in report footer.");
    }

    cb.addTemplate(total, document.right() - adjust, textBase);
    cb.restoreState();

}

From source file:com.qcadoo.report.api.pdf.PdfPageNumbering.java

License:Open Source License

private void buildHeader(final PdfWriter writer, final Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();/*  w  w w. j a  v a 2s .com*/
    String text = footer.getPage() + " " + writer.getPageNumber() + " " + footer.getIn() + " ";

    float textBase = document.top() + 22;
    float textSize = FontUtils.getDejavu().getWidthPoint(text, 7);

    cb.setColorFill(ColorUtils.getLightColor());
    cb.setColorStroke(ColorUtils.getLightColor());
    cb.beginText();
    cb.setFontAndSize(FontUtils.getDejavu(), 7);

    float adjust = FontUtils.getDejavu().getWidthPoint("0", 7);

    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(total, document.right() - adjust, textBase);
    cb.setLineWidth(1);
    cb.setLineDash(2, 2, 1);
    cb.moveTo(document.left(), document.top() + 12);
    cb.lineTo(document.right(), document.top() + 12);
    cb.stroke();
    cb.restoreState();

}

From source file:com.t2.compassionMeditation.ViewSessionsActivity.java

License:Open Source License

/**
 * Create a PDF file based on the contents of the graph
 */// w w w.  jav  a2  s.c om
void CreatePdf() {

    // Run the export on a separate thread.
    new Thread(new Runnable() {
        @Override
        public void run() {

            Document document = new Document();
            try {
                Date calendar = Calendar.getInstance().getTime();
                mResultsFileName = "BioZenResults_";
                mResultsFileName += (calendar.getYear() + 1900) + "-" + (calendar.getMonth() + 1) + "-"
                        + calendar.getDate() + "_";
                mResultsFileName += calendar.getHours() + "-" + calendar.getMinutes() + "-"
                        + calendar.getSeconds() + ".pdf";

                PdfWriter writer = PdfWriter.getInstance(document,
                        new FileOutputStream(android.os.Environment.getExternalStorageDirectory()
                                + java.io.File.separator + mResultsFileName));
                document.open();
                PdfContentByte contentByte = writer.getDirectContent();
                BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252,
                        BaseFont.NOT_EMBEDDED);
                // Note top of PDF = 900
                float chartWidth = 332;
                float chartHeight = 45;

                float spaceHeight = chartHeight + 30;
                int horizontalPos = 180;
                float verticalPos = 780;

                // Write document header
                contentByte.beginText();
                contentByte.setFontAndSize(baseFont, 20);
                contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "T2 BioZen Report", 300, 800, 0);
                contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER,
                        "Generated on: " + calendar.toLocaleString(), 300, 770, 0);
                contentByte.endText();

                contentByte.setLineWidth(1f);
                verticalPos -= spaceHeight;
                long startTime = startCal.getTimeInMillis();
                long endTime = endCal.getTimeInMillis();

                float maxChartValue = 0;
                float chartYAvg;

                BioSession tmpSession = sessionItems.get(0);
                int maxKeys = tmpSession.keyItemNames.length;

                // Loop through all of the the keys
                for (int key = 0; key < maxKeys; key++) {

                    //Draw a border rect
                    contentByte.setRGBColorStrokeF(0, 0, 0);
                    contentByte.setLineWidth(1f);
                    contentByte.rectangle(horizontalPos, verticalPos, chartWidth, chartHeight);
                    contentByte.stroke();

                    // Write band name
                    contentByte.beginText();
                    contentByte.setFontAndSize(baseFont, 12);
                    BioSession tmpSession1 = sessionItems.get(0);
                    contentByte.showTextAligned(PdfContentByte.ALIGN_RIGHT, tmpSession1.keyItemNames[key], 170,
                            (verticalPos + (chartHeight / 2)) - 5, 0);
                    contentByte.endText();

                    maxChartValue = 0;
                    // First find the max Y
                    for (BioSession session : sessionItems) {
                        if (session.time >= startTime && session.time <= endTime) {
                            chartYAvg = session.avgFilteredValue[key];
                            if (chartYAvg > maxChartValue)
                                maxChartValue = chartYAvg;
                        }
                    }

                    float lastY = -1;
                    float xIncrement = 0;
                    if (sessionItems.size() > 0) {
                        xIncrement = chartWidth / sessionItems.size();
                    }

                    float yIncrement = 0;
                    if (maxChartValue > 0) {
                        yIncrement = chartHeight / maxChartValue;
                    }

                    float highValue = 0;
                    int highTime = 0;
                    float highY = 0;
                    float highX = 0;
                    int lowTime = 0;
                    float lowY = 100;
                    float lowX = chartWidth;
                    float lowValue = maxChartValue;

                    int lCount = 0;
                    String keyName = "";

                    ArrayList<RegressionItem> ritems = new ArrayList<RegressionItem>();

                    // Loop through the session points of this key
                    String rawYValues = "";
                    for (BioSession session : sessionItems) {
                        keyName = session.keyItemNames[key];
                        if (session.time >= startTime && session.time <= endTime) {
                            chartYAvg = session.avgFilteredValue[key];
                            rawYValues += chartYAvg + ", ";
                            if (lastY < 0)
                                lastY = (float) chartYAvg;

                            contentByte.setLineWidth(3f);
                            contentByte.setRGBColorStrokeF(255, 0, 0);

                            float graphXFrom = horizontalPos + (lCount * xIncrement);
                            float graphYFrom = verticalPos + (lastY * yIncrement);
                            float graphXTo = (horizontalPos + ((lCount + 1) * xIncrement));
                            float graphYTo = verticalPos + (chartYAvg * yIncrement);
                            //                     Log.e(TAG, "[" + graphXFrom + ", " + graphYFrom + "] to [" + graphXTo + ", " + graphYTo + "]");
                            // Draw the actual graph
                            contentByte.moveTo(graphXFrom, graphYFrom);
                            contentByte.lineTo(graphXTo, graphYTo);
                            contentByte.stroke();

                            //Add regression Item
                            ritems.add(new RegressionItem(lCount, (chartYAvg * yIncrement)));

                            if (chartYAvg > highValue) {
                                highValue = chartYAvg;
                                highY = graphYTo;
                                highX = graphXTo;
                                highTime = (int) (session.time / 1000);
                            }

                            if (chartYAvg < lowValue) {
                                lowValue = chartYAvg;
                                lowY = graphYTo;
                                lowX = graphXTo;
                                lowTime = (int) (session.time / 1000);
                            }

                            lCount++;
                            lastY = (float) chartYAvg;

                        } // End if (session.time >= startTime && session.time <= endTime )
                    } // End for (BioSession session : sessionItems)            

                    //Draw high low dates
                    if (highY != 0 && lowY != 0) {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
                        String hDate = dateFormat.format(new Date((long) highTime * 1000L));
                        String lDate = dateFormat.format(new Date((long) lowTime * 1000L));
                        contentByte.beginText();
                        contentByte.setFontAndSize(baseFont, 8);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, hDate, highX, highY, 0);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, lDate, lowX, lowY, 0);
                        contentByte.endText();
                    }

                    //Draw Regression Line
                    RegressionResult regression = calculateRegression(ritems);
                    contentByte.saveState();
                    contentByte.setRGBColorStrokeF(0, 0, 250);
                    contentByte.setLineDash(3, 3, 0);
                    contentByte.moveTo(horizontalPos, verticalPos + (float) regression.intercept);
                    contentByte.lineTo(horizontalPos + chartWidth, (float) ((verticalPos + regression.intercept)
                            + (float) (regression.slope * (chartWidth / xIncrement))));
                    contentByte.stroke();
                    contentByte.restoreState();
                    contentByte.setRGBColorStrokeF(0, 0, 0);

                    //               Log.e(TAG, keyName + ": [" + rawYValues + "]");
                    // Get ready for the next key (and series of database points )
                    verticalPos -= spaceHeight;

                    if (verticalPos < 30) {
                        document.newPage();
                        verticalPos = 780 - spaceHeight;
                    }

                } // End for (int key = 0; key < maxKeys; key++)

                //document.add(new Paragraph("You can also write stuff directly tot he document like this!"));
            } catch (DocumentException de) {
                System.err.println(de.getMessage());
                Log.e(TAG, de.toString());
            } catch (IOException ioe) {
                System.err.println(ioe.getMessage());
                Log.e(TAG, ioe.toString());
            } catch (Exception e) {
                System.err.println(e.getMessage());
                Log.e(TAG, e.toString());
            }

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

        }
    }).start();

}

From source file:is.idega.idegaweb.egov.printing.business.DocumentBusinessBean.java

License:Open Source License

public void createCommuneFooter(PdfWriter writer) throws Exception {

    PdfContentByte cb = writer.getDirectContent();
    Font nameFont = getDefaultParagraphFont();
    nameFont.setSize(9);/*w  w w .  j  a v a  2s .  c o  m*/
    Font textFont = getDefaultTextFont();
    textFont.setSize(9);

    PdfPTable table = new PdfPTable(4);
    table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
    table.getDefaultCell().setNoWrap(true);

    IWBundle iwb = getIWApplicationContext().getIWMainApplication()
            .getBundle(is.idega.idegaweb.egov.message.business.MessageConstants.IW_BUNDLE_IDENTIFIER);

    table.addCell(new Phrase(iwb.getProperty("commune.name_mailaddr", "Mailaddress"), nameFont));
    table.addCell(new Phrase(iwb.getProperty("commune.name_visitaddr", "Visitaddress"), nameFont));
    table.addCell(new Phrase(iwb.getProperty("commune.name_contact", "Contact"), nameFont));
    table.addCell(new Phrase(iwb.getProperty("commune.name_org_nr", "Organizationsnr"), nameFont));

    table.addCell(new Phrase(iwb.getProperty("commune.mail_name", "Mail name"), getTextFont()));
    table.addCell(new Phrase(iwb.getProperty("commune.visit_name", "Visit name"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.website", "www.some-place.com"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.org_number", "XXXXXX-XXXX"), textFont));

    table.addCell(new Phrase(iwb.getProperty("commune.mail_zip", "Zip code"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.visit_streetaddr", "Street and number,"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.support_email", "email@someplace.com"), textFont));
    table.addCell(new Phrase(" ", textFont));

    table.addCell(new Phrase(" ", textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.visit_zip", "Visit zip"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.office_phone", "office phone"), textFont));
    table.addCell(new Phrase(" ", textFont));

    int distFromBottomMM = 30;
    int[] widths = { 20, 20, 30, 20 };
    table.setWidths(widths);
    table.setTotalWidth(getPointsFromMM(210 - 25 - 20));
    table.writeSelectedRows(0, -1, getPointsFromMM(25), getPointsFromMM(distFromBottomMM), cb);

    PdfContentByte linebyte = new PdfContentByte(writer);
    // we add some crosses to visualize the destinations

    linebyte.moveTo(getPointsFromMM(25), getPointsFromMM(distFromBottomMM + 2));
    linebyte.lineTo(getPointsFromMM(210 - 25), getPointsFromMM(distFromBottomMM + 2));

    linebyte.stroke();

    // we add the template on different positions
    cb.add(linebyte);
}

From source file:jm.web.Addons.java

License:GNU General Public License

public static void setEncabezado(PdfWriter writer, Document document, String texto) {
    if (writer.getPageNumber() > 1) {
        try {//from  w  w  w . j  a  v  a  2s.  c o  m
            PdfPTable encabezado = new PdfPTable(1);
            encabezado.setTotalWidth(document.right() - document.left() - 120);
            encabezado.addCell(Addons.setCeldaPDF(texto, Font.HELVETICA, 9, Font.BOLD, Element.ALIGN_LEFT, 0));
            encabezado.writeSelectedRows(0, -1, 60, document.top() + 25, writer.getDirectContent());

            PdfContentByte cb = writer.getDirectContent();
            cb.setLineWidth(2);
            cb.moveTo(60, document.top() + 10);
            cb.lineTo(document.right() - document.left() - 58, document.top() + 10);
        } catch (Exception e) {
            throw new ExceptionConverter(e);
        }
    }
}

From source file:org.eclipse.birt.report.engine.emitter.pdf.PDFPage.java

License:Open Source License

/**
 * Draws a line with the line-style specified in advance from the start
 * position to the end position with the given linewidth, color, and style
 * at the given pdf layer. If the line-style is NOT set before invoking this
 * method, "solid" will be used as the default line-style.
 *
 * @param startX//from  www  . ja  v  a 2  s . c  o m
 *            the start X coordinate of the line
 * @param startY
 *            the start Y coordinate of the line
 * @param endX
 *            the end X coordinate of the line
 * @param endY
 *            the end Y coordinate of the line
 * @param width
 *            the lineWidth
 * @param color
 *            the color of the line
 * @param contentByte
 *            the given pdf layer
 */
private void drawRawLine(float startX, float startY, float endX, float endY, float width, Color color,
        PdfContentByte contentByte) {
    startY = transformY(startY);
    endY = transformY(endY);
    contentByte.concatCTM(1, 0, 0, 1, startX, startY);

    contentByte.moveTo(0, 0);
    contentByte.lineTo(endX - startX, endY - startY);

    contentByte.setLineWidth(width);
    contentByte.setColorStroke(color);
    contentByte.stroke();
}

From source file:org.jaffa.modules.printing.services.FormPrintEngineIText.java

License:Open Source License

/**
 * This will fill in the page with data,
 * m_currentPageData contains the details of the current page being printed
 * @throws FormPrintException Thrown if there is any form processing problems
 *//*from w  w  w .j  av  a2  s  . co m*/
protected void fillPageFields() throws FormPrintException {
    log.debug("fillPageFields: Page=" + getCurrentPage());

    try {
        PdfContentByte cb = m_writer.getDirectContent();
        PageDetailsExtended page = (PageDetailsExtended) getCurrentPageData();

        //                // Test code to throw a barcode on the page...
        //                Barcode39 code39 = new Barcode39();
        //                code39.setCode("CODE39-1234567890");
        //                code39.setStartStopText(false);
        //                code39.setSize(0);
        //                Image image39 = code39.createImageWithBarcode(cb, null, null);
        //                com.lowagie.text.pdf.PdfPTable table = new com.lowagie.text.pdf.PdfPTable(2);
        //                table.setWidthPercentage(100);
        //                table.getDefaultCell().setBorder(com.lowagie.text.Rectangle.NO_BORDER);
        //                table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        //                table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        //                table.getDefaultCell().setFixedHeight(70);
        //                table.addCell("CODE 39");
        //                table.addCell(new Phrase(new Chunk(image39, 0, 0)));
        //                m_generatedDoc.add(table);
        //                //--------------------------------------------------

        // Loop through each field to be inserted
        for (Iterator i = page.fieldList.iterator(); i.hasNext();) {
            String fieldname = (String) i.next();

            // Get the properties for displaying this field
            FieldProperties props = (FieldProperties) page.fieldProperties.get(fieldname);

            // Get the data to display
            FormPrintEngine.DomValue data = new FormPrintEngine.DomValue(fieldname, props.sampleData);

            // Caluclate Clipping Region
            float x1 = Math.min(props.x1, props.x2);
            float x2 = Math.max(props.x1, props.x2);
            float y1 = Math.min(props.y1, props.y2);
            float y2 = Math.max(props.y1, props.y2);
            float w = Math.abs(props.x1 - props.x2) + 1;
            float h = Math.abs(props.y1 - props.y2) + 1;

            if (log.isDebugEnabled())
                log.debug("Print Field " + fieldname + "=" + data.getObject() + " @ [(" + x1 + "," + y1 + ")->("
                        + x2 + "," + y2 + ")]");

            // Default the font if not specified
            String font = BaseFont.HELVETICA;
            if (props.fontFace != null)
                font = props.fontFace;

            // Handle Barcodes diffently withing iText, don't just use fonts
            if (font.startsWith("Barcode")) {
                String bcClassName = "com.lowagie.text.pdf." + font;
                Object bcode = null;
                String dataStr = data.getValue();
                if (dataStr != null) {
                    log.debug("Barcode Data String = " + dataStr);
                    // Try and create the correct Barcode Object
                    try {
                        Class bcClass = Class.forName(bcClassName);
                        bcode = bcClass.newInstance();
                    } catch (Exception e) {
                        String err = "Can't Create Barcode Object for barcode type '" + font + "' on field "
                                + fieldname;
                        log.error(err, e);
                    }

                    // Only continue if the barcode object was created
                    if (bcode != null) {

                        // Generate and Print barcode, based on common interface
                        if (bcode instanceof Barcode) {
                            Barcode b = (Barcode) bcode;
                            // Set some default output a barcode
                            b.setCode(dataStr);
                            if (props.fontSize <= 0) {
                                // Hide text if font size is 0, and make the barcode height the size of the box
                                b.setBarHeight(h);
                                b.setFont(null);
                            } else {
                                b.setSize(props.fontSize); // size of text under barcode
                                b.setBarHeight(h - props.fontSize - 5); // Adjust Bar Height to allow for font size
                            }
                            b.setN(2); // Wide Bars

                            // Set custom parameters
                            setBarcodeParams(fieldname, bcode, props.style);

                            // Print out barcode
                            Image image = ((Barcode) bcode).createImageWithBarcode(cb, null, null);
                            printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);

                        } else

                        // Print PDF417 barcode, not based on common interface
                        if (bcode instanceof BarcodePDF417) {
                            BarcodePDF417 b = (BarcodePDF417) bcode;
                            // Set some default output a barcode
                            b.setText(dataStr);
                            b.setErrorLevel(5);
                            // Set custom parameters
                            setBarcodeParams(fieldname, bcode, props.style);
                            log.debug("PDF417 Settings\n" + "BitColumns=" + b.getBitColumns() + "\n"
                                    + "CodeColumns=" + b.getCodeColumns() + "\n" + "CodeRows=" + b.getCodeRows()
                                    + "\n" + "ErrorLevel=" + b.getErrorLevel() + "\n" + "YHeight="
                                    + b.getYHeight() + "\n" + "AspectRatio=" + b.getAspectRatio() + "\n"
                                    + "Options=" + b.getOptions() + "\n" + "LenCodewords="
                                    + b.getLenCodewords());

                            // Print out barcode
                            //image = b.getImage();
                            printImage(b.getImage(), cb, x1, y1, x2, y2, props.align, props.fitMethod,
                                    props.rotate);

                        } else {
                            // Error, unknown barcode
                            String err = "Error, No print handler for barcode object "
                                    + bcode.getClass().getName();
                            log.error(err);
                            //throw new EngineProcessingException(err);
                        }
                    }
                } else
                    log.debug("SKIPPED BARCODE : No data for " + fieldname);

                // Handle Images differently within iText, native support for JFreeChart
            } else if ("image".equalsIgnoreCase(font)) {
                try {
                    java.awt.Image image = data.getDomImage();
                    // Add an image to the page
                    if (image != null) {
                        if (fieldname.startsWith("watermark")) {
                            // Add an image-based watermark to the under content layer
                            PdfContentByte contentUnder = m_writer.getDirectContentUnder();
                            if (props.opacity != 1f) {
                                PdfGState gs = new PdfGState();
                                gs.setFillOpacity(props.opacity);
                                contentUnder.setGState(gs);
                            }
                            printImage(image, contentUnder, x1, y1, x2, y2, props.align, props.fitMethod,
                                    props.rotate);
                        } else {
                            // Add an image to main page layer
                            printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);
                        }
                    }
                } catch (IOException e) {
                    // Add Error on page.
                    Phrase text = new Phrase("Image Error", FontFactory
                            .getFont(FontFactory.HELVETICA_BOLDOBLIQUE, 8f, 0, ColorHelper.getColor("red")));
                    ColumnText ct = new ColumnText(cb);
                    ct.setSimpleColumn(text, x1, y1, x2, y2, 8f, Element.ALIGN_LEFT);
                }
            } else if (fieldname.startsWith("watermark")) {
                // Add a text-based watermark
                String text = data.getValue();
                PdfContentByte contentUnder = m_writer.getDirectContentUnder();
                if (props.opacity != 1f) {
                    PdfGState gs = new PdfGState();
                    gs.setFillOpacity(props.opacity);
                    contentUnder.setGState(gs);
                }
                // The text aligns (left, center, right) on the pivot point.
                // Default to align left.
                float pivotX = x1;
                float pivotY = y1;
                if (Element.ALIGN_CENTER == props.align) {
                    pivotX = (x1 / 2) + (x2 / 2);
                    pivotY = y1;
                } else if (Element.ALIGN_RIGHT == props.align) {
                    pivotX = x2;
                    pivotY = y1;
                }
                Phrase watermark = new Phrase(text, FontFactory.getFont(props.fontFace, props.fontSize,
                        decodeFontStyle(props.style), ColorHelper.getColor(defaultWatermarkColor)));
                ColumnText.showTextAligned(contentUnder, props.align, watermark, pivotX, pivotY, props.rotate);
            } else {
                // Handle printing of basic Text
                float lineHeight = props.fontSize;
                String str = data.getValue();
                if (str != null) {
                    // Add a bounded column to add text to.
                    Phrase text = new Phrase(str, FontFactory.getFont(props.fontFace, props.fontSize,
                            decodeFontStyle(props.style), ColorHelper.getColor(props.color)));
                    ColumnText ct = new ColumnText(cb);
                    if (props.fitMethod == FIT_METHOD_CLIP)
                        // set up column with height/width restrictions
                        ct.setSimpleColumn(text, x1, y1, x2, y2, lineHeight, props.align);
                    else
                        // set up column without (i.e. large) height/width restrictions
                        ct.setSimpleColumn(text, x1, y1, 1000, 0, lineHeight, props.align);
                    ct.go();
                }
            }

            // Draw outline boxes arround fields
            if (isTemplateMode()) {
                cb.setLineWidth(0.5f);
                cb.setLineDash(4f, 2f);
                cb.setColorStroke(new Color(0xA0, 0xA0, 0xA0));
                cb.moveTo(x1, y1);
                cb.lineTo(x1, y2);
                cb.lineTo(x2, y2);
                cb.lineTo(x2, y1);
                cb.lineTo(x1, y1);
                cb.stroke();
            }
        } // end for-loop
    } catch (DocumentException e) {
        String err = "Error printing data - " + e.getMessage();
        log.error(err, e);
        throw new EngineProcessingException(err);
        //        } catch (IOException e) {
        //            String err = "Error printing data - " + e.getMessage();
        //            log.error(err ,e);
        //            throw new EngineProcessingException(err);
    }

}

From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

public void handouts(String file) {
    try {//from ww w. ja v a2s.  co m
        File src = new File(selectedFile);

        File dest = new File(file);

        int pages = 4;

        float x1 = 30f;
        float x2 = 280f;
        float x3 = 320f;
        float x4 = 565f;

        float[] y1 = new float[pages];
        float[] y2 = new float[pages];

        float height = (778f - (20f * (pages - 1))) / pages;
        y1[0] = 812f;
        y2[0] = 812f - height;

        for (int i = 1; i < pages; i++) {
            y1[i] = y2[i - 1] - 20f;
            y2[i] = y1[i] - height;
        }

        // we create a reader for a certain document
        PdfReader reader = new PdfReader(src.getAbsolutePath());
        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();

        // step 1: creation of a document-object
        Document document = new Document(PageSize.A4);
        // step 2: we create a writer that listens to the document
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
        // step 3: we open the document
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfImportedPage page;
        int rotation;
        int i = 0;
        int p = 0;
        // step 4: we add content
        while (i < n) {
            i++;
            Rectangle rect = reader.getPageSizeWithRotation(i);
            float factorx = (x2 - x1) / rect.width();
            float factory = (y1[p] - y2[p]) / rect.height();
            float factor = (factorx < factory ? factorx : factory);
            float dx = (factorx == factor ? 0f : ((x2 - x1) - rect.width() * factor) / 2f);
            float dy = (factory == factor ? 0f : ((y1[p] - y2[p]) - rect.height() * factor) / 2f);
            page = writer.getImportedPage(reader, i);
            rotation = reader.getPageRotation(i);
            if (rotation == 90 || rotation == 270) {
                cb.addTemplate(page, 0, -factor, factor, 0, x1 + dx, y2[p] + dy + rect.height() * factor);
            } else {
                cb.addTemplate(page, factor, 0, 0, factor, x1 + dx, y2[p] + dy);
            }
            cb.setRGBColorStroke(0xC0, 0xC0, 0xC0);
            cb.rectangle(x3 - 5f, y2[p] - 5f, x4 - x3 + 10f, y1[p] - y2[p] + 10f);
            for (float l = y1[p] - 19; l > y2[p]; l -= 16) {
                cb.moveTo(x3, l);
                cb.lineTo(x4, l);
            }
            cb.rectangle(x1 + dx, y2[p] + dy, rect.width() * factor, rect.height() * factor);
            cb.stroke();

            p++;
            if (p == pages) {
                p = 0;
                document.newPage();
            }
        }
        // step 5: we close the document
        document.close();
    } catch (Exception e) {

        System.err.println(e.getMessage());
    }
}