Example usage for com.lowagie.text Document setPageSize

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

Introduction

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

Prototype


public boolean setPageSize(Rectangle pageSize) 

Source Link

Document

Sets the pagesize.

Usage

From source file:org.kuali.kra.printing.service.impl.PrintingServiceImpl.java

License:Educational Community License

/**
 * @param pdfBytesList/*  w  w  w . j a v  a2  s .  c  o  m*/
 *            List containing the PDF data bytes
 * @param bookmarksList
 *            List of bookmarks corresponding to the PDF bytes.
 * @return
 * @throws PrintingException
 */

protected byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList,
        boolean headerFooterRequired) throws PrintingException {
    Document document = null;
    PdfWriter writer = null;
    ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream();
    int totalNumOfPages = 0;
    PdfReader[] pdfReaderArr = new PdfReader[pdfBytesList.size()];
    int pdfReaderCount = 0;
    for (byte[] fileBytes : pdfBytesList) {
        LOG.debug("File Size " + fileBytes.length + " For " + bookmarksList.get(pdfReaderCount));
        PdfReader reader = null;
        try {
            reader = new PdfReader(fileBytes);
            pdfReaderArr[pdfReaderCount] = reader;
            pdfReaderCount = pdfReaderCount + 1;
            totalNumOfPages += reader.getNumberOfPages();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    HeaderFooter footer = null;
    if (headerFooterRequired) {
        Calendar calendar = dateTimeService.getCurrentCalendar();
        String dateString = formateCalendar(calendar);
        StringBuilder footerPhStr = new StringBuilder();
        footerPhStr.append(" of ");
        footerPhStr.append(totalNumOfPages);
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_60));
        footerPhStr.append(dateString);
        Font font = FontFactory.getFont(FontFactory.TIMES, 8, Font.NORMAL, Color.BLACK);
        Phrase beforePhrase = new Phrase("Page ", font);
        Phrase afterPhrase = new Phrase(footerPhStr.toString(), font);
        footer = new HeaderFooter(beforePhrase, afterPhrase);
        footer.setAlignment(Element.ALIGN_BASELINE);
        footer.setBorderWidth(0f);
    }
    for (int count = 0; count < pdfReaderArr.length; count++) {
        PdfReader reader = pdfReaderArr[count];
        int nop;
        if (reader == null) {
            LOG.debug("Empty PDF byetes found for " + bookmarksList.get(count));
            continue;
        } else {
            nop = reader.getNumberOfPages();
        }

        if (count == 0) {
            document = nop > 0 ? new com.lowagie.text.Document(reader.getPageSizeWithRotation(1))
                    : new com.lowagie.text.Document();
            try {
                writer = PdfWriter.getInstance(document, mergedPdfReport);
            } catch (DocumentException e) {
                LOG.error(e.getMessage(), e);
                throw new PrintingException(e.getMessage(), e);
            }
            if (footer != null) {
                document.setFooter(footer);
            }
            // writer.setPageEvent(new Watermark());  //  add watermark object here
            document.open();
        }

        PdfContentByte cb = writer.getDirectContent();
        int pageCount = 0;
        while (pageCount < nop) {
            document.setPageSize(reader.getPageSize(++pageCount));
            document.newPage();
            if (footer != null) {
                document.setFooter(footer);
            }
            PdfImportedPage page = writer.getImportedPage(reader, pageCount);

            cb.addTemplate(page, 1, 0, 0, 1, 0, 0);

            PdfOutline root = cb.getRootOutline();
            if (pageCount == 1) {
                String pageName = bookmarksList.get(count);
                cb.addOutline(new PdfOutline(root, new PdfDestination(PdfDestination.FITH), pageName),
                        pageName);
            }
        }
    }
    if (document != null) {
        try {
            document.close();
            return mergedPdfReport.toByteArray();
        } catch (Exception e) {
            LOG.error("Exception occured because the generated PDF document has no pages", e);
        }
    }
    return null;
}

From source file:org.mapfish.print.config.layout.Page.java

License:Open Source License

