Example usage for com.itextpdf.text.pdf PdfStamper getOverContent

List of usage examples for com.itextpdf.text.pdf PdfStamper getOverContent

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfStamper getOverContent.

Prototype

public PdfContentByte getOverContent(final int pageNum) 

Source Link

Document

Gets a PdfContentByte to write over the page of the original document.

Usage

From source file:fyp.JavaWritePDF.java

public void manipulatePdf2(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    stamper.insertPage(reader.getNumberOfPages() + 1, reader.getPageSizeWithRotation(1));
    stamper.insertPage(reader.getNumberOfPages() + 1, reader.getPageSizeWithRotation(1));// create a second new page
    Image img = Image.getInstance(IMG);
    Image img2 = Image.getInstance(IMG2);
    img.setAbsolutePosition(0, 350);//from   www .ja va2s  .  co  m
    img2.setAbsolutePosition(0, 350);
    stamper.getOverContent(2).addImage(img);
    stamper.getOverContent(3).addImage(img2); // add the second sessions image to the new page
    stamper.close();
    File delfile = new File(SRC);
    delfile.delete();
    respiratorytest.success();
}

From source file:gov.nih.nci.firebird.service.pdf.AdditionalContent.java

License:Open Source License

private void addText(PdfReader reader, PdfStamper stamper, ColumnText text) throws DocumentException {
    Rectangle pageSize = reader.getPageSize(1);
    int newPageNumber = reader.getNumberOfPages() + 1;
    do {//from  ww w. j  a  v a2  s  . com
        stamper.insertPage(newPageNumber, pageSize);
        PdfContentByte newContent = stamper.getOverContent(newPageNumber);
        text.setCanvas(newContent);
        text.setSimpleColumn(pageSize.getLeft(MARGIN_SIZE), pageSize.getTop(MARGIN_SIZE),
                pageSize.getRight(MARGIN_SIZE), pageSize.getBottom(MARGIN_SIZE));
        newPageNumber++;
    } while (ColumnText.hasMoreText(text.go()));
}

From source file:learn.PdfRendererBasicFragment.java

License:Apache License

public void merge(int pageNum) {
    try {//from ww  w .j  av a  2 s.  com
        Image image = Image.getInstance(signatureByte);
        pdfReader = new PdfReader(path);
        //fix y
        Matrix matrix = mSignatureImage.getImageMatrix();
        // Get the values of the matrix
        float[] values = new float[9];
        matrix.getValues(values);
        float relativeX = (mSignatureImage.getX() - values[2]) / values[0];
        float relativeY = (mSignatureImage.getY() - values[5]) / values[4];
        x = relativeX;
        y = relativeY;
        if (pageNum != -1) {
            y = pdfReader.getCropBox(pageNum).getHeight() - y;
            y -= mSign.getHeight();
        }
        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(newP));
        if (pageNum == -1) {
            y = pdfReader.getCropBox(1).getHeight() - y;
            y -= mSign.getHeight();
            for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
                //put content under
                PdfContentByte content;// = pdfStamper.getUnderContent(i);
                // image.setAbsolutePosition(x, y);
                // content.addImage(image);

                //put content over
                content = pdfStamper.getOverContent(i);
                image.setAbsolutePosition(x, y);
                content.addImage(image);

                //Text over the existing page
                /*BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                    BaseFont.WINANSI, BaseFont.EMBEDDED);
                content.beginText();
                content.setFontAndSize(bf, 18);
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, "Page No: " + i, 430, 15, 0);
                content.endText();*/
            }
        } else {
            PdfContentByte content = pdfStamper.getOverContent(pageNum);
            image.setAbsolutePosition(x, y);
            content.addImage(image);

        }
        pdfStamper.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:net.digitstar.vanadio.AbstractReportPdf.java

License:Apache License

protected void writeHeaderFooter(Document document, PdfReader reader, PdfStamper writer, int pag,
        int totalPages, ReportOptions reportOptions) {
    if (reportOptions.isShowHeader()) {
        if (pag != 1 || reportOptions.isShowHeaderOnFirstPage()) {
            PdfPTable header = createHeader(document, pag, totalPages, reportOptions);
            header.writeSelectedRows(0, -1, document.left(), document.top() + header.getTotalHeight(),
                    writer.getOverContent(pag));
        }//from   w  ww .  j a  v  a  2s . c om
    }
    if (reportOptions.isShowFooter()) {
        if (pag != 1 || reportOptions.isShowFooterOnFirstPage()) {
            PdfPTable footer = createFooter(document, pag, totalPages, reportOptions);
            footer.writeSelectedRows(0, -1, document.left(), document.bottom() - footer.getTotalHeight(),
                    writer.getOverContent(pag));
        }
    }
}

From source file:net.pflaeging.PortableSigner.PDFSigner.java

License:Open Source License

