Example usage for com.lowagie.text.pdf PdfWriter getImportedPage

List of usage examples for com.lowagie.text.pdf PdfWriter getImportedPage

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter getImportedPage.

Prototype

public PdfImportedPage getImportedPage(PdfReader reader, int pageNumber) 

Source Link

Document

Use this method to get a page from other PDF document.

Usage

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;//from w  w  w.j  av  a2s  .c om
    PdfWriter writer = null;
    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.oscarehr.common.printing.HtmlToPdfServlet.java

License:Open Source License

private static void appendFooter(byte[] pdf, ByteArrayOutputStream baos) {
    PdfReader reader = null;/*from w w w .  j  a va  2 s  . c  om*/
    PdfWriter writer = null;
    Document document = null;

    try {
        // do initialization
        reader = new PdfReader(pdf);
        document = new Document(PageSize.LETTER);
        writer = PdfWriterFactory.newInstance(document, baos, FontSettings.HELVETICA_6PT);
        document.open();
        PdfContentByte cb = writer.getDirectContent();

        // copy pages
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            cb.addTemplate(writer.getImportedPage(reader, i), 0, 0);
        }
    } catch (Exception e) {
        throw new RuntimeException("Unable to append document footer", e);
    } finally {
        close(document);
        close(writer);
        close(reader);
    }
}

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;

    try {/* ww  w .  j  ava 2  s  .  c  o  m*/
        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.sonarqube.report.extendedpdf.ExtendedHeader.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    String pageTemplate = "/templates/page.pdf";
    try {//from   w w  w  .  j  av  a 2s  . c o m
        PdfContentByte cb = writer.getDirectContentUnder();
        PdfReader reader = new PdfReader(this.getClass().getResourceAsStream(pageTemplate));
        PdfImportedPage page = writer.getImportedPage(reader, 1);
        cb.addTemplate(page, 0, 0);

        Font font = FontFactory.getFont(FontFactory.COURIER, 12, Font.NORMAL, Color.GRAY);
        Rectangle pageSize = document.getPageSize();
        PdfPTable head = new PdfPTable(1);
        head.getDefaultCell().setVerticalAlignment(PdfCell.ALIGN_MIDDLE);
        head.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
        head.getDefaultCell().setBorder(0);
        Phrase projectName = new Phrase(project.getName(), font);
        head.addCell(projectName);
        head.setTotalWidth(pageSize.getWidth() - document.leftMargin() - document.rightMargin());
        head.writeSelectedRows(0, -1, document.leftMargin(), pageSize.getHeight() - 15,
                writer.getDirectContent());
        head.setSpacingAfter(10);

        PdfPTable foot = new PdfPTable(1);
        foot.getDefaultCell().setVerticalAlignment(PdfCell.ALIGN_MIDDLE);
        foot.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
        foot.getDefaultCell().setBorder(0);
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        Phrase projectAnalysisDate = new Phrase(df.format(project.getMeasures().getDate()), font);
        foot.addCell(projectAnalysisDate);
        foot.setTotalWidth(pageSize.getWidth() - document.leftMargin() - document.rightMargin());
        foot.writeSelectedRows(0, -1, document.leftMargin(), 20, writer.getDirectContent());
        foot.setSpacingBefore(10);
    } catch (IOException e) {
        Logger.error("Cannot find the required template: " + pageTemplate);
        e.printStackTrace();
    }
}

From source file:org.sonarqube.report.extendedpdf.OverviewPDFReporter.java

License:Open Source License

