Example usage for com.itextpdf.text Image setAlignment

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

Introduction

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

Prototype


public void setAlignment(final int alignment) 

Source Link

Document

Sets the alignment for the image.

Usage

From source file:com.gp.cong.logisoft.reports.LclExportVoyageNotificationPdf.java

public PdfPTable imageBlock(String realPath, String path)
        throws IOException, BadElementException, DocumentException {
    Font fontArialBold = FontFactory.getFont("Courier", 18f, Font.NORMAL);
    table = new PdfPTable(1);
    table.setWidths(new float[] { 5.9f });
    table.setWidthPercentage(100f);/*from   w  ww  .jav  a2  s.  c o  m*/
    cell = new PdfPCell();
    cell.setBorder(0);
    cell.setPadding(0f);
    Image img = Image.getInstance(realPath + path);
    img.scalePercent(90);
    img.setAlignment(Element.ALIGN_CENTER);
    cell.addElement(img);
    table.addCell(cell);
    cell = new PdfPCell();
    cell.setBorder(0);
    cell.setPadding(0f);
    p = new Paragraph(12f, "    (866) 326-6648", fontArialBold);
    p.setAlignment(Element.ALIGN_CENTER);
    cell.addElement(p);
    table.addCell(cell);
    cell = new PdfPCell();
    cell.setBorder(0);
    cell.setPadding(0f);
    String companyWebsite = new PropertyDAO().getProperty(
            companyCode.equalsIgnoreCase("03") ? "application.ECU.website" : "application.OTI.website");
    p = new Paragraph(28f, "   " + companyWebsite, fontArialBold);
    p.setAlignment(Element.ALIGN_CENTER);
    cell.addElement(p);
    table.addCell(cell);
    return table;
}

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;/*from  www .  j  a v  a  2  s.c o  m*/
            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 float addConversationPart(ColumnText ct, int column, String dateString, String senderString,
        String contentString, Bitmap contentBitmap, Boolean isVideo, Boolean isMe)
        throws DocumentException, MalformedURLException, IOException {
    float messageWidth = 196.0f;
    Chunk dateChunk = new Chunk(new StringBuilder(String.valueOf(dateString))
            .append(MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR).toString(), this.sansFont6Gray);
    float dateWidth = dateChunk.getWidthPoint();
    Paragraph contentParagraph = new Paragraph();
    if (contentString.length() > 0) {
        Element contentChunk = new Chunk(contentString, this.sansFont9);
        messageWidth = contentChunk.getWidthPoint();
        contentParagraph.add(contentChunk);
    }/*from w w  w .  j  a  va2s .co m*/
    if (messageWidth < dateWidth) {
        messageWidth = dateWidth;
    }
    if (messageWidth > MAX_COLUMN_CONTENT_WIDTH) {
        messageWidth = MAX_COLUMN_CONTENT_WIDTH;
        dateWidth += 7.0f;
    }
    Paragraph dateParagraph = new Paragraph(dateChunk);
    if (isMe.booleanValue()) {
        dateParagraph.setAlignment(0);
        dateParagraph
                .setIndentationLeft((((BUBBLE_L_WIDTH + messageWidth) + BUBBLE_R_WIDTH) + 7.0f) - dateWidth);
    } else {
        dateParagraph.setAlignment(2);
        dateParagraph
                .setIndentationRight((((BUBBLE_L_WIDTH + messageWidth) + BUBBLE_R_WIDTH) + 7.0f) - dateWidth);
    }
    ct.addElement(dateParagraph);
    contentParagraph.setExtraParagraphSpace(10.0f);
    if (contentString.length() > 0) {
        contentParagraph.setAlignment(0);
        if (isMe.booleanValue()) {
            contentParagraph.setIndentationLeft(8.6f);
            contentParagraph.setIndentationRight(BUBBLE_TEXT_INDENT_ALTERNATE);
        } else {
            contentParagraph.setIndentationRight(8.6f);
            float indentLeft = COLUMN_WIDTH - (BUBBLE_L_WIDTH + messageWidth);
            if (messageWidth == MAX_COLUMN_CONTENT_WIDTH) {
                indentLeft += BUBBLE_TEXT_INDENT_ALTERNATE;
            }
            contentParagraph.setIndentationLeft(indentLeft);
        }
        ct.addElement(contentParagraph);
    } else if (contentBitmap != null) {
        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(198.0f, 198.0f);
        if (isVideo.booleanValue()) {
            contentImage.setCompressionLevel(this.settings.compressionLevel);
        }
        contentImage.setSpacingBefore(10.0f);
        contentImage.setSpacingAfter(10.0f);
        if (isMe.booleanValue()) {
            contentImage.setAlignment(1);
        } else {
            contentImage.setAlignment(1);
        }
        ct.addElement(contentImage);
    }
    Paragraph senderParagraph = new Paragraph(new Chunk(senderString, this.sansFont9Gray));
    if (!isMe.booleanValue()) {
        senderParagraph.setAlignment(2);
    }
    senderParagraph.setSpacingAfter(BUBBLE_TEXT_INDENT_ALTERNATE);
    ct.addElement(senderParagraph);
    return messageWidth;
}

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));
        }/*from   w  w  w  .  java 2s  . c  om*/
    } 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.kohmiho.mpsr.export.PDFGenerator.java

