Example usage for com.itextpdf.text Image getHeight

List of usage examples for com.itextpdf.text Image getHeight

Introduction

In this page you can find the example usage for com.itextpdf.text Image getHeight.

Prototype

public float getHeight() 

Source Link

Document

Returns the height of the rectangle.

Usage

From source file:ImagetoPDF.java

public void convertToPDF(String folderName, String fileName, float compressionFactor)
        throws DocumentException, FileNotFoundException, BadElementException, IOException {
    File folder = new File(folderName);
    File[] listOfFiles = folder.listFiles();
    Image img = Image.getInstance(listOfFiles[0].getAbsolutePath());
    float width, height, temp;
    width = img.getWidth();/*from  w  w w . j a v a2  s  .  co m*/
    height = img.getHeight();
    if (height < width) {
        temp = height;
        height = width;
        width = height;
    }
    Rectangle pageSize = new Rectangle(width, height);
    Document document = new Document(pageSize, 0, 0, 0, 0);

    for (int i = 0; i < listOfFiles.length; i++) {
        enhance(listOfFiles[i].getAbsolutePath());
    }
    float scalar;
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    writer.open();
    writer.setCompressionLevel(5);
    document.open();

    for (int i = 0; i < listOfFiles.length; i++) {
        img = Image.getInstance(listOfFiles[i].getAbsolutePath());
        if (img.getWidth() > img.getHeight()) {
            img.setRotationDegrees(270f);
        }
        scalar = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin() - 0)
                / img.getWidth()) * 100;
        img.scalePercent(scalar);

        document.add(img);
    }
    document.close();
    writer.close();

}

From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java

License:Open Source License

private byte[] personalize(byte[] pdf, Contact contact, Toc tableOfContents)
        throws IOException, DocumentException {

    try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

        final PdfReader reader = new PdfReader(pdf);
        final PdfStamper stamper = new PdfStamper(reader, bos);

        // stamp some text on first page
        PdfContentByte text = stamper.getOverContent(1);

        text.beginText();/*from www .j a va2  s.  c o  m*/

        text.setColorFill(iTextUtil.getFontCoverText().getColor());
        text.setFontAndSize(iTextUtil.getFontCoverText().getBaseFont(), iTextUtil.getFontCoverText().getSize());
        text.showTextAligned(Element.ALIGN_RIGHT, coverTitle1,
                text.getPdfDocument().getPageSize().getWidth() - 15, 195, 0);
        text.showTextAligned(Element.ALIGN_RIGHT, coverTitle2,
                text.getPdfDocument().getPageSize().getWidth() - 15, 175, 0);
        text.showTextAligned(Element.ALIGN_RIGHT, contact.getCurrency().getTitlePageDescription(),
                text.getPdfDocument().getPageSize().getWidth() - 15, 80, 0);

        text.setColorFill(iTextUtil.getFontCoverPricingguide().getColor());
        text.setFontAndSize(iTextUtil.getFontCoverPricingguide().getBaseFont(),
                iTextUtil.getFontCoverPricingguide().getSize());
        text.showTextAligned(Element.ALIGN_RIGHT, coverTitle3,
                text.getPdfDocument().getPageSize().getWidth() - 15, 145, 0);

        text.setColorFill(iTextUtil.getFontCoverYear().getColor());
        text.setFontAndSize(iTextUtil.getFontCoverYear().getBaseFont(), iTextUtil.getFontCoverYear().getSize());
        text.showTextAligned(Element.ALIGN_RIGHT, coverTitle4,
                text.getPdfDocument().getPageSize().getWidth() - 15, 105, 0);

        text.endText();

        // stamp some text on first page of the table of contents page
        final Image logoImage = iTextUtil.getImageFromByteArray(HttpUtil.readByteArray(
                pdfTemplate.getLogo().getUrl(), defaultService.getUserName(), defaultService.getPassword()));
        final PdfContentByte tocContent = stamper.getOverContent(tableOfContents.getFirstPageOfToc());
        final float resizeRatio = logoImage.getHeight() / 85; // define the desired height of the log
        tocContent.addImage(logoImage, logoImage.getWidth() / resizeRatio, 0, 0,
                logoImage.getHeight() / resizeRatio, 59, 615);

        text = stamper.getOverContent(tableOfContents.getFirstPageOfToc());

        text.beginText();

        text.setColorFill(iTextUtil.getFontPersonalization().getColor());
        text.setFontAndSize(iTextUtil.getFontPersonalization().getBaseFont(),
                iTextUtil.getFontPersonalization().getSize());
        text.showTextAligned(Element.ALIGN_LEFT, "Prepared for:", 355, 681, 0);
        text.showTextAligned(Element.ALIGN_LEFT, contact.getFullName(), 355, 662, 0);

        // set company name
        if (!StringUtils.isEmpty(contact.getCompany())) {
            text.showTextAligned(Element.ALIGN_LEFT, contact.getCompany(), 355, 643, 0);
            text.showTextAligned(Element.ALIGN_LEFT, new SimpleDateFormat("MM-dd-yyyy").format(new Date()), 355,
                    624, 0);
        } else {
            text.showTextAligned(Element.ALIGN_LEFT, new SimpleDateFormat("MM-dd-yyyy").format(new Date()), 355,
                    643, 0);
        }

        text.endText();

        final ColumnText ct = new ColumnText(tocContent);
        ct.setSimpleColumn(new Rectangle(55, 517, iTextUtil.PAGE_SIZE.getWidth() - 45, 575));
        final List<Element> elements = HTMLWorker.parseToList(new StringReader(disclaimer), null);
        final Paragraph p = new Paragraph();
        p.setAlignment(Element.ALIGN_JUSTIFIED);
        for (Element element : elements) {
            for (Chunk chunk : element.getChunks()) {
                chunk.setFont(iTextUtil.getFontDisclaimer());
            }
            p.add(element);
        }
        ct.addElement(p);
        ct.go();

        stamper.close();
        reader.close();
        return bos.toByteArray();

    }

}

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;
    }// w w w  .  j a v a 2 s  .c  o  m

    // 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.bluexml.side.Framework.alfresco.signature.repo.action.executer.BasePDFStampActionExecuter.java

