Example usage for com.lowagie.text Document setMargins

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

Introduction

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

Prototype


public boolean setMargins(float marginLeft, float marginRight, float marginTop, float marginBottom) 

Source Link

Document

Sets the margins.

Usage

From source file:com.aryjr.nheengatu.pdf.PDFDocument.java

License:Open Source License

public void generateFile(final OutputStream out) throws IOException {
    final Document document;
    if (styleSheet == null || styleSheet.getStyles() == null || !styleSheet.getStyles().containsKey("@page")) {
        document = new Document(PageSize.A4);
        document.setMargins(3.0f * PDFDocument.CM_UNIT, 2.0f * PDFDocument.CM_UNIT, 1.0f * PDFDocument.CM_UNIT,
                2.0f * PDFDocument.CM_UNIT);
        System.out.println("Processamento: terminou setMargins");
    } else {//  w  w w. j  av a 2 s.  c o  m
        Style style = ((Style) (styleSheet.getStyles().get("@page")));
        if ("landscape".equals(style.getPropertyValue("size"))) {
            document = new Document(PageSize.A4.rotate());
        } else {
            document = new Document(PageSize.A4);
        }
        String s = style.getPropertyValue("margin-left");
        Float f = styleMeasure(s, "3cm");
        document.setMargins(styleMeasure(style.getPropertyValue("margin-left"), "3cm"),
                styleMeasure(style.getPropertyValue("margin-right"), "2cm"),
                styleMeasure(style.getPropertyValue("margin-top"), "1cm"),
                styleMeasure(style.getPropertyValue("margin-bottom"), "2cm"));
        System.out.println("Processamento: terminou setMargins do else");
    }
    try {
        final PdfWriter writer = PdfWriter.getInstance(document, out);
        writer.setPageEvent(new PDFPageBreak(writer, document, headFirstPage, footFirstPage, head, foot));
        document.open();
        final MultiColumnText mct = new MultiColumnText();
        // set up 3 even columns with 10pt space between
        mct.addRegularColumns(document.left(), document.right(), 0f, 1);

        System.out.println("Processamento: prestes a extract visible components");

        // Extracting the document content
        extractVisibleComponents(body, document, mct, null, null);

        document.add(mct);
        document.close();
    } catch (final DocumentException de) {
        System.err.println(de.getMessage());
    }
}

From source file:com.aryjr.nheengatu.pdf.PDFPageBreak.java

License:Open Source License

public PDFPageBreak(final PdfWriter writer, final Document document, final Tag headFirstPageTag,
        final Tag footFirstPageTag, final Tag headTag, final Tag footTag) throws DocumentException {
    this.headFirstPageTag = headFirstPageTag;
    this.footFirstPageTag = footFirstPageTag;
    this.headTag = headTag;
    this.footTag = footTag;

    final Rectangle page = document.getPageSize();
    if (headTag != null) {
        final PDFTable pdft = createTable(writer, document, headTag);
        pdft.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        headHeight = pdft.getTotalHeight();
    }/*from  ww  w.j  a  va2  s .  c  om*/
    if (footTag != null) {
        final PDFTable pdft = createTable(writer, document, footTag);
        pdft.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        footHeight = pdft.getTotalHeight();
    }
    if (headFirstPageTag != null) {
        final PDFTable pdft = createTable(writer, document, headFirstPageTag);
        pdft.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        headFirstPageHeight = pdft.getTotalHeight();
    }
    if (footFirstPageTag != null) {
        final PDFTable pdft = createTable(writer, document, footFirstPageTag);
        pdft.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        footFirstPageHeight = pdft.getTotalHeight();
    }

    topMargin = document.topMargin();
    bottomMargin = document.bottomMargin();
    document.setMargins(document.leftMargin(), document.rightMargin(), topMargin + headFirstPageHeight,
            bottomMargin + footFirstPageHeight);

}

From source file:com.aryjr.nheengatu.pdf.PDFPageBreak.java

License:Open Source License

