Example usage for com.lowagie.text Document add

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

Introduction

In this page you can find the example usage for com.lowagie.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.efficio.fieldbook.web.demo.controller.BarCodeController.java

License:Open Source License

/**
 * Upload file./*from   ww w.  j av  a 2 s .c  o  m*/
 *
 * @param uploadForm the upload form
 * @param result the result
 * @param model the model
 * @return the string
 */
@ResponseBody
@RequestMapping(method = RequestMethod.POST)
public String uploadFile(@ModelAttribute("barCodeForm") BarCodeForm barCodeForm, BindingResult result,
        Model model, HttpServletResponse response) {
    int width = 60;
    int height = 48;
    String delimeter = "|";
    StringBuilder barCodeString = new StringBuilder();

    barCodeString.append(barCodeForm.getEntryNo()).append(delimeter).append(barCodeForm.getGid())
            .append(delimeter).append(barCodeForm.getDesignation()).append(delimeter)
            .append(barCodeForm.getName()).append(delimeter).append(barCodeForm.getRep()).append(delimeter)
            .append(barCodeForm.getColumn()).append(delimeter).append(barCodeForm.getRange());

    BitMatrix bitMatrix;
    try {
        String barCodeLabel = "3|SM114-1A-1-1-1B";
        //barCodeLabel = barCodeString.toString();
        bitMatrix = new Code128Writer().encode(barCodeLabel, BarcodeFormat.CODE_128, width, height, null);
        String imageLocation = Math.random() + ".png"; //"src/test/resources/barcode/zxing_barcode.png";
        MatrixToImageWriter.writeToStream(bitMatrix, "png", new FileOutputStream(new File(imageLocation)));

        String currentDate = DateUtil.getCurrentDate();
        String fileName = currentDate + ".doc";

        response.setHeader("Content-disposition", "attachment; filename=" + fileName);

        File xls = new File(fileName); // the selected name + current date
        FileInputStream in;

        try {

            Image image1 = Image.getInstance(imageLocation);
            //image1.scalePercent(50);
            //image1.setAbsolutePosition(10f, 10f);
            //document.add(image1);

            //PageSize.A4
            Document document = new Document(PageSize.LETTER);
            // step 2
            PdfWriter.getInstance(document, new FileOutputStream(fileName));
            // step 3
            document.open();
            // step 4
            // we'll use 4 images in this example
            /*
            Image[] img = {
                 Image.getInstance(String.format(RESOURCE, "0120903")),
                 Image.getInstance(String.format(RESOURCE, "0290334")),
                 Image.getInstance(String.format(RESOURCE, "0376994")),
                 Image.getInstance(String.format(RESOURCE, "0348150"))
            };*/

            PdfPTable table = new PdfPTable(4);
            table.setWidthPercentage(100);
            // first movie
            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
            Phrase phrase = new Phrase();
            phrase.add("Entry # " + barCodeForm.getEntryNo());
            phrase.add("\n");
            phrase.add("Designation " + barCodeForm.getDesignation());
            phrase.add("\n");
            phrase.add("Rep " + barCodeForm.getRep());
            phrase.add("\n");
            phrase.add("GID " + barCodeForm.getGid());
            phrase.add("\n");
            phrase.add("Trial/Nursery Name " + barCodeForm.getName());
            phrase.add("\n");
            phrase.add("Col " + barCodeForm.getColumn());
            phrase.add("\n");
            phrase.add("Range " + barCodeForm.getRange());
            table.addCell(phrase);
            // we add the image with addCell()
            table.addCell(image1);

            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
            table.addCell("X-Men: The Last Stand");
            // we add the image with addCell()
            table.addCell(image1);

            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
            table.addCell("X-Men: The Last Stand");
            // we add the image with addCell()
            table.addCell(image1);

            // we complete the table (otherwise the last row won't be rendered)
            table.completeRow();
            document.add(table);

            document.close();

            in = new FileInputStream(xls);
            OutputStream out = response.getOutputStream();

            byte[] buffer = new byte[BUFFER_SIZE]; // use bigger if you want
            int length = 0;

            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            in.close();
            out.close();
        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }

        return "";

    } catch (WriterException e) {
        LOG.error(e.getMessage(), e);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }

    return show(barCodeForm, model);
}

From source file:com.epam.spring.core.htask.cinema.mvc.view.pdf.UserPdfView.java

