Example usage for com.itextpdf.text Document add

List of usage examples for com.itextpdf.text Document add

Introduction

In this page you can find the example usage for com.itextpdf.text Document add.

Prototype


public boolean add(Element element) throws DocumentException 

Source Link

Document

Adds an Element to the Document.

Usage

From source file:com.icebreak.p2p.front.controller.trade.download.InvestReceiptPDFCreator.java

/**
 * ???/* ww w.j av  a  2s.co  m*/
 * @param tradeId
 * @param detailId
 * @param servletPath
 * @return ?  byte[]
 * @throws Exception
 */
public byte[] creatFileData4Receipt(long tradeId, long detailId, String servletPath) throws Exception {

    FileInputStream fis = null;
    BufferedInputStream buff = null;

    String fileKey = tradeId + "_" + detailId;//System.currentTimeMillis() + "";
    String filePath = servletPath + "/resources/pdf/investReceipt_" + fileKey + ".pdf";
    this.receiptFilePath = filePath;

    File file = new File(filePath);

    if (!file.exists()) {

        String timeLimit = "";
        String interestRate = "";
        String guaranteeName = "";
        String investFlowCode = null;
        String investor = "";
        String investorReal = "";
        String investorCertNo = "";
        String loanner = "";
        String loannerReal = "";
        String loannerCertNo = "";
        String investAmount = "";
        String totalAmountStr = "";
        String effectiveDate = "";
        String expireDate = "";

        Trade trade = tradeService.getByTradeId(tradeId);
        effectiveDate = DateUtil.simpleFormat(trade.getEffectiveDateTime());
        expireDate = DateUtil.simpleFormat(trade.getExpireDateTime());
        LoanDemandDO loanDemand = loanDemandManager.queryLoanDemandByDemandId(trade.getDemandId());
        guaranteeName = loanDemand.getGuaranteeName();
        if ("W".equals(loanDemand.getTimeLimitUnit()) || "M".equals(loanDemand.getTimeLimitUnit())) {
            timeLimit = loanDemand.getTimeLimit() + "";
        } else if ("Y".equals(loanDemand.getTimeLimitUnit())) {
            timeLimit = loanDemand.getTimeLimit() + "";
        } else {
            timeLimit = loanDemand.getTimeLimit() + "";
        }
        interestRate = CommonUtil.mul(loanDemand.getInterestRate(), 100) + "%";
        List<UserInvestEntry> userInvests = tradeService.getEntriesByTradeIdAndDetailId(tradeId, detailId);
        long totalAmount = 0;
        if (userInvests != null && userInvests.size() > 0) {
            UserInvestEntry tradeItem = userInvests.get(0);
            investAmount = MoneyUtil.getFormatAmount(tradeItem.getAmount());
            long investorId = userInvests.get(0).getInvestorId();
            long loannerId = userInvests.get(0).getLoanerId();
            investorCertNo = getCertNoByUserId(investorId);
            loannerCertNo = getCertNoByUserId(loannerId);
            investor = userInvests.get(0).getInvestorUserName();
            investorReal = userInvests.get(0).getInvestorRealName();
            loannerReal = userInvests.get(0).getLoanerRealName();
            loanner = userInvests.get(0).getLoanerUserName();
            totalAmount = userInvests.get(0).getAmount();
        }

        //?
        /*interest = caculateInterest(new Money(totalAmount), loanDemand.getInterestRate(),
        loanDemand.getTimeLimit(), loanDemand.getTimeLimitUnit());*/

        long divisionAmount = 0;
        long profitAmount = 0;
        List<TradeDetail> details = tradeService.getInvestProfitTrade(detailId);
        if (details != null && details.size() > 0) {
            for (TradeDetail detail : details) {
                divisionAmount += detail.getAmount();
                if (detail.getProfitType() > 0) {
                    profitAmount += detail.getAmount();
                }
            }
        }
        totalAmount += divisionAmount;

        TradeFlowCode tradeFlow = tradeService.queryInvestFlowCodesByTradeDetailId(detailId);
        if (tradeFlow != null) {
            investFlowCode = tradeFlow.getTradeFlowCode();
        }

        String guaranteeLicenseNo = "";
        Map<String, Object> cond = new HashMap<String, Object>();
        cond.put("roleId", 8L);

        cond.put("tradeId", trade.getId());
        List<TradeQueryDetail> det = loanDemandManager.getTradeDetailByConditions(cond);
        if (det != null && det.size() > 0) {
            tradeFlow = tradeService.queryInvestFlowCodesByTradeDetailId(det.get(0).getId());
            if (tradeFlow != null) {
                guaranteeLicenseNo = tradeFlow.getTradeFlowCode();
            }
        }

        LoanDemandDO demand = loanDemandManager.queryLoanDemandByDemandId(trade.getDemandId());
        long divisionTemplateId = demand.getDivisionTemplateId();
        DivisionTemplateLoanDO divisionTemplateLoan = divisionTemplateLoanService
                .getByBaseId(divisionTemplateId);
        List<DivsionRuleRole> investRolelist = divisionService
                .getRuleRole(String.valueOf(divisionTemplateLoan.getInvestTemplateId()));
        List<DivsionRuleRole> repayRolelist = divisionService
                .getRuleRole(String.valueOf(divisionTemplateLoan.getRepayTemplateId()));
        //??
        double totalAnnualInterest = 0;
        investRolelist.addAll(repayRolelist);
        if (investRolelist != null && investRolelist.size() > 0) {
            for (DivsionRuleRole druleRole : investRolelist) {
                if (DivisionPhaseEnum.INVESET_PHASE.code().equals(druleRole.getPhase())) {
                    if ("11".equals(String.valueOf(druleRole.getRoleId()))) {
                        totalAnnualInterest += druleRole.getRule();
                    }

                }
            }
        }

        totalAmountStr = MoneyUtil.getFormatAmount(totalAmount);
        String divisionAmountStr = MoneyUtil.getFormatAmount(divisionAmount);

        FileOutputStream fos = null;
        Document doc = new Document(PageSize.A4, 20, 20, 140, 20);
        try {
            fos = new FileOutputStream(filePath);
            PdfWriter writer = PdfWriter.getInstance(doc, fos);
            doc.open();
            //   
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font titleChinese = new Font(bfChinese, 20, Font.BOLD); // ?     
            Paragraph title = new Paragraph(AppConstantsUtil.getProductName() + "?", titleChinese);// 
            title.setAlignment(Element.ALIGN_CENTER); // 
            title.setLeading(1f);//?//?
            doc.add(title);

            Font fontZH = new Font(bfChinese, 12, Font.NORMAL);
            float[] widths = { 20f, 30f, 25f, 25f };
            PdfPTable table = new PdfPTable(widths);

            table.setSpacingBefore(20f);// ?
            table.setTotalWidth(500);// 
            table.setWidthPercentage(100);//%100
            // table.getDefaultCell().setBorder(0);//
            PdfPCell cell;
            //               cell = new PdfPCell(new Paragraph("?",fontZH));
            //               cell.setColspan(4);
            //               table.addCell(cell);

            cell = new PdfPCell(new Paragraph("??", fontZH));
            cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(AppConstantsUtil.getPlatformName(), fontZH));
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("?", fontZH));
            cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(loanDemand.getRepayDivisionWayMsg(), fontZH));
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("", fontZH));
            cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(interestRate, fontZH));
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("?", fontZH));
            cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(timeLimit, fontZH));
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("??", fontZH));
            cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(guaranteeName, fontZH));
            cell.setColspan(3);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("??", fontZH));
            cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
            table.addCell(cell);

            cell = new PdfPCell(
                    new Paragraph(StringUtil.nullToEmpty(loanDemand.getGuaranteeLicenseNo()), fontZH));
            cell.setColspan(3);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("", fontZH));
            cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph((loanDemand.getLoanAmount() / 100) + "", fontZH));
            cell.setColspan(3);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("", fontZH));
            cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(loanDemand.getLoanPurpose(), fontZH));
            cell.setColspan(3);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("??", fontZH));
            cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(investFlowCode, fontZH));
            cell.setColspan(3);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("?", fontZH));
            cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
            cell.setColspan(2);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("??", fontZH));
            cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
            cell.setColspan(2);

            table.addCell(cell);
            Paragraph iparas = new Paragraph("??" + investor, fontZH);
            iparas.add(Chunk.NEWLINE);
            iparas.add("??" + investorReal);
            iparas.add(Chunk.NEWLINE);
            iparas.add("??" + StringUtil.subString(investorCertNo, 7, "****"));
            iparas.add(Chunk.NEWLINE);
            iparas.add("?" + effectiveDate);
            iparas.add(Chunk.NEWLINE);
            iparas.add("" + expireDate);
            iparas.add(Chunk.NEWLINE);
            iparas.add("()" + investAmount);
            iparas.add(Chunk.NEWLINE);
            iparas.add("()" + divisionAmountStr);
            iparas.add(Chunk.NEWLINE);
            iparas.add("()" + totalAmountStr);

            cell = new PdfPCell(iparas);
            cell.setColspan(2);
            cell.setRowspan(8);

            cell.setMinimumHeight(120);
            table.addCell(cell);
            Paragraph paras = new Paragraph("??" + loanner, fontZH);
            paras.add(Chunk.NEWLINE);
            paras.add("??" + loannerReal);
            paras.add(Chunk.NEWLINE);
            paras.add("??" + StringUtil.subString(loannerCertNo, 7, "****"));
            paras.add(Chunk.NEWLINE);
            paras.add("?" + effectiveDate);
            paras.add(Chunk.NEWLINE);
            paras.add("" + expireDate);
            paras.add(Chunk.NEWLINE);
            paras.add(Chunk.NEWLINE);
            paras.add(Chunk.NEWLINE);
            paras.add("()" + totalAmountStr);
            cell = new PdfPCell(paras);
            cell.setColspan(2);
            cell.setRowspan(8);
            table.addCell(cell);
            doc.add(table);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            Paragraph tips = new Paragraph("  ?? ?"
                    + AppConstantsUtil.getPlatformName() + "", fontZH);// 
            tips.setLeading(1f);//?//?
            doc.add(tips);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            doc.add(Chunk.NEWLINE);
            tips = new Paragraph("  ??" + AppConstantsUtil.getPlatformAddress(), fontZH);// 
            tips.setLeading(1f);//?//?
            doc.add(tips);
            //               XMLWorkerHelper.getInstance().parseXHtml(writer, doc,
            //                     new ByteArrayInputStream(str.getBytes()));
            doc.close();
            logger.info("?");

        } catch (Exception e) {
            logger.error("?", e);
            throw new Exception("?:" + e.getMessage());
        } finally {

            if (fos != null) {
                fos.close();
            }
        }
    }

    byte[] data = new byte[1024];

    file = new File(filePath);
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] temp = new byte[1024];
        int size = 0;

        fis = new FileInputStream(file);
        buff = new BufferedInputStream(fis);

        int i = 0;

        while ((size = buff.read(temp)) != -1) {
            out.write(temp, 0, size);
            i += 1;
        }

        data = out.toByteArray();

        buff.close();
        fis.close();
        //file.delete();

        if (i == 0 && size == -1) { //PDF
            file.delete();
        }
    } catch (FileNotFoundException e) {
        logger.error("?", e);
    } catch (IOException e) {
        logger.error("delete file", e);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }

    return data;
}

