Example usage for com.itextpdf.text.pdf PdfContentByte addImage

List of usage examples for com.itextpdf.text.pdf PdfContentByte addImage

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfContentByte addImage.

Prototype

public void addImage(final Image image) throws DocumentException 

Source Link

Document

Adds an Image to the page.

Usage

From source file:org.javad.pdf.TitlePageContent.java

License:Apache License

@Override
public OutputBounds generate(PdfContentByte content) {
    if (isSkipped()) {
        return new OutputBounds(getX(), getY(), 0, 0);
    }/*  ww  w  .j  av a  2 s .  c  o m*/
    int maxWidth = 0;
    float top = getY() - PdfUtil.convertFromMillimeters(
            (configuration.getHeight() - configuration.getMarginBottom() - configuration.getMarginTop()) / 2);
    if (getImage() != null) {
        try {
            com.itextpdf.text.Image img = determineScaledImage(getImage());
            if (img != null) {
                content.addImage(img);
                top = img.getAbsoluteY() - PdfUtil.convertFromMillimeters(25.0f);
            }
        } catch (Exception e) {
            logger.log(Level.FINER, "An error occured scaling the image. ", e);
        }
    }
    content.setColorStroke(BaseColor.BLACK);

    Font f = FontRegistry.getInstance().getFont(PdfFontDefinition.AlbumTitle);
    content.setFontAndSize(f.getBaseFont(), f.getSize());

    content.setHorizontalScaling(110.0f);
    if (getTitle() != null && !getTitle().isEmpty()) {
        maxWidth = (int) f.getBaseFont().getWidthPoint(getTitle().toUpperCase(), f.getSize());
        PdfUtil.renderConstrainedText(content, getTitle().toUpperCase(), f, getX(), top, maxWidth);
    }
    if (getSubTitle() != null && !getSubTitle().isEmpty()) {
        Font subFont = FontRegistry.getInstance().getFont(PdfFontDefinition.AlbumSubtitle);
        top -= subFont.getCalculatedSize() + PdfUtil.convertFromMillimeters(3.0f);
        content.setFontAndSize(subFont.getBaseFont(), subFont.getSize());
        maxWidth = Math.max(maxWidth,
                (int) content.getEffectiveStringWidth(getSubTitle().toUpperCase(), false));
        PdfUtil.renderConstrainedText(content, getSubTitle().toUpperCase(), subFont, getX(), top, maxWidth);
    }
    if (getDescription() != null && !getDescription().isEmpty()) {
        Font subFont = FontRegistry.getInstance().getFont(PdfFontDefinition.AlbumDescription);
        top -= PdfUtil.convertFromMillimeters(15.0f);
        float width = PdfUtil.convertFromMillimeters(
                (configuration.getWidth() - configuration.getMarginLeft() - configuration.getMarginRight())
                        / 2);
        content.setFontAndSize(subFont.getBaseFont(), subFont.getSize());
        top += PdfUtil.renderConstrainedText(content, getDescription(), subFont,
                width + PdfUtil.convertFromMillimeters(configuration.getMarginLeft()), top,
                (int) (width * 0.7f));
    }
    if (!getItems().isEmpty()) {
        Font subFont = FontRegistry.getInstance().getFont(PdfFontDefinition.AlbumContents);
        top -= subFont.getCalculatedSize() + PdfUtil.convertFromMillimeters(6.0f);
        content.setFontAndSize(subFont.getBaseFont(), subFont.getSize());
        for (String s : getItems()) {
            maxWidth = Math.max(maxWidth, (int) subFont.getBaseFont().getWidthPoint(s, subFont.getSize()));
            PdfUtil.renderConstrainedText(content, s, subFont, getX(), top, maxWidth);
            top -= PdfUtil.convertFromMillimeters(3.0f);
        }
    }
    content.setHorizontalScaling(100.0f);

    OutputBounds rect = new OutputBounds(getX() - maxWidth / 2, getY(), maxWidth, getY() - top);
    return rect;
}

From source file:org.javad.stamp.pdf.StampBox.java

License:Apache License