License:Open Source License

/**
 * Gets the Y value for centering the watermark image
 * @param r/*from   www .j  av  a 2 s.  com*/
 * @param img
 * @return
 */
protected float getCenterY(Rectangle r, Image img) {
    float y = 0;
    float pdfheight = r.getHeight();
    float imgheight = img.getHeight();

    y = (pdfheight - imgheight) / 2;

    return y;
}

From source file:com.dev.saurabh.TiffToPdf.java

License:Open Source License

/**
 * @param args/*  w  w w. j a  v a2s.  com*/
 * @throws DocumentException
 * @throws IOException
 */
public static void main(String[] args) throws DocumentException, IOException {

    String imgeFilename = "/home/saurabh/Downloads/image.tif";

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream("/home/saurabh/Desktop/out" + Math.random() + ".pdf"));
    writer.setStrictImageSequence(true);
    document.open();

    document.add(new Paragraph("Multipages tiff file"));
    Image image;
    RandomAccessFileOrArray ra = new RandomAccessFileOrArray(imgeFilename);
    int pages = TiffImage.getNumberOfPages(ra);
    for (int i = 1; i <= pages; i++) {
        image = TiffImage.getTiffImage(ra, i);
        Rectangle pageSize = new Rectangle(image.getWidth(), image.getHeight());
        document.setPageSize(pageSize);
        document.add(image);
        document.newPage();
    }

    document.close();

}

From source file:com.ephesoft.dcma.imagemagick.impl.ITextPDFCreator.java

License:Open Source License

/**
 * Converts specified tiff file into pdf.
 * /*  ww w  .ja v a 2s .c  o  m*/
 * @param tiffFile{@link File} to be converted into pdf.
 * @throws DCMAApplicationException if any error occurs while conversion.
 */
