Example usage for com.itextpdf.text Rectangle setTop

List of usage examples for com.itextpdf.text Rectangle setTop

Introduction

In this page you can find the example usage for com.itextpdf.text Rectangle setTop.

Prototype

public void setTop(final float ury) 

Source Link

Document

Sets the upper right y-coordinate.

Usage

From source file:at.laborg.briss.CropManager.java

License:Open Source License

private static Rectangle calculateScaledRectangle(List<Rectangle> boxes, Float[] ratios, int rotation) {
    if (ratios == null || boxes.size() == 0)
        return null;
    Rectangle smallestBox = null;
    // find smallest box
    float smallestSquare = Float.MAX_VALUE;
    for (Rectangle box : boxes) {
        if (box != null) {
            if (smallestBox == null) {
                smallestBox = box;/*from   w ww .ja v  a  2 s . c  o m*/
            }
            if (smallestSquare > box.getWidth() * box.getHeight()) {
                // set new smallest box
                smallestSquare = box.getWidth() * box.getHeight();
                smallestBox = box;
            }
        }
    }
    if (smallestBox == null)
        return null; // no useable box was found

    // rotate the ratios according to the rotation of the page
    float[] rotRatios = rotateRatios(ratios, rotation);

    // use smallest box as basis for calculation
    Rectangle scaledBox = new Rectangle(smallestBox);

    scaledBox.setLeft(smallestBox.getLeft() + (smallestBox.getWidth() * rotRatios[0]));
    scaledBox.setBottom(smallestBox.getBottom() + (smallestBox.getHeight() * rotRatios[1]));
    scaledBox.setRight(smallestBox.getLeft() + (smallestBox.getWidth() * (1 - rotRatios[2])));
    scaledBox.setTop(smallestBox.getBottom() + (smallestBox.getHeight() * (1 - rotRatios[3])));

    return scaledBox;
}

From source file:com.chaschev.itext.ColumnTextBuilder.java

License:Apache License

public ColumnTextBuilder addTruncatedLine(Chunk chunk, boolean addEllipsis) {
    final float pixelsForEllipsis = 6;

    try {/*from w ww .  j a va 2s  .  co  m*/
        ColumnText dup = ColumnText.duplicate(columnText);

        final Rectangle oneLineRectangle = new Rectangle(simpleColumnRectangle);

        oneLineRectangle.setTop(dup.getYLine());

        final float fontHeight = calcApproximateFontHeight(chunk.getFont()) * 1.6f;

        oneLineRectangle.setBottom(dup.getYLine() - fontHeight);

        if (addEllipsis) {
            oneLineRectangle.setRight(oneLineRectangle.getRight() - pixelsForEllipsis);
        }

        dup.setSimpleColumn(oneLineRectangle);
        dup.addText(chunk);

        final int status = dup.go();

        float yLine;

        if (addEllipsis && ColumnText.hasMoreText(status)) {
            oneLineRectangle.setLeft(dup.getLastX() + 2);
            oneLineRectangle.setRight(oneLineRectangle.getRight() + pixelsForEllipsis * 2);

            dup = ColumnText.duplicate(dup);

            dup.setSimpleColumn(oneLineRectangle);

            final Chunk ellipses = new Chunk("...\n", chunk.getFont());

            dup.setText(new Phrase(ellipses));
            dup.go();
            yLine = dup.getYLine();
        } else {
            yLine = dup.getYLine();
        }

        setYLine(yLine);

        return this;

    } catch (DocumentException e) {
        throw Exceptions.runtime(e);
    }
}

From source file:com.dandymadeproductions.ajqvue.io.PDFDataTableDumpThread.java

License:Open Source License