private void addImage(Document document, String filename)
        throws BadElementException, MalformedURLException, IOException, DocumentException {

    if (null == filename) {
        addParagraph(document, null, null, String.format("[*** No Picture for %s ***]", ""), null, 0, 0, 0);
        return;/*from   w  w  w  . j  a v a  2s .  c  o  m*/
    }

    try {
        Image image = Image.getInstance(filename);
        image.scaleToFit(700, 500);
        image.setAlignment(Element.ALIGN_CENTER);
        // image.setRotationDegrees(90);
        document.add(image);

    } catch (Exception e) {
        addParagraph(document, null, null, String.format("[*** Unable to render picture for %s ***]", ""), null,
                0, 0, 0);
    }
}

From source file:com.kohmiho.mpsr.export.PDFGenerator.java

private void addCoverImage(Document document, String filename)
        throws BadElementException, MalformedURLException, IOException, DocumentException {

    if (null != filename) {
        try {//from w ww.j  av  a2 s  .c  o m
            Image image = Image.getInstance(filename);
            image.scaleToFit(300, 300);
            image.setAlignment(Element.ALIGN_CENTER);
            document.add(image);

        } catch (Exception e) {
            System.err.println("Can not load image " + filename);
            // e.printStackTrace();
        }
    }
}

From source file:com.masscustsoft.service.ToPdf.java

License:Open Source License

private Image getImage(Map row) throws Exception {
    Image image = null;
    String url = (String) row.get("url");
    if (url != null) {
        image = Image.getInstance(url);
    }/*w w w.jav a2  s. com*/
    String externalId = (String) row.get("externalId");
    if (externalId != null) {
        File tmp = File.createTempFile("tmp", ".image");
        InputStream is = getFs().getResource(externalId);
        FileOutputStream os = new FileOutputStream(tmp);
        StreamUtil.copyStream(is, os, 0);
        is.close();
        os.close();
        image = Image.getInstance(tmp.toURL());
        ThreadHelper.postponeDelete(tmp);
    }
    String img = (String) row.get("image");
    if (img != null) {
        byte[] bytes = LightStr.getHexContent(img);
        image = Image.getInstance(bytes);
    }
    if (image != null) {
        MapUtil.setIfFloat(row, "spacingAfter", image);
        MapUtil.setIfFloat(row, "spacingBefore", image);
        MapUtil.setIfFloat(row, "scalePercent", image);
        MapUtil.setIfFloat(row, "scaleDegree", image);
        Float fitPer = MapUtil.getFloat(row, "fitPercent", null);
        if (fitPer != null) {
            Document doc = this.getDoc();
            image.scaleToFit(
                    (doc.getPageSize().getWidth() - doc.leftMargin() - doc.rightMargin()) * fitPer / 100f,
                    (doc.getPageSize().getHeight() - doc.topMargin() - doc.bottomMargin()) * fitPer / 100f);
        }
        Float fitWidth = MapUtil.getFloat(row, "fitWidth", null);
        if (fitWidth != null) {
            Float fitHeight = MapUtil.getFloat(row, "fitHeight", fitWidth);
            image.scaleToFit(fitWidth, fitHeight);
        }
        image.setAlignment(getAlignment(row, "alignment"));
    }
    return image;
}