@Override
public void onEndPage(final PdfWriter writer, final Document document) {
    try {//from w  w  w  . j a v  a  2s .c o m
        final Rectangle page = document.getPageSize();
        PDFTable head = null;
        PDFTable foot = null;

        if (writer.getPageNumber() == 1) {
            if (headFirstPageTag != null)
                head = createTable(writer, document, headFirstPageTag);
            if (footFirstPageTag != null)
                foot = createTable(writer, document, footFirstPageTag);
        } else {
            if (headTag != null)
                head = createTable(writer, document, headTag);
            if (footTag != null)
                foot = createTable(writer, document, footTag);
        }

        if (head != null) {
            head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
            head.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - topMargin,
                    writer.getDirectContent());
        }
        if (foot != null) {
            foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
            foot.writeSelectedRows(0, -1, document.leftMargin(), bottomMargin + foot.getTotalHeight(),
                    writer.getDirectContent());
        }
    } catch (final Exception e) {
        throw new ExceptionConverter(e);
    }

    document.setMargins(document.leftMargin(), document.rightMargin(), topMargin + headHeight,
            bottomMargin + footHeight);
}

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

License:Open Source License

/**
 * Gets the cell height.//from  w  w w.  j av  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.ideaspymes.proyecttemplate.stock.web.ProductoConsultaBean.java

public String createPdf() throws IOException, DocumentException {

    EtiquetaConf conf = etiquetaConfDAO.getEtiquetaConfDefault();

    if (hayParaImprimir() && conf != null) {

        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();
        response.setContentType("application/x-pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"etiquetas.pdf\"");

        float ancho = Utilities.millimetersToPoints(conf.getAnchoHoja().floatValue());
        System.out.println("Ancho: " + ancho);
        float largo = Utilities.millimetersToPoints(conf.getLargoHoja().floatValue());
        System.out.println("Alto: " + largo);

        // step 1
        Document document = new Document(new Rectangle(ancho, largo));
        // step 2

        document.setMargins(0f, 0f, 0f, 0f);

        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
        // step 3
        document.open();/*from   ww  w .jav a 2s  .  c o  m*/

        // step 4
        PdfContentByte cb = writer.getDirectContent();

        for (Producto p : getLista()) {
            if (p.getCantidadEtiquetas() > 0) {

                PdfPTable table = new PdfPTable(2);
                table.setWidthPercentage(96);

                Font fontbold = FontFactory.getFont("Times-Roman", 8, Font.NORMAL);

                Chunk productTitle = new Chunk("HC", fontbold);

                Paragraph pTitile = new Paragraph(productTitle);
                pTitile.setAlignment(Element.ALIGN_LEFT);
                pTitile.setLeading(6, 0);

                PdfPCell cellTitle = new PdfPCell();
                cellTitle.setHorizontalAlignment(Element.ALIGN_LEFT);
                cellTitle.setVerticalAlignment(Element.ALIGN_TOP);
                cellTitle.setBorder(Rectangle.NO_BORDER);
                cellTitle.addElement(pTitile);

                Font font2 = FontFactory.getFont("Times-Roman", conf.getTamDescripcion().floatValue(),
                        Font.NORMAL);

                Chunk productName = new Chunk(p.getNombre(), font2);

                Paragraph pName = new Paragraph(productName);
                pName.setAlignment(Element.ALIGN_CENTER);
                //pTitile.setLeading(0, 1);

                cellTitle.addElement(pName);

                table.addCell(cellTitle);

                Barcode39 code39 = new Barcode39();
                code39.setCode(p.getCodigo());
                //code39.setCodeType(Barcode.EAN13);
                code39.setBarHeight(conf.getAltoCodBarra().floatValue());
                //codeEan.setX(0.7f);
                code39.setSize(conf.getTamDescripcion().floatValue());
                //code39.setAltText("HC - " + p.getNombre());

                PdfPCell cellBarcode = new PdfPCell();
                cellBarcode.setHorizontalAlignment(Element.ALIGN_CENTER);
                cellBarcode.setBorder(Rectangle.NO_BORDER);
                cellBarcode.addElement(code39.createImageWithBarcode(cb, null, Color.BLACK));

                table.addCell(cellBarcode);

                for (int i = 0; i < p.getCantidadEtiquetas(); i++) {
                    document.add(table);
                    document.newPage();
                }
            }
        }

        // step 5
        document.close();

        response.getOutputStream().flush();
        response.getOutputStream().close();
        FacesContext.getCurrentInstance().responseComplete();
    } else {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "No hay nada que imprimir", ""));
    }
    return null;
}

From source file:com.isdemu.controller.TBS_UsuarioController.java