public void run() {
    // Class Method Instances
    String title;// w w w.  j  av  a  2s  .c o m

    Font titleFont;
    Font rowHeaderFont;
    Font tableDataFont;
    BaseFont rowHeaderBaseFont;

    PdfPTable pdfTable;
    PdfPCell titleCell;
    PdfPCell rowHeaderCell;
    PdfPCell bodyCell;

    Document pdfDocument;
    PdfWriter pdfWriter;
    ByteArrayOutputStream byteArrayOutputStream;

    int columnCount, rowNumber;
    int[] columnWidths;
    int totalWidth;
    Rectangle pageSize;

    ProgressBar dumpProgressBar;
    HashMap<String, String> summaryListTableNameTypes;
    DataExportProperties pdfDataExportOptions;

    String currentTableFieldName;
    String currentType, currentString;

    // Setup
    columnCount = summaryListTable.getColumnCount();
    rowNumber = summaryListTable.getRowCount();
    columnWidths = new int[columnCount];

    pdfTable = new PdfPTable(columnCount);
    pdfTable.setWidthPercentage(100);
    pdfTable.getDefaultCell().setPaddingBottom(4);
    pdfTable.getDefaultCell().setBorderWidth(1);

    summaryListTableNameTypes = new HashMap<String, String>();
    pdfDataExportOptions = DBTablesPanel.getDataExportProperties();

    titleFont = new Font(pdfDataExportOptions.getFont());
    titleFont.setStyle(Font.BOLD);
    titleFont.setSize((float) pdfDataExportOptions.getTitleFontSize());
    titleFont.setColor(new BaseColor(pdfDataExportOptions.getTitleColor().getRGB()));

    rowHeaderFont = new Font(pdfDataExportOptions.getFont());
    rowHeaderFont.setStyle(Font.BOLD);
    rowHeaderFont.setSize((float) pdfDataExportOptions.getHeaderFontSize());
    rowHeaderFont.setColor(new BaseColor(pdfDataExportOptions.getHeaderColor().getRGB()));
    rowHeaderBaseFont = rowHeaderFont.getCalculatedBaseFont(false);

    tableDataFont = pdfDataExportOptions.getFont();

    // Constructing progress bar.
    dumpProgressBar = new ProgressBar(exportedTable + " Dump");
    dumpProgressBar.setTaskLength(rowNumber);
    dumpProgressBar.pack();
    dumpProgressBar.center();
    dumpProgressBar.setVisible(true);

    // Create a Title if Optioned.
    title = pdfDataExportOptions.getTitle();

    if (!title.equals("")) {
        if (title.equals("EXPORTED TABLE"))
            title = exportedTable;

        titleCell = new PdfPCell(new Phrase(title, titleFont));
        titleCell.setBorder(0);
        titleCell.setPadding(10);
        titleCell.setColspan(summaryListTable.getColumnCount());
        titleCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);

        pdfTable.addCell(titleCell);
        pdfTable.setHeaderRows(2);
    } else
        pdfTable.setHeaderRows(1);

    // Create Row Header.
    for (int i = 0; i < columnCount; i++) {
        currentTableFieldName = summaryListTable.getColumnName(i);
        rowHeaderCell = new PdfPCell(new Phrase(currentTableFieldName, rowHeaderFont));
        rowHeaderCell.setBorderWidth(pdfDataExportOptions.getHeaderBorderSize());
        rowHeaderCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        rowHeaderCell.setBorderColor(new BaseColor(pdfDataExportOptions.getHeaderBorderColor().getRGB()));
        pdfTable.addCell(rowHeaderCell);
        columnWidths[i] = Math.min(50000,
                Math.max(columnWidths[i], rowHeaderBaseFont.getWidth(currentTableFieldName + " ")));
        if (tableColumnTypeNameHashMap != null)
            summaryListTableNameTypes.put(Integer.toString(i),
                    tableColumnTypeNameHashMap.get(currentTableFieldName));
        else
            summaryListTableNameTypes.put(Integer.toString(i), "String");
    }

    // Create the Body of Data.
    int i = 0;
    while ((i < rowNumber) && !dumpProgressBar.isCanceled()) {
        dumpProgressBar.setCurrentValue(i);

        // Collecting rows of data & formatting date & timestamps
        // as needed according to the Export Properties.

        if (summaryListTable.getValueAt(i, 0) != null) {
            for (int j = 0; j < summaryListTable.getColumnCount(); j++) {
                currentString = summaryListTable.getValueAt(i, j) + "";
                currentString = currentString.replaceAll("\n", "");
                currentString = currentString.replaceAll("\r", "");
                currentType = summaryListTableNameTypes.get(Integer.toString(j));

                // Format Date & Timestamp Fields as Needed.

                if ((currentType != null) && (currentType.equals("DATE") || currentType.equals("DATETIME")
                        || currentType.indexOf("TIMESTAMP") != -1)) {
                    if (!currentString.toLowerCase(Locale.ENGLISH).equals("null")) {
                        int firstSpace;
                        String time;

                        // Dates fall through DateTime and Timestamps try
                        // to get the time separated before formatting
                        // the date.

                        if (currentString.indexOf(" ") != -1) {
                            firstSpace = currentString.indexOf(" ");
                            time = currentString.substring(firstSpace);
                            currentString = currentString.substring(0, firstSpace);
                        } else
                            time = "";

                        currentString = Utils.convertViewDateString_To_DBDateString(currentString,
                                DBTablesPanel.getGeneralDBProperties().getViewDateFormat());
                        currentString = Utils.convertDBDateString_To_ViewDateString(currentString,
                                pdfDataExportOptions.getPDFDateFormat()) + time;
                    }
                }
                bodyCell = new PdfPCell(new Phrase(currentString, tableDataFont));
                bodyCell.setPaddingBottom(4);

                if (currentType != null) {
                    // Set Numeric Fields Alignment.
                    if (currentType.indexOf("BIT") != -1 || currentType.indexOf("BOOL") != -1
                            || currentType.indexOf("NUM") != -1 || currentType.indexOf("INT") != -1
                            || currentType.indexOf("FLOAT") != -1 || currentType.indexOf("DOUBLE") != -1
                            || currentType.equals("REAL") || currentType.equals("DECIMAL")
                            || currentType.indexOf("COUNTER") != -1 || currentType.equals("BYTE")
                            || currentType.equals("CURRENCY")) {
                        bodyCell.setHorizontalAlignment(pdfDataExportOptions.getNumberAlignment());
                        bodyCell.setPaddingRight(4);
                    }
                    // Set Date/Time Field Alignment.
                    if (currentType.indexOf("DATE") != -1 || currentType.indexOf("TIME") != -1
                            || currentType.indexOf("YEAR") != -1)
                        bodyCell.setHorizontalAlignment(pdfDataExportOptions.getDateAlignment());
                }

                pdfTable.addCell(bodyCell);
                columnWidths[j] = Math.min(50000,
                        Math.max(columnWidths[j], BASE_FONT.getWidth(currentString + " ")));
            }
        }
        i++;
    }
    dumpProgressBar.dispose();

    // Check to see if any data was in the summary
    // table to even be saved.

    if (pdfTable.size() <= pdfTable.getHeaderRows())
        return;

    // Create a document of the PDF formatted data
    // to be saved to the given output file.

    try {
        // Sizing & Layout
        totalWidth = 0;
        for (int width : columnWidths)
            totalWidth += width;

        if (pdfDataExportOptions.getPageLayout() == PDFExportPreferencesPanel.LAYOUT_PORTRAIT)
            pageSize = PageSize.A4;
        else {
            pageSize = PageSize.A4.rotate();
            pageSize.setRight(pageSize.getRight() * Math.max(1f, totalWidth / 53000f));
            pageSize.setTop(pageSize.getTop() * Math.max(1f, totalWidth / 53000f));
        }

        pdfTable.setWidths(columnWidths);

        // Document
        pdfDocument = new Document(pageSize);
        byteArrayOutputStream = new ByteArrayOutputStream();
        pdfWriter = PdfWriter.getInstance(pdfDocument, byteArrayOutputStream);
        pdfDocument.open();
        pdfTemplate = pdfWriter.getDirectContent().createTemplate(100, 100);
        pdfTemplate.setBoundingBox(new com.itextpdf.text.Rectangle(-20, -20, 100, 100));
        pdfWriter.setPageEvent(this);
        pdfDocument.add(pdfTable);
        pdfDocument.close();

        // Outputting
        WriteDataFile.mainWriteDataString(fileName, byteArrayOutputStream.toByteArray(), false);

    } catch (DocumentException de) {
        if (Ajqvue.getDebug()) {
            System.out.println("Failed to Create Document Needed to Output Data. \n" + de.toString());
        }
    }
}