protected void buildPdfDocument(Map model, Document document, PdfWriter pdfWriter, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    List lstUsers = (List) model.get("users");
    Table userTable = new Table(4); //  
    userTable.setWidth(90);/*from w ww .j  a v  a 2  s. c o m*/
    userTable.setBorderWidth(1);
    userTable.addCell(""); //  ? 
    userTable.addCell("Id");
    userTable.addCell("Name");
    userTable.addCell("Birthday");
    int count = 0;
    for (Iterator iter = lstUsers.iterator(); iter.hasNext();) {
        User user = (User) iter.next();
        userTable.addCell(new Integer(++count).toString());
        userTable.addCell(new Integer(user.getId()).toString()); // 
        userTable.addCell(user.getName()); // 
        userTable.addCell(user.getDateBirth().toString()); // 
    }
    document.add(userTable);
}

From source file:com.estate.pdf.PageBorder.java

public void draw(Document doc, int iconNum, String pageNum, String toolName) {
    try {//from  ww  w  .j a  v  a  2  s .  c  o  m
        PdfContentByte cb = writer.getDirectContentUnder();
        BaseFont fontBold = BaseFont.createFont(Locations.getFontLocation() + "timesbd.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);
        BaseFont font = BaseFont.createFont(Locations.getFontLocation() + "times.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);
        Rectangle rct = new Rectangle(doc.getPageSize());
        float iconBase = (1.25f * 72); // This is the base of the icons on
        // the page
        Image icon = Image.getInstance(Locations.getImageLocation() + icons[iconNum]);
        // Image box = Image.getInstance(Locations.ImageLocation() +
        // "blueBOX.png");
        icon.scalePercent(23);
        float scale = .23f;
        float iconLeft = (icon.getWidth() / 2) * scale;
        float boxSize = (.1875f * 72);

        // Adjust the top
        rct.setTop(rct.getTop() - (.5f * 72));

        // Place the Icon
        icon.setAbsolutePosition((1.25f * 72) - iconLeft, rct.getTop() - iconBase);
        doc.add(icon);

        // Set our line color
        cb.setRGBColorStroke(0, 72, 117);

        cb.setLineWidth(.75f);

        // do the bottom line
        cb.moveTo(1.25f * 72, (.5f * 72));
        cb.lineTo(rct.getRight() - (.5f * 72), (.5f * 72));

        cb.moveTo(1.25f * 72, (.5f * 72));
        cb.lineTo(1.25f * 72, rct.getTop());

        // stroke the lines
        cb.stroke();

        // Do the lower left box
        cb.rectangle((1.25f - 0.09375f) * 72, (.5f - 0.09375f) * 72, boxSize, boxSize);
        cb.setRGBColorFill(0, 72, 117);
        cb.closePathFillStroke();

        // Do the lower right box
        Rectangle pnRect = new Rectangle(0, 0);
        pnRect.setLeft(rct.getRight() - ((.5f + 0.09375f) * 72));
        pnRect.setTop((.5f - 0.09375f) * 72);
        pnRect.setRight(pnRect.getLeft() + boxSize);
        pnRect.setBottom(pnRect.getTop() - boxSize);

        // cb.rectangle(rct.getRight() - ((.5f + 0.09375f) * 72), (.5f -
        // 0.09375f) * 72, (.1875f * 72), (.1875f * 72));
        cb.rectangle(pnRect.getLeft(), pnRect.getTop(), boxSize, boxSize);
        cb.setRGBColorFill(0, 72, 117);
        cb.closePathFillStroke();

        // Now we do the page number if one is supplied.
        if (pageNum.length() > 0) {
            float pnHeight = fontBold.getAscentPoint(pageNum, 9) - fontBold.getDescentPoint(pageNum, 9);
            float pnWidth = fontBold.getWidthPoint(pageNum, 9);

            float l = pnRect.getLeft() + ((boxSize - pnWidth) / 2);
            float b = pnRect.getTop() + ((boxSize - pnHeight) / 2);

            cb.beginText();
            cb.setFontAndSize(fontBold, 9);
            cb.setRGBColorFill(255, 255, 255);
            cb.setTextMatrix(l, b);
            cb.showText(pageNum);
            cb.endText();

        }

        // Display the copyright
        SimpleDateFormat df = new SimpleDateFormat("yyyy");
        char cs = 0x00a9; // Unicode for the copyright symbol
        String copyRight = com.estate.constants.StringConstants.copyRight + cs + " " + df.format(new Date());
        float crWidth;
        float crLeft;

        crWidth = font.getWidthPoint(copyRight, 8);
        cb.beginText();

        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(0, 0, 0);

        crLeft = (doc.getPageSize().getRight() - crWidth) / 2;
        cb.setTextMatrix(crLeft, .375f * 72); // Place the base of the
        // copyright at 3/8" up from
        // the bottom
        cb.showText(copyRight);
        cb.endText();

        if (toolName.length() > 0) {
            cb.beginText();

            cb.setFontAndSize(font, 8);
            cb.setRGBColorFill(0, 0, 0);

            cb.setTextMatrix((1.25f * 72) + boxSize, .375f * 72);
            cb.showText(toolName);
            cb.endText();
        }

        // Fix a licensee at left
        cb.beginText();
        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(0, 0, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, " Licensee: " + getLicense(), (10.2f * 72), .375f * 72,
                0);
        cb.endText();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.eugenefe.controller.TableBean.java

License:Apache License

public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException {
    Document pdf = (Document) document;
    pdf.open();/*from  ww  w .j  a v a2s.c  o m*/
    pdf.setPageSize(PageSize.A4);

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();
    String logo = servletContext.getRealPath("") + File.separator + "images" + File.separator
            + "prime_logo.png";

    pdf.add(Image.getInstance(logo));
}

From source file:com.exam.server.ConvertPDF.java

private static void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);//w ww  .  ja v  a  2  s.  com
    // Lets write a big header
    preface.add(new Paragraph("Title of the document", catFont));

    addEmptyLine(preface, 1);
    // Will create: Report generated by: _name, _date
    preface.add(new Paragraph("Report generated by:  Ashutosh , " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    //                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.exam.server.ConvertPDF.java

private static void addContent(Document document, ArrayList<DeviceDTO> input) throws DocumentException {
    Anchor anchor = new Anchor("", catFont);
    anchor.setName("User Report");

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

    Paragraph subPara = new Paragraph("", 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);
    //                Paragraph paragraph = new Paragraph();
    //                addEmptyLine(paragraph, 5);
    //                subCatPart.add(paragraph);

    // add a table
    createTable(subCatPart, input);// www  .j  a v  a2 s .  c  om

    // now add all this to the document
    document.add(catPart);

    // 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
    //                document.add(catPart);

    document.newPage();

}

From source file:com.example.dwr.simple.UploadDownload.java

License:Apache License

/**
 * Generates a PDF file with the given text
 * http://itext.ugent.be/itext-in-action/
 * @return A PDF file as a byte array/* w  w w . j a va 2s . c om*/
 */
public FileTransfer downloadPdfFile(String contents) throws Exception {
    if (contents == null || contents.length() == 0) {
        contents = "[BLANK]";
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, buffer);

    document.addCreator("DWR.war using iText");
    document.open();
    document.add(new Paragraph(contents));
    document.close();

    return new FileTransfer("example.pdf", "application/pdf", buffer.toByteArray());
}

From source file:com.foc.vaadin.FPrint.java

License:Apache License

public FPrint(Stack<Component> stack) {
    Document document = null;
    try {//w ww.  j a v  a 2s  . c  o m
        document = new Document(PageSize.A4, 50, 50, 50, 50);

        PdfWriter.getInstance(document, os);
        document.open();
        ////////////////////////////////////////
        String value = null;
        String caption = null;
        while (!stack.isEmpty()) {
            Component comp = stack.pop();
            if (comp instanceof FVTextField) {
                caption = ((FVTextField) comp).getCaption();
                value = (String) ((FVTextField) comp).getValue();
            }

            document.add(new Paragraph("\n" + caption + ": " + value));

        }
        ////////////////////////////////////////
        Paragraph pp = new Paragraph();
        // Chapter ch = new Chapter();
        // ch.addSection(pp);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:com.geek.tutorial.itext.acroform.TextFieldForm.java

License:Open Source License

public TextFieldForm() throws Exception {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("TextFieldForm.pdf"));
    document.open();/* w ww  .  j a va 2s  .  c  om*/

    PdfPTable table = new PdfPTable(2);
    table.getDefaultCell().setPadding(5f); // Code 1, will only affect empty field
    table.setHorizontalAlignment(Element.ALIGN_LEFT);
    PdfPCell cell;

    // Code 2, add name TextField      
    table.addCell("Name");
    TextField nameField = new TextField(writer, new Rectangle(0, 0, 200, 10), "nameField");
    nameField.setBackgroundColor(Color.WHITE);
    nameField.setBorderColor(Color.BLACK);
    nameField.setBorderWidth(1);
    nameField.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    nameField.setText("");
    nameField.setAlignment(Element.ALIGN_LEFT);
    nameField.setOptions(TextField.REQUIRED);
    cell = new PdfPCell();
    cell.setMinimumHeight(10);
    cell.setCellEvent(new FieldCell(nameField.getTextField(), 200, writer));
    table.addCell(cell);

    // force upper case javascript
    writer.addJavaScript("var nameField = this.getField('nameField');" + "nameField.setAction('Keystroke',"
            + "'forceUpperCase()');" + "" + "function forceUpperCase(){"
            + "if(!event.willCommit)event.change = " + "event.change.toUpperCase();" + "}");

    // Code 3, add empty row
    table.addCell("");
    table.addCell("");

    // Code 4, add age TextField
    table.addCell("Age");
    TextField ageComb = new TextField(writer, new Rectangle(0, 0, 30, 10), "ageField");
    ageComb.setBorderColor(Color.BLACK);
    ageComb.setBorderWidth(1);
    ageComb.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    ageComb.setText("12");
    ageComb.setAlignment(Element.ALIGN_RIGHT);
    ageComb.setMaxCharacterLength(2);
    ageComb.setOptions(TextField.COMB | TextField.DO_NOT_SCROLL);
    cell = new PdfPCell();
    cell.setMinimumHeight(10);
    cell.setCellEvent(new FieldCell(ageComb.getTextField(), 30, writer));
    table.addCell(cell);

    // validate age javascript
    writer.addJavaScript("var ageField = this.getField('ageField');"
            + "ageField.setAction('Validate','checkAge()');" + "function checkAge(){" + "if(event.value < 12){"
            + "app.alert('Warning! Applicant\\'s age can not" + " be younger than 12.');" + "event.value = 12;"
            + "}}");

    // add empty row
    table.addCell("");
    table.addCell("");

    // Code 5, add age TextField
    table.addCell("Comment");
    TextField comment = new TextField(writer, new Rectangle(0, 0, 200, 100), "commentField");
    comment.setBorderColor(Color.BLACK);
    comment.setBorderWidth(1);
    comment.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    comment.setText("");
    comment.setOptions(TextField.MULTILINE | TextField.DO_NOT_SCROLL);
    cell = new PdfPCell();
    cell.setMinimumHeight(100);
    cell.setCellEvent(new FieldCell(comment.getTextField(), 200, writer));
    table.addCell(cell);

    // check comment characters length javascript
    writer.addJavaScript("var commentField = " + "this.getField('commentField');" + "commentField"
            + ".setAction('Keystroke','checkLength()');" + "function checkLength(){"
            + "if(!event.willCommit && " + "event.value.length > 100){" + "app.alert('Warning! Comment can not "
            + "be more than 100 characters.');" + "event.change = '';" + "}}");

    // add empty row
    table.addCell("");
    table.addCell("");

    // Code 6, add submit button   
    PushbuttonField submitBtn = new PushbuttonField(writer, new Rectangle(0, 0, 35, 15), "submitPOST");
    submitBtn.setBackgroundColor(Color.GRAY);
    submitBtn.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
    submitBtn.setText("POST");
    submitBtn.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField submitField = submitBtn.getField();
    submitField.setAction(PdfAction.createSubmitForm("http://www.geek-tutorials.com/java/itext/submit.php",
            null, PdfAction.SUBMIT_HTML_FORMAT));
    cell = new PdfPCell();
    cell.setMinimumHeight(15);
    cell.setCellEvent(new FieldCell(submitField, 35, writer));
    table.addCell(cell);

    // Code 7, add reset button
    PushbuttonField resetBtn = new PushbuttonField(writer, new Rectangle(0, 0, 35, 15), "reset");
    resetBtn.setBackgroundColor(Color.GRAY);
    resetBtn.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
    resetBtn.setText("RESET");
    resetBtn.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField resetField = resetBtn.getField();
    resetField.setAction(PdfAction.createResetForm(null, 0));
    cell = new PdfPCell();
    cell.setMinimumHeight(15);
    cell.setCellEvent(new FieldCell(resetField, 35, writer));
    table.addCell(cell);

    document.add(table);
    document.close();
}

From source file:com.geek.tutorial.itext.bookmarks.Anchor.java

License:Open Source License

public Anchor() throws Exception {

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("anchor.pdf"));
    document.open();/*from  w w w .  j  a v a  2  s  .  c o m*/

    // Code 1
    Font font = new Font();
    font.setColor(Color.BLUE);
    font.setStyle(Font.UNDERLINE);

    document.add(new Chunk("Chapter 1"));
    document.add(new Paragraph(new Chunk("Press here to go chapter 2", font).setLocalGoto("2")));// Code 2
    document.newPage();

    document.add(new Chunk("Chapter 2").setLocalDestination("2"));
    document.add(new Paragraph(
            new Chunk("http://www.geek-tutorials.com", font).setAnchor("http://www.geek-tutorials.com")));//Code 3
    document.add(
            new Paragraph(new Chunk("Open outline.pdf chapter 3", font).setRemoteGoto("outline.pdf", "3")));//Code 4

    document.close();

}