public void render(PJsonObject params, RenderingContext context) throws DocumentException {
    final Document doc = context.getDocument();
    doc.setPageSize(getPageSizeRect(context, params));
    doc.setMargins(getMarginLeft(context, params), getMarginRight(context, params),
            getMarginTop(context, params) + (header != null ? header.getHeight() : 0),
            getMarginBottom(context, params) + (footer != null ? footer.getHeight() : 0));

    context.getCustomBlocks().setBackgroundPdf(PDFUtils.evalString(context, params, backgroundPdf));
    if (doc.isOpen()) {
        doc.newPage();//from   w  w  w .j a  va2 s.  com
    } else {
        doc.open();
    }
    context.getCustomBlocks().setHeader(header, params);
    context.getCustomBlocks().setFooter(footer, params);

    for (int i = 0; i < items.size(); i++) {
        Block block = items.get(i);
        if (block.isVisible(context, params)) {
            block.render(params, new Block.PdfElement() {
                public void add(Element element) throws DocumentException {
                    doc.add(element);
                }
            }, context);
        }
    }
}

From source file:org.ofbiz.content.compdoc.CompDocServices.java

License:Apache License

public static Map<String, Object> renderCompDocPdf(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();

    Locale locale = (Locale) context.get("locale");
    String rootDir = (String) context.get("rootDir");
    String webSiteId = (String) context.get("webSiteId");
    String https = (String) context.get("https");

    Delegator delegator = dctx.getDelegator();

    String contentId = (String) context.get("contentId");
    String contentRevisionSeqId = (String) context.get("contentRevisionSeqId");
    String oooHost = (String) context.get("oooHost");
    String oooPort = (String) context.get("oooPort");
    GenericValue userLogin = (GenericValue) context.get("userLogin");

    try {//from   w ww . j a  va2s  . c  o  m
        List<EntityCondition> exprList = FastList.newInstance();
        exprList.add(EntityCondition.makeCondition("contentIdTo", EntityOperator.EQUALS, contentId));
        exprList.add(
                EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.EQUALS, "COMPDOC_PART"));
        exprList.add(EntityCondition.makeCondition("rootRevisionContentId", EntityOperator.EQUALS, contentId));
        if (UtilValidate.isNotEmpty(contentRevisionSeqId)) {
            exprList.add(EntityCondition.makeCondition("contentRevisionSeqId",
                    EntityOperator.LESS_THAN_EQUAL_TO, contentRevisionSeqId));
        }

        List<GenericValue> compDocParts = EntityQuery.use(delegator)
                .select("rootRevisionContentId", "itemContentId", "maxRevisionSeqId", "contentId",
                        "dataResourceId", "contentIdTo", "contentAssocTypeId", "fromDate", "sequenceNum")
                .from("ContentAssocRevisionItemView").where(exprList).orderBy("sequenceNum").filterByDate()
                .queryList();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Document document = new Document();
        document.setPageSize(PageSize.LETTER);
        //Rectangle rect = document.getPageSize();
        //PdfWriter writer = PdfWriter.getInstance(document, baos);
        PdfCopy writer = new PdfCopy(document, baos);
        document.open();
        int pgCnt = 0;
        for (GenericValue contentAssocRevisionItemView : compDocParts) {
            //String thisContentId = contentAssocRevisionItemView.getString("contentId");
            //String thisContentRevisionSeqId = contentAssocRevisionItemView.getString("maxRevisionSeqId");
            String thisDataResourceId = contentAssocRevisionItemView.getString("dataResourceId");
            GenericValue dataResource = EntityQuery.use(delegator).from("DataResource")
                    .where("dataResourceId", thisDataResourceId).queryOne();
            String inputMimeType = null;
            if (dataResource != null) {
                inputMimeType = dataResource.getString("mimeTypeId");
            }
            byte[] inputByteArray = null;
            PdfReader reader = null;
            if (inputMimeType != null && inputMimeType.equals("application/pdf")) {
                ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId,
                        https, webSiteId, locale, rootDir);
                inputByteArray = byteBuffer.array();
                reader = new PdfReader(inputByteArray);
            } else if (inputMimeType != null && inputMimeType.equals("text/html")) {
                ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId,
                        https, webSiteId, locale, rootDir);
                inputByteArray = byteBuffer.array();
                String s = new String(inputByteArray);
                Debug.logInfo("text/html string:" + s, module);
                continue;
            } else if (inputMimeType != null && inputMimeType.equals("application/vnd.ofbiz.survey.response")) {
                String surveyResponseId = dataResource.getString("relatedDetailId");
                String surveyId = null;
                String acroFormContentId = null;
                GenericValue surveyResponse = null;
                if (UtilValidate.isNotEmpty(surveyResponseId)) {
                    surveyResponse = EntityQuery.use(delegator).from("SurveyResponse")
                            .where("surveyResponseId", surveyResponseId).queryOne();
                    if (surveyResponse != null) {
                        surveyId = surveyResponse.getString("surveyId");
                    }
                }
                if (UtilValidate.isNotEmpty(surveyId)) {
                    GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId)
                            .queryOne();
                    if (survey != null) {
                        acroFormContentId = survey.getString("acroFormContentId");
                        if (UtilValidate.isNotEmpty(acroFormContentId)) {
                            // TODO: is something supposed to be done here?
                        }
                    }
                }
                if (surveyResponse != null) {
                    if (UtilValidate.isEmpty(acroFormContentId)) {
                        // Create AcroForm PDF
                        Map<String, Object> survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse",
                                UtilMisc.toMap("surveyResponseId", surveyId));
                        if (ServiceUtil.isError(survey2PdfResults)) {
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                                    "ContentSurveyErrorBuildingPDF", locale), null, null, survey2PdfResults);
                        }

                        ByteBuffer outByteBuffer = (ByteBuffer) survey2PdfResults.get("outByteBuffer");
                        inputByteArray = outByteBuffer.array();
                        reader = new PdfReader(inputByteArray);
                    } else {
                        // Fill in acroForm
                        Map<String, Object> survey2AcroFieldResults = dispatcher.runSync(
                                "setAcroFieldsFromSurveyResponse",
                                UtilMisc.toMap("surveyResponseId", surveyResponseId));
                        if (ServiceUtil.isError(survey2AcroFieldResults)) {
                            return ServiceUtil
                                    .returnError(
                                            UtilProperties.getMessage(resource,
                                                    "ContentSurveyErrorSettingAcroFields", locale),
                                            null, null, survey2AcroFieldResults);
                        }

                        ByteBuffer outByteBuffer = (ByteBuffer) survey2AcroFieldResults.get("outByteBuffer");
                        inputByteArray = outByteBuffer.array();
                        reader = new PdfReader(inputByteArray);
                    }
                }
            } else {
                ByteBuffer inByteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator,
                        thisDataResourceId, https, webSiteId, locale, rootDir);

                Map<String, Object> convertInMap = UtilMisc.<String, Object>toMap("userLogin", userLogin,
                        "inByteBuffer", inByteBuffer, "inputMimeType", inputMimeType, "outputMimeType",
                        "application/pdf");
                if (UtilValidate.isNotEmpty(oooHost))
                    convertInMap.put("oooHost", oooHost);
                if (UtilValidate.isNotEmpty(oooPort))
                    convertInMap.put("oooPort", oooPort);

                Map<String, Object> convertResult = dispatcher.runSync("convertDocumentByteBuffer",
                        convertInMap);

                if (ServiceUtil.isError(convertResult)) {
                    return ServiceUtil.returnError(
                            UtilProperties.getMessage(resource, "ContentConvertingDocumentByteBuffer", locale),
                            null, null, convertResult);
                }

                ByteBuffer outByteBuffer = (ByteBuffer) convertResult.get("outByteBuffer");
                inputByteArray = outByteBuffer.array();
                reader = new PdfReader(inputByteArray);
            }
            if (reader != null) {
                int n = reader.getNumberOfPages();
                for (int i = 0; i < n; i++) {
                    PdfImportedPage pg = writer.getImportedPage(reader, i + 1);
                    //cb.addTemplate(pg, left, height * pgCnt);
                    writer.addPage(pg);
                    pgCnt++;
                }
            }
        }
        document.close();
        ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());

        Map<String, Object> results = ServiceUtil.returnSuccess();
        results.put("outByteBuffer", outByteBuffer);
        return results;
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(e.toString());
    } catch (IOException e) {
        Debug.logError(e, "Error in CompDoc operation: ", module);
        return ServiceUtil.returnError(e.toString());
    } catch (Exception e) {
        Debug.logError(e, "Error in CompDoc operation: ", module);
        return ServiceUtil.returnError(e.toString());
    }
}