From source file:com.dandymadeproductions.myjsqlview.io.PDFDataTableDumpThread.java

License:Open Source License

public void run() {
    // Class Method Instances
    String title;//from w  w w. j  a  v a 2 s . c  o  m
    PdfPTable pdfTable;
    PdfPCell titleCell, rowHeaderCell, bodyCell;
    Document pdfDocument;
    PdfWriter pdfWriter;
    ByteArrayOutputStream byteArrayOutputStream;

    int columnCount, rowNumber;
    int[] columnWidths;
    int totalWidth;
    Rectangle pageSize;

    MyJSQLView_ProgressBar dumpProgressBar;
    HashMap<String, String> summaryListTableNameTypes;
    String currentTableFieldName;
    String currentType, currentString;

    // Setup
    columnCount = summaryListTable.getColumnCount();
    rowNumber = summaryListTable.getRowCount();
    columnWidths = new int[columnCount];

    pdfTable = new PdfPTable(columnCount);
    pdfTable.setWidthPercentage(100);
    pdfTable.getDefaultCell().setPaddingBottom(4);
    pdfTable.getDefaultCell().setBorderWidth(1);

    summaryListTableNameTypes = new HashMap<String, String>();
    pdfDataExportOptions = DBTablesPanel.getDataExportProperties();

    titleFont = new Font(pdfDataExportOptions.getFont());
    titleFont.setStyle(Font.BOLD);
    titleFont.setSize((float) pdfDataExportOptions.getTitleFontSize());
    titleFont.setColor(new BaseColor(pdfDataExportOptions.getTitleColor().getRGB()));

    rowHeaderFont = new Font(pdfDataExportOptions.getFont());
    rowHeaderFont.setStyle(Font.BOLD);
    rowHeaderFont.setSize((float) pdfDataExportOptions.getHeaderFontSize());
    rowHeaderFont.setColor(new BaseColor(pdfDataExportOptions.getHeaderColor().getRGB()));
    rowHeaderBaseFont = rowHeaderFont.getCalculatedBaseFont(false);

    tableDataFont = pdfDataExportOptions.getFont();

    // Constructing progress bar.
    rowNumber = summaryListTable.getRowCount();
    dumpProgressBar = new MyJSQLView_ProgressBar(exportedTable + " Dump");
    dumpProgressBar.setTaskLength(rowNumber);
    dumpProgressBar.pack();
    dumpProgressBar.center();
    dumpProgressBar.setVisible(true);

    // Create a Title if Optioned.
    title = pdfDataExportOptions.getTitle();

    if (!title.equals("")) {
        if (title.equals("EXPORTED TABLE"))
            title = exportedTable;

        titleCell = new PdfPCell(new Phrase(title, titleFont));
        titleCell.setBorder(0);
        titleCell.setPadding(10);
        titleCell.setColspan(summaryListTable.getColumnCount());
        titleCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);

        pdfTable.addCell(titleCell);
        pdfTable.setHeaderRows(2);
    } else
        pdfTable.setHeaderRows(1);

    // Create Row Header.
    for (int i = 0; i < columnCount; i++) {
        currentTableFieldName = summaryListTable.getColumnName(i);
        rowHeaderCell = new PdfPCell(new Phrase(currentTableFieldName, rowHeaderFont));
        rowHeaderCell.setBorderWidth(pdfDataExportOptions.getHeaderBorderSize());
        rowHeaderCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        rowHeaderCell.setBorderColor(new BaseColor(pdfDataExportOptions.getHeaderBorderColor().getRGB()));
        pdfTable.addCell(rowHeaderCell);
        columnWidths[i] = Math.min(50000,
                Math.max(columnWidths[i], rowHeaderBaseFont.getWidth(currentTableFieldName + " ")));
        if (tableColumnTypeHashMap != null)
            summaryListTableNameTypes.put(Integer.toString(i),
                    tableColumnTypeHashMap.get(currentTableFieldName));
        else
            summaryListTableNameTypes.put(Integer.toString(i), "String");
    }

    // Create the Body of Data.
    int i = 0;
    while ((i < rowNumber) && !dumpProgressBar.isCanceled()) {
        dumpProgressBar.setCurrentValue(i);

        // Collecting rows of data & formatting date & timestamps
        // as needed according to the Export Properties.

        if (summaryListTable.getValueAt(i, 0) != null) {
            for (int j = 0; j < summaryListTable.getColumnCount(); j++) {
                currentString = summaryListTable.getValueAt(i, j) + "";
                currentString = currentString.replaceAll("\n", "");
                currentString = currentString.replaceAll("\r", "");
                currentType = summaryListTableNameTypes.get(Integer.toString(j));

                // Format Date & Timestamp Fields as Needed.

                if ((currentType != null) && (currentType.equals("DATE") || currentType.equals("DATETIME")
                        || currentType.indexOf("TIMESTAMP") != -1)) {
                    if (!currentString.toLowerCase().equals("null")) {
                        int firstSpace;
                        String time;

                        // Dates fall through DateTime and Timestamps try
                        // to get the time separated before formatting
                        // the date.

                        if (currentString.indexOf(" ") != -1) {
                            firstSpace = currentString.indexOf(" ");
                            time = currentString.substring(firstSpace);
                            currentString = currentString.substring(0, firstSpace);
                        } else
                            time = "";

                        currentString = MyJSQLView_Utils.convertViewDateString_To_DBDateString(currentString,
                                DBTablesPanel.getGeneralDBProperties().getViewDateFormat());
                        currentString = MyJSQLView_Utils.convertDBDateString_To_ViewDateString(currentString,
                                pdfDataExportOptions.getPDFDateFormat()) + time;
                    }
                }
                bodyCell = new PdfPCell(new Phrase(currentString, tableDataFont));
                bodyCell.setPaddingBottom(4);

                if (currentType != null) {
                    // Set Numeric Fields Alignment.
                    if (currentType.indexOf("BIT") != -1 || currentType.indexOf("BOOL") != -1
                            || currentType.indexOf("NUM") != -1 || currentType.indexOf("INT") != -1
                            || currentType.indexOf("FLOAT") != -1 || currentType.indexOf("DOUBLE") != -1
                            || currentType.equals("REAL") || currentType.equals("DECIMAL")
                            || currentType.indexOf("COUNTER") != -1 || currentType.equals("BYTE")
                            || currentType.equals("CURRENCY")) {
                        bodyCell.setHorizontalAlignment(pdfDataExportOptions.getNumberAlignment());
                        bodyCell.setPaddingRight(4);
                    }
                    // Set Date/Time Field Alignment.
                    if (currentType.indexOf("DATE") != -1 || currentType.indexOf("TIME") != -1
                            || currentType.indexOf("YEAR") != -1)
                        bodyCell.setHorizontalAlignment(pdfDataExportOptions.getDateAlignment());
                }

                pdfTable.addCell(bodyCell);
                columnWidths[j] = Math.min(50000,
                        Math.max(columnWidths[j], BASE_FONT.getWidth(currentString + " ")));
            }
        }
        i++;
    }
    dumpProgressBar.dispose();

    // Check to see if any data was in the summary
    // table to even be saved.

    if (pdfTable.size() <= pdfTable.getHeaderRows())
        return;

    // Create a document of the PDF formatted data
    // to be saved to the given output file.

    try {
        // Sizing & Layout
        totalWidth = 0;
        for (int width : columnWidths)
            totalWidth += width;

        if (pdfDataExportOptions.getPageLayout() == PDFExportPreferencesPanel.LAYOUT_PORTRAIT)
            pageSize = PageSize.A4;
        else {
            pageSize = PageSize.A4.rotate();
            pageSize.setRight(pageSize.getRight() * Math.max(1f, totalWidth / 53000f));
            pageSize.setTop(pageSize.getTop() * Math.max(1f, totalWidth / 53000f));
        }

        pdfTable.setWidths(columnWidths);

        // Document
        pdfDocument = new Document(pageSize);
        byteArrayOutputStream = new ByteArrayOutputStream();
        pdfWriter = PdfWriter.getInstance(pdfDocument, byteArrayOutputStream);
        pdfDocument.open();
        pdfTemplate = pdfWriter.getDirectContent().createTemplate(100, 100);
        pdfTemplate.setBoundingBox(new com.itextpdf.text.Rectangle(-20, -20, 100, 100));
        pdfWriter.setPageEvent(this);
        pdfDocument.add(pdfTable);
        pdfDocument.close();

        // Outputting
        WriteDataFile.mainWriteDataString(fileName, byteArrayOutputStream.toByteArray(), false);

    } catch (DocumentException de) {
        if (MyJSQLView.getDebug()) {
            System.out.println("Failed to Create Document Needed to Output Data. \n" + de.toString());
        }
    }
}

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