/** Creates a new instance of DoSignPDF */
public void doSignPDF(String pdfInputFileName, String pdfOutputFileName, String pkcs12FileName, String password,
        Boolean signText, String signLanguage, String sigLogo, Boolean finalize, String sigComment,
        String signReason, String signLocation, Boolean noExtraPage, float verticalPos, float leftMargin,
        float rightMargin, Boolean signLastPage, byte[] ownerPassword) throws PDFSignerException {
    try {/* w w w  .  j  a  v a2  s . c  o m*/
        //System.out.println("-> DoSignPDF <-");
        //System.out.println("Eingabedatei: " + pdfInputFileName);
        //System.out.println("Ausgabedatei: " + pdfOutputFileName);
        //System.out.println("Signaturdatei: " + pkcs12FileName);
        //System.out.println("Signaturblock?: " + signText);
        //System.out.println("Sprache der Blocks: " + signLanguage);
        //System.out.println("Signaturlogo: " + sigLogo);
        System.err.println("Position V:" + verticalPos + " L:" + leftMargin + " R:" + rightMargin);
        Rectangle signatureBlock;

        java.security.Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 2);

        pkcs12 = new GetPKCS12(pkcs12FileName, password);

        PdfReader reader = null;
        try {
            //                System.out.println("Password:" + ownerPassword.toString());
            if (ownerPassword == null)
                reader = new PdfReader(pdfInputFileName);
            else
                reader = new PdfReader(pdfInputFileName, ownerPassword);
        } catch (IOException e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle(
                "net/pflaeging/PortableSigner/i18n").getString(
                "CouldNotBeOpened"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("CouldNotBeOpened"), true, e.getLocalizedMessage());
        }
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(pdfOutputFileName);
        } catch (FileNotFoundException e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("CouldNotBeWritten"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("CouldNotBeWritten"), true, e.getLocalizedMessage());

        }
        PdfStamper stp = null;
        try {
            Date datum = new Date(System.currentTimeMillis());

            int pages = reader.getNumberOfPages();

            Rectangle size = reader.getPageSize(pages);
            stp = PdfStamper.createSignature(reader, fout, '\0', null, true);
            HashMap<String, String> pdfInfo = reader.getInfo();
            // thanks to Markus Feisst
            String pdfInfoProducer = "";

            if (pdfInfo.get("Producer") != null) {
                pdfInfoProducer = pdfInfo.get("Producer").toString();
                pdfInfoProducer = pdfInfoProducer + " (signed with PortableSigner " + Version.release + ")";
            } else {
                pdfInfoProducer = "Unknown Producer (signed with PortableSigner " + Version.release + ")";
            }
            pdfInfo.put("Producer", pdfInfoProducer);
            //System.err.print("++ Producer:" + pdfInfo.get("Producer").toString());
            stp.setMoreInfo(pdfInfo);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XmpWriter xmp = new XmpWriter(baos, pdfInfo);
            xmp.close();
            stp.setXmpMetadata(baos.toByteArray());
            if (signText) {
                String greet, signator, datestr, ca, serial, special, note, urn, urnvalue;
                int specialcount = 0;
                int sigpage;
                int rightMarginPT, leftMarginPT;
                float verticalPositionPT;
                ResourceBundle block = ResourceBundle
                        .getBundle("net/pflaeging/PortableSigner/Signatureblock_" + signLanguage);
                greet = block.getString("greeting");
                signator = block.getString("signator");
                datestr = block.getString("date");
                ca = block.getString("issuer");
                serial = block.getString("serial");
                special = block.getString("special");
                note = block.getString("note");
                urn = block.getString("urn");
                urnvalue = block.getString("urnvalue");

                //sigcomment = block.getString(signLanguage + "-comment");
                // upper y
                float topy = size.getTop();
                System.err.println("Top: " + topy * ptToCm);
                // right x
                float rightx = size.getRight();
                System.err.println("Right: " + rightx * ptToCm);
                if (!noExtraPage) {
                    sigpage = pages + 1;
                    stp.insertPage(sigpage, size);
                    // 30pt left, 30pt right, 20pt from top
                    rightMarginPT = 30;
                    leftMarginPT = 30;
                    verticalPositionPT = topy - 20;
                } else {
                    if (signLastPage) {
                        sigpage = pages;
                    } else {
                        sigpage = 1;
                    }
                    System.err.println("Page: " + sigpage);
                    rightMarginPT = Math.round(rightMargin / ptToCm);
                    leftMarginPT = Math.round(leftMargin / ptToCm);
                    verticalPositionPT = topy - Math.round(verticalPos / ptToCm);
                }
                if (!GetPKCS12.atEgovOID.equals("")) {
                    specialcount = 1;
                }
                PdfContentByte content = stp.getOverContent(sigpage);

                float[] cellsize = new float[2];
                cellsize[0] = 100f;
                // rightx = width of page
                // 60 = 2x30 margins
                // cellsize[0] = description row
                // cellsize[1] = 0
                // 70 = logo width
                cellsize[1] = rightx - rightMarginPT - leftMarginPT - cellsize[0] - cellsize[1] - 70;

                // Pagetable = Greeting, signatureblock, comment
                // sigpagetable = outer table
                //      consist: greetingcell, signatureblock , commentcell
                PdfPTable signatureBlockCompleteTable = new PdfPTable(2);
                PdfPTable signatureTextTable = new PdfPTable(2);
                PdfPCell signatureBlockHeadingCell = new PdfPCell(
                        new Paragraph(new Chunk(greet, new Font(Font.FontFamily.HELVETICA, 12))));
                signatureBlockHeadingCell.setPaddingBottom(5);
                signatureBlockHeadingCell.setColspan(2);
                signatureBlockHeadingCell.setBorderWidth(0f);
                signatureBlockCompleteTable.addCell(signatureBlockHeadingCell);

                // inner table start
                // Line 1
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(signator, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(GetPKCS12.subject, new Font(Font.FontFamily.COURIER, 10))));
                // Line 2
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(datestr, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(datum.toString(), new Font(Font.FontFamily.COURIER, 10))));
                // Line 3
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(ca, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(GetPKCS12.issuer, new Font(Font.FontFamily.COURIER, 10))));
                // Line 4
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(serial, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(new Paragraph(
                        new Chunk(GetPKCS12.serial.toString(), new Font(Font.FontFamily.COURIER, 10))));
                // Line 5
                if (specialcount == 1) {
                    signatureTextTable.addCell(new Paragraph(
                            new Chunk(special, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                    signatureTextTable.addCell(new Paragraph(
                            new Chunk(GetPKCS12.atEgovOID, new Font(Font.FontFamily.COURIER, 10))));
                }
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(urn, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable
                        .addCell(new Paragraph(new Chunk(urnvalue, new Font(Font.FontFamily.COURIER, 10))));
                signatureTextTable.setTotalWidth(cellsize);
                System.err.println(
                        "signatureTextTable Width: " + cellsize[0] * ptToCm + " " + cellsize[1] * ptToCm);
                // inner table end

                signatureBlockCompleteTable.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                Image logo;
                //                     System.out.println("Logo:" + sigLogo + ":");
                if (sigLogo == null || "".equals(sigLogo)) {
                    logo = Image.getInstance(
                            getClass().getResource("/net/pflaeging/PortableSigner/SignatureLogo.png"));
                } else {
                    logo = Image.getInstance(sigLogo);
                }

                PdfPCell logocell = new PdfPCell();
                logocell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
                logocell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                logocell.setImage(logo);
                signatureBlockCompleteTable.addCell(logocell);
                PdfPCell incell = new PdfPCell(signatureTextTable);
                incell.setBorderWidth(0f);
                signatureBlockCompleteTable.addCell(incell);
                PdfPCell commentcell = new PdfPCell(
                        new Paragraph(new Chunk(sigComment, new Font(Font.FontFamily.HELVETICA, 10))));
                PdfPCell notecell = new PdfPCell(
                        new Paragraph(new Chunk(note, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                //commentcell.setPaddingTop(10);
                //commentcell.setColspan(2);
                // commentcell.setBorderWidth(0f);
                if (!sigComment.equals("")) {
                    signatureBlockCompleteTable.addCell(notecell);
                    signatureBlockCompleteTable.addCell(commentcell);
                }
                float[] cells = { 70, cellsize[0] + cellsize[1] };
                signatureBlockCompleteTable.setTotalWidth(cells);
                System.err.println(
                        "signatureBlockCompleteTable Width: " + cells[0] * ptToCm + " " + cells[1] * ptToCm);
                signatureBlockCompleteTable.writeSelectedRows(0, 4 + specialcount, leftMarginPT,
                        verticalPositionPT, content);
                System.err.println(
                        "signatureBlockCompleteTable Position " + 30 * ptToCm + " " + (topy - 20) * ptToCm);
                signatureBlock = new Rectangle(30 + signatureBlockCompleteTable.getTotalWidth() - 20,
                        topy - 20 - 20, 30 + signatureBlockCompleteTable.getTotalWidth(), topy - 20);
                //                    //////
                //                    AcroFields af = reader.getAcroFields();
                //                    ArrayList names = af.getSignatureNames();
                //                    for (int k = 0; k < names.size(); ++k) {
                //                        String name = (String) names.get(k);
                //                        System.out.println("Signature name: " + name);
                //                        System.out.println("\tSignature covers whole document: " + af.signatureCoversWholeDocument(name));
                //                        System.out.println("\tDocument revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());
                //                        PdfPKCS7 pk = af.verifySignature(name);
                //                        X509Certificate tempsigner = pk.getSigningCertificate();
                //                        Calendar cal = pk.getSignDate();
                //                        Certificate pkc[] = pk.getCertificates();
                //                        java.util.ResourceBundle tempoid =
                //                                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/SpecialOID");
                //                        String tmpEgovOID = "";
                //
                //                        for (Enumeration<String> o = tempoid.getKeys(); o.hasMoreElements();) {
                //                            String element = o.nextElement();
                //                            // System.out.println(element + ":" + oid.getString(element));
                //                            if (tempsigner.getNonCriticalExtensionOIDs().contains(element)) {
                //                                if (!tmpEgovOID.equals("")) {
                //                                    tmpEgovOID += ", ";
                //                                }
                //                                tmpEgovOID += tempoid.getString(element) + " (OID=" + element + ")";
                //                            }
                //                        }
                //                        //System.out.println("\tSigniert von: " + PdfPKCS7.getSubjectFields(pk.getSigningCertificate()));
                //                        System.out.println("\tSigniert von: " + tempsigner.getSubjectX500Principal().toString());
                //                        System.out.println("\tDatum: " + cal.getTime().toString());
                //                        System.out.println("\tAusgestellt von: " + tempsigner.getIssuerX500Principal().toString());
                //                        System.out.println("\tSeriennummer: " + tempsigner.getSerialNumber());
                //                        if (!tmpEgovOID.equals("")) {
                //                            System.out.println("\tVerwaltungseigenschaft: " + tmpEgovOID);
                //                        }
                //                        System.out.println("\n");
                //                        System.out.println("\tDocument modified: " + !pk.verify());
                ////                Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal);
                ////                if (fails == null) {
                ////                    System.out.println("\tCertificates verified against the KeyStore");
                ////                } else {
                ////                    System.out.println("\tCertificate failed: " + fails[1]);
                ////                }
                //                    }
                //
                //                //////
            } else {
                signatureBlock = new Rectangle(0, 0, 0, 0); // fake definition
            }
            PdfSignatureAppearance sap = stp.getSignatureAppearance();
            //                sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null,
            //                        PdfSignatureAppearance.WINCER_SIGNED );
            sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null, null);
            sap.setReason(signReason);
            sap.setLocation(signLocation);
            //                if (signText) {
            //                    sap.setVisibleSignature(signatureBlock,
            //                            pages + 1, "PortableSigner");
            //                }
            if (finalize) {
                sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
            } else {
                sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
            }
            stp.close();

            /* MODIFY BY: Denis Torresan
            Main.setResult(
              java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("IsGeneratedAndSigned"),
              false,
              "");
                */

        } catch (Exception e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorWhileSigningFile"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("ErrorWhileSigningFile"), true, e.getLocalizedMessage());

        }
    } catch (KeyStoreException kse) {

        /* MODIFY BY: Denis Torresan
         Main.setResult(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorCreatingKeystore"),
            true, kse.getLocalizedMessage());
         */

        throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                .getString("ErrorCreatingKeystore"), true, kse.getLocalizedMessage());

    }
}

From source file:nz.ac.waikato.cms.doc.OverlayFilename.java

License:Open Source License

/**
 * Performs the overlay./*from   w w  w  . j  a v a 2s .  co  m*/
 *
 * @param input   the input file/dir
 * @param output   the output file/dir
 * @param vpos   the vertical position
 * @param hpos   the horizontal position
 * @param stripPath   whether to strip the path
 * @param stripExt   whether to strip the extension
 * @param pages   the array of pages (1-based) to add the overlay to, null for all
 * @param evenPages   whether to enforce even pages in the document
 * @return      true if successfully overlay
 */
public boolean overlay(File input, File output, int vpos, int hpos, boolean stripPath, boolean stripExt,
        int[] pages, boolean evenPages) {
    PdfReader reader;
    PdfStamper stamper;
    FileOutputStream fos;
    PdfContentByte canvas;
    int i;
    String text;
    int numPages;
    File tmpFile;
    Document document;
    PdfWriter writer;
    PdfImportedPage page;
    PdfContentByte cb;

    reader = null;
    stamper = null;
    fos = null;
    numPages = -1;
    try {
        reader = new PdfReader(input.getAbsolutePath());
        fos = new FileOutputStream(output.getAbsolutePath());
        stamper = new PdfStamper(reader, fos);
        numPages = reader.getNumberOfPages();
        if (pages == null) {
            pages = new int[reader.getNumberOfPages()];
            for (i = 0; i < pages.length; i++)
                pages[i] = i + 1;
        }

        if (stripPath)
            text = input.getName();
        else
            text = input.getAbsolutePath();
        if (stripExt)
            text = text.replaceFirst("\\.[pP][dD][fF]$", "");

        for (i = 0; i < pages.length; i++) {
            canvas = stamper.getOverContent(pages[i]);
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Paragraph(text), hpos, vpos, 0.0f);
        }
    } catch (Exception e) {
        System.err.println("Failed to process " + input + ":");
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (stamper != null)
                stamper.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            if (reader != null)
                reader.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            if (fos != null) {
                fos.flush();
                fos.close();
            }
        } catch (Exception e) {
            // ignored
        }
    }

    // enforce even pages?
    if (evenPages && (numPages > 0) && (numPages % 2 == 1)) {
        reader = null;
        fos = null;
        writer = null;
        tmpFile = new File(output.getAbsolutePath() + "tmp");
        try {
            if (!output.renameTo(tmpFile)) {
                System.err.println("Failed to rename '" + output + "' to '" + tmpFile + "'!");
                return false;
            }
            reader = new PdfReader(tmpFile.getAbsolutePath());
            document = new Document(reader.getPageSize(1));
            fos = new FileOutputStream(output.getAbsoluteFile());
            writer = PdfWriter.getInstance(document, fos);
            document.open();
            document.addCreationDate();
            document.addAuthor(System.getProperty("user.name"));
            cb = writer.getDirectContent();
            for (i = 0; i < reader.getNumberOfPages(); i++) {
                page = writer.getImportedPage(reader, i + 1);
                document.newPage();
                cb.addTemplate(page, 0, 0);
            }
            document.newPage();
            document.add(new Paragraph(" ")); // fake content
            document.close();
        } catch (Exception e) {
            System.err.println("Failed to process " + tmpFile + ":");
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fos != null) {
                    fos.flush();
                    fos.close();
                }
            } catch (Exception e) {
                // ignored
            }
            try {
                if (reader != null)
                    reader.close();
            } catch (Exception e) {
                // ignored
            }
            try {
                if (writer != null)
                    writer.close();
            } catch (Exception e) {
                // ignored
            }
            if (tmpFile.exists()) {
                try {
                    tmpFile.delete();
                } catch (Exception e) {
                    // ignored
                }
            }
        }
    }

    return true;
}

