Example usage for com.lowagie.text Document open

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

Introduction

In this page you can find the example usage for com.lowagie.text Document open.

Prototype

boolean open

To view the source code for com.lowagie.text Document open.

Click Source Link

Document

Is the document open or not?

Usage

From source file:com.crm.webapp.util.PDFCustomExporter.java

License:Apache License

@Override
public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle,
        boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor, boolean subTable) throws IOException {
    try {//from w  w  w. jav  a  2s  .c  o m
        Document document = new Document();
        if (orientation.equalsIgnoreCase("Landscape")) {
            document.setPageSize(PageSize.A4.rotate());
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        StringTokenizer st = new StringTokenizer(tableId, ",");
        while (st.hasMoreElements()) {
            String tableName = (String) st.nextElement();
            UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(),
                    tableName);
            if (component == null) {
                throw new FacesException("Cannot find component \"" + tableName + "\" in view.");
            }

            if (!(component instanceof DataTable || component instanceof DataList)) {
                throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName()
                        + "\", exporter must target a PrimeFaces DataTable/DataList.");
            }

            if (preProcessor != null) {
                preProcessor.invoke(context.getELContext(), new Object[] { document });
            }

            if (!document.isOpen()) {
                document.open();
            }

            if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) {
                Font tableTitleFont = FontFactory.getFont(FontFactory.TIMES, encodingType, Font.DEFAULTSIZE,
                        Font.BOLD);
                Paragraph title = new Paragraph(tableTitle, tableTitleFont);
                document.add(title);

                Paragraph preface = new Paragraph();
                addEmptyLine(preface, 3);
                document.add(preface);
            }

            PdfPTable pdf;
            DataList list = null;
            DataTable table = null;
            if (component instanceof DataList) {
                list = (DataList) component;
                pdf = exportPDFTable(context, list, pageOnly, encodingType);
            } else {
                table = (DataTable) component;
                pdf = exportPDFTable(context, table, pageOnly, selectionOnly, encodingType, subTable);
            }

            if (pdf != null) {
                document.add(pdf);
            }

            // add a couple of blank lines
            Paragraph preface = new Paragraph();
            addEmptyLine(preface, datasetPadding);
            document.add(preface);

            if (postProcessor != null) {
                postProcessor.invoke(context.getELContext(), new Object[] { document });
            }
        }

        document.close();

        writePDFToResponse(context.getExternalContext(), baos, filename);
    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:com.efficio.fieldbook.service.LabelPrintingServiceImpl.java

License:Open Source License

/**
 * Gets the cell height.//from  w  w  w  . jav  a2 s . c  o m
 *
 * @param numberOfRowsPerPage the number of rows per page
 * @param pageSizeId the page size id
 * @return the cell height
 */
/*
private float getCellHeight(int numberOfRowsPerPage, int pageSizeId){
if(pageSizeId == AppConstants.SIZE_OF_PAPER_A4){
    if(numberOfRowsPerPage == 7){
        return 108f; //ok
    }else if(numberOfRowsPerPage == 8){
        return 97f;//ok
    }else if(numberOfRowsPerPage == 10){
        return 72.5f;
    }
}else{
    if(numberOfRowsPerPage == 7){
        return 108f; //ok
    }else if(numberOfRowsPerPage == 8){
        return 98.1f;//ok
    }else if(numberOfRowsPerPage == 10){
        return 72.5f;//ok
    }
}
           
return 0f;
}
*/
/* (non-Javadoc)
 * @see com.efficio.fieldbook.service.api.LabelPrintingService#generateLabels(com.efficio.fieldbook.web.fieldmap.bean.UserFieldmap)
 */