@Override
public OutputBounds generate(PdfContentByte content) {
    if (isSkipped()) {
        return new OutputBounds(getX(), getY(), 0, 0);
    }//  w  ww  .java 2s. c  om
    OutputBounds rect = new OutputBounds(getX(), getY(),
            PdfUtil.convertFromMillimeters(getWidth() + getPadding()),
            PdfUtil.convertFromMillimeters(getHeight() + getVerticalPadding()));
    if (bisect != Bisect.none && isBorder()) {
        drawBisect(content, rect);
    }
    if (getSetTenantPosition() == null) {
        drawShape(content, rect);
    }

    float verticalPadding = PdfUtil.convertFromMillimeters(getVerticalPadding());
    float w = rect.width;
    Font f = FontRegistry.getInstance().getFont(PdfFontDefinition.Stampbox);
    float center = getX() + w / 2;
    float top = getY() + verticalPadding + f.getCalculatedSize() * 6
            + PdfUtil.convertFromMillimeters(getTextPadding());

    if (image != null) {
        try {
            com.itextpdf.text.Image img = determineScaledImage(rect, f.getCalculatedSize(), top, isImageOnly());
            if (img != null) {
                content.addImage(img);
            }
        } catch (Exception e) {
            logger.log(Level.FINER, "An error occured scaling the image. ", e);
        }
    }
    if (!isImageOnly()) {
        if (shape == Shape.diamond || shape == Shape.triangleInverted) {
            top = getY() + rect.height / 2.0f + f.getCalculatedSize() * 1.5f;
        }
        top += PdfUtil.renderConstrainedText(content, getDenomination(), f, center, top, getWidth());
        top -= f.getCalculatedSize() + 1;
        float d_delta = PdfUtil.renderConstrainedText(content, getDescription(), f, center, top, getWidth());
        float rows = (float) Math.ceil(d_delta / f.getCalculatedSize());
        top += d_delta;
        Font f2 = FontRegistry.getInstance().getFont(PdfFontDefinition.StampboxOther);
        float delta = PdfUtil.renderConstrainedText(content, getDescriptionSecondary(), f2, center, top,
                getWidth());
        if (delta < 1.0f && rows > -3.00) {
            delta = -1 * (f.getSize() + 1);
        }
        if (d_delta >= -1 * (f.getSize() + 1)) { // handle one line descriptions
            top -= f.getSize() + 1;
        }
        top += delta;
        PdfUtil.renderConstrainedText(content, getCatalogueNumber(), f, center, top, getWidth());
    }
    return rect;
}

From source file:org.obiba.mica.PdfUtils.java

License:Open Source License

public static void addImage(byte[] input, OutputStream output, Image image, String placeholder)
        throws IOException, DocumentException {
    try (PdfReaderAutoclosable pdfReader = new PdfReaderAutoclosable(input);
            PdfStamperAutoclosable pdfStamper = new PdfStamperAutoclosable(pdfReader, output)) {
        AcroFields form = pdfStamper.getAcroFields();
        List<AcroFields.FieldPosition> positions = form.getFieldPositions(placeholder);

        positions.forEach(p -> {//ww  w .  j av a 2s  . c om
            image.scaleToFit(p.position.getWidth(), p.position.getHeight());
            image.setAbsolutePosition(
                    p.position.getLeft() + (p.position.getWidth() - image.getScaledWidth()) / 2,
                    p.position.getBottom() + (p.position.getHeight() - image.getScaledHeight()) / 2);
            PdfContentByte cb = pdfStamper.getOverContent(p.page);

            try {
                cb.addImage(image);
            } catch (DocumentException e) {
                throw Throwables.propagate(e);
            }
        });
    }
}

From source file:org.primaresearch.pdf.PageToPdfConverter.java

License:Apache License

/**
 * Adds the document page image to the current PDF page (spanning the whole page). 
 *///from  w ww  .j  ava  2s .c  om
private void addImage(String filepath, PdfWriter writer, Document doc, Page page)
        throws MalformedURLException, IOException, DocumentException {

    PdfContentByte cb = writer.getDirectContentUnder();
    cb.saveState();

    Image img = Image.getInstance(filepath);
    img.setAbsolutePosition(0f, 0f);
    //if (img.getScaledWidth() > 300 || img.getScaledHeight() > 300) {
    //img.scaleToFit(300, 300);
    //}
    img.scaleToFit(page.getLayout().getWidth(), page.getLayout().getHeight());

    cb.addImage(img);

    cb.restoreState();

}

From source file:org.yale.cs.graphics.gephi.imagepreview.ImageNodes.java

License:Open Source License