From source file:nz.ac.waikato.cms.doc.SimplePDFOverlay.java

License:Open Source License

/**
 * Applies the instructions to the input PDF.
 *
 * @return      null if successful, otherwise error message
 *///from  ww w.j  a  v  a  2  s.com
public String execute() {
    String result;
    String line;
    BufferedReader breader;
    FileReader freader;
    int i;
    int lineNo;
    String units;
    int pageNo;
    PdfReader reader;
    PdfStamper stamper;
    PdfContentByte cb;
    ColumnText ct;
    Font font;
    String[] parts;
    StringBuilder text;

    result = null;

    freader = null;
    breader = null;
    try {
        reader = new PdfReader(new FileInputStream(m_Pdf.getAbsolutePath()));
        stamper = new PdfStamper(reader, new FileOutputStream(m_Output.getAbsolutePath()));
        freader = new FileReader(m_Instructions);
        breader = new BufferedReader(freader);
        lineNo = 0;
        units = "pt";
        pageNo = 1;
        cb = stamper.getOverContent(pageNo);
        font = null;
        while ((line = breader.readLine()) != null) {
            lineNo++;
            if (line.trim().startsWith(PREFIX_COMMENT))
                continue;
            if (line.trim().length() == 0)
                continue;
            if (line.startsWith(PREFIX_UNITS)) {
                units = line.substring(PREFIX_UNITS.length()).trim().toLowerCase();
            } else if (line.startsWith(PREFIX_PAGE)) {
                pageNo = Integer.parseInt(line.substring(PREFIX_PAGE.length()).trim());
                cb = stamper.getOverContent(pageNo);
            } else if (line.startsWith(PREFIX_FONT)) {
                parts = line.substring(PREFIX_FONT.length()).trim().split(" ");
                if (parts.length == 3)
                    font = FontFactory.getFont(parts[0], Float.parseFloat(parts[1]),
                            new BaseColor(parseColor(parts[2]).getRGB()));
                else
                    m_Logger.warning("Font instruction not in expected format (" + FORMAT_FONT + "):\n" + line);
            } else if (line.startsWith(PREFIX_TEXT)) {
                parts = line.substring(PREFIX_TEXT.length()).trim().split(" ");
                if (parts.length >= 7) {
                    ct = new ColumnText(cb);
                    ct.setSimpleColumn(parseLocation(parts[0], reader.getPageSize(pageNo).getWidth(), units), // llx
                            parseLocation(parts[1], reader.getPageSize(pageNo).getHeight(), units), // lly
                            parseLocation(parts[2], reader.getPageSize(pageNo).getWidth(), units), // urx
                            parseLocation(parts[3], reader.getPageSize(pageNo).getHeight(), units), // ury
                            Float.parseFloat(parts[4]), // leading
                            parseAlignment(parts[5])); // alignment
                    text = new StringBuilder();
                    for (i = 6; i < parts.length; i++) {
                        if (text.length() > 0)
                            text.append(" ");
                        text.append(parts[i]);
                    }
                    if (font == null)
                        ct.setText(new Phrase(text.toString()));
                    else
                        ct.setText(new Phrase(text.toString(), font));
                    ct.go();
                } else {
                    m_Logger.warning("Text instruction not in expected format (" + FORMAT_TEXT + "):\n" + line);
                }
            } else if (line.startsWith(PREFIX_LINE)) {
                parts = line.substring(PREFIX_LINE.length()).trim().split(" ");
                if (parts.length >= 6) {
                    cb.saveState();
                    cb.setLineWidth(Float.parseFloat(parts[4])); // line width
                    cb.setColorStroke(new BaseColor(parseColor(parts[5]).getRGB())); // color
                    cb.moveTo(parseLocation(parts[0], reader.getPageSize(pageNo).getWidth(), units), // x
                            parseLocation(parts[1], reader.getPageSize(pageNo).getWidth(), units)); // y
                    cb.lineTo(parseLocation(parts[2], reader.getPageSize(pageNo).getWidth(), units), // w
                            parseLocation(parts[3], reader.getPageSize(pageNo).getWidth(), units)); // h
                    cb.stroke();
                    cb.restoreState();
                } else {
                    m_Logger.warning("Line instruction not in expected format (" + FORMAT_LINE + "):\n" + line);
                }
            } else if (line.startsWith(PREFIX_RECT)) {
                parts = line.substring(PREFIX_RECT.length()).trim().split(" ");
                if (parts.length >= 6) {
                    cb.saveState();
                    cb.rectangle(parseLocation(parts[0], reader.getPageSize(pageNo).getWidth(), units), // x
                            parseLocation(parts[1], reader.getPageSize(pageNo).getWidth(), units), // y
                            parseLocation(parts[2], reader.getPageSize(pageNo).getWidth(), units), // w
                            parseLocation(parts[3], reader.getPageSize(pageNo).getWidth(), units) // h
                    );
                    cb.setLineWidth(Float.parseFloat(parts[4])); // line width
                    cb.setColorStroke(new BaseColor(parseColor(parts[5]).getRGB())); // stroke
                    if (parts.length >= 7) {
                        cb.setColorFill(new BaseColor(parseColor(parts[6]).getRGB())); // fill
                        cb.fillStroke();
                    } else {
                        cb.stroke();
                    }
                    cb.restoreState();
                } else {
                    m_Logger.warning(
                            "Rectangle instruction not in expected format (" + FORMAT_RECT + "):\n" + line);
                }
            } else if (line.startsWith(PREFIX_OVAL)) {
                parts = line.substring(PREFIX_OVAL.length()).trim().split(" ");
                if (parts.length >= 6) {
                    cb.saveState();
                    cb.ellipse(parseLocation(parts[0], reader.getPageSize(pageNo).getWidth(), units), // x1
                            parseLocation(parts[1], reader.getPageSize(pageNo).getWidth(), units), // y1
                            parseLocation(parts[2], reader.getPageSize(pageNo).getWidth(), units), // x2
                            parseLocation(parts[3], reader.getPageSize(pageNo).getWidth(), units) // y2
                    );
                    cb.setLineWidth(Float.parseFloat(parts[4])); // line width
                    cb.setColorStroke(new BaseColor(parseColor(parts[5]).getRGB())); // stroke
                    if (parts.length >= 7) {
                        cb.setColorFill(new BaseColor(parseColor(parts[6]).getRGB())); // fill
                        cb.fillStroke();
                    } else {
                        cb.stroke();
                    }
                    cb.restoreState();
                } else {
                    m_Logger.warning("Oval instruction not in expected format (" + FORMAT_OVAL + "):\n" + line);
                }
            } else {
                m_Logger.warning("Unknown command on line #" + lineNo + ":\n" + line);
            }
        }
        stamper.close();
    } catch (Exception e) {
        result = "Failed to process!\n" + Utils.throwableToString(e);
    } finally {
        FileUtils.closeQuietly(breader);
        FileUtils.closeQuietly(freader);
    }

    return result;
}

