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

From source file:com.mobicage.rogerthat.enterprise.samples.hr.bizz.GenerateExpenseNote.java

License:Open Source License

public int handle(final User user, final User manager, final ExpenseNote en)
        throws MalformedURLException, IOException, DocumentException {

    log.info("Building list of expenses ...");
    List<Expense> expenses = Expense.list(en);
    log.info("Retrieved " + expenses.size() + " expenses from the datastore");

    log.info("Creating ExpenseNoteDocOutputStream");
    ExpenseNoteDocOutputStream stream = new ExpenseNoteDocOutputStream(en);

    Document document = new Document();
    PdfWriter.getInstance(document, stream);
    document.open();/*from  w w w. j  a  v  a2 s . c o  m*/

    document.addTitle("Expense note " + en.id + " of " + user.name);
    document.addSubject("Expense note generated by Rogerthat Enterprise!");
    document.addKeywords("expense note");
    document.addAuthor(user.name);
    document.addCreator("Rogerthat OneApp Enterprise Mobility");

    Paragraph preface = new Paragraph();

    preface.add(new Paragraph("TP Vision expense note", titleFont));
    preface.add(new Paragraph(" "));

    DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
    Date date = new Date();
    preface.add(new Paragraph("Date: " + dateFormat.format(date)));
    preface.add(new Paragraph("Requestor: " + user.name));
    preface.add(new Paragraph("Approver: " + manager.name));
    preface.add(new Paragraph(" "));

    PdfPTable table = new PdfPTable(7);
    table.setWidthPercentage(110);
    table.setWidths(new int[] { 5, 15, 15, 35, 10, 15, 10 });
    addHeader(table, "Id");
    addHeader(table, "Date");
    addHeader(table, "Nature");
    addHeader(table, "Description");
    addHeader(table, "Account");
    addHeader(table, "Amount");
    addHeader(table, "Voucher");
    table.setHeaderRows(1);

    Collections.sort(expenses, new Comparator<Expense>() {
        @Override
        public int compare(Expense e1, Expense e2) {
            return (int) (e1.date - e2.date);
        }
    });
    int i = 0;
    double total = 0;
    for (Expense expense : expenses) {
        PdfPCell c1 = new PdfPCell(new Phrase("" + ++i));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
        table.addCell(dateFormat.format(new Date(expense.date * 1000)));
        table.addCell(expense.nature);
        table.addCell(expense.description);
        table.addCell("" + expense.account);
        c1 = new PdfPCell(new Phrase(DECIMAL_FORMAT.format(expense.amount) + " " + expense.currency));
        c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell(c1);
        table.addCell(expense.voucher);
        total += expense.amount;
    }

    preface.add(table);

    preface.add(new Paragraph(" "));
    preface.add(new Paragraph("Total: " + DECIMAL_FORMAT.format(total), titleFont));

    document.add(preface);

    i = 0;
    for (Expense expense : expenses) {
        i++;
        if (expense.receipt == null)
            continue;

        document.newPage();
        Paragraph receipt = new Paragraph();
        receipt.add(new Paragraph("Attachment " + i, titleFont));
        document.add(receipt);
        Image image = Image.getInstance(new URL(expense.receipt));
        image.setRotationDegrees(-90);
        float scaler = (document.getPageSize().getWidth() / image.getWidth()) * 100;

        image.scalePercent(scaler);
        document.add(image);
    }

    document.close();
    stream.close();

    return stream.getSize();

}

From source file:com.mui.certificate.core.HalalCertification.java

License:Apache License

@Override
public void exportCertificate(Certificate cert, File outputPdf) throws Exception {
    ByteMatrix matrix = generateQRCode(cert.getCertificateURL().toString());
    int scale = sMagicNumber / matrix.getWidth();
    BufferedImage buffImage = convertToImage(matrix, scale);
    File tempOutput = new File("tmp-qrcode.png");
    ImageIO.write(buffImage, "png", tempOutput);
    Image itImage = Image.getInstance(tempOutput.getCanonicalPath());
    PdfReader reader = new PdfReader("doc/template_certificate_halal.pdf");
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputPdf));
    int centerY = 715;
    int centerX = 135;
    itImage.setAbsolutePosition(centerX - (itImage.getWidth() / 2), centerY - (itImage.getHeight() / 2));
    stamper.getOverContent(1).addImage(itImage);
    AcroFields form1 = stamper.getAcroFields();
    String nameHeader = "topmostSubform[0].Page1[0].";
    form1.setField(nameHeader + "no_certificate[0]", cert.getCertificateNumber().toString());
    form1.setField(nameHeader + "name_product[0]", cert.getProductName());
    form1.setField(nameHeader + "type_product[0]", cert.getProductType());
    form1.setField(nameHeader + "name_company[0]", cert.getCompanyName());
    form1.setField(nameHeader + "company_address[0]", cert.getCompanyAddress());
    Calendar cal = Calendar.getInstance(new Locale("id"));
    Locale idLocale = new Locale("id");
    cal.setTime(cert.getIssuedDate());//from  w w  w.ja  v a2s.c o  m
    form1.setField(nameHeader + "issued_date[0]", String.format(idLocale, "%1$tA, %1$te %1$tB %1$tY", cal));
    cal.setTime(cert.getValidDate());
    form1.setField(nameHeader + "expired_date[0]", String.format(idLocale, "%1$tA, %1$te %1$tB %1$tY", cal));
    stamper.setFormFlattening(true);
    stamper.close();
    tempOutput.delete();
}