public static void convertTiffIntoPdf(final File tiffFile) throws DCMAApplicationException {
    if (null == tiffFile) {
        LOGGER.error("Unable to convert tiff file as specified file is null.");
    } else {
        com.itextpdf.text.Document document = null;
        RandomAccessFile randomAccessFile = null;
        RandomAccessFileOrArray randomAccessFileOrArray = null;
        FileChannelRandomAccessSource fileChannelRandomAccessSource = null;
        try {
            final String tiffFilePath = tiffFile.getAbsolutePath();
            if (tiffFilePath.endsWith(FileType.TIF.getExtensionWithDot())
                    || tiffFilePath.endsWith(FileType.TIFF.getExtensionWithDot())) {
                randomAccessFile = new RandomAccessFile(tiffFile, ICommonConstants.READ_MODE);
                fileChannelRandomAccessSource = new FileChannelRandomAccessSource(
                        randomAccessFile.getChannel());
                document = new com.itextpdf.text.Document();
                final int lastIndexofTiffExtension = tiffFilePath.toLowerCase()
                        .lastIndexOf(FileType.TIF.getExtensionWithDot());
                PdfWriter.getInstance(document,
                        new FileOutputStream(EphesoftStringUtil.concatenate(
                                tiffFilePath.substring(0, lastIndexofTiffExtension),
                                FileType.PDF.getExtensionWithDot())));
                document.open();
                randomAccessFileOrArray = new RandomAccessFileOrArray(fileChannelRandomAccessSource);
                final int pageCount = TiffImage.getNumberOfPages(randomAccessFileOrArray);
                Image image;
                for (int index = 1; index <= pageCount; index++) {
                    image = TiffImage.getTiffImage(randomAccessFileOrArray, index);
                    final Rectangle pageSize = new Rectangle(image.getWidth(), image.getHeight());
                    document.setPageSize(pageSize);
                    document.newPage();
                    document.add(image);
                }
                LOGGER.info(EphesoftStringUtil.concatenate(tiffFilePath, " successfully converted into PDF."));
            } else {
                LOGGER.error("Unable to convert as specified file is not a valid tiff file.");
            }
        } catch (final DocumentException e) {
            LOGGER.error("DocumentException is occurred while processing specified tiff file for conversion.");
            throw new DCMAApplicationException(EphesoftStringUtil
                    .concatenate("DocumentException occured while generating PDF", e.getMessage()), e);
        } catch (final IOException e) {
            LOGGER.error("IOException is occurred while processing specified tiff file for conversion.");
            throw new DCMAApplicationException(
                    EphesoftStringUtil.concatenate("IOException occured while generating PDF", e.getMessage()),
                    e);
        } finally {
            FileUtils.closeStream(randomAccessFileOrArray);
            FileUtils.closeFileChannelRandomAccessSource(fileChannelRandomAccessSource);
            FileUtils.closeResource(randomAccessFile);
            document.close();
        }

    }
}

From source file:com.ephesoft.dcma.imagemagick.MultiPageExecutor.java

License:Open Source License

/**
 * The <code>addImageToPdf</code> method is used to add image to pdf and make it searchable by adding image text in invisible mode
 * w.r.t parameter 'isPdfSearchable' passed.
 * /*  ww  w.  j  ava 2  s  .c  om*/
 * @param pdfWriter {@link PdfWriter} writer of pdf in which image has to be added
 * @param htmlUrl {@link HocrPage} corresponding html file for fetching text and coordinates
 * @param imageUrl {@link String} url of image to be added in pdf
 * @param isPdfSearchable true for searchable pdf else otherwise
 * @param widthOfLine
 */