From source file:om.edu.squ.squportal.portlet.tsurvey.dao.pdf.TeachingSurveyPdfImpl.java

License:Open Source License

/**
 * /*from  w  w w  . java  2 s .  com*/
 * method name  : getPdfSurveyAnalysis
 * @param object
 * @param semesterYear
 * @param questionByYear
 * @param questionSetNo
 * @param byos
 * @param inputStream
 * @param res
 * @return
 * @throws DocumentException
 * @throws IOException
 * TeachingSurveyPdfImpl
 * return type  : OutputStream
 * 
 * purpose      : Generate PDF content
 *
 * Date          :   Mar 28, 2016 7:21:04 PM
 */
public OutputStream getPdfSurveyAnalysis(Object object, String semesterYear, String questionByYear,
        int questionSetNo, ByteArrayOutputStream byos, InputStream inputStream, ResourceResponse res)
        throws DocumentException, IOException {

    Font font = FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, BaseColor.BLACK);

    PdfReader pdfTemplate = new PdfReader(inputStream);
    PdfStamper pdfStamper = new PdfStamper(pdfTemplate, byos);
    Survey survey = (Survey) object;
    String sectionNos = "";
    String seatsTaken = "";
    DecimalFormat formatter = new DecimalFormat("###.##");

    String RIGHT = Constants.RIGHT;
    String CENTER = Constants.CENTER;
    String LEFT = Constants.LEFT;

    pdfStamper.getAcroFields().setField("txtCourse", survey.getCourseCode() + " / " + survey.getCourseName());
    pdfStamper.getAcroFields().setField("txtCollegeName", survey.getCollegeName());

    for (SurveyResponse resp : survey.getSurveyResponses()) {
        sectionNos = sectionNos + resp.getSectionNo() + " ";
        seatsTaken = String.valueOf(resp.getSeatsTaken());
    }

    pdfStamper.getAcroFields().setField("txtSectionNo", sectionNos);
    pdfStamper.getAcroFields().setField("txtDepartmentName", survey.getDepartmentName());
    pdfStamper.getAcroFields().setField("txtEmpName", survey.getEmpName());
    pdfStamper.getAcroFields().setField("txtStudentRegistered", seatsTaken);

    pdfStamper.getAcroFields().setField("txtSemesterYear", semesterYear);

    pdfStamper.getAcroFields().setGenerateAppearances(true);

    /* ****************** */

    PdfPTable table = new PdfPTable(13);

    table.addCell(getPdfCell("", 2, 0, font, LEFT));
    table.addCell(getPdfCell(
            UtilProperty.getMessage("prop.course.teaching.survey.analysis.course.teaching.items", null), 2, 0,
            font, CENTER));
    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.response.number", null), 0,
                    6, font, CENTER));
    table.addCell(getPdfCell(
            UtilProperty.getMessage("prop.course.teaching.survey.analysis.response.percentage", null), 2, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.mean", null), 0, 4,
            font, CENTER));

    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.disagree.strong", null), 0,
                    0, font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.disagree", null), 0,
            0, font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.agree", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.agree.strong", null),
            0, 0, font, CENTER));
    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.applicable.not", null), 0,
                    0, font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.total", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.sect", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.crs", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.dept", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.col", null), 0, 0,
            font, CENTER));

    /* ---------------------------------------------------------------------------- */
    table.addCell(getPdfCell("", 0, 0, font));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.course.items", null),
            0, 12, font, CENTER));

    int cTotal = 0;
    float cPctVal = 0f;
    float cSectionMean = 0f;
    float cCourseMean = 0f;
    float cDepart = 0f;
    float cCollege = 0f;
    int rowCount = 0;

    for (SurveyResponse sures : survey.getSurveyResponses()) {
        for (Analysis analysis : sures.getAnalysisList()) {
            if (analysis.getQuestion().equals("Q2") || analysis.getQuestion().equals("Q14")
                    || analysis.getQuestion().equals(questionByYear)) {
                /***  First part    ***/
                table.addCell(getPdfCell(analysis.getQuestion(), 0, 0, font));
                table.addCell(
                        getPdfCell(
                                UtilProperty.getMessage("prop.course.teaching.survey.analysis.set"
                                        + questionSetNo + ".question" + analysis.getQuestionLabel(), null),
                                0, 0, font, LEFT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongDisagree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDisAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getNotApplicable()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getTotal()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getPercentageResponse()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getSectionMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCourseMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDepartmentMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCollegeMean()), 0, 0, font, RIGHT));

                cTotal = cTotal + analysis.getTotal();
                cPctVal = cPctVal + analysis.getPercentageResponse();
                cSectionMean = cSectionMean + analysis.getSectionMean();
                cCourseMean = cCourseMean + analysis.getCollegeMean();
                cDepart = cDepart + analysis.getDepartmentMean();
                cCollege = cCollege + analysis.getCollegeMean();
                rowCount = rowCount + 1;

            }
        }
    }

    /***  First part - Summary   ***/
    table.addCell(getPdfCell(String.valueOf(""), 0, 0, font));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.summary", null), 0,
            0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(""), 0, 5, font));
    table.addCell(getPdfCell(String.valueOf(cTotal), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cPctVal / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cSectionMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCourseMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cDepart / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCollege / rowCount)), 0, 0, font, RIGHT));

    table.addCell(getPdfCell("", 0, 13, font));

    table.addCell(getPdfCell("", 0, 0, font));
    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.teaching.items", null), 0,
                    12, font, LEFT));

    cTotal = 0;
    cPctVal = 0f;
    cSectionMean = 0f;
    cCourseMean = 0f;
    cDepart = 0f;
    cCollege = 0f;
    rowCount = 0;
    for (SurveyResponse sures : survey.getSurveyResponses()) {
        for (Analysis analysis : sures.getAnalysisList()) {
            if (!(analysis.getQuestion().equals("Q2") || analysis.getQuestion().equals("Q14")
                    || analysis.getQuestion().equals(questionByYear))) {

                table.addCell(getPdfCell(analysis.getQuestion(), 0, 0, font));
                table.addCell(
                        getPdfCell(
                                UtilProperty.getMessage("prop.course.teaching.survey.analysis.set"
                                        + questionSetNo + ".question" + analysis.getQuestionLabel(), null),
                                0, 0, font, LEFT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongDisagree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDisAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getNotApplicable()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getTotal()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getPercentageResponse()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getSectionMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCourseMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDepartmentMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCollegeMean()), 0, 0, font, RIGHT));

                cTotal = cTotal + analysis.getTotal();
                cPctVal = cPctVal + analysis.getPercentageResponse();
                cSectionMean = cSectionMean + analysis.getSectionMean();
                cCourseMean = cCourseMean + analysis.getCollegeMean();
                cDepart = cDepart + analysis.getDepartmentMean();
                cCollege = cCollege + analysis.getCollegeMean();
                rowCount = rowCount + 1;

            }

        }

    }

    /***  Second part - Summary   ***/
    table.addCell(getPdfCell(String.valueOf(""), 0, 0, font));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.summary", null), 0,
            0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(""), 0, 5, font));
    table.addCell(getPdfCell(String.valueOf(cTotal), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cPctVal / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cSectionMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCourseMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cDepart / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCollege / rowCount)), 0, 0, font, RIGHT));

    if (!survey.getMessage().equals("")) {
        table.addCell(getPdfCell("", 0, 13, font));
        table.addCell(getPdfCell("", 0, 0, font));
        table.addCell(getPdfCell(survey.getMessage(), 0, 12, font, CENTER));
    }

    table.setTotalWidth(750);
    table.setLockedWidth(true);
    table.setWidths(new float[] { 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 });

    ColumnText column = new ColumnText(pdfStamper.getOverContent(1));
    Rectangle rectPage1 = new Rectangle(120, 20, 659, 480);

    column.setSimpleColumn(rectPage1);
    column.addElement(table);

    int status = column.go();

    pdfStamper.setFormFlattening(true);

    pdfStamper.close();

    pdfTemplate.close();

    res.setContentType("application/pdf");

    return res.getPortletOutputStream();

}