License:Open Source License

/**
 * Calls the super and {@link Advanced#draw(com.itextpdf.text.Rectangle, java.lang.String) } for each Advanced styler
 * registered. Adds a debugging link for images when in debug mode.
 *
 * @param writer/*w  w  w  .  ja va2s  . c o m*/
 * @param document
 * @param rect
 * @param genericTag
 * @see #addDelayedStyler(java.lang.String, java.util.Collection, com.itextpdf.text.Chunk) 
 * @see Advanced#addDelayedData(java.lang.String, com.itextpdf.text.Chunk)
 * @see VectorPrintDocument
 */
@Override
public final void onGenericTag(PdfWriter writer, Document document, final Rectangle rect, String genericTag) {
    //      if (log.isLoggable(Level.FINE)) {
    //         Collection<Advanced> av = doOnGenericTag.get(genericTag);
    //         String data = null;
    //         if (av!=null) {
    //            for (Advanced a : av) {
    //               data += a.getDelayed(genericTag).getDataPart();
    //               break;
    //            }
    //         }
    //         System.out.println("wrapped: " + carriageReturns.toString() + ", " + genericTag + " " + data + " " + rect.toString() + ", x=" + rect.getLeft());
    //      }
    if (doOnGenericTag.get(genericTag) != null && !genericTag.startsWith(VectorPrintDocument.DRAWNEAR)
            && !genericTag.startsWith(VectorPrintDocument.DRAWSHADOW)) {
        int i = -1;
        for (Advanced a : doOnGenericTag.get(genericTag)) {
            ++i;
            if (genericTag.startsWith(DefaultElementProducer.ADV) && Integer
                    .parseInt(genericTag.replace(DefaultElementProducer.ADV, "")) > maxTagForGenericTagOnPage) {
                continue;
            }
            try {
                if (a.shouldDraw(a.getDelayed(genericTag).getData())) {
                    if (a instanceof DebugStyler && imageChunks.containsKey(genericTag)) {
                        Chunk wrapper = imageChunks.get(genericTag);
                        Object[] atts = (Object[]) wrapper.getAttributes().get(Chunk.IMAGE);
                        Rectangle shifted = new Rectangle(rect);
                        shifted.setLeft(shifted.getLeft() + (Float) atts[1]);
                        shifted.setRight(shifted.getRight() + (Float) atts[1]);
                        shifted.setTop(shifted.getTop() + (Float) atts[2]);
                        shifted.setBottom(shifted.getBottom() + (Float) atts[2]);
                        a.draw(shifted, genericTag);
                    } else if (!genericTag.startsWith(VectorPrintDocument.IMG_DEBUG)) {
                        a.draw(rect, genericTag);
                    }
                }
            } catch (VectorPrintException ex) {
                throw new VectorPrintRuntimeException(ex);
            }
        }
    }
    // images
    if (genericTag.startsWith(VectorPrintDocument.IMG_DEBUG)
            && getSettings().getBooleanProperty(false, DEBUG)) {
        // only now we can define a goto action, we know the position of the image
        if (rectangles.containsKey(genericTag)) {
            Rectangle rectangle = imageRectFromChunk(genericTag, rect);
            DebugHelper.debugAnnotation(rectangle, genericTag.replaceFirst(VectorPrintDocument.IMG_DEBUG, ""),
                    writer);
        } else {
            DebugHelper.debugAnnotation(rect, genericTag.replaceFirst(VectorPrintDocument.IMG_DEBUG, ""),
                    writer);
        }
    }
    if (genericTag.startsWith(VectorPrintDocument.DRAWNEAR)) {
        Rectangle rectangle = imageRectFromChunk(genericTag, rect);
        com.vectorprint.report.itext.style.stylers.Image image = (com.vectorprint.report.itext.style.stylers.Image) doOnGenericTag
                .get(genericTag).iterator().next();
        short i = -1;
        for (Advanced a : doOnGenericTag.get(genericTag)) {
            try {
                if (++i > 0 && a.shouldDraw(a.getDelayed(genericTag).getData())) {
                    if (getSettings().getBooleanProperty(false, DEBUG)) {
                        DebugHelper.styleLink(writer.getDirectContent(), a.getStyleClass(), "draw near",
                                rectangle.getLeft(), rectangle.getTop(), getSettings(), elementProducer);
                    }
                    a.draw(rectangle, genericTag);
                }
            } catch (VectorPrintException ex) {
                throw new VectorPrintRuntimeException(ex);
            }

        }
    }
    if (genericTag.startsWith(VectorPrintDocument.DRAWSHADOW)) {
        // we know the position of the image
        Rectangle r = imageRectFromChunk(genericTag, rect);
        com.vectorprint.report.itext.style.stylers.Image image = (com.vectorprint.report.itext.style.stylers.Image) doOnGenericTag
                .get(genericTag).iterator().next();
        try {
            image.drawShadow(r.getLeft(), r.getBottom(), r.getWidth(), r.getHeight(),
                    genericTag.replaceFirst(VectorPrintDocument.DRAWSHADOW, ""));
        } catch (VectorPrintException ex) {
            throw new VectorPrintRuntimeException(ex);
        }
    }
}