From source file:com.ostrichemulators.semtool.util.ExportUtility.java

License:Open Source License

public static void exportAsPdf(BufferedImage img, File pdf) throws IOException, DocumentException {
    final double MAX_DIM = 14400;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(img, "PNG", baos);
    Image image1 = Image.getInstance(baos.toByteArray(), true);
    Rectangle r;/*w  ww.j a  va 2  s.  co  m*/
    if (image1.getHeight() > MAX_DIM) {
        r = new Rectangle((int) image1.getWidth(), (int) MAX_DIM);
    } else if (image1.getWidth() > MAX_DIM) {
        r = new Rectangle((int) MAX_DIM, (int) image1.getHeight());
    } else {
        r = new Rectangle((int) image1.getWidth() + 20, (int) image1.getHeight() + 20);
    }
    Document document = new Document(r, 15, 25, 15, 25);
    PdfWriter.getInstance(document, new FileOutputStream(pdf));
    document.open();

    int pages = (int) Math.ceil((double) img.getHeight() / MAX_DIM);
    if (pages == 0) {
        pages = 1;
    }
    for (int i = 0; i < pages; i++) {
        BufferedImage temp;
        if (i < pages - 1) {
            temp = img.getSubimage(0, i * (int) MAX_DIM, img.getWidth(), (int) MAX_DIM);
        } else {
            temp = img.getSubimage(0, i * (int) MAX_DIM, img.getWidth(), img.getHeight() % (int) MAX_DIM);
        }
        File tempFile = new File(i + Constants.PNG);
        ImageIO.write(temp, Constants.PNG, tempFile);
        Image croppedImage = Image.getInstance(i + Constants.PNG);
        document.add(croppedImage);
        tempFile.delete();
        if (i < pages - 1) {
            document.newPage();
        }
    }

    document.close();
}

From source file:com.primeleaf.krystal.util.PDFConverter.java

License:Open Source License

public File getConvertedFile(DocumentRevision documentRevision, Document document, String password)
        throws Exception {
    File tempFile = documentRevision.getDocumentFile();
    if ("TIF".equalsIgnoreCase(document.getExtension()) || "TIFF".equalsIgnoreCase(document.getExtension())) {
        try {/*from  w  w  w  .  j av a2  s . co  m*/
            tempFile = File.createTempFile("temp", ".PDF");
            com.itextpdf.text.Document pdf = new com.itextpdf.text.Document();
            PdfWriter.getInstance(pdf, new FileOutputStream(tempFile));
            pdf.open();
            pdf.setMargins(0, 0, 0, 0);
            FileInputStream fis = new FileInputStream(documentRevision.getDocumentFile());
            RandomAccessFileOrArray file = new RandomAccessFileOrArray(fis);
            int pages = TiffImage.getNumberOfPages(file);
            for (int page = 1; page <= pages; page++) {
                Image img = TiffImage.getTiffImage(file, page);
                img.setAbsolutePosition(0f, 0f);
                img.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
                pdf.setMargins(0, 0, 0, 0);
                pdf.add(img);
                pdf.newPage();
            }
            fis.close();
            pdf.close();
            document.setExtension("PDF");
        } catch (Exception e) {
            tempFile = documentRevision.getDocumentFile();
            throw new Exception("Unable to convert TIFF Document to PDF");
        }
    } else if ("JPG".equalsIgnoreCase(document.getExtension())
            || "JPEG".equalsIgnoreCase(document.getExtension())
            || "PNG".equalsIgnoreCase(document.getExtension())
            || "BMP".equalsIgnoreCase(document.getExtension())
            || "GIF".equalsIgnoreCase(document.getExtension())) {
        try {
            tempFile = File.createTempFile("temp", ".PDF");
            Image img = Image.getInstance(documentRevision.getDocumentFile().getAbsolutePath());
            com.itextpdf.text.Document pdf = new com.itextpdf.text.Document(
                    new Rectangle(img.getWidth(), img.getHeight()), 0, 0, 0, 0);
            img.setAbsolutePosition(0f, 0f);
            PdfWriter.getInstance(pdf, new FileOutputStream(tempFile));
            pdf.open();
            pdf.add(img);
            pdf.close();
            document.setExtension("PDF");
        } catch (Exception e) {
            tempFile = documentRevision.getDocumentFile();
            throw new Exception("Unable to convert Image Document to PDF");
        }
    } else if ("PDF".equalsIgnoreCase(document.getExtension())) {
        tempFile = documentRevision.getDocumentFile();
    } else {
        String tempFilePath = "";
        String KRYSTAL_HOME = System.getProperty("krystal.home");
        if (KRYSTAL_HOME == null) {
            KRYSTAL_HOME = System.getProperty("user.dir");
            System.setProperty("krystal.home", KRYSTAL_HOME);
        }
        tempFilePath = KRYSTAL_HOME + File.separator + "/webapps/DMC/images/unsupport.pdf";
        tempFile = new File(tempFilePath);
    }
    return tempFile;
}