@RequestMapping(value = "/codigo_barra", method = RequestMethod.POST)
@ResponseBody//w  w  w.  java 2 s . c  om
public String codigo(@RequestBody String codigos) throws FileNotFoundException, DocumentException {

    JSONObject array = new JSONObject(codigos);

    Document document = new Document();

    File file = new File(this.getClass().getResource("/codigoBarraIsdemu.pdf").getFile());

    String absolutePath = file.getAbsolutePath();

    absolutePath = absolutePath.replaceAll("%20", " ");

    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(absolutePath));

    Rectangle one = new Rectangle(76, 35);
    document.setPageSize(one);
    document.setMargins(2, 2, 2, 2);

    document.open();

    Barcode128 code128 = new Barcode128();
    code128.setGenerateChecksum(true);

    JSONArray object = array.getJSONArray("Inventario");
    for (int i = 0; i < object.length(); i++) {
        JSONObject object2 = object.getJSONObject(i);

        //JSONArray object = array.getJSONArray("Inventario");
        String id = object2.getString("idInv");

        code128.setCode(id);
        document.add(code128.createImageWithBarcode(writer.getDirectContent(), null, null));

        document.newPage();

    }

    document.close();

    return "Almacenado";

}

From source file:com.kahlon.guard.controller.DocumentManager.java

/**
 *
 * @param document//from   w  w  w  . j  a va 2  s . co  m
 */
public void preProcessPDF(Object document) {
    try {

        BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", false);

        Document pdf = (Document) document;
        pdf.setPageSize(PageSize.A4);
        pdf.setMargins(5f, 5f, 10f, 5f);

        // headers and footers must be added before the document is opened
        HeaderFooter footer = new HeaderFooter(new Phrase("page: ", new Font(bf_courier)), true);
        footer.setBorder(Rectangle.NO_BORDER);
        footer.setAlignment(Element.ALIGN_CENTER);
        pdf.setFooter(footer);

        //            HeaderFooter header = new HeaderFooter(
        //                        new Phrase("This is a header without a page number", new Font(bf_courier)), false);
        //            header.setAlignment(Element.ALIGN_CENTER);
        //            pdf.setHeader(header);

        pdf.open();

        String logoPath = "/resources/image/logo.png";
        ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
        String logo = servletContext.getRealPath(logoPath);

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

        Person person = context.getSelectedPerson().getDisplayPerson();

        String name = FacesMessageUtil.getMessage("person.name") + " : " + person.getName();
        String age = FacesMessageUtil.getMessage("person.age") + " : " + Integer.toString(person.getAge());
        String gender = FacesMessageUtil.getMessage("person.gender") + " : "
                + person.getGender().getDescription();
        String race = FacesMessageUtil.getMessage("person.ethnicity") + " : "
                + person.getEthnicity().getDescription();

        Person rootPerson = person.getRootPerson();
        PersonImage imgp = imageService.getLastestPersonImage(rootPerson.getId());
        Image imgb = Image.getInstance(imgp.getContent());
        imgb.scaleToFit(100, 120);

        PdfPTable headerTable = new PdfPTable(2);

        PdfPTable personTable = new PdfPTable(1);
        personTable.setWidthPercentage(100);
        PdfPCell cell;

        cell = new PdfPCell(new Phrase(name));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        cell = new PdfPCell(new Phrase(age));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        cell = new PdfPCell(new Phrase(gender));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        cell = new PdfPCell(new Phrase(race));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        BarcodePDF417 pdf417 = new BarcodePDF417();
        pdf417.setText(Integer.toString(person.getId()));
        Image img = pdf417.getImage();
        img.scalePercent(150, 60 * pdf417.getYHeight());
        cell = new PdfPCell(img);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(15);
        personTable.addCell(cell);

        cell.addElement(personTable);
        headerTable.addCell(cell);

        cell = new PdfPCell(imgb);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(Rectangle.NO_BORDER);
        headerTable.addCell(cell);

        headerTable.setSpacingAfter(15);
        pdf.add(headerTable);

        LineSeparator lineSeparator = new LineSeparator();
        lineSeparator.setPercentage(82);
        pdf.add(lineSeparator);
        Paragraph space = new Paragraph();
        space.add("");
        space.setSpacingAfter(15);
        pdf.add(space);

    } catch (IOException e) {
        logger.log(Level.INFO, e.getMessage());
    } catch (BadElementException e) {
        logger.log(Level.INFO, e.getMessage());
    } catch (DocumentException e) {
        logger.log(Level.INFO, e.getMessage());
    } catch (Exception e) {
        logger.log(Level.INFO, e.getMessage());
    }

}