From source file:com.vectorprint.report.itext.style.stylers.AbstractFieldStyler.java

License:Open Source License

@Override
protected void draw(PdfContentByte canvas, float x, float y, float width, float height, String genericTag)
        throws VectorPrintException {
    Rectangle box = new Rectangle(x, y, x + width, y - height);
    PdfFormField pff = null;/* w w w.  ja  va  2  s  .co m*/
    if (getValue(DocumentSettings.WIDTH, Float.class) > 0) {
        box.setRight(box.getLeft() + getValue(DocumentSettings.WIDTH, Float.class));
    }
    if (getValue(DocumentSettings.HEIGHT, Float.class) > 0) {
        float diff = box.getHeight() - getValue(DocumentSettings.HEIGHT, Float.class);
        box.setBottom(box.getBottom() + diff / 2);
        box.setTop(box.getTop() - diff / 2);
    }
    bf.setBox(box);
    try {
        List<BaseStyler> stylers = stylerFactory.getStylers(getStyleClass());
        List<FormFieldStyler> ffStylers = StyleHelper.getStylers(stylers, FormFieldStyler.class);
        pff = makeField();
        if (FormFieldStyler.FIELDTYPE.BUTTON.equals(getFieldtype())) {
            for (FormFieldStyler f : ffStylers) {
                if (f.isParameterSet(Image.URLPARAM)) {
                    pff.setAction(PdfAction.createSubmitForm(f.getValue(Image.URLPARAM, URL.class).toString(),
                            null, PdfAction.SUBMIT_HTML_FORMAT));
                    break;
                }
            }
        }
    } catch (IOException | DocumentException | VectorPrintException ex) {
        throw new VectorPrintRuntimeException(ex);
    }
    getWriter().addAnnotation(pff);
    if (stylerFactory.getSettings().getBooleanProperty(false, DEBUG)) {
        DebugHelper.debugRect(canvas, box, new float[] { 2, 2 }, 0.7f, stylerFactory.getSettings(),
                elementProducer);
        DebugHelper.styleLink(canvas, getStyleClass(), "", box.getLeft(), box.getTop(),
                stylerFactory.getSettings(), elementProducer);
    }
}