From source file:org.ofbiz.content.compdoc.CompDocServices.java

License:Apache License

public static Map<String, Object> renderContentPdf(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Map<String, Object> results = ServiceUtil.returnSuccess();
    String dataResourceId = null;

    Locale locale = (Locale) context.get("locale");
    String rootDir = (String) context.get("rootDir");
    String webSiteId = (String) context.get("webSiteId");
    String https = (String) context.get("https");

    Delegator delegator = dctx.getDelegator();

    String contentId = (String) context.get("contentId");
    String contentRevisionSeqId = (String) context.get("contentRevisionSeqId");
    String oooHost = (String) context.get("oooHost");
    String oooPort = (String) context.get("oooPort");
    GenericValue userLogin = (GenericValue) context.get("userLogin");

    try {/*  ww w  .  jav  a 2  s.  c  om*/
        //Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
        //ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Document document = new Document();
        document.setPageSize(PageSize.LETTER);
        //Rectangle rect = document.getPageSize();
        //PdfCopy writer = new PdfCopy(document, baos);
        document.open();

        GenericValue dataResource = null;
        if (UtilValidate.isEmpty(contentRevisionSeqId)) {
            GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId)
                    .cache().queryOne();
            dataResourceId = content.getString("dataResourceId");
            Debug.logInfo("SCVH(0b)- dataResourceId:" + dataResourceId, module);
            dataResource = EntityQuery.use(delegator).from("DataResource")
                    .where("dataResourceId", dataResourceId).queryOne();
        } else {
            GenericValue contentRevisionItem = EntityQuery.use(delegator).from("ContentRevisionItem")
                    .where("contentId", contentId, "itemContentId", contentId, "contentRevisionSeqId",
                            contentRevisionSeqId)
                    .cache().queryOne();
            if (contentRevisionItem == null) {
                throw new ViewHandlerException("ContentRevisionItem record not found for contentId=" + contentId
                        + ", contentRevisionSeqId=" + contentRevisionSeqId + ", itemContentId=" + contentId);
            }
            Debug.logInfo("SCVH(1)- contentRevisionItem:" + contentRevisionItem, module);
            Debug.logInfo("SCVH(2)-contentId=" + contentId + ", contentRevisionSeqId=" + contentRevisionSeqId
                    + ", itemContentId=" + contentId, module);
            dataResourceId = contentRevisionItem.getString("newDataResourceId");
            Debug.logInfo("SCVH(3)- dataResourceId:" + dataResourceId, module);
            dataResource = EntityQuery.use(delegator).from("DataResource")
                    .where("dataResourceId", dataResourceId).queryOne();
        }
        String inputMimeType = null;
        if (dataResource != null) {
            inputMimeType = dataResource.getString("mimeTypeId");
        }
        byte[] inputByteArray = null;
        if (inputMimeType != null && inputMimeType.equals("application/pdf")) {
            ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, dataResourceId, https,
                    webSiteId, locale, rootDir);
            inputByteArray = byteBuffer.array();
        } else if (inputMimeType != null && inputMimeType.equals("text/html")) {
            ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, dataResourceId, https,
                    webSiteId, locale, rootDir);
            inputByteArray = byteBuffer.array();
            String s = new String(inputByteArray);
            Debug.logInfo("text/html string:" + s, module);
        } else if (inputMimeType != null && inputMimeType.equals("application/vnd.ofbiz.survey.response")) {
            String surveyResponseId = dataResource.getString("relatedDetailId");
            String surveyId = null;
            String acroFormContentId = null;
            GenericValue surveyResponse = null;
            if (UtilValidate.isNotEmpty(surveyResponseId)) {
                surveyResponse = EntityQuery.use(delegator).from("SurveyResponse")
                        .where("surveyResponseId", surveyResponseId).queryOne();
                if (surveyResponse != null) {
                    surveyId = surveyResponse.getString("surveyId");
                }
            }
            if (UtilValidate.isNotEmpty(surveyId)) {
                GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId)
                        .queryOne();
                if (survey != null) {
                    acroFormContentId = survey.getString("acroFormContentId");
                    if (UtilValidate.isNotEmpty(acroFormContentId)) {
                        // TODO: is something supposed to be done here?
                    }
                }
            }

            if (surveyResponse != null) {
                if (UtilValidate.isEmpty(acroFormContentId)) {
                    // Create AcroForm PDF
                    Map<String, Object> survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse",
                            UtilMisc.toMap("surveyResponseId", surveyResponseId));
                    if (ServiceUtil.isError(survey2PdfResults)) {
                        return ServiceUtil.returnError(
                                UtilProperties.getMessage(resource, "ContentSurveyErrorBuildingPDF", locale),
                                null, null, survey2PdfResults);
                    }

                    ByteBuffer outByteBuffer = (ByteBuffer) survey2PdfResults.get("outByteBuffer");
                    inputByteArray = outByteBuffer.array();
                } else {
                    // Fill in acroForm
                    Map<String, Object> survey2AcroFieldResults = dispatcher.runSync(
                            "setAcroFieldsFromSurveyResponse",
                            UtilMisc.toMap("surveyResponseId", surveyResponseId));
                    if (ServiceUtil.isError(survey2AcroFieldResults)) {
                        return ServiceUtil
                                .returnError(
                                        UtilProperties.getMessage(resource,
                                                "ContentSurveyErrorSettingAcroFields", locale),
                                        null, null, survey2AcroFieldResults);
                    }

                    ByteBuffer outByteBuffer = (ByteBuffer) survey2AcroFieldResults.get("outByteBuffer");
                    inputByteArray = outByteBuffer.array();
                }
            }
        } else {
            ByteBuffer inByteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, dataResourceId,
                    https, webSiteId, locale, rootDir);

            Map<String, Object> convertInMap = UtilMisc.<String, Object>toMap("userLogin", userLogin,
                    "inByteBuffer", inByteBuffer, "inputMimeType", inputMimeType, "outputMimeType",
                    "application/pdf");
            if (UtilValidate.isNotEmpty(oooHost))
                convertInMap.put("oooHost", oooHost);
            if (UtilValidate.isNotEmpty(oooPort))
                convertInMap.put("oooPort", oooPort);

            Map<String, Object> convertResult = dispatcher.runSync("convertDocumentByteBuffer", convertInMap);

            if (ServiceUtil.isError(convertResult)) {
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "ContentConvertingDocumentByteBuffer", locale),
                        null, null, convertResult);
            }

            ByteBuffer outByteBuffer = (ByteBuffer) convertResult.get("outByteBuffer");
            inputByteArray = outByteBuffer.array();
        }

        ByteBuffer outByteBuffer = ByteBuffer.wrap(inputByteArray);
        results.put("outByteBuffer", outByteBuffer);
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(e.toString());
    } catch (IOException e) {
        Debug.logError(e, "Error in PDF generation: ", module);
        return ServiceUtil.returnError(e.toString());
    } catch (Exception e) {
        Debug.logError(e, "Error in PDF generation: ", module);
        return ServiceUtil.returnError(e.toString());
    }
    return results;
}

