Example usage for com.lowagie.text.pdf PdfReader getPageSize

List of usage examples for com.lowagie.text.pdf PdfReader getPageSize

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfReader getPageSize.

Prototype

public Rectangle getPageSize(PdfDictionary page) 

Source Link

Document

Gets the page from a page dictionary

Usage

From source file:org.lucee.extension.pdf.tag.PDF.java

License:Open Source License

private void doActionAddHeaderFooter(boolean isHeader) throws PageException, IOException, DocumentException {
    required("pdf", "write", "source", source);
    // required("pdf", "write", "destination", destination);

    /*/*from  www  .  j  a v  a2 s . c o m*/
     * optinal - pages
     */
    /*
     * isBase64 = "yes|no" showonprint = "yes|no"> opacity = "header opacity" image = "image file name to be used as the header"
     * 
     */
    PDFStruct doc = toPDFDocument(source, password, null);
    PdfReader reader = doc.getPdfReader();
    BIF bif = null;
    if (NUMBERFORMAT_NUMERIC != numberformat) {
        ClassUtil classUtil = engine.getClassUtil();
        try {
            bif = classUtil.loadBIF(pageContext, "lucee.runtime.functions.displayFormatting.NumberFormat");
        } catch (Exception e) {
            e.printStackTrace();
            throw engine.getCastUtil().toPageException(e);
        }
    }
    // output stream
    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    OutputStream os = null;
    if (!Util.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }
    PdfStamper stamper = null;
    try {
        if (destination != null && destination.exists() && !overwrite)
            throw engine.getExceptionUtil()
                    .createApplicationException("destination file [" + destination + "] already exists");

        int len = reader.getNumberOfPages();
        Set<Integer> pageSet = PDFUtil.parsePageDefinition(pages, len);
        stamper = new PdfStamper(reader, destination.getOutputStream());
        if (font == null)
            font = getDefaultFont();
        // , new Font(FontFamily.HELVETICA, 14)
        for (int p = 1; p <= len; p++) {
            if (pageSet != null && !pageSet.contains(p))
                continue;

            Phrase header = text(text, p, len, numberformat, bif, font);
            // vertical orientation
            float y;

            if (isHeader) {
                y = reader.getPageSize(p).getTop(header.getFont().getCalculatedSize() + (topmargin - 3));
            } else {
                y = reader.getPageSize(p).getBottom((bottommargin + 2));
                /*
                 * System.out.println("y:"+y); System.out.println("bottom:"+reader.getPageSize(p).getBottom()); System.out.println("margin:"+bottommargin);
                 * System.out.println("font:"+header.getFont().getSize()); System.out.println("CalculatedStyle:"+header.getFont().getCalculatedStyle());
                 * System.out.println("CalculatedSize:"+header.getFont().getCalculatedSize());
                 */
            }
            // float yh = reader.getPageSize(p).getTop(topmargin);
            // float yf = reader.getPageSize(p).getBottom(bottommargin);
            System.out.println("++++++++++++");
            System.out.println(y);
            System.out.println(reader.getPageSize(p).getTop());
            // horizontal orientation

            float x = reader.getPageSize(p).getWidth() / 2;
            if (Element.ALIGN_LEFT == align) {
                x = leftmargin;
            } else if (Element.ALIGN_RIGHT == align) {
                x = reader.getPageSize(p).getWidth() - rightmargin;
            } else {
                x = reader.getPageSize(p).getWidth() / 2;
            }
            ColumnText.showTextAligned(stamper.getOverContent(p), align, header, x, y, 0);

        }
    } finally {
        try {
            if (stamper != null)
                stamper.close();
        } catch (IOException ioe) {
        }
        ;
        Util.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
                        destination, true);// MUST overwrite
            if (!Util.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }

    // PdfReader pr = doc.getPdfReader();
    // output
    /*
     * boolean destIsSource = doc.getResource()!=null && destination.equals(doc.getResource());
     * 
     * OutputStream os=null; if(destIsSource){ os=new ByteArrayOutputStream(); } else if(destination!=null) { os=destination.getOutputStream(); }
     * 
     * try { PDFUtil.concat(new PDFStruct[]{doc}, os, true, true, true,version); } finally { Util.closeEL(os); if(os instanceof ByteArrayOutputStream) {
     * if(destination!=null)engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream)os).toByteArray()), destination,true);// MUST overwrite
     * } }
     */
}