@Override
public String generatePDFLabels(List<StudyTrialInstanceInfo> trialInstances,
        UserLabelPrinting userLabelPrinting, ByteArrayOutputStream baos) throws MiddlewareQueryException {

    // setUserLabelPrinting(form.getUserLabelPrinting());
    int pageSizeId = Integer.parseInt(userLabelPrinting.getSizeOfLabelSheet());
    int numberOfLabelPerRow = Integer.parseInt(userLabelPrinting.getNumberOfLabelPerRow());
    int numberofRowsPerPageOfLabel = Integer.parseInt(userLabelPrinting.getNumberOfRowsPerPageOfLabel());
    int totalPerPage = numberOfLabelPerRow * numberofRowsPerPageOfLabel;
    String leftSelectedFields = userLabelPrinting.getLeftSelectedLabelFields();
    String rightSelectedFields = userLabelPrinting.getRightSelectedLabelFields();
    String barcodeNeeded = userLabelPrinting.getBarcodeNeeded();

    String firstBarcodeField = userLabelPrinting.getFirstBarcodeField();
    String secondBarcodeField = userLabelPrinting.getSecondBarcodeField();
    String thirdBarcodeField = userLabelPrinting.getThirdBarcodeField();

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

    String fileName = userLabelPrinting.getFilenameDLLocation();

    try {
        FileOutputStream fileOutputStream = new FileOutputStream(fileName);

        try {

            // Image image1 = Image.getInstance(imageLocation);

            // PageSize.A4
            LabelPaper paper = LabelPaperFactory.generateLabelPaper(numberOfLabelPerRow,
                    numberofRowsPerPageOfLabel, pageSizeId);

            Rectangle pageSize = PageSize.LETTER;

            if (pageSizeId == AppConstants.SIZE_OF_PAPER_A4.getInt())
                pageSize = PageSize.A4;

            Document document = new Document(pageSize);
            /*
             * 2, 2, 33.3f, 5
             * 15, 0, 42, 5
             * 10, 0, 17, 5
             * 10, 0, 17, 5
             * 5, 0, 0, 5
             * 15, 0, 37, 5
             * 10, 0, 17, 5
            if (pageSizeId == AppConstants.SIZE_OF_PAPER_LETTER) {
            if (numberofRowsPerPageOfLabel == 7)
                document.setMargins(10, 0, 17, 5);
            else if (numberofRowsPerPageOfLabel == 8)
                document.setMargins(5, 0, 0, 5);
            else if (numberofRowsPerPageOfLabel == 10)
                document.setMargins(2, 2, 33.3f, 5);
            } else if (pageSizeId == AppConstants.SIZE_OF_PAPER_A4) {
            if (numberofRowsPerPageOfLabel == 7)
                document.setMargins(15, 0, 42, 5);
            else if (numberofRowsPerPageOfLabel == 8)
                document.setMargins(15, 0, 37, 5);
            else if (numberofRowsPerPageOfLabel == 10)
                document.setMargins(6, 2, 17.5f, 5);
            }
            */
            //float marginLeft, float marginRight, float marginTop, float marginBottom
            document.setMargins(paper.getMarginLeft(), paper.getMarginRight(), paper.getMarginTop(),
                    paper.getMarginBottom());

            // PdfWriter writer = PdfWriter.getInstance(document, baos);
            PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
            // step 3
            document.open();
            // step 4

            PdfContentByte canvas = writer.getDirectContent();

            int i = 0;
            int fixTableRowSize = numberOfLabelPerRow;
            PdfPTable table = new PdfPTable(fixTableRowSize);

            // table.writeSelectedRows(0, -1, 10, 12, canvas);
            float columnWidthSize = 265f;// 180f;
            float[] widthColumns = new float[fixTableRowSize];

            for (int counter = 0; counter < widthColumns.length; counter++) {
                widthColumns[counter] = columnWidthSize;
            }

            table.setWidths(widthColumns);
            table.setWidthPercentage(100);
            int width = 600;
            int height = 75;

            List<File> filesToBeDeleted = new ArrayList<File>();
            //float cellHeight = getCellHeight(numberofRowsPerPageOfLabel, pageSizeId);
            float cellHeight = paper.getCellHeight();

            for (StudyTrialInstanceInfo trialInstance : trialInstances) {
                FieldMapTrialInstanceInfo fieldMapTrialInstanceInfo = trialInstance.getTrialInstance();

                Map<String, String> moreFieldInfo = new HashMap<String, String>();
                moreFieldInfo.put("locationName", fieldMapTrialInstanceInfo.getLocationName());
                moreFieldInfo.put("blockName", fieldMapTrialInstanceInfo.getBlockName());
                moreFieldInfo.put("selectedName", trialInstance.getFieldbookName());
                moreFieldInfo.put("trialInstanceNumber", fieldMapTrialInstanceInfo.getTrialInstanceNo());

                for (FieldMapLabel fieldMapLabel : fieldMapTrialInstanceInfo.getFieldMapLabels()) {

                    i++;
                    String barcodeLabel = generateBarcodeField(moreFieldInfo, fieldMapLabel, firstBarcodeField,
                            secondBarcodeField, thirdBarcodeField, barcodeNeeded);
                    if ("0".equalsIgnoreCase(barcodeNeeded)) {
                        barcodeLabel = " ";
                    }

                    BitMatrix bitMatrix = new Code128Writer().encode(barcodeLabel, BarcodeFormat.CODE_128,
                            width, height, null);
                    String imageLocation = System.getProperty("user.home") + "/" + Math.random() + ".png";
                    File imageFile = new File(imageLocation);
                    FileOutputStream fout = new FileOutputStream(imageFile);
                    MatrixToImageWriter.writeToStream(bitMatrix, "png", fout);
                    filesToBeDeleted.add(imageFile);

                    Image mainImage = Image.getInstance(imageLocation);

                    PdfPCell cell = new PdfPCell();
                    cell.setFixedHeight(cellHeight);
                    cell.setNoWrap(false);
                    cell.setPadding(5f);
                    cell.setPaddingBottom(1f);

                    PdfPTable innerImageTableInfo = new PdfPTable(1);
                    innerImageTableInfo.setWidths(new float[] { 1 });
                    innerImageTableInfo.setWidthPercentage(82);
                    PdfPCell cellImage = new PdfPCell();
                    if ("1".equalsIgnoreCase(barcodeNeeded)) {
                        cellImage.addElement(mainImage);
                    } else {
                        cellImage.addElement(new Paragraph(" "));
                    }
                    cellImage.setBorder(Rectangle.NO_BORDER);
                    cellImage.setBackgroundColor(Color.white);
                    cellImage.setPadding(1.5f);

                    innerImageTableInfo.addCell(cellImage);

                    //float fontSize = 6.8f;
                    float fontSize = paper.getFontSize();
                    //if (numberofRowsPerPageOfLabel == 10)
                    //    fontSize = 4.8f;

                    Font fontNormal = FontFactory.getFont("Arial", fontSize, Font.NORMAL);

                    // cell.addElement(mainImage);
                    cell.addElement(innerImageTableInfo);

                    cell.addElement(new Paragraph());
                    for (int row = 0; row < 5; row++) {
                        if (row == 0) {
                            PdfPTable innerDataTableInfo = new PdfPTable(1);
                            innerDataTableInfo.setWidths(new float[] { 1 });
                            innerDataTableInfo.setWidthPercentage(85);

                            Font fontNormalData = FontFactory.getFont("Arial", 5.0f, Font.NORMAL);
                            PdfPCell cellInnerData = new PdfPCell(new Phrase(barcodeLabel, fontNormalData));

                            cellInnerData.setBorder(Rectangle.NO_BORDER);
                            cellInnerData.setBackgroundColor(Color.white);
                            cellInnerData.setPaddingBottom(0.2f);
                            cellInnerData.setPaddingTop(0.2f);
                            cellInnerData.setHorizontalAlignment(Element.ALIGN_MIDDLE);

                            innerDataTableInfo.addCell(cellInnerData);
                            innerDataTableInfo.setHorizontalAlignment(Element.ALIGN_MIDDLE);
                            cell.addElement(innerDataTableInfo);
                        }
                        PdfPTable innerTableInfo = new PdfPTable(2);
                        innerTableInfo.setWidths(new float[] { 1, 1 });
                        innerTableInfo.setWidthPercentage(85);

                        String leftText = generateBarcodeLabel(moreFieldInfo, fieldMapLabel, leftSelectedFields,
                                row);
                        PdfPCell cellInnerLeft = new PdfPCell(new Paragraph(leftText, fontNormal));

                        cellInnerLeft.setBorder(Rectangle.NO_BORDER);
                        cellInnerLeft.setBackgroundColor(Color.white);
                        cellInnerLeft.setPaddingBottom(0.5f);
                        cellInnerLeft.setPaddingTop(0.5f);

                        innerTableInfo.addCell(cellInnerLeft);

                        String rightText = generateBarcodeLabel(moreFieldInfo, fieldMapLabel,
                                rightSelectedFields, row);
                        PdfPCell cellInnerRight = new PdfPCell(new Paragraph(rightText, fontNormal));

                        cellInnerRight.setBorder(Rectangle.NO_BORDER);
                        cellInnerRight.setBackgroundColor(Color.white);
                        cellInnerRight.setPaddingBottom(0.5f);
                        cellInnerRight.setPaddingTop(0.5f);

                        innerTableInfo.addCell(cellInnerRight);

                        cell.addElement(innerTableInfo);
                    }

                    cell.setBorder(Rectangle.NO_BORDER);
                    cell.setBackgroundColor(Color.white);

                    //cell.setBorderColor(Color.BLUE);

                    table.addCell(cell);

                    if (i % numberOfLabelPerRow == 0) {
                        // we go the next line

                        int needed = fixTableRowSize - numberOfLabelPerRow;

                        for (int neededCount = 0; neededCount < needed; neededCount++) {
                            PdfPCell cellNeeded = new PdfPCell();

                            cellNeeded.setBorder(Rectangle.NO_BORDER);
                            cellNeeded.setBackgroundColor(Color.white);

                            table.addCell(cellNeeded);
                        }

                        table.completeRow();
                        if (numberofRowsPerPageOfLabel == 10) {

                            //table.setSpacingAfter(9f);
                            table.setSpacingAfter(paper.getSpacingAfter());
                        }

                        document.add(table);

                        table = new PdfPTable(fixTableRowSize);
                        table.setWidths(widthColumns);
                        table.setWidthPercentage(100);

                    }
                    if (i % totalPerPage == 0) {
                        // we go the next page
                        document.newPage();
                    }
                    fout.flush();
                    fout.close();

                }
            }
            // we need to add the last row
            if (i % numberOfLabelPerRow != 0) {
                // we go the next line

                int needed = fixTableRowSize - numberOfLabelPerRow;
                int remaining = numberOfLabelPerRow - (i % numberOfLabelPerRow);
                for (int neededCount = 0; neededCount < remaining; neededCount++) {
                    PdfPCell cellNeeded = new PdfPCell();

                    cellNeeded.setBorder(Rectangle.NO_BORDER);
                    cellNeeded.setBackgroundColor(Color.white);

                    table.addCell(cellNeeded);
                }

                table.completeRow();
                if (numberofRowsPerPageOfLabel == 10) {

                    table.setSpacingAfter(paper.getSpacingAfter());
                }

                document.add(table);

                table = new PdfPTable(fixTableRowSize);
                table.setWidths(widthColumns);
                table.setWidthPercentage(100);

            }

            document.close();
            for (File file : filesToBeDeleted) {
                file.delete();
            }
            fileOutputStream.close();

        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }

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

From source file:com.efficio.fieldbook.web.demo.controller.BarCodeController.java

License:Open Source License

/**
 * Upload file./*w  w  w .j  av  a2  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.eteks.sweethome3d.swing.HomePDFPrinter.java

License:Open Source License

/**
 * Writes to <code>outputStream</code> the print of a home in PDF format.
 *//*from   ww w . j av  a  2s.  c om*/
public void write(OutputStream outputStream) throws IOException {
    PageFormat pageFormat = HomePrintableComponent.getPageFormat(this.home.getPrint());
    Document pdfDocument = new Document(
            new Rectangle((float) pageFormat.getWidth(), (float) pageFormat.getHeight()));
    try {
        // Get a PDF writer that will write to the given PDF output stream
        PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, outputStream);
        pdfDocument.open();

        // Set PDF document description
        pdfDocument.addAuthor(System.getProperty("user.name", ""));
        String pdfDocumentCreator = this.preferences.getLocalizedString(HomePDFPrinter.class,
                "pdfDocument.creator");
        pdfDocument.addCreator(pdfDocumentCreator);
        pdfDocument.addCreationDate();
        String homeName = this.home.getName();
        if (homeName != null) {
            pdfDocument.addTitle(this.controller.getContentManager().getPresentationName(homeName,
                    ContentManager.ContentType.PDF));
        }

        PdfContentByte pdfContent = pdfWriter.getDirectContent();
        HomePrintableComponent printableComponent = new HomePrintableComponent(this.home, this.controller,
                this.defaultFont);
        // Print each page
        for (int page = 0, pageCount = printableComponent.getPageCount(); page < pageCount; page++) {
            // Check current thread isn't interrupted
            if (Thread.interrupted()) {
                throw new InterruptedIOException();
            }
            PdfTemplate pdfTemplate = pdfContent.createTemplate((float) pageFormat.getWidth(),
                    (float) pageFormat.getHeight());
            Graphics g = pdfTemplate.createGraphicsShapes((float) pageFormat.getWidth(),
                    (float) pageFormat.getHeight());

            printableComponent.print(g, pageFormat, page);

            pdfContent.addTemplate(pdfTemplate, 0, 0);
            g.dispose();

            if (page != pageCount - 1) {
                pdfDocument.newPage();
            }
        }
        pdfDocument.close();
    } catch (DocumentException ex) {
        IOException exception = new IOException("Couldn't print to PDF");
        exception.initCause(ex);
        throw exception;
    } catch (InterruptedPrinterException ex) {
        throw new InterruptedIOException("Print to PDF interrupted");
    } catch (PrinterException ex) {
        IOException exception = new IOException("Couldn't print to PDF");
        exception.initCause(ex);
        throw exception;
    }
}

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();
    pdf.setPageSize(PageSize.A4);/* ww w.  j  ava 2 s  .c o  m*/

    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

public ConvertPDF(ArrayList<DeviceDTO> input) {

    try {//from   w  ww. j a va2  s  .  c o m
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILE));
        System.out.println("opening document " + FILE);
        document.open();
        addMetaData(document);
        addTitlePage(document);
        addContent(document, input);
        addPieChart(generatePieChart(input), 500, 400, writer);
        document.close();
        System.out.println("closing document " + FILE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

public static void main(String[] args) {

    try {//ww w  .  j a  v a2  s.co  m
        ArrayList<DeviceDTO> input = new ArrayList<DeviceDTO>();
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILE));
        System.out.println("opening document " + FILE);
        document.open();
        addMetaData(document);
        addTitlePage(document);
        addContent(document, input);
        addPieChart(generatePieChart(input), 500, 400, writer);
        document.close();
        System.out.println("closing document " + FILE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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.ja  va2s . 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 {//from   w w  w . j a  va  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.ListFieldForm.java

License:Open Source License

public ListFieldForm() throws Exception {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("ListFieldForm.pdf"));
    document.open();

    // Code 1// ww  w  . ja  va 2s  .co m
    String options[] = { "PS3", "XBOX 360", "Wii", "PSP", "NDS", "GBA" };

    // Code 2 create drop-down list
    PdfFormField dropDown = PdfFormField.createCombo(writer, true, options, 0);
    dropDown.setWidget(new Rectangle(50, 785, 120, 800), PdfAnnotation.HIGHLIGHT_INVERT);
    dropDown.setFieldName("dropDownList");
    dropDown.setValueAsString("PS3");
    dropDown.setMKBorderColor(Color.BLACK);
    writer.addAnnotation(dropDown);

    // Code 3 create scrollable list
    TextField scrollableList = new TextField(writer, new Rectangle(150, 740, 250, 800), "scrollableList");
    scrollableList.setBackgroundColor(Color.WHITE);
    scrollableList.setBorderColor(Color.BLUE);
    scrollableList.setBorderWidth(2);
    scrollableList.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    scrollableList.setFontSize(10);
    scrollableList.setChoices(options);
    scrollableList.setChoiceSelection(0);
    writer.addAnnotation(scrollableList.getListField());

    // Code 4 add function and button for showing state 
    writer.addJavaScript(
            "function showState(){" + "app.alert('DropDown:'+ this.getField('dropDownList').value +'\\n'+"
                    + "'Scrollable List:'+this.getField('scrollableList').value);" + "}");
    PushbuttonField push = new PushbuttonField(writer, new Rectangle(70, 710, 140, 730), "pushAction");
    push.setBackgroundColor(Color.LIGHT_GRAY);
    push.setBorderColor(Color.GRAY);
    push.setText("Show State");
    push.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
    push.setTextColor(Color.BLACK);
    PdfFormField pushbutton = push.getField();
    pushbutton.setAction(PdfAction.javaScript("showState()", writer));
    writer.addAnnotation(pushbutton);

    document.close();
}