From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java

License:Apache License

/**
 * Applies an image watermark/*from  w w  w .  ja  v a 2s. c om*/
 * 
 * @param reader
 * @param writer
 * @param options
 * @throws Exception
 */
private void imageAction(Action ruleAction, NodeRef actionedUponNodeRef, NodeRef watermarkNodeRef,
        ContentReader actionedUponContentReader, ContentReader watermarkContentReader,
        Map<String, Object> options) {

    PdfStamper stamp = null;
    File tempDir = null;
    ContentWriter writer = null;

    try {
        // get a temp file to stash the watermarked PDF in before moving to
        // repo
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());

        // get the PDF input stream and create a reader for iText
        PdfReader reader = new PdfReader(actionedUponContentReader.getContentInputStream());
        stamp = new PdfStamper(reader, new FileOutputStream(file));
        PdfContentByte pcb;

        // get a com.itextpdf.text.Image object via java.imageio.ImageIO
        Image img = Image.getInstance(ImageIO.read(watermarkContentReader.getContentInputStream()), null);

        // get the PDF pages and position
        String pages = (String) options.get(PARAM_PAGE);
        String position = (String) options.get(PARAM_POSITION);
        String depth = (String) options.get(PARAM_WATERMARK_DEPTH);

        // image requires absolute positioning or an exception will be
        // thrown
        // set image position according to parameter. Use
        // PdfReader.getPageSizeWithRotation
        // to get the canvas size for alignment.
        img.setAbsolutePosition(100f, 100f);

        // stamp each page
        int numpages = reader.getNumberOfPages();
        for (int i = 1; i <= numpages; i++) {
            Rectangle r = reader.getPageSizeWithRotation(i);
            // set stamp position
            if (position.equals(POSITION_BOTTOMLEFT)) {
                img.setAbsolutePosition(0, 0);
            } else if (position.equals(POSITION_BOTTOMRIGHT)) {
                img.setAbsolutePosition(r.getWidth() - img.getWidth(), 0);
            } else if (position.equals(POSITION_TOPLEFT)) {
                img.setAbsolutePosition(0, r.getHeight() - img.getHeight());
            } else if (position.equals(POSITION_TOPRIGHT)) {
                img.setAbsolutePosition(r.getWidth() - img.getWidth(), r.getHeight() - img.getHeight());
            } else if (position.equals(POSITION_CENTER)) {
                img.setAbsolutePosition(getCenterX(r, img), getCenterY(r, img));
            }

            // if this is an under-text stamp, use getUnderContent.
            // if this is an over-text stamp, usse getOverContent.
            if (depth.equals(DEPTH_OVER)) {
                pcb = stamp.getOverContent(i);
            } else {
                pcb = stamp.getUnderContent(i);
            }

            // only apply stamp to requested pages
            if (checkPage(pages, i, numpages)) {
                pcb.addImage(img);
            }
        }

        stamp.close();

        // Get a writer and prep it for putting it back into the repo
        //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination
        NodeRef destinationNode = createDestinationNode(file.getName(),
                (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef);
        writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT,
                true);

        writer.setEncoding(actionedUponContentReader.getEncoding());
        writer.setMimetype(FILE_MIMETYPE);

        // Put it in the repo
        writer.putContent(file);

        // delete the temp file
        file.delete();
    } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }

        if (stamp != null) {
            try {
                stamp.close();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }
    }
}