From source file:org.openepics.discs.names.ui.ReportManager.java

License:Open Source License

public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException {
    Document pdf = (Document) document;
    pdf.setPageSize(PageSize.LETTER.rotate());
    // pdf.open();
    // pdf.setPageSize(PageSize.LETTER.rotate());
    pdf.addCreationDate();/*  w ww .j a  v a 2s  . c  om*/
    pdf.addHeader("Header", "Proteus: Naming Convention Rep");
    pdf.addTitle("Proteus: Naming Convention Report");

    // 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:org.oscarehr.phr.web.PHRUserManagementAction.java

License:Open Source License

public ByteArrayOutputStream generateUserRegistrationLetter(String demographicNo, String username,
        String password) throws Exception {
    log.debug("Demographic " + demographicNo + " username " + username + " password " + password);
    DemographicDao demographicDao = (DemographicDao) SpringUtils.getBean("demographicDao");
    Demographic demographic = demographicDao.getDemographic(demographicNo);

    final String PAGESIZE = "printPageSize";
    Document document = new Document();

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfWriter writer = null;/*from   ww  w  .j  a v a 2 s .  c o  m*/

    try {
        writer = PdfWriter.getInstance(document, baosPDF);

        String title = "TITLE";
        String template = "MyOscarLetterHead.pdf";

        Properties printCfg = getCfgProp();

        String[] cfgVal = null;
        StringBuilder tempName = null;

        // get the print prop values

        Properties props = new Properties();
        props.setProperty("letterDate", UtilDateUtilities.getToday("yyyy-MM-dd"));
        props.setProperty("name", demographic.getFirstName() + " " + demographic.getLastName());
        props.setProperty("dearname", demographic.getFirstName() + " " + demographic.getLastName());
        props.setProperty("address", demographic.getAddress());
        props.setProperty("city", demographic.getCity() + ", " + demographic.getProvince());
        props.setProperty("postalCode", demographic.getPostal());
        props.setProperty("credHeading", "MyOscar User Account Details");
        props.setProperty("username", "Username: " + username);
        props.setProperty("password", "Password: " + password);
        //Temporary - the intro will change to be dynamic
        props.setProperty("intro",
                "We are pleased to provide you with a log in and password for your new MyOSCAR Personal Health Record. This account will allow you to connect electronically with our clinic. Please take a few minutes to review the accompanying literature for further information.We look forward to you benefiting from this service.");

        document.addTitle(title);
        document.addSubject("");
        document.addKeywords("pdf, itext");
        document.addCreator("OSCAR");
        document.addAuthor("");
        document.addHeader("Expires", "0");

        Rectangle pageSize = PageSize.LETTER;

        document.setPageSize(pageSize);
        document.open();

        // create a reader for a certain document
        String propFilename = oscar.OscarProperties.getInstance().getProperty("pdfFORMDIR", "") + "/"
                + template;
        PdfReader reader = null;
        try {
            reader = new PdfReader(propFilename);
            log.debug("Found template at " + propFilename);
        } catch (Exception dex) {
            log.debug("change path to inside oscar from :" + propFilename);
            reader = new PdfReader("/oscar/form/prop/" + template);
            log.debug("Found template at /oscar/form/prop/" + template);
        }

        // retrieve the total number of pages
        int n = reader.getNumberOfPages();
        // retrieve the size of the first page
        Rectangle pSize = reader.getPageSize(1);
        float width = pSize.getWidth();
        float height = pSize.getHeight();
        log.debug("Width :" + width + " Height: " + height);

        PdfContentByte cb = writer.getDirectContent();
        ColumnText ct = new ColumnText(cb);
        int fontFlags = 0;

        document.newPage();
        PdfImportedPage page1 = writer.getImportedPage(reader, 1);
        cb.addTemplate(page1, 1, 0, 0, 1, 0, 0);

        BaseFont bf; // = normFont;
        String encoding;

        cb.setRGBColorStroke(0, 0, 255);

        String[] fontType;
        for (Enumeration e = printCfg.propertyNames(); e.hasMoreElements();) {
            tempName = new StringBuilder(e.nextElement().toString());
            cfgVal = printCfg.getProperty(tempName.toString()).split(" *, *");

            if (cfgVal[4].indexOf(";") > -1) {
                fontType = cfgVal[4].split(";");
                if (fontType[1].trim().equals("italic"))
                    fontFlags = Font.ITALIC;
                else if (fontType[1].trim().equals("bold"))
                    fontFlags = Font.BOLD;
                else if (fontType[1].trim().equals("bolditalic"))
                    fontFlags = Font.BOLDITALIC;
                else
                    fontFlags = Font.NORMAL;
            } else {
                fontFlags = Font.NORMAL;
                fontType = new String[] { cfgVal[4].trim() };
            }

            if (fontType[0].trim().equals("BaseFont.HELVETICA")) {
                fontType[0] = BaseFont.HELVETICA;
                encoding = BaseFont.CP1252; //latin1 encoding
            } else if (fontType[0].trim().equals("BaseFont.HELVETICA_OBLIQUE")) {
                fontType[0] = BaseFont.HELVETICA_OBLIQUE;
                encoding = BaseFont.CP1252;
            } else if (fontType[0].trim().equals("BaseFont.ZAPFDINGBATS")) {
                fontType[0] = BaseFont.ZAPFDINGBATS;
                encoding = BaseFont.ZAPFDINGBATS;
            } else {
                fontType[0] = BaseFont.COURIER;
                encoding = BaseFont.CP1252;
            }

            bf = BaseFont.createFont(fontType[0], encoding, BaseFont.NOT_EMBEDDED);

            // write in a rectangle area
            if (cfgVal.length >= 9) {
                Font font = new Font(bf, Integer.parseInt(cfgVal[5].trim()), fontFlags);
                ct.setSimpleColumn(Integer.parseInt(cfgVal[1].trim()),
                        (height - Integer.parseInt(cfgVal[2].trim())), Integer.parseInt(cfgVal[7].trim()),
                        (height - Integer.parseInt(cfgVal[8].trim())), Integer.parseInt(cfgVal[9].trim()),
                        (cfgVal[0].trim().equals("left") ? Element.ALIGN_LEFT
                                : (cfgVal[0].trim().equals("right") ? Element.ALIGN_RIGHT
                                        : Element.ALIGN_CENTER)));

                ct.setText(new Phrase(12, props.getProperty(tempName.toString(), ""), font));
                ct.go();
                continue;
            }

            // draw line directly
            if (tempName.toString().startsWith("__$line")) {
                cb.setRGBColorStrokeF(0f, 0f, 0f);
                cb.setLineWidth(Float.parseFloat(cfgVal[4].trim()));
                cb.moveTo(Float.parseFloat(cfgVal[0].trim()), Float.parseFloat(cfgVal[1].trim()));
                cb.lineTo(Float.parseFloat(cfgVal[2].trim()), Float.parseFloat(cfgVal[3].trim()));
                // stroke the lines
                cb.stroke();
                // write text directly

            } else if (tempName.toString().startsWith("__")) {
                cb.beginText();
                cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim()));
                cb.showTextAligned(
                        (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT
                                : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT
                                        : PdfContentByte.ALIGN_CENTER)),
                        (cfgVal.length >= 7 ? (cfgVal[6].trim()) : props.getProperty(tempName.toString(), "")),
                        Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0);

                cb.endText();
            } else if (tempName.toString().equals("forms_promotext")) {
                if (OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT") != null) {
                    cb.beginText();
                    cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim()));
                    cb.showTextAligned(
                            (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT
                                    : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT
                                            : PdfContentByte.ALIGN_CENTER)),
                            OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"),
                            Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())),
                            0);

                    cb.endText();
                }
            } else { // write prop text

                cb.beginText();
                cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim()));
                cb.showTextAligned(
                        (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT
                                : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT
                                        : PdfContentByte.ALIGN_CENTER)),
                        (cfgVal.length >= 7 ? ((props.getProperty(tempName.toString(), "").equals("") ? ""
                                : cfgVal[6].trim())) : props.getProperty(tempName.toString(), "")),
                        Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0);

                cb.endText();
            }
        }

    } catch (DocumentException dex) {
        baosPDF.reset();
        throw dex;
    } finally {
        if (document != null)
            document.close();
        if (writer != null)
            writer.close();
    }
    return baosPDF;
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfDocumentWriter.java

