Example usage for com.itextpdf.text Image getWidth

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

Introduction

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

Prototype

public float getWidth() 

Source Link

Document

Returns the width 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();
    height = img.getHeight();/*w  w  w .ja v a2  s.  c o m*/
    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. jav a2 s .  c  om*/

        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 av 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.atacadao.almoxarifado.model.GerandoPDF.java

public void pdfImpressaoBarraDeCodigo(String codigo) {
    Document documento = new Document(new Rectangle(90, 65));
    documento.setMargins(0, 0, 0, 0);/*from  w ww  . j a v a  2 s . c  o  m*/

    PdfWriter pdf;

    try {
        pdf = PdfWriter.getInstance(documento, new FileOutputStream("codigodebarras.pdf"));
        documento.open();
        PdfContentByte contB = pdf.getDirectContent();
        Barcode128 barCode = new Barcode128();
        barCode.setCode(codigo);
        barCode.setCodeType(Barcode128.CODE128);

        Image image = barCode.createImageWithBarcode(contB, BaseColor.BLACK, BaseColor.BLACK);
        Paragraph titulo = new Paragraph("ATCADO DOS PISOS\n",
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 5));
        titulo.setPaddingTop(0);
        titulo.setAlignment(Element.ALIGN_CENTER);

        float scaler = ((documento.getPageSize().getWidth() - documento.leftMargin() - documento.rightMargin()
                - 0) / image.getWidth()) * 60;

        image.scalePercent(scaler);
        image.setPaddingTop(0);
        image.setAlignment(Element.ALIGN_CENTER);

        documento.add(titulo);
        documento.add(image);

        documento.close();

        Desktop.getDesktop().open(new File("codigodebarras.pdf"));

    } catch (DocumentException | FileNotFoundException ex) {
        Logger.getLogger(GerandoPDF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GerandoPDF.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.bluexml.side.Framework.alfresco.signature.repo.action.executer.BasePDFStampActionExecuter.java

License:Open Source License

/**
 * Gets the X value for centering the watermark image
 * @param r//  ww  w.  j a v  a 2 s .  c  o  m
 * @param img
 * @return
 */
protected float getCenterX(Rectangle r, Image img) {
    float x = 0;
    float pdfwidth = r.getWidth();
    float imgwidth = img.getWidth();

    x = (pdfwidth - imgwidth) / 2;

    return x;
}

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

License:Open Source License

/**
 * @param args/*from  www  . j av  a  2 s . 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.
 * //from  w  ww. j  a v a  2  s .  co 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.
 * //from  w w w.j  a  v  a 2 s  .  c o m
 * @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 {//from   w ww .j  av  a  2  s. c  o 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.jpsycn.print.util.PDFUtils.java

private static void zxing(String zxing, Context mContext, Document document)
        throws MalformedURLException, IOException, DocumentException {

    if (!TextUtils.isEmpty(zxing)) {
        Bitmap bitmap = BarcodeCreater.creatBarcode(mContext, zxing, 100, 20, false);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        Image image = Image.getInstance(stream.toByteArray());

        Chunk c1 = new Chunk(image, 0, 0, false);
        float width = image.getWidth();
        Chunk c2 = new Chunk(image, 595 - 30 * 2 - width * 2, 0, false);
        Paragraph pp = new Paragraph();
        pp.setLeading(30f);/*from  ww  w. j ava  2 s .  co m*/
        pp.add(c1);
        pp.add(c2);
        document.add(pp);
    }
}