From source file:com.vectorprint.report.itext.style.stylers.SimpleColumns.java

License:Open Source License

/**
 * writes out content taking into account the current vertical position in the document and making sure that the next
 * call to {@link Document#add(com.itextpdf.text.Element)} will start at the correct vertical position.
 *
 * @see #getSpaceBefore()//from   w  ww  .j  a  va  2 s  .  c om
 * @see #getSpaceAfter()
 *
 * @param last when true space will be appended to start adding content at the correct position after the columns
 * @throws DocumentException
 */
public SimpleColumns write(boolean last) throws DocumentException {
    int status = ColumnText.START_COLUMN;
    ct.setSimpleColumn(columns.get(column));
    if (firstWrite) {
        float top = getWriter().getVerticalPosition(false) > getTop() ? getTop()
                : getWriter().getVerticalPosition(false);
        pageTop = minY = top - getValue(Spacing.SPACEBEFOREPARAM, Float.class);
        ct.setYLine(pageTop);
        firstWrite = false;
        if (log.isLoggable(Level.FINE)) {
            log.fine(String.format("first write of columns top for content determined: %s",
                    top - getValue(Spacing.SPACEBEFOREPARAM, Float.class)));
        }
    } else {
        if (log.isLoggable(Level.FINE)) {
            log.fine(String.format("following write of columns, using current top for content: %s", currentY));
        }
        ct.setYLine(currentY);
    }
    while (ColumnText.hasMoreText(status)) {
        if (getSettings().getBooleanProperty(Boolean.FALSE, ReportConstants.DEBUG)) {
            Rectangle rect = new Rectangle(columns.get(column));
            rect.setTop(ct.getYLine());
            DebugHelper.debugRect(ct.getCanvas(), rect, new float[] { 2, 2 }, 0.3f, getSettings(),
                    elementProducer);
        }
        status = ct.go();
        currentY = ct.getYLine();
        if (ct.getYLine() < minY) {
            minY = ct.getYLine();
        }
        if (ColumnText.hasMoreText(status)) {
            if (column == getNumColumns() - 1) {
                column = 0;
                getDocument().newPage();
                minY = pageTop = currentY = getTop();
                if (log.isLoggable(Level.FINE)) {
                    log.fine(String.format("starting next page for columns"));
                }
            } else {
                column++;
                if (log.isLoggable(Level.FINE)) {
                    log.fine(String.format("going to column %s", column));
                }
            }
            ct.setSimpleColumn(columns.get(column));
            ct.setYLine(pageTop);
        } else {
            contentWritten = addedContent;
            if (log.isLoggable(Level.FINE)) {
                log.fine(String.format("column content written %s", addedContent));
            }
        }
    }
    if (last) {
        float space = (pageTop - minY < getBottom())
                ? getBottom() + getValue(Spacing.SPACEAFTERPARAM, Float.class)
                : pageTop - minY + getValue(Spacing.SPACEAFTERPARAM, Float.class);
        // add necessary spacing, space otherwise ignored!
        if (log.isLoggable(Level.FINE)) {
            log.fine(String.format("appending %s mm to start following content at the correct position",
                    ItextHelper.ptsToMm(space)));
        }
        Paragraph p = new Paragraph(" ");
        p.setSpacingAfter(space);
        getDocument().add(p);
    }
    return this;
}