From source file:org.nuxeo.ecm.platform.signature.core.sign.SignatureServiceImpl.java

License:Open Source License

/**
 * @since 5.8 Provides the position rectangle for the next certificate. An assumption is made that all previous
 *        certificates in a given PDF were placed using the same technique and settings. New certificates are added
 *        depending of signature layout contributed.
 *//* www  .ja va  2 s . c om*/
protected Rectangle getNextCertificatePosition(PdfReader pdfReader, List<X509Certificate> pdfCertificates)
        throws SignException {
    int numberOfSignatures = pdfCertificates.size();

    Rectangle pageSize = pdfReader.getPageSize(PAGE_TO_SIGN);

    // PDF size
    float width = pageSize.getWidth();
    float height = pageSize.getHeight();

    // Signature size
    float rectangleWidth = width / getSignatureLayout().getColumns();
    float rectangeHeight = height / getSignatureLayout().getLines();

    // Signature location
    int column = numberOfSignatures % getSignatureLayout().getColumns() + getSignatureLayout().getStartColumn();
    int line = numberOfSignatures / getSignatureLayout().getColumns() + getSignatureLayout().getStartLine();
    if (column > getSignatureLayout().getColumns()) {
        column = column % getSignatureLayout().getColumns();
        line++;
    }

    // Skip rectangle display If number of signatures exceed free locations
    // on pdf layout
    if (line > getSignatureLayout().getLines()) {
        return new Rectangle(0, 0, 0, 0);
    }

    // make smaller by page margin
    float topRightX = rectangleWidth * column;
    float bottomLeftY = height - rectangeHeight * line;
    float bottomLeftX = topRightX - SIGNATURE_FIELD_WIDTH;
    float topRightY = bottomLeftY + SIGNATURE_FIELD_HEIGHT;

    // verify current position coordinates in case they were
    // misconfigured
    validatePageBounds(pdfReader, 1, bottomLeftX, true);
    validatePageBounds(pdfReader, 1, bottomLeftY, false);
    validatePageBounds(pdfReader, 1, topRightX, true);
    validatePageBounds(pdfReader, 1, topRightY, false);

    Rectangle positionRectangle = new Rectangle(bottomLeftX, bottomLeftY, topRightX, topRightY);

    return positionRectangle;
}

From source file:org.nuxeo.ecm.platform.signature.core.sign.SignatureServiceImpl.java

License:Open Source License

/**
 * Verifies that a provided value fits within the page bounds. If it does not, a sign exception is thrown. This is
 * to verify externally configurable signature positioning.
 *
 * @param isHorizontal - if false, the current value is checked agains the vertical page dimension
 *///from w  ww.  j  ava  2s .  co m
protected void validatePageBounds(PdfReader pdfReader, int pageNo, float valueToCheck, boolean isHorizontal)
        throws SignException {
    if (valueToCheck < 0) {
        String message = "The new signature position " + valueToCheck
                + " exceeds the page bounds. The position must be a positive number.";
        log.debug(message);
        throw new SignException(message);
    }

    Rectangle pageRectangle = pdfReader.getPageSize(pageNo);
    if (isHorizontal && valueToCheck > pageRectangle.getRight()) {
        String message = "The new signature position " + valueToCheck
                + " exceeds the horizontal page bounds. The page dimensions are: (" + pageRectangle + ").";
        log.debug(message);
        throw new SignException(message);
    }
    if (!isHorizontal && valueToCheck > pageRectangle.getTop()) {
        String message = "The new signature position " + valueToCheck
                + " exceeds the vertical page bounds. The page dimensions are: (" + pageRectangle + ").";
        log.debug(message);
        throw new SignException(message);
    }
}

