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, final double a, final double b, final double c, final double d,
        final double e, final double f) throws DocumentException 

Source Link

Document

Adds an Image to the page.

Usage

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

License:Open Source License

private byte[] fixBackground(byte[] pdf, Toc tableOfContents) throws IOException, DocumentException {

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

        final byte[] tocTemplate = templateRepository.findOne(pdfTemplate.getTocTemplate().getUrl());
        final byte[] modelPageTemplate = templateRepository.findOne(pdfTemplate.getModel().getUrl());

        final Image tocBackgroundImage = iTextUtil.getImageFromPdf(tocTemplate);
        tocBackgroundImage.setAbsolutePosition(0, 0);

        final Image modelPageBackgroundImage = iTextUtil.getImageFromPdf(modelPageTemplate);
        modelPageBackgroundImage.setAbsolutePosition(0, 0);

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

        final PdfContentByte tocContent = stamper.getUnderContent(tableOfContents.getFirstPageOfToc());
        tocContent.addImage(tocBackgroundImage, 612, 0, 0, 792, 0, 0);

        for (int pageNumber = tableOfContents.getFirstPageOfToc() + 1; pageNumber <= tableOfContents
                .getLastPageNumberOfModelPages(); pageNumber++) {

            final PdfContentByte content = stamper.getUnderContent(pageNumber);
            content.addImage(modelPageBackgroundImage, 612, 0, 0, 792, 0, 0);

        }/*from   w  w w  .j a va  2  s.co  m*/

        stamper.close();
        reader.close();

        return bos.toByteArray();
    }

}

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 ww w  .  j a v  a  2 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:classes.DocumentSignature.java

public static ByteArrayOutputStream getSignedDocument(Document document) throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    PdfReader reader = new PdfReader(document.getContent());
    PdfStamper stamper = new PdfStamper(reader, os);

    // get all signers of the document
    ArrayList<User> signers = DocumentSignature.getDocumentSigners(document.getDocumentId());

    try {/*from  w  w w .  j a v  a2  s  . c om*/
        for (User signer : signers) {
            if (signer.getSignature() == null) {
                continue;
            }

            // get user signature
            Image signatureImage = Image.getInstance(getImageBytes(signer.getSignature()));

            for (DocumentSignature signature : getDocumentSignatures(document.getDocumentId(),
                    signer.getUserId())) {
                int x = signature.getSignLocationX();
                int y = signature.getSignLocationY();
                //signatureImage.setAbsolutePosition(x, y);
                PdfContentByte canvas = stamper.getOverContent(signature.getPageNumber());

                //System.out.println("bottom: " + canvas.getPdfDocument().bottom());
                //System.out.println("top: " + canvas.getPdfDocument().top());
                //System.out.println("left: " + canvas.getPdfDocument().left());
                //System.out.println("right: " + canvas.getPdfDocument().right());

                //canvas.addImage(signatureImage);
                canvas.addImage(signatureImage, SIGNATURE_IMAGE_WIDTH, 0, 0, SIGNATURE_IMAGE_HEIGHT, x, y);
            }
        }

        return os;
    } finally {
        stamper.close();
    }
}

From source file:com.cib.statementstamper.windows.StatementStamperMainWindow.java

License:Open Source License

protected ByteArrayOutputStream doStamper(ByteArrayOutputStream baos) throws IOException, DocumentException {

    map.clear();/*from ww  w  .j av  a2 s. c om*/
    ByteArrayOutputStream baosFinal = new ByteArrayOutputStream();
    PdfReader reader = new PdfReader(baos.toByteArray());

    PdfContentStreamProcessor processor = new PdfContentStreamProcessor(this);
    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
        actualPage = i;
        PdfDictionary pageDic = reader.getPageN(i);
        PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES);
        processor.processContent(ContentByteUtils.getContentBytesForPage(reader, i), resourcesDic);
    }

    Document newDocument = new Document(PageSize.A4);
    PdfWriter writer = PdfWriter.getInstance(newDocument, baosFinal);

    newDocument.open();
    PdfContentByte canvas = writer.getDirectContent();
    //      Font myFont = FontFactory.getFont(FontFactory.COURIER, 7, Font.BOLD);
    Iterator<Entry<Integer, Map<Float, StringBuffer>>> it = map.entrySet().iterator();

    while (it.hasNext()) {
        Map.Entry<Integer, Map<Float, StringBuffer>> pairs = (Map.Entry<Integer, Map<Float, StringBuffer>>) it
                .next();

        Iterator<Entry<Float, StringBuffer>> iter = pairs.getValue().entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<Float, StringBuffer> actualEntry = iter.next();
            canvas.beginText();
            canvas.setFontAndSize(myFontBase, 7);
            canvas.showTextAligned(Element.ALIGN_LEFT, actualEntry.getValue().toString(), 25,
                    actualEntry.getKey() + 60, 0);
            canvas.endText();
        }
        newDocument.newPage();
    }
    newDocument.close();

    reader = new PdfReader(baosFinal.toByteArray());

    PdfReaderContentParser parser = new PdfReaderContentParser(reader);
    TextMarginFinder finder;
    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
        finder = parser.processContent(i, new TextMarginFinder());
        if (finder.getLly() <= 68) {
            getWindow().showNotification("Hiba", "A(z) " + i + ".ik oldalon tl sok a szveg !!!",
                    Notification.TYPE_ERROR_MESSAGE);
            return null;
        }
    }

    reader = new PdfReader(baosFinal.toByteArray());
    PdfStamper stamper = new PdfStamper(reader, baosFinal);
    int n = reader.getNumberOfPages();
    for (int i = 1; i <= n; i++) {
        PdfContentByte overContent = stamper.getOverContent(i);
        overContent.addImage(logo, 131, 0, 0, 32, 44, 775);
        getFooterTable(i, n).writeSelectedRows(0, -1, 27, 68, stamper.getOverContent(i)); // ez a jo
        getIspLogoTable(i, n).writeSelectedRows(0, -1, 425, 45, stamper.getOverContent(i));
    }
    stamper.close();
    reader.close();
    return baosFinal;
}

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);//from  ww  w.  j  av a2 s  .c om

    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:org.h819.commons.file.MyPDFUtils.java