private void addImageToPdf(PdfWriter pdfWriter, HocrPage hocrPage, String imageUrl, boolean isPdfSearchable,
        final int widthOfLine) {
    if (null != pdfWriter && null != imageUrl && imageUrl.length() > 0) {
        try {
            LOGGER.info("Adding image" + imageUrl + " to pdf using iText");
            Image pageImage = Image.getInstance(imageUrl);
            float dotsPerPointX = pageImage.getDpiX() / PDF_RESOLUTION;
            float dotsPerPointY = pageImage.getDpiY() / PDF_RESOLUTION;
            PdfContentByte pdfContentByte = pdfWriter.getDirectContent();

            pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY);

            pageImage.setAbsolutePosition(0, 0);

            // Add image to pdf
            pdfWriter.getDirectContentUnder().addImage(pageImage);
            pdfWriter.getDirectContentUnder().add(pdfContentByte);

            // If pdf is to be made searchable
            if (isPdfSearchable) {
                LOGGER.info("Adding invisible text for image: " + imageUrl);
                float pageImagePixelHeight = pageImage.getHeight();
                Font defaultFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, CMYKColor.BLACK);

                // Fetch text and coordinates for image to be added
                Map<String, int[]> textCoordinatesMap = getTextWithCoordinatesMap(hocrPage, widthOfLine);
                Set<String> ketSet = textCoordinatesMap.keySet();

                // Add text at specific location
                for (String key : ketSet) {
                    int[] coordinates = textCoordinatesMap.get(key);
                    float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX;
                    float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY;
                    pdfContentByte.beginText();

                    // To make text added as invisible
                    pdfContentByte.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
                    pdfContentByte.setLineWidth(Math.round(bboxWidthPt));

                    // Ceil is used so that minimum font of any text is 1
                    // For exception of unbalanced beginText() and endText()
                    if (bboxHeightPt > 0.0) {
                        pdfContentByte.setFontAndSize(defaultFont.getBaseFont(),
                                (float) Math.ceil(bboxHeightPt));
                    } else {
                        pdfContentByte.setFontAndSize(defaultFont.getBaseFont(), 1);
                    }
                    float xCoordinate = (float) (coordinates[0] / dotsPerPointX);
                    float yCoordinate = (float) ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY);
                    pdfContentByte.moveText(xCoordinate, yCoordinate);
                    pdfContentByte.showText(key);
                    pdfContentByte.endText();
                }
            }
            pdfContentByte.closePath();
        } catch (BadElementException badElementException) {
            LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: "
                    + badElementException.toString());
        } catch (DocumentException documentException) {
            LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: "
                    + documentException.toString());
        } catch (MalformedURLException malformedURLException) {
            LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: "
                    + malformedURLException.toString());
        } catch (IOException ioException) {
            LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: "
                    + ioException.toString());
        }
    }
}

From source file:com.github.albfernandez.joinpdf.JoinPdf.java

License:Open Source License

private void addImage(final Image image, final Document document, final PdfWriter writer) throws Exception {
    if (image.getWidth() > image.getHeight()) {
        document.setPageSize(new Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth()));
    } else {// w w w .j  ava 2  s . co  m
        document.setPageSize(new Rectangle(PageSize.A4.getWidth(), PageSize.A4.getHeight()));
    }
    image.scaleToFit(document.getPageSize().getWidth() - this.margin * 2f,
            document.getPageSize().getHeight() - this.margin * 2f);
    float px = (document.getPageSize().getWidth() - image.getScaledWidth()) / 2f;
    float py = (document.getPageSize().getHeight() - image.getScaledHeight()) / 2f;
    image.setAbsolutePosition(px, py);
    document.newPage();
    document.add(image);
    writePageNumber(writer);
}

From source file:com.masscustsoft.service.ToPdf.java

License:Open Source License

private void getDirectContent(PdfContentByte cb, Rectangle ps, Map it) throws Exception {
    BaseColor color = getColor(it, "fillColor");
    if (color != null)
        cb.setColorFill(color);/*  ww w.  j  ava  2  s  . co m*/

    float x = MapUtil.getFloat(it, "x", 0f);
    float y = MapUtil.getFloat(it, "y", 0f);
    float w = MapUtil.getFloat(it, "w", 0f);
    float h = MapUtil.getFloat(it, "h", 0f);

    float xPer = MapUtil.getFloat(it, "xPer", 0f);
    float yPer = MapUtil.getFloat(it, "yPer", 0f);
    float wPer = MapUtil.getFloat(it, "wPer", 0f);
    float hPer = MapUtil.getFloat(it, "hPer", 0f);

    String pos = MapUtil.getStr(it, "position", "bottom");
    switch (pos) {
    case "top":
        y += ps.getHeight();
        break;
    case "right":
        x += ps.getWidth();
        break;
    }

    float xx = x + ps.getWidth() * xPer / 100f;
    float yy = y + ps.getWidth() * yPer / 100f;
    float ww = ps.getWidth() * wPer / 100f + w;
    float hh = ps.getHeight() * hPer / 100f + h;

    int font = MapUtil.getInt(it, "fontSize", 8);
    cb.setFontAndSize(getDefaultFont(), font);

    cb.beginText();

    String cls = MapUtil.getStr(it, "cls", "");

    if (cls.equals("image")) {
        Image img = getImage(it);
        cb.addImage(img, img.getWidth(), 0, 0, img.getHeight(), xx, yy);
    } else {
        String text = LightUtil.macro(MapUtil.getStr(it, "text", ""), '$').toString();
        float degree = MapUtil.getFloat(it, "rotateDegree", 0f);
        boolean kerned = MapUtil.getBool(it, "kerned", false);
        int align = getAlignment(it, "alignment");
        x = xx;
        y = yy;
        switch (align) {
        case Element.ALIGN_CENTER:
            x = xx + ww / 2;
            break;
        case Element.ALIGN_RIGHT:
            x = xx + ww;
            break;
        default:
            align = Element.ALIGN_LEFT;
            break;
        }
        if (kerned)
            cb.showTextAlignedKerned(align, text, x, y, degree);
        else
            cb.showTextAligned(align, text, x, y, degree);
    }

    cb.endText();
}