From source file:dbedit.actions.ExportPdfAction.java

License:Open Source License

@Override
protected void performThreaded(ActionEvent e) throws Exception {
    boolean selection = false;
    JTable table = ResultSetTable.getInstance();
    if (table.getSelectedRowCount() > 0 && table.getSelectedRowCount() != table.getRowCount()) {
        Object option = Dialog.show("PDF", "Export", Dialog.QUESTION_MESSAGE,
                new Object[] { "Everything", "Selection" }, "Everything");
        if (option == null || "-1".equals(option.toString())) {
            return;
        }//from  w w  w. ja  v a 2s  . com
        selection = "Selection".equals(option);
    }
    List list = ((DefaultTableModel) table.getModel()).getDataVector();
    int columnCount = table.getColumnCount();
    PdfPTable pdfPTable = new PdfPTable(columnCount);
    pdfPTable.setWidthPercentage(100);
    pdfPTable.getDefaultCell().setPaddingBottom(4);
    int[] widths = new int[columnCount];

    // Row Header
    pdfPTable.getDefaultCell().setBorderWidth(2);
    for (int i = 0; i < columnCount; i++) {
        String columnName = table.getColumnName(i);
        pdfPTable.addCell(new Phrase(columnName, ROW_HEADER_FONT));
        widths[i] = Math.min(50000, Math.max(widths[i], ROW_HEADER_BASE_FONT.getWidth(columnName + " ")));
    }
    pdfPTable.getDefaultCell().setBorderWidth(1);
    if (!list.isEmpty()) {
        pdfPTable.setHeaderRows(1);
    }

    // Body
    for (int i = 0; i < list.size(); i++) {
        if (!selection || table.isRowSelected(i)) {
            List record = (List) list.get(i);
            for (int j = 0; j < record.size(); j++) {
                Object o = record.get(j);
                if (o != null) {
                    if (ResultSetTable.isLob(j)) {
                        o = Context.getInstance().getColumnTypeNames()[j];
                    }
                } else {
                    o = "";
                }
                PdfPCell cell = new PdfPCell(new Phrase(o.toString()));
                cell.setPaddingBottom(4);
                if (o instanceof Number) {
                    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                }
                pdfPTable.addCell(cell);
                widths[j] = Math.min(50000, Math.max(widths[j], BASE_FONT.getWidth(o.toString())));
            }
        }
    }

    // Size
    pdfPTable.setWidths(widths);
    int totalWidth = 0;
    for (int width : widths) {
        totalWidth += width;
    }
    Rectangle pageSize = PageSize.A4.rotate();
    pageSize.setRight(pageSize.getRight() * Math.max(1f, totalWidth / 53000f));
    pageSize.setTop(pageSize.getTop() * Math.max(1f, totalWidth / 53000f));

    // Document
    Document document = new Document(pageSize);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, byteArrayOutputStream);
    document.open();
    pdfTemplate = writer.getDirectContent().createTemplate(100, 100);
    pdfTemplate.setBoundingBox(new Rectangle(-20, -20, 100, 100));
    writer.setPageEvent(this);
    document.add(pdfPTable);
    document.close();
    FileIO.saveAndOpenFile("export.pdf", byteArrayOutputStream.toByteArray());
}