From source file:com.maxl.java.amikodesk.SaveBasket.java

License:Open Source License

public void generatePdf(Author author, String filename, String type) {
    // A4: 8.267in x 11.692in => 595.224units x 841.824units (72units/inch)

    // marginLeft, marginRight, marginTop, marginBottom
    Document document = new Document(PageSize.A4, 50, 50, 80, 50);
    try {/*ww w  .  j  av a2s .c o  m*/
        if (m_shopping_basket.size() > 0) {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
            writer.setBoxSize("art", new Rectangle(50, 50, 560, 790));

            HeaderFooter event = new HeaderFooter();
            writer.setPageEvent(event);

            document.open();

            PdfContentByte cb = writer.getDirectContent();

            document.addAuthor("ywesee GmbH");
            document.addCreator("AmiKo for Windows");
            document.addCreationDate();

            // Logo
            String logoImageStr = m_prefs.get(LogoImageID, Constants.IMG_FOLDER + "empty_logo.png");
            File logoFile = new File(logoImageStr);
            if (!logoFile.exists())
                logoImageStr = Constants.IMG_FOLDER + "empty_logo.png";

            Image logo = Image.getInstance(logoImageStr);
            logo.scalePercent(30);
            logo.setAlignment(Rectangle.ALIGN_RIGHT);
            document.add(logo);
            document.add(Chunk.NEWLINE);

            // Bestelladresse
            // --> String bestellAdrStr = m_prefs.get(BestellAdresseID, m_rb.getString("noaddress1")); 
            String bestellAdrStr = getAddressAsString(BestellAdresseID);
            Paragraph p = new Paragraph(12);
            // p.setIndentationLeft(60);
            p.add(new Chunk(bestellAdrStr, font_norm_10));
            document.add(p);
            document.add(Chunk.NEWLINE);

            // Title
            p = new Paragraph(m_rb.getString("order"), font_bold_16);
            document.add(p);

            // Date
            DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
            Date date = new Date();
            p = new Paragraph(m_rb.getString("date") + ": " + dateFormat.format(date), font_bold_10);
            p.setSpacingAfter(20);
            document.add(p);

            // document.add(Chunk.NEWLINE);

            // Add addresses (Lieferadresse + Rechnungsadresse)
            /* --> OLD
            String lieferAdrStr = m_prefs.get(LieferAdresseID, m_rb.getString("noaddress2"));
            String rechnungsAdrStr = m_prefs.get(RechnungsAdresseID, m_rb.getString("noaddress3"));              
            */
            // --> NEW
            String lieferAdrStr = getAddressAsString(LieferAdresseID);
            String rechnungsAdrStr = getAddressAsString(RechnungsAdresseID);

            PdfPTable addressTable = new PdfPTable(new float[] { 1, 1 });
            addressTable.setWidthPercentage(100f);
            addressTable.getDefaultCell().setPadding(5);
            addressTable.setSpacingAfter(5f);
            addressTable.addCell(getStringCell(m_rb.getString("shipaddress"), font_bold_10, PdfPCell.NO_BORDER,
                    Element.ALIGN_MIDDLE, 1));
            addressTable.addCell(getStringCell(m_rb.getString("billaddress"), font_bold_10, PdfPCell.NO_BORDER,
                    Element.ALIGN_MIDDLE, 1));
            addressTable.addCell(
                    getStringCell(lieferAdrStr, font_norm_10, PdfPCell.NO_BORDER, Element.ALIGN_MIDDLE, 1));
            addressTable.addCell(
                    getStringCell(rechnungsAdrStr, font_norm_10, PdfPCell.NO_BORDER, Element.ALIGN_MIDDLE, 1));
            document.add(addressTable);

            document.add(Chunk.NEWLINE);

            // Add shopping basket
            if (type.equals("specific"))
                document.add(getShoppingBasketForAuthor(author, cb));
            else if (type.equals("all"))
                document.add(getFullShoppingBasket(cb, "all"));
            else if (type.equals("rest"))
                document.add(getFullShoppingBasket(cb, "rest"));
            LineSeparator separator = new LineSeparator();
            document.add(separator);
        }
    } catch (IOException e) {

    } catch (DocumentException e) {

    }

    document.close();
    // System.out.println("Saved PDF to " + filename);
}