public void renderImagePDF(ImageItem item, PDFTarget target, PreviewProperties properties, File directory) {

    Image image = item.renderPDF(directory);

    if (image == null) {
        logger.log(Level.WARNING, "Unable to load image: {0}", item.getSource());
        return;/*from w  w  w. j a  v a  2  s.c o  m*/
    }

    Float x = item.getData(NodeItem.X);
    Float y = item.getData(NodeItem.Y);
    Float size = item.getData(NodeItem.SIZE);

    float alpha = properties.getFloatValue(IMAGE_OPACITY) / 100f;

    PdfContentByte cb = target.getContentByte();

    if (alpha < 1f) {
        cb.saveState();
        PdfGState gState = new PdfGState();
        gState.setFillOpacity(alpha);
        gState.setStrokeOpacity(alpha);
        cb.setGState(gState);
    }

    image.setAbsolutePosition(x - size / 2, -y - size / 2);
    image.scaleToFit(size, size);
    try {
        cb.addImage(image);
    } catch (DocumentException ex) {
        logger.log(Level.SEVERE, "Unable to add image to document: " + item.getSource(), ex);
    }

    if (alpha < 1f) {
        cb.restoreState();
    }
}

From source file:pdf.watermark.java

License:Open Source License

public watermark() {
    try {/*from  w  ww .  j a  v a  2  s.co  m*/
        PdfReader Read_PDF_To_Watermark = new PdfReader(
                "D:\\Dropbox\\Studium\\Bachelor Thesis\\Resourcen\\pdfexport\\xmltopdf\\test.pdf");
        int number_of_pages = Read_PDF_To_Watermark.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(Read_PDF_To_Watermark, new FileOutputStream(
                "D:\\Dropbox\\Studium\\Bachelor Thesis\\Resourcen\\pdfexport\\xmltopdf\\New_PDF_With_Watermark_Image.pdf"));
        int i = 0;
        Image watermark_image = Image
                .getInstance("D:\\Dropbox\\Studium\\Bachelor Thesis\\Resourcen\\pdfexport\\xmltopdf\\desy.png");
        watermark_image.setAbsolutePosition(50, 150);
        watermark_image.scaleToFit(500, 500);
        PdfContentByte add_watermark;
        while (i < number_of_pages) {
            i++;
            add_watermark = stamp.getUnderContent(i);
            add_watermark.addImage(watermark_image);
        }
        stamp.close();
    } catch (IOException | DocumentException i1) {
        i1.printStackTrace();
    }
}

From source file:pdfMaker.MakePdfFile.java

MakePdfFile(String text1, String text2, String text3) throws IOException, DocumentException, RuntimeException {

    // /*  w  w  w  .  j  ava2  s  . co m*/
    url = text1;

    Document document = null;
    String fileDir = "TEST_MAT.pdf";
    // step 1
    document = new Document(PageSize.A4, 20, 20, 20, 20);
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileDir));

    // step 3
    document.open();
    // step 4
    PdfContentByte cb = writer.getDirectContent();

    Image image = ZxingUti.getQRCode(url); //  SHIFT_JIS
    com.itextpdf.text.Image iTextImage = com.itextpdf.text.Image.getInstance(image, null);

    // http://d.hatena.ne.jp/MoonMtLab/20130920/1379626380
    //Image??
    com.itextpdf.text.Image img = iTextImage;

    //??()
    img.setAbsolutePosition(document.getPageSize().getWidth() - 30, document.getPageSize().getHeight() - 30);
    System.out.println(document.getPageSize().getWidth());
    System.out.println(document.getPageSize().getHeight());
    //?
    img.scaleAbsolute(30, 30);

    //PdfContentByte??
    PdfContentByte pdfContentByte = writer.getDirectContent();

    //???
    pdfContentByte.addImage(img);

    /* 
     writer.setEncryption("Hello".getBytes(), "World".getBytes(),
     PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STANDARD_ENCRYPTION_128);
     // 
     */
    document.close();

}

From source file:se.billes.pdf.renderer.model.Barcode.java

License:Open Source License

public void onRender(PdfContentByte cb) throws PdfRenderException {

    float[] positions = new BlockFactory().getBoundsInPs(this);

    BarcodeEAN barcode = new BarcodeEAN();
    barcode.setCodeType(BarCodeType.getBarCodeType(barCodeType).codeType);
    barcode.setCode(getCode());//  www .  j  a v a  2  s.co  m
    barcode.setSize(getFontSize());
    barcode.setGuardBars(isShowGuardBars());
    barcode.setBarHeight(positions[3]);
    barcode.setTextAlignment(Element.ALIGN_RIGHT);
    if (getBaseFont() != null) {
        barcode.setFont(getBaseFont());
    }

    if (align.equals("top")) {
        barcode.setBaseline(-1f);
    }

    PdfDocument request = getPage().getPdfDocument();
    float pageHeight = request.getSize()[1];
    float pageHeightInPs = SizeFactory.millimetersToPostscriptPoints(pageHeight);

    com.itextpdf.text.Image image = barcode.createImageWithBarcode(cb, getBarBaseColor(), getCodeBaseColor());
    image.setRotationDegrees(rotation);
    image.setAbsolutePosition(positions[0], pageHeightInPs - (positions[1] + positions[3] + fontSize));
    try {
        cb.addImage(image);
    } catch (DocumentException e) {
        throw new PdfRenderException(e);
    }
}