From source file:info.longnetpro.examples.PdfLibExamples.java

public static void generatePdf()
        throws DocumentException, URISyntaxException, MalformedURLException, IOException {
    String licFile = getLicenseFilePath();
    loadLicenseFile(licFile);/*from   ww w .ja v  a 2 s  .c  o m*/

    String dest = getTargetFilePath();
    Document doc = new Document();
    PdfWriter.getInstance(doc, new FileOutputStream(dest));
    Rectangle pageSize = PageSize.LETTER;
    Rectangle rect = new Rectangle(0f, 0f, 50f, 100f);
    rect.setBorder(15);
    rect.setBorderColor(BaseColor.RED);
    rect.setBorderWidth(.5f);
    rect.setBackgroundColor(BaseColor.BLUE);
    doc.setPageSize(pageSize);
    doc.open();

    Page page = new Page(pageSize.getWidth(), pageSize.getHeight());
    ContentBox rpage = page.margin(new Float[] { 10f, 50f, 10f, 50f });

    for (Anchor anchor : Anchor.values()) {
        ContentBox box = new ContentBox(50f, 100f);
        float offx = anchor.equals(Anchor.CENTER) ? -50f : 0f;
        float offy = anchor.equals(Anchor.CENTER) ? -50f : 0f;

        ContentBox rr = anchor.anchorElement(rpage, box, offx, offy);

        if (anchor.equals(Anchor.BOTTOM_LEFT)) {
            float[] dim = box.scaleByPercentage(0.5f);
            //rr = rr.reposition(dim[0], dim[1], Anchor.TOP_RIGHT);
        }

        rect.setLeft(rr.getLeft());
        rect.setBottom(rr.getBottom());
        rect.setRight(rr.getRight());
        rect.setTop(rr.getTop());
        doc.add(rect);
    }
    String imageFile = getImageFilePath();
    Image image = Image.getInstance(imageFile);

    float width = Measurement.dotsToUserUnits(image.getWidth(), 1200);
    float height = Measurement.dotsToUserUnits(image.getHeight(), 1200);

    System.out.println(width + " " + height);

    ContentBox img = Anchor.BOTTOM_LEFT.anchorElement(rpage, width, height);

    image.scaleToFit(width, height);
    image.setAbsolutePosition(img.getLeft(), img.getBottom());

    System.out.println(image.getWidth() + " " + image.getHeight());
    System.out.println(image.getAbsoluteX() + " " + image.getAbsoluteY());

    doc.add(image);
    doc.close();
}