From source file:com.ideationdesignservices.txtbook.pdf.TxtBookPdf.java

public Boolean createFrontCoverPage(Document document, String coverTitle, Bitmap photo)
        throws DocumentException, MalformedURLException, IOException {
    if (photo != null) {
        int imageMaxWidth;
        int imageMaxHeight;
        int imagePosX;
        int imagePosY;
        if (photo.getWidth() < photo.getHeight()) {
            imageMaxWidth = 900;/* w ww  .j av a 2  s .c om*/
            imageMaxHeight = 1200;
            imagePosX = 198;
            imagePosY = 379;
        } else {
            imageMaxWidth = 1200;
            imageMaxHeight = 900;
            imagePosX = 162;
            imagePosY = 379;
        }
        OutputStream stream = new ByteArrayOutputStream();
        ImageUtilities.scaleCenterCrop(photo, imageMaxWidth, imageMaxHeight).compress(CompressFormat.JPEG, 50,
                stream);
        Image coverImage = Image.getInstance(stream.toByteArray());
        coverImage.setAbsolutePosition(0.0f, 0.0f);
        PdfTemplate t = this.writer.getDirectContent().createTemplate((float) imageMaxWidth,
                (float) imageMaxHeight);
        t.newPath();
        t.moveTo(0.0f, (float) imageMaxHeight);
        t.lineTo(0.0f, 71.0f);
        t.lineTo(17.0f, 71.0f);
        t.lineTo(17.0f, 0.0f);
        t.lineTo(72.0f, 71.0f);
        t.lineTo((float) imageMaxWidth, 71.0f);
        t.lineTo((float) imageMaxWidth, (float) imageMaxHeight);
        t.lineTo(0.0f, (float) imageMaxHeight);
        t.closePath();
        t.clip();
        t.newPath();
        t.addImage(coverImage);
        t.setColorStroke(new BaseColor(0, 0, 0));
        t.setLineWidth(BUBBLE_TEXT_INDENT_ALTERNATE);
        t.newPath();
        t.moveTo(0.0f, (float) imageMaxHeight);
        t.lineTo(0.0f, 71.0f);
        t.lineTo(17.0f, 71.0f);
        t.lineTo(17.0f, 0.0f);
        t.lineTo(72.0f, 71.0f);
        t.lineTo((float) imageMaxWidth, 71.0f);
        t.lineTo((float) imageMaxWidth, (float) imageMaxHeight);
        t.lineTo(0.0f, (float) imageMaxHeight);
        t.closePathStroke();
        Image clipped = Image.getInstance(t);
        clipped.scalePercent(24.0f);
        clipped.setAbsolutePosition((float) imagePosX, (float) imagePosY);
        clipped.setCompressionLevel(this.settings.compressionLevel);
        clipped.setAlignment(5);
        document.add(clipped);
    }
    if (coverTitle != null && coverTitle.length() > 0) {
        PdfContentByte canvas = this.writer.getDirectContent();
        Paragraph coverTitleEl = new Paragraph(coverTitle, this.serifFont24);
        coverTitleEl.setAlignment(1);
        PdfPTable table = new PdfPTable(1);
        table.setTotalWidth(311.0f);
        PdfPCell cell = new PdfPCell();
        cell.setBorder(0);
        cell.addElement(coverTitleEl);
        cell.setPadding(0.0f);
        cell.setIndent(0.0f);
        table.addCell(cell);
        table.completeRow();
        table.writeSelectedRows(0, -1, 147.0f, 390.0f, canvas);
    }
    return Boolean.valueOf(true);
}