protected void printFrontPage(Document frontPageDocument, PdfWriter frontPageWriter)
        throws org.dom4j.DocumentException, ReportException {
    String frontPageTemplate = "/templates/frontpage.pdf";
    try {// w  w  w. j  a  va  2 s .  c o  m
        PdfContentByte cb = frontPageWriter.getDirectContent();
        PdfReader reader = new PdfReader(this.getClass().getResourceAsStream(frontPageTemplate));
        PdfImportedPage page = frontPageWriter.getImportedPage(reader, 1);
        frontPageDocument.newPage();
        cb.addTemplate(page, 0, 0);

        Project project = getProject();

        Rectangle pageSize = frontPageDocument.getPageSize();
        PdfPTable projectInfo = new PdfPTable(1);
        projectInfo.getDefaultCell().setVerticalAlignment(PdfCell.ALIGN_MIDDLE);
        projectInfo.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
        projectInfo.getDefaultCell().setBorder(Rectangle.BOTTOM);
        projectInfo.getDefaultCell().setPaddingBottom(10);
        projectInfo.getDefaultCell().setBorderColor(Color.GRAY);
        Font font = FontFactory.getFont(FontFactory.COURIER, 18, Font.NORMAL, Color.LIGHT_GRAY);

        Phrase projectName = new Phrase("Project: " + project.getName(), font);
        projectInfo.addCell(projectName);

        Phrase projectVersion = new Phrase("Version: " + project.getMeasures().getVersion(), font);
        projectInfo.addCell(projectVersion);

        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        Phrase projectAnalysisDate = new Phrase("Analysis Date: " + df.format(project.getMeasures().getDate()),
                font);
        projectInfo.addCell(projectAnalysisDate);

        projectInfo.setTotalWidth(
                pageSize.getWidth() - frontPageDocument.leftMargin() * 2 - frontPageDocument.rightMargin() * 2);
        projectInfo.writeSelectedRows(0, -1, frontPageDocument.leftMargin(), pageSize.getHeight() - 575,
                frontPageWriter.getDirectContent());
        projectInfo.setSpacingAfter(10);
    } catch (IOException e) {
        Logger.error("Cannot find the required template: " + frontPageTemplate);
        e.printStackTrace();
    }
}

From source file:org.viafirma.util.QRCodeUtil.java

License:Apache License

/**
 * Genera un justificante de firma de un fichero pdf de entrada.
 * /* w w  w . j a va  2 s .com*/
 * @param input
 *            Fichero pdf de entrada
 * @param texto
 * @param textoQR
 * @param codFirma
 * @param out
 * @throws ExcepcionErrorInterno
 */
public void firmarPDF(InputStream input, String texto, String texto2Line, String textoQR, String codFirma,
        OutputStream out) throws ExcepcionErrorInterno {
    // leemos el pdf utilizando iText.
    try {
        // Recuperamos el documento original
        PdfReader reader = new PdfReader(input);

        // Obtenemos el tamao de la pgina
        Rectangle pageSize = reader.getPageSize(1);

        // Creamos un nuevo documento del mismo tamao que el original
        Document document = new Document(pageSize);

        // creo una instancia para escritura en el documento
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.open();

        // insertamos la portada del documento que estamos firmando.
        float escala = (pageSize.getHeight() - 350) / pageSize.getHeight();

        // Aadimos al documento la imagen de cabecera y de pie
        addContent(texto, texto2Line, textoQR, codFirma, document, pageSize, true, false);

        PdfContentByte cb = writer.getDirectContent();

        PdfImportedPage portada = writer.getImportedPage(reader, 1);
        cb.setRGBColorStroke(0xCC, 0xCC, 0xCC);
        cb.transform(AffineTransform.getTranslateInstance(document.leftMargin(), 210));
        cb.transform(AffineTransform.getScaleInstance(escala, escala));
        cb.addTemplate(portada, 0, 0);// , escala, 0, 0, escala,dx,dy);
        document.close();
        out.close();
    } catch (Exception e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    }
}

From source file:org.viafirma.util.QRCodeUtil.java

License:Apache License

/**
 * Genera un documento sellado en fichero pdf.
 * /*ww  w.  ja  v  a  2 s  . co m*/
 * @param input
 *            Fichero pdf de entrada
 * @param texto
 * @param textoQR
 * @param codFirma
 * @param out
 * @throws ExcepcionErrorInterno
 */