From source file:com.masscustsoft.service.ToPdf.java

License:Open Source License

@Override
public Image createImage(String src, final Map<String, String> attrs, final ChainedProperties chain,
        final DocListener document, final ImageProvider img_provider, final HashMap<String, Image> img_store,
        final String img_baseurl) throws DocumentException, IOException {
    Image img = null;
    // getting the image using an image provider
    if (img_provider != null)
        img = img_provider.getImage(src, attrs, chain, document);
    // getting the image from an image store
    if (img == null && img_store != null) {
        Image tim = img_store.get(src);
        if (tim != null)
            img = Image.getInstance(tim);
    }//w w w.  j a v a2s  .  c om
    if (img != null)
        return img;
    ////if src start with data: it's dataUri and parse it imme.
    if (src.startsWith("remote?")) {
        BeanFactory bf = BeanFactory.getBeanFactory();
        String pp = src.substring(7);
        String[] ss = pp.split("\\&");
        try {
            String id = "~", fsId = LightUtil.getRepository().getFsId();
            for (String s : ss) {
                String[] sss = s.split("=");
                if (sss[0].equals("id"))
                    id = sss[1];
                if (sss[0].equals("fsId"))
                    fsId = sss[1];
            }
            IRepository fs = bf.getRepository(fsId);

            InputStream is = fs.getResource(id);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            StreamUtil.copyStream(is, os, 0);
            is.close();
            os.close();
            img = Image.getInstance(os.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (src.startsWith("data:")) {
        int i = src.indexOf(",");
        byte[] bits = Base64.decode(src.substring(i + 1));
        img = Image.getInstance(bits);
    } else {
        ////
        // introducing a base url
        // relative src references only
        if (!src.startsWith("http") && img_baseurl != null) {
            src = img_baseurl + src;
        } else if (img == null && !src.startsWith("http")) {
            String path = chain.getProperty(HtmlTags.IMAGEPATH);
            if (path == null)
                path = "";
            src = new File(path, src).getPath();
        }
        img = Image.getInstance(src);
    }

    if (img == null)
        return null;

    float actualFontSize = HtmlUtilities.parseLength(chain.getProperty(HtmlTags.SIZE),
            HtmlUtilities.DEFAULT_FONT_SIZE);
    if (actualFontSize <= 0f)
        actualFontSize = HtmlUtilities.DEFAULT_FONT_SIZE;
    String width = attrs.get(HtmlTags.WIDTH);
    float widthInPoints = HtmlUtilities.parseLength(width, actualFontSize);
    String height = attrs.get(HtmlTags.HEIGHT);

    float heightInPoints = HtmlUtilities.parseLength(height, actualFontSize);

    if (widthInPoints == 0 && heightInPoints == 0) {
        Document doc = (Document) document;
        widthInPoints = doc.getPageSize().getWidth();
    }

    if (widthInPoints > 0 && heightInPoints > 0) {
        img.scaleAbsolute(widthInPoints, heightInPoints);
    } else if (widthInPoints > 0) {
        heightInPoints = img.getHeight() * widthInPoints / img.getWidth();
        img.scaleAbsolute(widthInPoints, heightInPoints);
    } else if (heightInPoints > 0) {
        widthInPoints = img.getWidth() * heightInPoints / img.getHeight();
        img.scaleAbsolute(widthInPoints, heightInPoints);
    }

    String before = chain.getProperty(HtmlTags.BEFORE);
    if (before != null)
        img.setSpacingBefore(Float.parseFloat(before));
    String after = chain.getProperty(HtmlTags.AFTER);
    if (after != null)
        img.setSpacingAfter(Float.parseFloat(after));
    img.setWidthPercentage(0);
    return img;
}