From source file:se.billes.pdf.renderer.process.TemplatePageRenderer.java

License:Open Source License

public void render(PdfWriter writer, Document document) throws PdfRenderException {
    writer.setPageEvent(page);/* w  w w . j  a v a 2  s. c  o m*/
    Template template = page.getTemplate();

    try {
        PdfReader reader = new PdfReader(template.getTemplatePath());
        PdfImportedPage pageImportedPage = writer.getImportedPage(reader, template.getPage());
        Image pdfMirror;

        float width = SizeFactory.CUT_MARK;
        float height = SizeFactory.CUT_MARK;

        pdfMirror = Image.getInstance(pageImportedPage);
        pdfMirror.setAbsolutePosition(SizeFactory.millimetersToPostscriptPoints(width),
                SizeFactory.millimetersToPostscriptPoints(height));
        document.newPage();
        ImageFactory.getInstances().add(new ImageInstance(pdfMirror, reader));
        PdfContentByte cb = writer.getDirectContent();
        try {
            cb.addImage(pdfMirror);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        if (page.getBlocks() != null) {
            for (BaseElement block : page.getBlocks()) {
                block.onRender(cb);
            }
        }

    } catch (BadElementException e) {
        e.printStackTrace();
        throw new PdfRenderException(e);
    } catch (IOException e) {
        throw new PdfRenderException(e);
    }

}

From source file:tn.esprit.twin1.brogrammers.eventify.Eventify.util.TicketGenerator.java

public static void GenerateTicket(Ticket ticket) {
    Document document = new Document();
    try {/*from w w w  .ja va2s  . c  o  m*/
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILE));
        Rectangle pagesize = new Rectangle(700, 300);
        document.open();
        Paragraph emptyline = new Paragraph();
        emptyline.add(new Paragraph(" "));
        document.setPageSize(pagesize);
        document.newPage();
        //PIC
        PdfContentByte canvas = writer.getDirectContentUnder();
        Image image = Image.getInstance(IMAGE);
        //image.scaleAbsolute(pagesize.rotate());
        image.setAbsolutePosition(0, 0);
        canvas.addImage(image);
        //PIC
        document.addTitle("Your Access To" + ticket.getEvent().getTitle());
        document.addSubject(ticket.getEvent().getTheme());
        document.addKeywords(ticket.getEvent().getTitle() + "Ticket");
        document.addAuthor("Mohamed Firas Ouertani");
        document.addCreator("Mohamed Firas Ouertani");
        Paragraph prefacetitle = new Paragraph();
        prefacetitle.add(new Paragraph("Your Ticket For " + ticket.getEvent().getTitle(), bigFont));
        document.add(prefacetitle);
        document.add(emptyline);

        Paragraph prefacetime = new Paragraph();
        prefacetime.add(new Paragraph(ticket.getEvent().getStartTime().toString(), greyFont));
        document.add(prefacetime);
        document.add(emptyline);
        document.add(emptyline);
        Paragraph prefacetype = new Paragraph();
        prefacetype.add(new Paragraph("You Reserved For: " + ticket.getTypeTicket(), catFont));
        document.add(prefacetype);
        //QR
        BarcodeQRCode qrcode = new BarcodeQRCode(
                "REF:#" + ticket.getEvent().getId() + "" + ticket.getEvent().getTitle().trim(), 1, 1, null);
        Image qrcodeImage = qrcode.getImage();
        qrcodeImage.setAbsolutePosition(520, 70);
        qrcodeImage.scalePercent(400);
        document.add(qrcodeImage);
        //QR

        //Bar
        PdfContentByte cb = writer.getDirectContent();
        Barcode128 code128 = new Barcode128();

        BarcodeEAN codeEAN = new BarcodeEAN();
        codeEAN.setCode("REF:#" + ticket.getEvent().getId() + "" + ticket.getEvent().getTitle().trim());
        codeEAN.setCodeType(BarcodeEAN.EAN13);
        Image codeEANImage = code128.createImageWithBarcode(cb, null, null);
        codeEANImage.setAbsolutePosition(10, 10);
        codeEANImage.scalePercent(125);
        document.add(codeEANImage);
        //Bar

        document.close();

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

}