public void firmarPDFSellado(InputStream input, String texto, String texto2Line, String textoQR,
        String codFirma, OutputStream out) throws ExcepcionErrorInterno {
    // leemos el pdf utilizando iText.
    try {
        // Recuperamos el documento original
        PdfReader reader = new PdfReader(input);

        // Obtenemos el tamao de la pgina
        Rectangle pageSize = reader.getPageSize(1);

        // Creamos un nuevo documento del mismo tamao que el original
        Document document = new Document(pageSize);

        // creo una instancia para escritura en el documento
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.open();

        // Aadimos al documento la imagen de cabecera y de pie
        float altoCabeceraYPie = addContent(texto, texto2Line, textoQR, codFirma, document, pageSize, true,
                true);
        altoCabeceraYPie = altoCabeceraYPie + document.topMargin();
        // insertamos la portada del documento que estamos firmando.
        float escala = (pageSize.getHeight() - altoCabeceraYPie) / pageSize.getHeight();

        PdfContentByte cb = writer.getDirectContent();

        PdfImportedPage portada = writer.getImportedPage(reader, 1);
        cb.setRGBColorStroke(0xCC, 0xCC, 0xCC);
        cb.transform(AffineTransform.getScaleInstance(escala, escala));
        cb.transform(AffineTransform.getTranslateInstance(document.leftMargin() * 2.5,
                ALTO_ETIQUETA + document.topMargin()));

        cb.addTemplate(portada, 0, 0);// , escala, 0, 0, escala,dx,dy);
        document.close();
        out.close();
    } catch (Exception e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    }
}

From source file:oscar.eform.util.EFormPDFServlet.java

License:Open Source License

/**
 * the form txt file has lines in the form:
 *
 * For Checkboxes://from  w ww. ja  v a 2  s .  c  om
 * ie.  ohip : left, 76, 193, 0, BaseFont.ZAPFDINGBATS, 8, \u2713
 * requestParamName : alignment, Xcoord, Ycoord, 0, font, fontSize, textToPrint[if empty, prints the value of the request param]
 * NOTE: the Xcoord and Ycoord refer to the bottom-left corner of the element
 *
 * For single-line text:
 * ie. patientCity  : left, 242, 261, 0, BaseFont.HELVETICA, 12
 * See checkbox explanation
 *
 * For multi-line text (textarea)
 * ie.  aci : left, 20, 308, 0, BaseFont.HELVETICA, 8, _, 238, 222, 10
 * requestParamName : alignment, bottomLeftXcoord, bottomLeftYcoord, 0, font, fontSize, _, topRightXcoord, topRightYcoord, spacingBtwnLines
 *
 *NOTE: When working on these forms in linux, it helps to load the PDF file into gimp, switch to pt. coordinate system and use the mouse to find the coordinates.
 *Prepare to be bored!
 *
 *
 * @throws Exception 
 */