From source file:com.ideationdesignservices.txtbook.pdf.TxtBookPdf.java

public Boolean createBackCoverPage(Document document, String backCoverNote)
        throws DocumentException, MalformedURLException, IOException {
    document.newPage();//from  w w w  .j  ava 2 s.c  om
    Image backCoverImageFrame = Image
            .getInstance(ImageUtilities.getImageDataForFile(this.mContext, "pdf/txtbook_backpage_300.png"));
    backCoverImageFrame.scalePercent(24.0f);
    backCoverImageFrame.setAbsolutePosition(87.0f, 78.0f);
    backCoverImageFrame.setCompressionLevel(this.settings.compressionLevel);
    document.add(backCoverImageFrame);
    PdfContentByte canvas = this.writer.getDirectContent();
    PdfPTable table = new PdfPTable(1);
    table.setTotalWidth(215.0f);
    if (backCoverNote != null && backCoverNote.length() > 0) {
        Paragraph backCoverEl = new Paragraph(backCoverNote, this.serifFont14);
        PdfPCell cell = new PdfPCell();
        cell.setBorder(0);
        cell.addElement(backCoverEl);
        cell.setPadding(13.0f);
        cell.setIndent(0.0f);
        cell.setFixedHeight(310.0f);
        table.addCell(cell);
        table.completeRow();
    }
    Element backUrl = new Anchor("txt-book.com", this.sansFont11Gray);
    backUrl.setName("txt-book.com");
    backUrl.setReference("http://www.txt-book.com");
    Paragraph paragraph = new Paragraph();
    paragraph.setAlignment(2);
    paragraph.add(backUrl);
    PdfPCell cell2 = new PdfPCell();
    cell2.setBorder(0);
    cell2.setHorizontalAlignment(2);
    cell2.addElement(paragraph);
    cell2.setPadding(0.0f);
    cell2.setPaddingTop(0.0f);
    cell2.setIndent(0.0f);
    table.addCell(cell2);
    table.completeRow();
    table.writeSelectedRows(0, -1, 306.0f, 400.0f, canvas);
    return Boolean.valueOf(true);
}