/**
 * ??//from w  w w  .  ja v a2  s  . com
 *
 * @param srcPdf         ?
 * @param destPdf        
 * @param waterMarkText  ?
 * @param waterMarkImage ?
 */
public static void addWaterMarkFile(File srcPdf, File destPdf, String waterMarkText, File waterMarkImage)
        throws IOException, DocumentException {

    if (waterMarkText == null && waterMarkImage == null)
        throw new FileNotFoundException(waterMarkText + " " + waterMarkImage + " all null.");

    if (srcPdf == null || !srcPdf.exists() || !srcPdf.isFile())
        throw new FileNotFoundException("pdf file :  '" + srcPdf + "' does not exsit.");

    if (!FilenameUtils.getExtension(srcPdf.getAbsolutePath()).toLowerCase().equals("pdf"))
        return;

    if (waterMarkImage != null) {
        if (!waterMarkImage.exists() || !waterMarkImage.isFile())
            throw new FileNotFoundException("img file :  '" + srcPdf + "' does not exsit.");

        if (!FilenameUtils.getExtension(waterMarkImage.getAbsolutePath()).toLowerCase().equals("png"))
            throw new FileNotFoundException("image file '" + srcPdf
                    + "'  not png.(???? pdf )");
    }

    PdfReader reader = getPdfReader(srcPdf);

    int n = reader.getNumberOfPages();
    PdfStamper stamper = getPdfStamper(srcPdf, destPdf);

    //
    //        HashMap<String, String> moreInfo = new HashMap<String, String>();
    //        moreInfo.put("Author", "H819 create");
    //        moreInfo.put("Producer", "H819 Producer");
    //        Key = CreationDate, Value = D:20070425182920
    //        Key = Producer, Value = TH-OCR 2000 (C++/Win32)
    //        Key = Author, Value = TH-OCR 2000
    //        Key = Creator, Value = TH-OCR PDF Writer

    // stamp.setMoreInfo(moreInfo);

    // text
    Phrase text = null;
    if (waterMarkText != null) {
        //
        Font bfont = getPdfFont();
        bfont.setSize(35);
        bfont.setColor(new BaseColor(192, 192, 192));
        text = new Phrase(waterMarkText, bfont);
    }
    // image watermark
    Image img = null;
    float w = 0;
    float h = 0;
    if (waterMarkImage != null) {
        img = Image.getInstance(waterMarkImage.getAbsolutePath());
        w = img.getScaledWidth();
        h = img.getScaledHeight();
        //  img.
        img.setRotationDegrees(45);

    }

    // transparency
    PdfGState gs1 = new PdfGState();
    gs1.setFillOpacity(0.5f);
    // properties
    PdfContentByte over;
    Rectangle pageSize;
    float x, y;
    // loop over every page
    for (int i = 1; i <= n; i++) {
        pageSize = reader.getPageSizeWithRotation(i);
        x = (pageSize.getLeft() + pageSize.getRight()) / 2;
        y = (pageSize.getTop() + pageSize.getBottom()) / 2;
        //  pdf pdf ???
        over = stamper.getOverContent(i);
        // ?
        // over = stamp.getUnderContent(i);
        // ?? over.beginText(); over.endText(); ?
        // ,?,:????
        over.saveState(); //??
        over.setGState(gs1);

        if (waterMarkText != null && waterMarkImage != null) { // 
            if (i % 2 == 1) {
                ColumnText.showTextAligned(over, Element.ALIGN_CENTER, text, x, y, 45);
            } else
                over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
        } else if (waterMarkText != null) { //?

            ColumnText.showTextAligned(over, Element.ALIGN_CENTER, text, x, y, 45);
            //?? ,?, :?????
            // ...

        } else { //?
            over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
        }

        over.restoreState();//???
    }

    stamper.close();
    reader.close();

}