From source file:org.openconcerto.erp.core.finance.accounting.report.PdfGenerator.java

License:Open Source License

private void init() throws FileNotFoundException {

    // we create a reader for a certain document
    PdfReader reader = null;
    PdfWriter writer = null;/*  ww w.  j  a  v  a2 s .c  o  m*/
    try {
        reader = new PdfReader(getStreamStatic(this.fileNameIn));

        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();
        // we retrieve the size of the first page
        Rectangle psize = reader.getPageSize(1);

        psize.setRight(psize.getRight() - this.templateOffsetX);
        psize.setTop(psize.getTop() - this.templateOffsetY);

        this.width = (int) psize.getWidth();
        float height = psize.getHeight();

        // step 1: creation of a document-object
        int MARGIN = 32;
        this.document = new Document(psize, MARGIN, MARGIN, MARGIN, MARGIN);
        // step 2: we create a writer that listens to the document
        if (!this.directoryOut.exists()) {
            this.directoryOut.mkdirs();
        }
        System.err.println("Directory out " + this.directoryOut.getAbsolutePath());
        File f = new File(this.directoryOut, this.fileNameOut);
        if (f.exists()) {
            f.renameTo(new File(this.directoryOut, "Old" + this.fileNameOut));
            f = new File(this.directoryOut, this.fileNameOut);
        }

        System.err.println("Creation du fichier " + f.getAbsolutePath());

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

        this.document.open();
        // step 4: we add content
        this.cb = writer.getDirectContent();

        System.out.println("There are " + n + " pages in the document.");

        this.document.newPage();

        PdfImportedPage page1 = writer.getImportedPage(reader, 1);

        this.cb.addTemplate(page1, -this.templateOffsetX, -this.templateOffsetY);

        this.bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED);
        this.bfb = BaseFont.createFont(BaseFont.TIMES_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED);

    } catch (FileNotFoundException fE) {
        throw fE;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:org.orbeon.oxf.processor.pdf.PDFTemplateProcessor.java

License:Open Source License

protected void readInput(PipelineContext pipelineContext, ProcessorInput input, Config config,
        OutputStream outputStream) {
    final org.dom4j.Document configDocument = readCacheInputAsDOM4J(pipelineContext, "model");// TODO: after all, should we use "config"?
    final org.dom4j.Document instanceDocument = readInputAsDOM4J(pipelineContext, input);

    final Configuration configuration = XPathCache.getGlobalConfiguration();
    final DocumentInfo configDocumentInfo = new DocumentWrapper(configDocument, null, configuration);
    final DocumentInfo instanceDocumentInfo = new DocumentWrapper(instanceDocument, null, configuration);

    try {//w ww.  j a  v a 2  s . co m
        // Get reader
        final String templateHref = XPathCache.evaluateAsString(configDocumentInfo, "/*/template/@href", null,
                null, functionLibrary, null, null, null);//TODO: LocationData

        // Create PDF reader
        final PdfReader reader;
        {
            final String inputName = ProcessorImpl.getProcessorInputSchemeInputName(templateHref);
            if (inputName != null) {
                // Read the input
                final ByteArrayOutputStream os = new ByteArrayOutputStream();
                readInputAsSAX(pipelineContext, inputName,
                        new BinaryTextXMLReceiver(null, os, true, false, null, false, false, null, false));

                // Create the reader
                reader = new PdfReader(os.toByteArray());
            } else {
                // Read and create the reader
                reader = new PdfReader(URLFactory.createURL(templateHref));
            }
        }

        // Get total number of pages
        final int pageCount = reader.getNumberOfPages();

        // Get size of first page
        final Rectangle pageSize = reader.getPageSize(1);
        final float width = pageSize.getWidth();
        final float height = pageSize.getHeight();

        final String showGrid = XPathCache.evaluateAsString(configDocumentInfo, "/*/template/@show-grid", null,
                null, functionLibrary, null, null, null);//TODO: LocationData

        final PdfStamper stamper = new PdfStamper(reader, outputStream);
        stamper.setFormFlattening(true);

        for (int currentPage = 1; currentPage <= pageCount; currentPage++) {
            final PdfContentByte contentByte = stamper.getOverContent(currentPage);
            // Handle root group
            final GroupContext initialGroupContext = new GroupContext(contentByte, stamper.getAcroFields(),
                    height, currentPage, Collections.singletonList((Item) instanceDocumentInfo), 1, 0, 0,
                    "Courier", 14, 15.9f);
            handleGroup(pipelineContext, initialGroupContext,
                    Dom4jUtils.elements(configDocument.getRootElement()), functionLibrary, reader);

            // Handle preview grid (NOTE: This can be heavy in memory.)
            if ("true".equalsIgnoreCase(showGrid)) {
                final float topPosition = 10f;

                final BaseFont baseFont2 = BaseFont.createFont("Courier", BaseFont.CP1252,
                        BaseFont.NOT_EMBEDDED);
                contentByte.beginText();
                {
                    // 20-pixel lines and side legends

                    contentByte.setFontAndSize(baseFont2, (float) 7);

                    for (int w = 0; w <= width; w += 20) {
                        for (int h = 0; h <= height; h += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }
                    for (int h = 0; h <= height; h += 20) {
                        for (int w = 0; w <= width; w += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }

                    for (int w = 0; w <= width; w += 20) {
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + w, (float) w,
                                height - topPosition, 0);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + w, (float) w, topPosition,
                                0);
                    }
                    for (int h = 0; h <= height; h += 20) {
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + h, (float) 5, height - h,
                                0);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + h, width - (float) 5,
                                height - h, 0);
                    }

                    // 10-pixel lines

                    contentByte.setFontAndSize(baseFont2, (float) 3);

                    for (int w = 10; w <= width; w += 10) {
                        for (int h = 0; h <= height; h += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }
                    for (int h = 10; h <= height; h += 10) {
                        for (int w = 0; w <= width; w += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }
                }
                contentByte.endText();
            }
        }

        // Close the document
        //            document.close();
        stamper.close();
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:org.oscarehr.common.printing.HtmlToPdfServlet.java

License:Open Source License

public static byte[] stamp(byte[] content) throws Exception {
    PdfReader reader = null;
    ByteArrayOutputStream os = null;
    PdfStamper stamper = null;//from  w ww . j  a va  2 s  .  co  m

    try {
        reader = new PdfReader(content);
        os = new ByteArrayOutputStream(content.length);
        stamper = new PdfStamper(reader, os);

        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            PdfContentByte over = stamper.getOverContent(i);
            BaseFont font = FontSettings.HELVETICA_6PT.createFont();

            over.setFontAndSize(font, 10);
            float center = reader.getPageSize(i).getWidth() / 2.0f;

            // TODO Consider refactoring this into is own class 
            printText(over, "Page " + i + " of " + reader.getNumberOfPages(), center, 35);
            printText(over, OscarProperties.getConfidentialityStatement(), center, 25);
        }

        // this is ugly, but there is no flush method for readers in itext....
        stamper.close();
        reader.close();
        os.flush();

        return os.toByteArray();
    } finally {
        if (os != null)
            IOUtils.closeQuietly(os);
    }
}

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 w w  w  . j a v a  2s .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.sejda.impl.itext.component.AbstractPdfCopier.java

License:Apache License

public void addBlankPage(PdfReader reader) {
    pdfCopy.addPage(reader.getPageSize(1), reader.getPageRotation(1));
    numberOfCopiedPages++;
}

From source file:org.silverpeas.core.util.PdfUtil.java

License:Open Source License

/**
 * Gets some document info from a PDF file.
 * @param pdfSource the source pdf file, this content is not modified by this method
 * @return a {@link DocumentInfo} instance.
 *//*  w w  w.  j ava 2  s  .  com*/
public static DocumentInfo getDocumentInfo(File pdfSource) {
    if (pdfSource == null || !pdfSource.isFile()) {
        throw new SilverpeasRuntimeException(PDF_FILE_ERROR_MSG);
    } else if (!FileUtil.isPdf(pdfSource.getPath())) {
        throw new SilverpeasRuntimeException(NOT_PDF_FILE_ERROR_MSG);
    }
    PdfReader reader = null;
    try (final InputStream pdfSourceIS = FileUtils.openInputStream(pdfSource)) {
        reader = new PdfReader(pdfSourceIS);
        final DocumentInfo documentInfo = new DocumentInfo();
        documentInfo.setNbPages(reader.getNumberOfPages());
        for (int i = 1; i <= documentInfo.getNbPages(); i++) {
            final Rectangle rectangle = reader.getPageSize(i);
            final int maxWidth = Math.round(rectangle.getWidth());
            final int maxHeight = Math.round(rectangle.getHeight());
            if (maxWidth > documentInfo.getMaxWidth()) {
                documentInfo.setMaxWidth(maxWidth);
            }
            if (maxHeight > documentInfo.getMaxHeight()) {
                documentInfo.setMaxHeight(maxHeight);
            }
        }
        return documentInfo;
    } catch (Exception e) {
        SilverLogger.getLogger(PdfUtil.class).error(e);
        throw new SilverpeasRuntimeException("A problem has occurred during the reading of a pdf file", e);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:org.silverpeas.core.util.PdfUtil.java

License:Open Source License

/**
 * Add a image under or over content on each page of a PDF file.
 * @param pdfSource the source pdf file, this content is not modified by this method
 * @param imageToAdd the image file/*from  w  ww  .j a  v  a 2 s  . co m*/
 * @param pdfDestination the destination pdf file, with the image under or over content
 * @param isBackground indicates if image is addes under or over the content of the pdf source
 * file
 */
private static void addImageOnEachPage(InputStream pdfSource, File imageToAdd, OutputStream pdfDestination,
        final boolean isBackground) {

    // Verify given arguments
    if (imageToAdd == null || !imageToAdd.isFile()) {
        throw new SilverpeasRuntimeException("The image file doesn't exist");
    } else if (!FileUtil.isImage(imageToAdd.getPath())) {
        throw new SilverpeasRuntimeException("The picture to add is not an image file");
    }

    PdfReader reader = null;
    try {

        // Get a reader of PDF content
        reader = new PdfReader(pdfSource);

        // Obtain the total number of pages
        int pdfNbPages = reader.getNumberOfPages();
        PdfStamper stamper = new PdfStamper(reader, pdfDestination);

        // Load the image
        Image image = Image.getInstance(imageToAdd.getPath());
        float imageWidth = image.getWidth();
        float imageHeigth = image.getHeight();

        // Adding the image on each page of the PDF
        for (int i = 1; i <= pdfNbPages; i++) {

            // Page sizes
            Rectangle rectangle = reader.getPageSize(i);

            // Compute the scale of the image
            float scale = Math.min(100, (rectangle.getWidth() / imageWidth * 100));
            image.scalePercent(Math.min(scale, (rectangle.getHeight() / imageHeigth * 100)));

            // Setting the image position for the current page
            image.setAbsolutePosition(computeImageCenterPosition(rectangle.getWidth(), image.getScaledWidth()),
                    computeImageCenterPosition(rectangle.getHeight(), image.getScaledHeight()));

            // Adding image
            PdfContentByte imageContainer = isBackground ? stamper.getUnderContent(i)
                    : stamper.getOverContent(i);
            imageContainer.addImage(image);
        }

        // End of the treatment : closing the stamper
        stamper.close();

    } catch (Exception e) {
        SilverLogger.getLogger(PdfUtil.class).error(e);
        throw new SilverpeasRuntimeException(
                "A problem has occurred during the adding of an image into a pdf file", e);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}