From source file:com.mycom.products.mywebsite.backend.util.DownloadHandler.java

License:Open Source License

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
protected final void downloadUserInformation(@PathVariable int id, HttpServletRequest request,
        final HttpServletResponse response) throws ServletException, BusinessException, DocumentException {
    UserBean user = userService.select(id, FetchMode.EAGER);
    if (user == null) {
        return;//from  w w  w .  j  a v a2 s . c  o m
    }
    Document document = new Document();
    document.setMargins(70, 70, 20, 20);

    try {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + user.getName() + "_profile.pdf\"");
        PdfWriter.getInstance(document, response.getOutputStream());
        document.open();
        Image profileImage = null;
        try {
            profileImage = Image.getInstance(user.getContent().getFilePath());
        } catch (Exception e) {
            // e.printStackTrace();
        }
        if (profileImage != null) {
            profileImage.setAlignment(Image.MIDDLE | Image.TEXTWRAP);
            profileImage.setBorder(Image.BOX);
            profileImage.setBorderWidth(5);
            BaseColor bgcolor = WebColors.getRGBColor("#E5E3E3");
            profileImage.setBorderColor(bgcolor);
            profileImage.scaleToFit(100, 100);
            document.add(profileImage);
        }
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);

        // Adding Table Data
        PdfPTable table = new PdfPTable(2); // 2 columns.
        table.setWidthPercentage(100); // Width 100%
        table.setSpacingBefore(15f); // Space before table
        table.setSpacingAfter(15f); // Space after table

        // Set Column widths
        float[] columnWidths = { 1f, 2f, };
        table.setWidths(columnWidths);

        // Name
        setTableHeader("Name", table);
        setTableContent(user.getName(), table);

        // Gender
        setTableHeader("Gender", table);
        String gender = "Male";
        if (user.getGender() == Gender.FEMALE) {
            gender = "Female";
        }
        setTableContent(gender, table);

        // Age
        setTableHeader("Age", table);
        setTableContent("" + user.getAge(), table);

        // Date of Birth
        setTableHeader("DOB", table);
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        setTableContent(dateFormatter.format(user.getDob()), table);

        // Email
        setTableHeader("Email", table);
        setTableContent(user.getEmail(), table);

        // NRC
        setTableHeader("NRC", table);
        setTableContent(user.getNrc(), table);

        // Phone
        setTableHeader("Phone", table);
        setTableContent(user.getPhone(), table);

        // Roles
        String roleStr = "";
        List<RoleBean> roles = user.getRoles();
        if (roles != null && roles.size() > 0) {
            Iterator<RoleBean> itr = roles.iterator();
            while (itr.hasNext()) {
                RoleBean role = itr.next();
                roleStr += role.getName();
                if (itr.hasNext()) {
                    roleStr += ",";
                }
            }
        }
        setTableHeader("Role(s)", table);
        setTableContent(roleStr, table);

        // Address
        setTableHeader("Address", table);
        setTableContent(user.getAddress(), table);

        document.add(table);
        document.add(new Paragraph(new Date().toString()));

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

    }
    document.close();
}

From source file:com.pdi.util.PdfGenerator.java