License:Open Source License

public void processPhysicalPage(final PageGrid pageGrid, final LogicalPageBox logicalPage, final int row,
        final int col, final PhysicalPageKey pageKey) throws DocumentException {
    final PhysicalPageBox page = pageGrid.getPage(row, col);
    if (page == null) {
        return;/*from   ww w.  jav a2 s  . c  o  m*/
    }

    final float width = (float) StrictGeomUtility.toExternalValue(page.getWidth());
    final float height = (float) StrictGeomUtility.toExternalValue(page.getHeight());

    final Rectangle pageSize = new Rectangle(width, height);

    final float marginLeft = (float) StrictGeomUtility.toExternalValue(page.getImageableX());
    final float marginRight = (float) StrictGeomUtility
            .toExternalValue(page.getWidth() - page.getImageableWidth() - page.getImageableX());
    final float marginTop = (float) StrictGeomUtility.toExternalValue(page.getImageableY());
    final float marginBottom = (float) StrictGeomUtility
            .toExternalValue(page.getHeight() - page.getImageableHeight() - page.getImageableY());

    final Document document = getDocument();
    document.setPageSize(pageSize);
    document.setMargins(marginLeft, marginRight, marginTop, marginBottom);

    if (awaitOpenDocument) {
        document.open();
        awaitOpenDocument = false;
    }

    final PdfContentByte directContent = writer.getDirectContent();
    final Graphics2D graphics = new PdfGraphics2D(directContent, width, height, metaData);
    final PdfLogicalPageDrawable logicalPageDrawable = createLogicalPageDrawable(logicalPage, page);
    final PhysicalPageDrawable drawable = createPhysicalPageDrawable(logicalPageDrawable, page);
    drawable.draw(graphics, new Rectangle2D.Double(0, 0, width, height));

    graphics.dispose();

    document.newPage();
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfDocumentWriter.java

License:Open Source License

public void processLogicalPage(final LogicalPageKey key, final LogicalPageBox logicalPage)
        throws DocumentException {

    final float width = (float) StrictGeomUtility.toExternalValue(logicalPage.getPageWidth());
    final float height = (float) StrictGeomUtility.toExternalValue(logicalPage.getPageHeight());

    final Rectangle pageSize = new Rectangle(width, height);

    final Document document = getDocument();
    document.setPageSize(pageSize);
    document.setMargins(0, 0, 0, 0);//from   w  w  w. ja  v  a  2 s.c  o  m

    if (awaitOpenDocument) {
        document.open();
        awaitOpenDocument = false;
    }

    final Graphics2D graphics = new PdfGraphics2D(writer.getDirectContent(), width, height, metaData);
    // and now process the box ..
    final PdfLogicalPageDrawable logicalPageDrawable = createLogicalPageDrawable(logicalPage, null);
    logicalPageDrawable.draw(graphics, new Rectangle2D.Double(0, 0, width, height));

    graphics.dispose();

    document.newPage();
}

From source file:org.primefaces.showcase.view.data.dataexporter.CustomizedDocumentsView.java

License:Open Source License

public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException {
    Document pdf = (Document) document;
    pdf.open();/*from  w w w .j ava2  s .  co  m*/
    pdf.setPageSize(PageSize.A4);

    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    String logo = externalContext.getRealPath("") + File.separator + "resources" + File.separator + "demo"
            + File.separator + "images" + File.separator + "prime_logo.png";

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

From source file:org.projectlibre.export.ImageExport.java

License:Common Public License

public static void export(final GraphPageable pageable, Component parentComponent) throws IOException {
    final File file = chooseFile(pageable.getRenderer().getProject().getName(), parentComponent);
    final JobQueue jobQueue = SessionFactory.getInstance().getJobQueue();
    Job job = new Job(jobQueue, "Image Export", "Exporting Image...", true, parentComponent);
    job.addRunnable(new JobRunnable("Image Export", 1.0f) {
        public Object run() throws Exception {
            boolean pdf = true;
            if (file.getName().endsWith(".png"))
                pdf = false;//www.  ja v a2  s. co  m
            Document document = null;
            PdfWriter writer = null;
            if (pdf) {
                document = new Document();
                writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            } else {

            }
            pageable.update();
            int pageCount = pageable.getNumberOfPages();

            if (pageCount > 0) {
                ViewPrintable printable = pageable.getSafePrintable();
                ExtendedPageFormat pageFormat = pageable.getSafePageFormat();
                double width = pageFormat.getWidth();
                double height = pageFormat.getHeight();
                float startIncrement = 0.1f;
                float endIncrement = 0.0f;
                float progressIncrement = (1.0f - startIncrement - endIncrement) / pageCount;
                for (int p = 0; p < pageCount; p++) {
                    setProgress(startIncrement + p * progressIncrement);
                    if (pdf) {
                        document.setPageSize(new Rectangle((float) width, (float) height));
                        if (p == 0)
                            document.open();
                        else
                            document.newPage();
                        Graphics2D g = writer.getDirectContent().createGraphics((float) width, (float) height);
                        printable.print(g, p);
                        g.dispose();
                    } else {
                        BufferedImage bi = new BufferedImage((int) width, (int) height,
                                BufferedImage.TYPE_INT_ARGB);

                        Graphics2D g2 = (Graphics2D) bi.createGraphics();
                        g2.setBackground(Color.WHITE);
                        printable.print(g2, p);
                        g2.dispose();
                        ImageIO.write(bi, "png", new FileOutputStream(file));
                        break;
                    }
                }
                if (pdf)
                    document.close();
            }
            setProgress(1.0f);
            return null;
        }
    });
    jobQueue.schedule(job);
}