From source file:com.mitchell.services.business.partialloss.assignmentdelivery.handler.ndu.util.AssignmentEmailDeliveryUtils.java

public void createPDF(final String content, final String path) throws Exception {

    // Create the PDF Document

    // step 1: creation of a document-object
    com.lowagie.text.Document document = new com.lowagie.text.Document(PageSize.LETTER, 36, 36, 36, 36);

    // step 2://from   w  ww  .ja  va 2  s.  c  o m
    // we create a writer that listens to the document
    // and directs a PDF-stream to a file
    PdfWriter.getInstance(document, new java.io.FileOutputStream(path));

    // step 3: we open the document
    document.open();

    // step 4:
    document.setMargins(36, 36, 36, 36);
    Paragraph paragraph = new Paragraph();
    paragraph.setAlignment(Element.ALIGN_LEFT);
    paragraph.add(content);
    document.add(paragraph);

    // step 5: we close the document
    document.close();
}

From source file:com.qcadoo.plugins.qcadooExport.internal.ExportToPDFController.java

License:Open Source License

@Monitorable(threshold = 500)
@ResponseBody//from   w w  w. j  a  va2 s .  co m
@RequestMapping(value = { CONTROLLER_PATH }, method = RequestMethod.POST)
public Object generatePdf(@PathVariable(PLUGIN_IDENTIFIER_VARIABLE) final String pluginIdentifier,
        @PathVariable(VIEW_NAME_VARIABLE) final String viewName, @RequestBody final JSONObject body,
        final Locale locale) {
    try {
        changeMaxResults(body);
        ViewDefinitionState state = crudService.invokeEvent(pluginIdentifier, viewName, body, locale);
        GridComponent grid = (GridComponent) state.getComponentByReference("grid");
        Document document = new Document(PageSize.A4.rotate());
        String date = DateFormat.getDateInstance().format(new Date());
        File file = fileService.createExportFile("export_" + grid.getName() + "_" + date + ".pdf");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);

        writer.setPageEvent(new PdfPageNumbering(footerResolver.resolveFooter(locale)));

        document.setMargins(40, 40, 60, 60);

        document.addTitle("export.pdf");
        pdfHelper.addMetaData(document);
        writer.createXmpMetadata();
        document.open();

        String title = translationService.translate(
                pluginIdentifier + "." + viewName + ".window.mainTab." + grid.getName() + ".header", locale);

        Date generationDate = new Date();

        pdfHelper.addDocumentHeader(document, "", title,
                translationService.translate("qcadooReport.commons.generatedBy.label", locale), generationDate);

        int columns = 0;
        List<String> exportToPDFTableHeader = new ArrayList<String>();
        for (String name : grid.getColumnNames().values()) {
            exportToPDFTableHeader.add(name);
            columns++;
        }
        PdfPTable table = pdfHelper.createTableWithHeader(columns, exportToPDFTableHeader, false);

        List<Map<String, String>> rows;
        if (grid.getSelectedEntitiesIds().isEmpty()) {
            rows = grid.getColumnValuesOfAllRecords();
        } else {
            rows = grid.getColumnValuesOfSelectedRecords();
        }

        for (Map<String, String> row : rows) {
            for (String value : row.values()) {
                table.addCell(new Phrase(value, FontUtils.getDejavuRegular7Dark()));
            }
        }
        document.add(table);
        document.close();

        state.redirectTo(fileService.getUrl(file.getAbsolutePath()) + "?clean", true, false);
        return crudService.renderView(state);
    } catch (JSONException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:com.qcadoo.report.api.pdf.PdfDocumentService.java

License:Open Source License

private void generate(final Entity entity, final Locale locale, final String filename, final Rectangle pageSize)
        throws IOException, DocumentException {
    Document document = new Document(pageSize);
    try {/*from  www  .ja  va2  s. co  m*/
        FileOutputStream fileOutputStream = new FileOutputStream(
                fileService.createReportFile(filename + "." + ReportService.ReportType.PDF.getExtension()));
        PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
        writer.setPageEvent(new PdfPageNumbering(footerResolver.resolveFooter(locale)));
        document.setMargins(40, 40, 60, 60);
        buildPdfMetadata(document, locale);
        writer.createXmpMetadata();
        document.open();
        buildPdfContent(document, entity, locale);
        document.close();
    } catch (DocumentException e) {
        LOG.error("Problem with generating document - " + e.getMessage());
        document.close();
        throw e;
    }
}