public static void generarPresupuesto(String lugar, Date fecha, float cantidad, String tipo, Cliente cliente,
        float precio, Aliado aliado, String path) {

    try {/*  w  w  w  .  j a v  a2 s. co m*/

        NEGRITA_12_VERDE.setColor(145, 189, 57);

        long miliSemana = System.currentTimeMillis() + (86400 * 7 * 1000);
        Date vtoPresup = new Date(miliSemana);
        float precioPers = precio / cantidad;
        int precioTotalInt = Math.round(precio);
        int precioPersInt = Math.round(precioPers);
        int cantPersonasInt = Math.round(cantidad);

        //Referencia al objeto Doc
        Document document = new Document(PageSize.A4, //Dimensiones
                36, //margIzq
                36, //margDer
                36, //margenSup
                36); // margenInf

        //Creamos el archivo fisico
        FileOutputStream salida = new FileOutputStream(path);

        //Referencia e inicializacion del objeto que "escribe" el PDF
        PdfWriter writer = PdfWriter.getInstance(document, salida);
        writer.setInitialLeading(0);

        //Imagen Logo
        Image logoPDI = Image.getInstance("Logo PDI.png");
        logoPDI.scaleToFit(215, 205);
        logoPDI.setAlignment(Chunk.ALIGN_LEFT);
        //image.setAbsolutePosition(200, 200);

        //Imagen QR
        Image qr = Image.getInstance("QR PDI.png");
        qr.scaleToFit(211, 165);
        qr.setAbsolutePosition(295, PageSize.A4.getHeight() - 390);

        //Parrafo info evento
        Paragraph infoEvento = new Paragraph();
        infoEvento.add(new Chunk("Informacin del Evento", NEGRITA_SUB_12));
        infoEvento.add(Chunk.NEWLINE);
        infoEvento.add(negritaNormal("Solicitante: ", cliente.toString()));
        infoEvento.add(negritaNormal("Evento: ", tipo));
        infoEvento.add(negritaNormal("Cantidad de personas: ", Integer.toString(cantPersonasInt)));
        infoEvento.add(negritaNormal("Fecha: ", General.formatoFecha.format(fecha)));
        infoEvento.add(negritaNormal("Lugar:  ", lugar));
        infoEvento.add(Chunk.NEWLINE);
        infoEvento.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Modalidad del Servicio
        Paragraph modalidadServicio = new Paragraph();
        modalidadServicio.add(new Chunk("Modalidad Servicio Integral", NEGRITA_SUB_12));
        modalidadServicio.add(Chunk.NEWLINE);
        modalidadServicio.add(new Chunk("Nuestro servicio incluye la totalidad de lo referido a"
                + " los elementos necesarios para el despacho de bebidas: Barras, Bartenders,"
                + " Artculos de Coctelera, Insumos de calidad para los tragos y Mucha Buena Onda."
                + " Con esta modalidad aseguramos la expedicin de "
                + "los tragos desde las 00hs hasta las 05hs, para que se desentiendan del asunto "
                + "y disfruten al mximo.", NORMAL_12));
        modalidadServicio.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Ver Carta
        Paragraph verCarta = new Paragraph();
        verCarta.add(negritaNormal("\u2022 Carta de Tragos: ", "Ver archivo adjunto."));
        verCarta.setIndentationLeft(20);
        verCarta.add(Chunk.NEWLINE);
        verCarta.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Titulo Info Contratacion
        Paragraph infoContratacionTitulo = new Paragraph();
        infoContratacionTitulo.add(new Chunk("Informacin de Contratacin", NEGRITA_SUB_12));
        infoContratacionTitulo.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Inf de Contratacion
        Paragraph infoContratacion = new Paragraph();
        infoContratacion.add(negritaNormal("\u2022 Mtodo de contratacin y reserva de la fecha: ",
                "A travs de contrato firmado por ambas partes. "));
        Phrase lineaCosto = new Phrase();
        lineaCosto.add(new Chunk("\u2022 Costo: ", NEGRITA_12));
        lineaCosto.add(new Chunk("$" + Integer.toString(precioPersInt) + " ", NEGRITA_14));
        lineaCosto.add(new Chunk("por persona ", NEGRITA_12));
        lineaCosto.add(new Chunk("(Total: $" + Integer.toString(precioTotalInt) + ")", NEGRITA_14));
        infoContratacion.add(lineaCosto);
        infoContratacion.add(Chunk.NEWLINE);
        infoContratacion.add(negritaNormal("\u2022 Forma de Pago : ",
                "50% al momento de la firma del contrato y 50% como mximo una semana antes del evento. "));
        infoContratacion.add(Chunk.NEWLINE);
        infoContratacion.setIndentationLeft(20);
        infoContratacion.setFirstLineIndent(0);
        infoContratacion.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Despedida
        Paragraph despedida = new Paragraph();
        despedida.add(new Phrase("Quedamos al aguardo de tus comentarios,", NEGRITA_14));
        despedida.add(Chunk.NEWLINE);
        despedida.add(new Phrase("Muchas Gracias.", NEGRITA_14));
        despedida.add(Chunk.NEWLINE);
        despedida.add(Chunk.NEWLINE);
        despedida.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Firma
        Paragraph firma = new Paragraph();
        firma.add(new Phrase("Piel de Iguana Tragos.-", NEGRITA_CUR_14));
        firma.add(Chunk.NEWLINE);
        firma.add(new Phrase("Cel.: 3462-15337860", NEGRITA_12_VERDE));
        firma.setAlignment(Paragraph.ALIGN_RIGHT);

        float llxLink = 279;
        float llyLink = PageSize.A4.getHeight() - 145;
        float anchoLink = 199;
        float altoLink = 16;

        //Link al facebook
        URL urlPDI = new URL("https://www.facebook.com/pieldeiguanatragos.vt");
        PdfAction irAlFace = new PdfAction(urlPDI);
        Rectangle linkLocation = new Rectangle(llxLink, llyLink, llxLink + anchoLink, llyLink + altoLink);
        PdfAnnotation link = PdfAnnotation.createLink(writer, linkLocation, PdfAnnotation.HIGHLIGHT_NONE,
                irAlFace);
        link.setBorder(new PdfBorderArray(0, 0, 0));
        writer.addAnnotation(link);

        //Espacios Vacios
        Paragraph dosEspacios = new Paragraph();
        dosEspacios.add(Chunk.NEWLINE);
        dosEspacios.add(Chunk.NEWLINE);

        //Hay que abrir el Documento, llenarlo con los elemntos creados
        //en el orden que queremos y cerrarlo
        document.open();

        PdfContentByte cb = writer.getDirectContent();

        ColumnText ct = new ColumnText(cb);
        Phrase recuadro = new Phrase();
        recuadro.add(new Chunk("Piel de Iguana Tragos", NEGRITA_SUB_14));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("Servicio de tragos para eventos", NEGRITA_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("\"Piel de Iguana, para que tu noche nica sea inigualable.\"", NORMAL_CUR_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        Image logoFB = Image.getInstance("Icono FB.png");
        logoFB.scaleToFit(13, 13);
        recuadro.add(new Chunk(logoFB, 0, -3));
        recuadro.add(new Chunk("/pieldeiguanatragos.vt  -> Click Aqu!", NORMAL_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("Vencimiento del Prepuesto " + General.formatoFecha.format(vtoPresup),
                NORMAL_SUB_12));

        float llx = 279;
        float lly = PageSize.A4.getHeight() - 185;
        float ancho = 228;
        float alto = 150;

        ct.setSimpleColumn(recuadro, //Texto
                llx, //punta inf izquierda (x)
                lly, //punta inf izquierda (y) PageSize.A4.getHeight() - 185
                llx + ancho, //ancho del cuadro
                lly + alto, // alto del cuadro
                15, //espaciado
                Element.ALIGN_LEFT // Alineacion
        );

        ct.go();

        document.add(logoPDI);
        document.add(qr);
        document.add(dosEspacios);
        document.add(infoEvento);
        document.add(modalidadServicio);
        document.add(verCarta);
        document.add(infoContratacionTitulo);
        document.add(infoContratacion);
        document.add(despedida);
        document.add(firma);
        document.close();
        System.out.println("Archivo creado");
        int rta = JOptionPane.showConfirmDialog(VentanaMaestra.eventosCurrent,
                "Se guard el presupesto en:\n" + path + "\nDesea abrirlo?", "Presupuesto guardado",
                JOptionPane.YES_NO_OPTION);

        if (rta == JOptionPane.YES_OPTION) {
            if (Desktop.isDesktopSupported()) {
                try {
                    File myFile = new File(path);
                    Desktop.getDesktop().open(myFile);
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(VentanaMaestra.eventosCurrent,
                            "No se puede abrir el archivo. Ubiquelo en su equipo" + "y abralo manualmente.",
                            "Error al abrir el archivo", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(VentanaMaestra.eventosCurrent,
                        "No se puede abrir el archivo. Ubiquelo en su equipo" + "y abralo manualmente.",
                        "Error al abrir el archivo", JOptionPane.ERROR_MESSAGE);
            }

        }

    } catch (FileNotFoundException ex) {
        System.out.println("Error: " + ex.toString());
    } catch (DocumentException ex) {
        System.out.println("Error: " + ex.toString());
    } catch (IOException ex) {
        System.out.println("Error: " + ex.toString());
    }

}