From source file:com.qmetric.document.watermark.PdfWatermarkFactory.java

License:Open Source License

private float getXOffset(final Rectangle pageSize, final Image image) {
    return (float) Math.round(pageSize.getWidth() - image.getWidth()) / 2;
}

From source file:com.sparksoftsolutions.com.pdfcreator.MainActivity.java

private File generatePDFFromImages(ArrayList<ImageItem> images) {
    Document document = new Document();

    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard, generateFileName());

    try {/* w ww  . ja  v a  2  s  .com*/
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    } catch (Exception ex) {
        return null;
    }

    // document = new PdfDocument();
    Boolean opened = false;
    for (ImageItem img : images) {

        Bitmap bitmap = BitmapFactory.decodeFile(img.path);

        try {

            Image image = Image.getInstance(img.path);
            document.setPageSize(new Rectangle(image.getWidth(), image.getHeight()));

            if (!opened) {
                document.open();
                opened = true;
            } else
                document.newPage();
            document.add(image);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    document.close();
    return file;
}

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

License:Open Source License

public PdfPCell style(PdfPCell cell, Object data) throws VectorPrintException {
    Image img = (Image) data;

    if (getWidth() <= 0) {
        throw new VectorPrintException("You need to specify width of the cell");
    }/*from  www .  j  a  v a  2s  .c om*/

    cell.setVerticalAlignment(getAlign().getVertical());

    float paddingLeft = (getWidth() - img.getWidth()) / 2;
    if (getAlign().getHorizontal() == PdfPCell.ALIGN_LEFT) {
        paddingLeft = 0;
    } else if (getAlign().getHorizontal() == PdfPCell.ALIGN_RIGHT) {
        paddingLeft = (getWidth() - img.getWidth());
    }

    cell.setPaddingLeft(paddingLeft);

    return cell;
}

From source file:com.vimbox.hr.LicensePDFGenerator.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w  w  w.jav  a2 s.c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/pdf");
    String fileName = request.getParameter("license_name");
    String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
    String path = System.getProperty("user.dir") + "/documents/licenses/" + fileName;
    path = path.replaceAll("%20", " ");
    if (ext.equalsIgnoreCase("pdf")) {
        FileInputStream baos = new FileInputStream(path);

        OutputStream os = response.getOutputStream();

        byte buffer[] = new byte[8192];
        int bytesRead;

        while ((bytesRead = baos.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }

        os.flush();
        os.close();
    } else {
        try {
            // Document Settings //
            Document document = new Document();
            PdfWriter.getInstance(document, response.getOutputStream());
            document.open();

            // Loading MC //
            PdfPTable table = new PdfPTable(1);
            table.setWidthPercentage(100);
            // the cell object
            PdfPCell cell;

            Image img = Image.getInstance(path);
            int indentation = 0;
            float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin()
                    - indentation) / img.getWidth()) * 100;
            img.scalePercent(scaler);
            //img.scaleAbsolute(80f, 80f);
            cell = new PdfPCell(img);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
            document.add(table);
            //-----------------------------------//
            document.close();
        } catch (DocumentException de) {
            throw new IOException(de.getMessage());
        }
    }

}