From source file:com.ideationdesignservices.txtbook.pdf.TxtBookPdf.java

public void addStorybookPart(Document document, int i, Long date, Long previousDate, String senderString,
        String previousSenderString, String receiverString, String contentString, Bitmap contentBitmap,
        Boolean isVideo) throws DocumentException, MalformedURLException, IOException {
    Paragraph paragraph = new Paragraph();
    if (i == 0) {
        paragraph.add(new Chunk("T", this.serifFont24));
        paragraph.add(new Chunk("his story begins", this.serifFont11));
        if (!this.settings.useTimestamps.booleanValue()) {
            paragraph.add(new Chunk(MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR, this.serifFont11));
        }// w  w w .j a va  2s.  c  o  m
    } else if (!senderString.equals(previousSenderString)) {
        document.add(Chunk.NEWLINE);
    }
    Boolean dateChanged = Boolean.valueOf(false);
    if (this.settings.useTimestamps.booleanValue()) {
        SimpleDateFormat dateFormat;
        if (i == 0) {
            dateFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
            dateFormat.setTimeZone(TimeZone.getDefault());
            paragraph.add(new Chunk(" on " + dateFormat.format(new Date(date.longValue()))
                    + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR, this.serifFont11));
        } else {
            dateFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
            dateFormat.setTimeZone(TimeZone.getDefault());
            String dateString = dateFormat.format(new Date(date.longValue()));
            String previousDateString = PdfObject.NOTHING;
            if (previousDate != null) {
                previousDateString = dateFormat.format(new Date(previousDate.longValue()));
            }
            if (!previousDateString.equals(dateString)) {
                dateChanged = Boolean.valueOf(true);
                document.add(Chunk.NEWLINE);
                paragraph.add(new Chunk("O", this.serifFont24));
                paragraph.add(new Chunk("n " + dateString + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR,
                        this.serifFont11));
            }
        }
    }
    if (i == 0) {
        paragraph.add(new Chunk("when " + senderString + " texted " + receiverString + ", ", this.serifFont11));
    }
    if (contentString.length() > 0) {
        Boolean addPhrase = Boolean.valueOf(false);
        String phrase = null;
        if (dateChanged.booleanValue()) {
            paragraph.add(new Chunk(new StringBuilder(String.valueOf(senderString)).append(" texted ")
                    .append(receiverString).append(", ").toString(), this.serifFont11));
        } else if (!(i == 0 || dateChanged.booleanValue() || senderString.equals(previousSenderString))) {
            Boolean isOpening = Boolean
                    .valueOf(this.wasLastPhraseOpening.booleanValue() ? this.generator.nextBoolean() : true);
            int phraseIdx = this.lastPhraseIdx;
            if (isOpening.booleanValue() && !this.wasLastPhraseOpening.booleanValue()) {
                this.lastPhraseIdx = -1;
            }
            if (isOpening.booleanValue()) {
                do {
                    phraseIdx = this.generator.nextInt(this.openings.length);
                } while (phraseIdx == this.lastPhraseIdx);
                phrase = this.openings[phraseIdx];
            } else {
                do {
                    phraseIdx = this.generator.nextInt(this.closings.length);
                } while (phraseIdx == this.lastPhraseIdx);
                phrase = this.closings[phraseIdx];
            }
            this.lastPhraseIdx = phraseIdx;
            this.wasLastPhraseOpening = isOpening;
            phrase = phrase.replace("[speaker]", senderString);
            addPhrase = Boolean.valueOf(true);
        }
        if (addPhrase.booleanValue() && this.wasLastPhraseOpening.booleanValue()) {
            paragraph.add(new Chunk(phrase, this.serifFont11));
        }
        paragraph.add(new Chunk("\"" + contentString.trim() + "\"", this.serifFont11));
        if (addPhrase.booleanValue() && !this.wasLastPhraseOpening.booleanValue()) {
            paragraph.add(new Chunk(phrase, this.serifFont11));
        }
        document.add(paragraph);
    } else if (contentBitmap != null) {
        if (i != 0) {
            paragraph.add(new Chunk(new StringBuilder(String.valueOf(senderString)).append(" sent ")
                    .append(receiverString).append(":").toString(), this.serifFont11));
            document.add(paragraph);
            document.add(Chunk.NEWLINE);
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        if (isVideo.booleanValue()) {
            contentBitmap.compress(CompressFormat.PNG, 50, stream);
        } else {
            contentBitmap.compress(CompressFormat.JPEG, 50, stream);
        }
        Image contentImage = Image.getInstance(stream.toByteArray());
        contentImage.scaleToFit(445.0f, 195.0f);
        contentImage.setAlignment(1);
        if (isVideo.booleanValue()) {
            contentImage.setCompressionLevel(this.settings.compressionLevel);
        }
        document.add(contentImage);
        document.add(Chunk.NEWLINE);
    }
}

From source file:com.imageConverter.imageConverter.java

public static void main(String[] args) {

    try {/*from w w w.ja  va  2s  .c om*/
        //Create Document Object
        Document convertJpgToPdf = new Document();
        //Create PdfWriter for Document to hold physical file
        PdfWriter.getInstance(convertJpgToPdf,
                new FileOutputStream("C:\\Users\\HARSHVARDHAN.SOLANKI\\Desktop\\ConvertImagetoPDF.pdf"));
        convertJpgToPdf.open();
        //Get the input image to Convert to PDF
        Image convertJpg = Image.getInstance("C:\\Users\\HARSHVARDHAN.SOLANKI\\Desktop\\text2.jpg");
        //Add image to Document
        convertJpgToPdf.add(convertJpg);
        //Close Document
        convertJpgToPdf.close();
        System.out.println("Successfully Converted JPG to PDF in iText");
    } catch (Exception i1) {
        i1.printStackTrace();
    }

}

From source file:com.imipgroup.hieuvt.pdf.PdfUtils.java

private static void addTitlePage(Document document) {
    Paragraph preface = new Paragraph();
    addEmptyLine(preface, 1);//from  ww w.ja  v  a 2 s  .c  o  m
    preface.add(new Paragraph("Title of the document", catFont));

    addEmptyLine(preface, 1);
    preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("This document describes something which is very important ", smallBold));

    addEmptyLine(preface, 8);

    preface.add(new Paragraph(
            "This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
            redFont));

    try {
        document.add(preface);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    // Start a new page
    document.newPage();
}

From source file:com.imipgroup.hieuvt.pdf.PdfUtils.java

private static void addContent(Document document) {
    Anchor anchor = new Anchor("First Chapter", catFont);
    anchor.setName("First Chapter");

    // Second parameter is the number of the chapter
    Chapter catPart = new Chapter(new Paragraph(anchor), 1);

    Paragraph subPara = new Paragraph("Subcategory 1", subFont);
    Section subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("Hello"));

    subPara = new Paragraph("Subcategory 2", subFont);
    subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("Paragraph 1"));
    subCatPart.add(new Paragraph("Paragraph 2"));
    subCatPart.add(new Paragraph("Paragraph 3"));

    // add a list
    createList(subCatPart);/*ww w .  j  a v a 2s. c o m*/
    Paragraph paragraph = new Paragraph();
    addEmptyLine(paragraph, 5);
    subCatPart.add(paragraph);
    // add a table
    createTable(subCatPart);

    // now add all this to the document
    try {
        document.add(catPart);
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    // Next section
    anchor = new Anchor("Second Chapter", catFont);
    anchor.setName("Second Chapter");

    // Second parameter is the number of the chapter
    catPart = new Chapter(new Paragraph(anchor), 1);

    subPara = new Paragraph("Subcategory", subFont);
    subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("This is a very important message"));

    // now add all this to the document
    try {
        document.add(catPart);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:com.imipgroup.hieuvt.pdf.PdfUtils.java

public Document readPdf(String inputPath) {
    String outputPath = "files/Pdf/testRead.pdf";
    Document document = new Document();
    PdfWriter writer = null;//  w  w  w.ja  v a 2  s . c  o m
    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream(outputPath));
        document.open();
        PdfReader reader = new PdfReader(inputPath);
        int n = reader.getNumberOfPages();
        PdfImportedPage page;
        // Go through all pages
        for (int i = 1; i <= n; i++) {
            // only page number 2 will be included
            if (i == 2) {
                page = writer.getImportedPage(reader, i);
                Image instance = Image.getInstance(page);
                document.add(instance);
            }
        }
        document.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return document;
}