From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java

License:Apache License

/**
 * Applies a text watermark (current date, user name, etc, depending on
 * options)// www .  j  a  va2 s. co m
 * 
 * @param reader
 * @param writer
 * @param options
 */
private void textAction(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader actionedUponContentReader,
        Map<String, Object> options) {

    PdfStamper stamp = null;
    File tempDir = null;
    ContentWriter writer = null;
    String watermarkText;
    StringTokenizer st;
    Vector<String> tokens = new Vector<String>();

    try {
        // get a temp file to stash the watermarked PDF in before moving to
        // repo
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());

        // get the PDF input stream and create a reader for iText
        PdfReader reader = new PdfReader(actionedUponContentReader.getContentInputStream());
        stamp = new PdfStamper(reader, new FileOutputStream(file));
        PdfContentByte pcb;

        // get the PDF pages and position
        String pages = (String) options.get(PARAM_PAGE);
        String position = (String) options.get(PARAM_POSITION);
        String depth = (String) options.get(PARAM_WATERMARK_DEPTH);

        // create the base font for the text stamp
        BaseFont bf = BaseFont.createFont((String) options.get(PARAM_WATERMARK_FONT), BaseFont.CP1250,
                BaseFont.EMBEDDED);

        // get watermark text and process template with model
        String templateText = (String) options.get(PARAM_WATERMARK_TEXT);
        Map<String, Object> model = buildWatermarkTemplateModel(actionedUponNodeRef);
        StringWriter watermarkWriter = new StringWriter();
        freemarkerProcessor.processString(templateText, model, watermarkWriter);
        watermarkText = watermarkWriter.getBuffer().toString();

        // tokenize watermark text to support multiple lines and copy tokens
        // to vector for re-use
        st = new StringTokenizer(watermarkText, "\r\n", false);
        while (st.hasMoreTokens()) {
            tokens.add(st.nextToken());
        }

        // stamp each page
        int numpages = reader.getNumberOfPages();
        for (int i = 1; i <= numpages; i++) {
            Rectangle r = reader.getPageSizeWithRotation(i);

            // if this is an under-text stamp, use getUnderContent.
            // if this is an over-text stamp, use getOverContent.
            if (depth.equals(DEPTH_OVER)) {
                pcb = stamp.getOverContent(i);
            } else {
                pcb = stamp.getUnderContent(i);
            }

            // set the font and size
            float size = Float.parseFloat((String) options.get(PARAM_WATERMARK_SIZE));
            pcb.setFontAndSize(bf, size);

            // only apply stamp to requested pages
            if (checkPage(pages, i, numpages)) {
                writeAlignedText(pcb, r, tokens, size, position);
            }
        }

        stamp.close();

        // Get a writer and prep it for putting it back into the repo
        //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination
        NodeRef destinationNode = createDestinationNode(file.getName(),
                (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef);
        writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT,
                true);
        writer.setEncoding(actionedUponContentReader.getEncoding());
        writer.setMimetype(FILE_MIMETYPE);

        // Put it in the repo
        writer.putContent(file);

        // delete the temp file
        file.delete();
    } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }

        if (stamp != null) {
            try {
                stamp.close();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }
    }
}