protected ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, final ServletContext ctx,
        int multiple) throws Exception {

    // added by vic, hsfo
    if (HSFO_RX_DATA_KEY.equals(req.getParameter("__title")))
        return generateHsfoRxPDF(req);

    String suffix = (multiple > 0) ? String.valueOf(multiple) : "";

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(document, baosPDF);

        String title = req.getParameter("__title" + suffix) != null ? req.getParameter("__title" + suffix)
                : "Unknown";
        String template = req.getParameter("__template" + suffix) != null
                ? req.getParameter("__template" + suffix) + ".pdf"
                : "";

        int numPages = 1;
        String pages = req.getParameter("__numPages" + suffix);
        if (pages != null) {
            numPages = Integer.parseInt(pages);
        }

        //load config files
        Properties[] printCfg = loadPrintCfg(req, suffix);
        Properties[][] graphicCfg = loadGraphicCfg(req, suffix, numPages);
        int cfgFileNo = printCfg == null ? 0 : printCfg.length;

        Properties props = new Properties();
        getPrintPropValues(props, req, suffix);

        Properties measurements = new Properties();

        //initialise measurement collections = a list of pages sections measurements
        List<List<List<String>>> xMeasurementValues = new ArrayList<List<List<String>>>();
        List<List<List<String>>> yMeasurementValues = new ArrayList<List<List<String>>>();
        for (int idx = 0; idx < numPages; ++idx) {
            MiscUtils.getLogger().debug("Adding page " + idx);
            xMeasurementValues.add(new ArrayList<List<String>>());
            yMeasurementValues.add(new ArrayList<List<String>>());
        }

        saveMeasurementValues(measurements, props, req, numPages, xMeasurementValues, yMeasurementValues);
        addDocumentProps(document, title, props);

        // create a reader for a certain document
        String propFilename = OscarProperties.getInstance().getProperty("eform_image", "") + "/" + template;
        PdfReader reader = null;

        try {
            reader = new PdfReader(propFilename);
            log.debug("Found template at " + propFilename);
        } catch (Exception dex) {
            log.warn("Cannot find template at : " + propFilename);
        }

        // retrieve the total number of pages
        int n = reader.getNumberOfPages();
        // retrieve the size of the first page
        Rectangle pSize = reader.getPageSize(1);
        float height = pSize.getHeight();

        PdfContentByte cb = writer.getDirectContent();
        int i = 0;

        while (i < n) {
            document.newPage();

            i++;
            PdfImportedPage page1 = writer.getImportedPage(reader, i);
            cb.addTemplate(page1, 1, 0, 0, 1, 0, 0);

            cb.setRGBColorStroke(0, 0, 255);
            // LEFT/CENTER/RIGHT, X, Y,

            if (i <= cfgFileNo) {
                writeContent(printCfg[i - 1], props, measurements, height, cb);
            } //end if there are print properties

            //graphic
            Properties[] tempPropertiesArray;
            if (i <= graphicCfg.length) {
                tempPropertiesArray = graphicCfg[i - 1];
                MiscUtils.getLogger().debug("Plotting page " + i);
            } else {
                tempPropertiesArray = null;
                MiscUtils.getLogger().debug("Skipped Plotting page " + i);
            }

            //if there are properties to plot
            if (tempPropertiesArray != null) {
                MiscUtils.getLogger().debug("TEMP PROP LENGTH " + tempPropertiesArray.length);
                for (int k = 0; k < tempPropertiesArray.length; k++) {

                    //initialise with measurement values which are mapped to config file by form get graphic function
                    List<String> xDate, yHeight;
                    if (xMeasurementValues.get(i - 1).size() > k && yMeasurementValues.get(i - 1).size() > k) {
                        xDate = new ArrayList<String>(xMeasurementValues.get(i - 1).get(k));
                        yHeight = new ArrayList<String>(yMeasurementValues.get(i - 1).get(k));
                    } else {
                        xDate = new ArrayList<String>();
                        yHeight = new ArrayList<String>();
                    }
                    plotProperties(tempPropertiesArray[k], props, xDate, yHeight, height, cb, (k % 2 == 0));
                }
            } //end: if there are properties to plot
        }
    } finally {
        if (document.isOpen())
            document.close();
        if (writer != null)
            writer.close();
    }
    return baosPDF;
}

From source file:questions.importpages.HelloWorldImportedPages.java

public static void main(String[] args) {
    // we create a PDF file
    createPdf(SOURCE);//from   ww w . j av a2  s. co m
    // step 1
    Document document = new Document(PageSize.A4);
    try {
        // we create a PdfReader object
        PdfReader reader = new PdfReader(SOURCE);
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        // step 3
        document.open();
        // step 4
        PdfImportedPage page;
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            page = writer.getImportedPage(reader, i);
            Image image = Image.getInstance(page);
            image.scalePercent(15f);
            image.setBorder(Rectangle.BOX);
            image.setBorderWidth(3f);
            image.setBorderColor(new GrayColor(0.5f));
            image.setRotationDegrees(-reader.getPageRotation(i));
            document.add(image);
            document.add(new Paragraph("This is page: " + i));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    // step 5
    document.close();
}

From source file:questions.importpages.NameCard.java

public static void main(String[] args) {
    try {/*from w  ww  .j a va 2s  .co  m*/
        createOneCard();
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        PdfReader reader = new PdfReader(CARD);
        document.open();
        PdfContentByte canvas = writer.getDirectContent();
        canvas.addTemplate(writer.getImportedPage(reader, 1), 36, 600);
        canvas.addTemplate(writer.getImportedPage(reader, 2), 200, 600);
        canvas.moveTo(0, 600);
        canvas.lineTo(595, 600);
        canvas.stroke();
        document.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}