From source file:com.insider.kontrollactive.QualityReportActivity.java

private static void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);//from   w ww .  ja  v  a2 s .  c o  m
    // Lets write a big header
    preface.add(new Paragraph("Vr frste pdf!", catFont));

    addEmptyLine(preface, 1);
    // Will create: Report generated by: _name, _date
    preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("This document describes something which is very important ", smallBold));

    addEmptyLine(preface, 8);

    preface.add(new Paragraph(
            "This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
            redFont));

    document.add(preface);
    // Start a new page
    document.newPage();
}

From source file:com.iox.rms.mbean.UserBean.java

@SuppressWarnings("deprecation")
private byte[] generateInvoiceForCustomerPurchase(CustomerProduct cp) {
    byte[] data = null;

    if (cp != null) {
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {/*from www  . ja v a  2s  .  co m*/
            PdfWriter writer = PdfWriter.getInstance(document, baos);
            writer.setPageEvent(new HeaderFooter());
            writer.setBoxSize("footer", new Rectangle(36, 54, 559, 788));
            if (!document.isOpen()) {
                document.open();
            }
            document.setPageSize(PageSize.A4);
            document.addAuthor("AutoLife");
            document.addCreationDate();
            document.addCreator("AutoLife");
            document.addSubject("Invoice");
            document.addTitle("Purchase Invoice");

            PdfPTable headerTable = new PdfPTable(3);

            ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance()
                    .getExternalContext().getContext();
            String logo = servletContext.getRealPath("") + File.separator + "images" + File.separator
                    + "sattrak-logo.png";
            PdfPCell c = new PdfPCell(Image.getInstance(logo));
            c.setBorder(0);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            headerTable.addCell(c);

            BaseFont helvetica = null;
            try {
                helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
            } catch (Exception e) {
            }
            Font font = new Font(helvetica, 16, Font.NORMAL | Font.BOLD);
            c = new PdfPCell(new Paragraph("INVOICE", font));
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            c.setBorder(0);
            headerTable.addCell(c);

            font = new Font(helvetica, 10, Font.NORMAL | Font.BOLD);
            c = new PdfPCell(new Paragraph("TRANSACTION REF. NO.: " + cp.getPurchaseTranRef(), font));
            c.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
            c.setBorder(0);
            headerTable.addCell(c);

            document.add(headerTable);

            font = new Font(helvetica, 12, Font.NORMAL | Font.BOLD);
            Paragraph p = new Paragraph("DETAILS", font);
            p.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(p);

            PdfPTable pdfTable = new PdfPTable(3);

            font = new Font(helvetica, 8, Font.BOLDITALIC);
            pdfTable.addCell(new Paragraph("INITIATED DATE", font));
            pdfTable.addCell(new Paragraph("PRODUCT", font));
            pdfTable.addCell(new Paragraph("AMOUNT", font));
            font = new Font(helvetica, 8, Font.NORMAL);
            pdfTable.addCell(
                    new Paragraph(cp.getPurchaseTransaction().getTranInitDate().toLocaleString(), font));
            pdfTable.addCell(new Paragraph(cp.getProductBooked().getDetails(), font));
            pdfTable.addCell(new Paragraph("" + cp.getPurchasedAmount(), font));
            document.add(pdfTable);

            document.close();

            data = baos.toByteArray();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    return data;
}