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

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

Introduction

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

Prototype

public PdfImportedPage getImportedPage(PdfReader reader, int pageNumber) 

Source Link

Document

Gets a page from other PDF document.

Usage

From source file:classroom.filmfestival_c.Movies25.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    createTemplate();//w  ww  .jav a 2 s. c  o m
    Session session = (Session) MySessionFactory.currentSession();
    Query q = session.createQuery("from FilmTitle order by title");
    java.util.List<FilmTitle> results = q.list();
    try {
        Document document = new Document();
        PdfSmartCopy copy = new PdfSmartCopy(document, new FileOutputStream(RESULT));
        document.open();

        PdfReader reader;
        PdfStamper stamper = null;
        ByteArrayOutputStream baos = null;
        AcroFields form = null;
        int count = 0;
        for (FilmTitle movie : results) {
            if (count == 0) {
                baos = new ByteArrayOutputStream();
                reader = new PdfReader(BACKGROUND);
                stamper = new PdfStamper(reader, baos);
                stamper.setFormFlattening(true);
                form = stamper.getAcroFields();
            }
            count++;
            byte[] pdf = createPdf(movie);
            reader = new PdfReader(pdf);
            PdfImportedPage page = stamper.getImportedPage(reader, 1);
            PushbuttonField bt = form.getNewPushbuttonFromField("movie_" + count);
            bt.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
            bt.setProportionalIcon(true);
            bt.setTemplate(page);
            form.replacePushbuttonField("movie_" + count, bt.getField());
            if (count == 16) {
                stamper.close();
                reader = new PdfReader(baos.toByteArray());
                copy.addPage(copy.getImportedPage(reader, 1));
                count = 0;
            }
        }
        if (count > 0) {
            stamper.close();
            reader = new PdfReader(baos.toByteArray());
            copy.addPage(copy.getImportedPage(reader, 1));
            count = 0;
        }
        document.close();
    } catch (IOException ioe) {
        LOGGER.error("IOException: ", ioe);
    } catch (DocumentException de) {
        LOGGER.error("DocumentException: ", de);
    }
}

From source file:classroom.newspaper_b.Newspaper13.java

public static void addButton(PdfStamper stamper, Rectangle rect, String path, String name, int pagenumber)
        throws IOException, DocumentException {
    PushbuttonField field = new PushbuttonField(stamper.getWriter(), rect, name);
    if (path.endsWith(".pdf")) {
        PdfReader reader = new PdfReader(path);
        field.setTemplate(stamper.getImportedPage(reader, 1));
    } else {//from w ww .j  av  a  2 s.  c om
        field.setImage(Image.getInstance(path));
    }
    field.setBackgroundColor(new Color(0xFF, 0xFF, 0xFF));
    field.setBorderColor(new Color(0xC0, 0xC0, 0xC0));
    field.setBorderWidth(0.5f);
    field.setScaleIcon(PushbuttonField.SCALE_ICON_ALWAYS);
    field.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
    stamper.addAnnotation(field.getField(), pagenumber);
}

From source file:classroom.newspaper_b.Newspaper14.java

public static void changeField(PdfStamper stamper, String button, String path)
        throws IOException, DocumentException {
    AcroFields fields = stamper.getAcroFields();
    PushbuttonField bt = fields.getNewPushbuttonFromField(button);
    bt.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
    bt.setProportionalIcon(true);/*from  w  ww  .  j a v  a2 s.  co m*/
    PdfReader reader = new PdfReader(path);
    bt.setTemplate(stamper.getImportedPage(reader, 1));
    fields.replacePushbuttonField(button, bt.getField());
}

From source file:com.orange.atk.atkUI.corecli.utils.PdfUtilities.java

License:Apache License

public void addTemplate(String pdfFileName, String templatePDFFileName) throws Exception {
    // see example on http://itextdocs.lowagie.com/examples/com/lowagie/examples/general/copystamp/AddWatermarkPageNumbers.java
    // 1. copy//from   w  ww.ja  v  a2  s.c o  m
    File tmpPDFFile = new File(tmpDir, "tmpPDF.pdf");
    copyFile(new File(pdfFileName), tmpPDFFile);
    // 2. add template on all pages
    // we create a reader for a certain document
    PdfReader reader = new PdfReader(tmpPDFFile.getAbsolutePath());
    // we create a stamper that will copy the document to a new file
    PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(pdfFileName));
    // adding content to each page
    int n = reader.getNumberOfPages();
    int i = 0;
    // a reader for the template document
    PdfReader reader2 = new PdfReader(templatePDFFileName);

    PdfContentByte under;
    while (i < n) {
        i++;
        // template under the existing page
        under = stamp.getUnderContent(i);
        //under.addTemplate(stamp.getImportedPage(reader2, 1), 1, 0, 0, 1, 0, 0);
        under.addTemplate(stamp.getImportedPage(reader2, 1), -10, -50);
    }
    // closing PdfStamper will generate the new PDF file
    stamp.close();

}

From source file:com.userweave.batch.CreatePDF.java

License:Open Source License

public static void main(String[] args) {
    if (args.length == 0) {
        args = new String[] { "one.pdf", "two.pdf", "out.pdf" };
    }/*from   w w w.  j  a  v a 2 s .co m*/
    if (args.length == 3) {
        try {
            // the document we're watermarking
            PdfReader document = new PdfReader(args[0]);
            int num_pages = document.getNumberOfPages();

            // the watermark (or letterhead, etc.)
            PdfReader mark = new PdfReader(args[1]);
            Rectangle mark_page_size = mark.getPageSize(1);

            // the output document
            PdfStamper writer = new PdfStamper(document, new FileOutputStream(args[2]));

            // create a PdfTemplate from the first page of mark
            // (PdfImportedPage is derived from PdfTemplate)
            PdfImportedPage mark_page = writer.getImportedPage(mark, 1);

            for (int ii = 0; ii < num_pages;) {
                // iterate over document's pages, adding mark_page as
                // a layer 'underneath' the page content; scale mark_page
                // and move it so it fits within the document's page;
                // if document's page is cropped, then this scale might
                // not be small enough

                ++ii;
                Rectangle doc_page_size = document.getPageSize(ii);
                float h_scale = doc_page_size.getWidth() / mark_page_size.getWidth();
                float v_scale = doc_page_size.getHeight() / mark_page_size.getHeight();
                float mark_scale = (h_scale < v_scale) ? h_scale : v_scale;

                float h_trans = (float) ((doc_page_size.getWidth() - mark_page_size.getWidth() * mark_scale)
                        / 2.0);
                float v_trans = (float) ((doc_page_size.getHeight() - mark_page_size.getHeight() * mark_scale)
                        / 2.0);

                PdfContentByte contentByte = writer.getUnderContent(ii);
                contentByte.addTemplate(mark_page, mark_scale, 0, 0, mark_scale, h_trans, v_trans);
            }

            writer.close();
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    } else { // input error
        System.err.println("arguments: in_document in_watermark out_pdf_fn");
    }

}

From source file:com.userweave.domain.service.pdf.ItextUtils.java

License:Open Source License

public OutputStream createPDF(InputStream generatedPDF, InputStream stampPDF, OutputStream out)
        throws IOException, DocumentException {

    // the document we're watermarking
    PdfReader document = new PdfReader(generatedPDF);
    int num_pages = document.getNumberOfPages();

    // the watermark (or letterhead, etc.)
    PdfReader mark = new PdfReader(stampPDF);
    Rectangle mark_page_size = mark.getPageSize(1);

    // the output document
    PdfStamper writer = new PdfStamper(document, out);

    // create a PdfTemplate from the first page of mark
    // (PdfImportedPage is derived from PdfTemplate)
    PdfImportedPage mark_page = writer.getImportedPage(mark, 1);

    for (int ii = 0; ii < num_pages;) {
        // iterate over document's pages, adding mark_page as
        // a layer 'underneath' the page content; scale mark_page
        // and move it so it fits within the document's page;
        // if document's page is cropped, then this scale might
        // not be small enough

        ++ii;//from   w w  w.j a v  a 2s  . c om
        Rectangle doc_page_size = document.getPageSize(ii);
        float h_scale = doc_page_size.getWidth() / mark_page_size.getWidth();
        float v_scale = doc_page_size.getHeight() / mark_page_size.getHeight();
        float mark_scale = (h_scale < v_scale) ? h_scale : v_scale;

        float h_trans = (float) ((doc_page_size.getWidth() - mark_page_size.getWidth() * mark_scale) / 2.0);
        float v_trans = (float) ((doc_page_size.getHeight() - mark_page_size.getHeight() * mark_scale) / 2.0);

        PdfContentByte contentByte = writer.getUnderContent(ii);
        contentByte.addTemplate(mark_page, mark_scale, 0, 0, mark_scale, h_trans, v_trans);
    }

    writer.close();

    return out;

    /*      
                  
                  
                  
                  
              PdfReader reader = new PdfReader(origPDF);
                      
              int n = reader.getNumberOfPages();
                      
              Document document = new Document(reader.getPageSizeWithRotation(1));
              PdfWriter writer = PdfWriter.getInstance(document, outfile);
              writer.setEncryption(PdfWriter.STRENGTH40BITS, "pdf", null,
    PdfWriter.AllowCopy);
              document.open();
              PdfContentByte cb = writer.getDirectContent();
              PdfImportedPage page;
              int rotation;
              int i = 0;
              while (i < n) {
    i++;
    document.setPageSize(reader.getPageSizeWithRotation(i));
    document.newPage();
    page = writer.getImportedPage(reader, i);
    rotation = reader.getPageRotation(i);
    if (rotation == 90 || rotation == 270) {
      cb.addTemplate(page, 0, -1f, 1f, 0, 0,
      reader.getPageSizeWithRotation(i).height());
    } else {
      cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
    }
    System.out.println("Processed page " + i);
              }
              document.close();
            } catch( Exception e) {
              e.printStackTrace();
            }
          */

}

From source file:lucee.runtime.tag.PDF.java

License:Open Source License

private void doActionAddWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "addWatermark", "source", source);
    if (copyFrom == null && image == null)
        throw new ApplicationException(
                "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
        throw new ApplicationException("destination file [" + destination + "] already exists");

    // image/*w  w w.j a  v a  2 s  .  com*/
    Image img = null;
    if (image != null) {
        lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext, image, false, false, true,
                null);
        img = Image.getInstance(ri.getBufferedImage(), null, false);
    }
    // copy From
    else {
        byte[] barr;
        try {
            Resource res = Caster.toResource(pageContext, copyFrom, true);
            barr = IOUtil.toBytes(res);
        } catch (ExpressionException ee) {
            barr = Caster.toBinary(copyFrom);
        }
        img = Image.getInstance(PDFUtil.toImage(barr, 1).getBufferedImage(), null, false);

    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!StringUtil.isEmpty(position)) {
        int index = position.indexOf(',');
        if (index == -1)
            throw new ApplicationException("attribute [position] has an invalid value [" + position + "],"
                    + "value should follow one of the following pattern [40,50], [40,] or [,50]");
        String strX = position.substring(0, index).trim();
        String strY = position.substring(index + 1).trim();
        if (!StringUtil.isEmpty(strX))
            x = Caster.toIntValue(strX);
        if (!StringUtil.isEmpty(strY))
            y = Caster.toIntValue(strY);

    }

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null)
        master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }

    try {

        int len = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, os);

        if (len > 0) {
            if (x == UNDEFINED || y == UNDEFINED) {
                PdfImportedPage first = stamp.getImportedPage(reader, 1);
                if (y == UNDEFINED)
                    y = (first.getHeight() - img.getHeight()) / 2;
                if (x == UNDEFINED)
                    x = (first.getWidth() - img.getWidth()) / 2;
            }
            img.setAbsolutePosition(x, y);
            //img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte

        }

        // rotation
        if (rotation != 0) {
            img.setRotationDegrees(rotation);
        }

        Set _pages = doc.getPages();
        for (int i = 1; i <= len; i++) {
            if (_pages != null && !_pages.contains(Integer.valueOf(i)))
                continue;
            PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
            PdfGState gs1 = new PdfGState();
            //print.out("op:"+opacity);
            gs1.setFillOpacity(opacity);
            //gs1.setStrokeOpacity(opacity);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        IOUtil.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                IOUtil.copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination,
                        true);// MUST overwrite
            if (!StringUtil.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:net.sourceforge.fenixedu.util.report.ReportsUtils.java

License:Open Source License

static public byte[] stampPdfAt(byte[] originalPdf, byte[] toStampPdf, int positionX, int positionY) {
    try {// w w  w .j a  va  2s.co  m
        PdfReader originalPdfReader = new PdfReader(originalPdf);
        PdfReader toStampPdfReader = new PdfReader(toStampPdf);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(originalPdfReader, stream);

        PdfImportedPage importedPage = stamper.getImportedPage(toStampPdfReader, 1);

        PdfContentByte overContent = stamper.getOverContent(1);

        Rectangle pageSizeWithRotation = originalPdfReader.getPageSizeWithRotation(1);
        Rectangle pageSizeWithRotationStamper = toStampPdfReader.getPageSizeWithRotation(1);

        logger.info(
                String.format("[ %s, %s]", pageSizeWithRotation.getWidth(), pageSizeWithRotation.getHeight()));
        logger.info(String.format("[ %s, %s]", pageSizeWithRotationStamper.getWidth(),
                pageSizeWithRotationStamper.getHeight()));

        Image image = Image.getInstance(importedPage);

        overContent.addImage(image, image.getWidth(), 0f, 0f, image.getHeight(), positionX, positionY);

        stamper.close();

        originalPdfReader.close();
        toStampPdfReader.close();

        return stream.toByteArray();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.allcolor.yahp.cl.converter.CDocumentReconstructor.java

License:Open Source License

/**
 * construct a pdf document from pdf parts.
 * /*ww  w. j  av a 2  s .c  o m*/
 * @param files
 *            list containing the pdf to assemble
 * @param properties
 *            converter properties
 * @param fout
 *            outputstream to write the new pdf
 * @param base_url
 *            base url of the document
 * @param producer
 *            producer of the pdf
 * 
 * @throws CConvertException
 *             if an error occured while reconstruct.
 */
public static void reconstruct(final List files, final Map properties, final OutputStream fout,
        final String base_url, final String producer, final PageSize[] size, final List hf)
        throws CConvertException {
    OutputStream out = fout;
    OutputStream out2 = fout;
    boolean signed = false;
    OutputStream oldOut = null;
    File tmp = null;
    File tmp2 = null;
    try {
        tmp = File.createTempFile("yahp", "pdf");
        tmp2 = File.createTempFile("yahp", "pdf");
        oldOut = out;
        if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) {
            signed = true;
            out2 = new FileOutputStream(tmp2);
        } // end if
        else {
            out2 = oldOut;
        }
        out = new FileOutputStream(tmp);
        com.lowagie.text.Document document = null;
        PdfCopy writer = null;
        boolean first = true;

        Map mapSizeDoc = new HashMap();

        int totalPage = 0;

        for (int i = 0; i < files.size(); i++) {
            final File fPDF = (File) files.get(i);
            final PdfReader reader = new PdfReader(fPDF.getAbsolutePath());
            reader.consolidateNamedDestinations();

            final int n = reader.getNumberOfPages();

            if (first) {
                first = false;
                // step 1: creation of a document-object
                // set title/creator/author
                document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, out);
                // use pdf version 1.5
                writer.setPdfVersion(PdfWriter.VERSION_1_3);
                // compress the pdf
                writer.setFullCompression();

                // check if encryption is needed
                if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                    final String password = (String) properties
                            .get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
                    final int securityType = CDocumentReconstructor.getSecurityFlags(properties);
                    writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, securityType);
                } // end if

                final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE);

                if (title != null) {
                    document.addTitle(title);
                } // end if
                else if (base_url != null) {
                    document.addTitle(base_url);
                } // end else if

                final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR);

                if (creator != null) {
                    document.addCreator(creator);
                } // end if
                else {
                    document.addCreator(IHtmlToPdfTransformer.VERSION);
                } // end else

                final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR);

                if (author != null) {
                    document.addAuthor(author);
                } // end if

                final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER);

                if (sproducer != null) {
                    document.add(new Meta("Producer", sproducer));
                } // end if
                else {
                    document.add(new Meta("Producer", (IHtmlToPdfTransformer.VERSION
                            + " - http://www.allcolor.org/YaHPConverter/ - " + producer)));
                } // end else

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

            PdfImportedPage page;

            for (int j = 0; j < n;) {
                ++j;
                totalPage++;
                mapSizeDoc.put("" + totalPage, "" + i);
                page = writer.getImportedPage(reader, j);
                writer.addPage(page);
            } // end for
        } // end for

        document.close();
        out.flush();
        out.close();
        {
            final PdfReader reader = new PdfReader(tmp.getAbsolutePath());
            ;
            final int n = reader.getNumberOfPages();
            final PdfStamper stp = new PdfStamper(reader, out2);
            int i = 0;
            BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer();
            while (i < n) {
                i++;
                int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i));
                final int[] dsize = size[indexSize].getSize();
                final int[] dmargin = size[indexSize].getMargin();
                for (final Iterator it = hf.iterator(); it.hasNext();) {
                    final CHeaderFooter chf = (CHeaderFooter) it.next();
                    if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) {
                        continue;
                    } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) {
                        continue;
                    }
                    final String text = chf.getContent().replaceAll("<pagenumber>", "" + i)
                            .replaceAll("<pagecount>", "" + n);
                    // text over the existing page
                    final PdfContentByte over = stp.getOverContent(i);
                    final ByteArrayOutputStream bbout = new ByteArrayOutputStream();
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(),
                                properties, bbout);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(),
                                properties, bbout);
                    }
                    final PdfReader readerHF = new PdfReader(bbout.toByteArray());
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0);
                    }
                    readerHF.close();
                }
            }
            stp.close();
        }
        try {
            out2.flush();
        } catch (Exception ignore) {
        } finally {
            try {
                out2.close();
            } catch (Exception ignore) {
            }
        }
        if (signed) {

            final String keypassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD);
            final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
            final String keyStorepassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD);
            final String privateKeyFile = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE);
            final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON);
            final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION);
            final boolean selfSigned = !"false"
                    .equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING));
            PdfReader reader = null;

            if (password != null) {
                reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes());
            } // end if
            else {
                reader = new PdfReader(tmp2.getAbsolutePath());
            } // end else

            final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType())
                    : KeyStore.getInstance("pkcs12");
            ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray());

            final String alias = (String) ks.aliases().nextElement();
            final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray());
            final Certificate chain[] = ks.getCertificateChain(alias);
            final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0');

            if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                stp.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null,
                        CDocumentReconstructor.getSecurityFlags(properties));
            } // end if

            final PdfSignatureAppearance sap = stp.getSignatureAppearance();

            if (selfSigned) {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
            } // end if
            else {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            } // end else

            if (reason != null) {
                sap.setReason(reason);
            } // end if

            if (location != null) {
                sap.setLocation(location);
            } // end if

            stp.close();
            oldOut.flush();
        } // end if
    } // end try
    catch (final Exception e) {
        throw new CConvertException(
                "ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e);
    } // end catch
    finally {
        try {
            tmp.delete();
        } // end try
        catch (final Exception ignore) {
        }
        try {
            tmp2.delete();
        } // end try
        catch (final Exception ignore) {
        }
    } // end finally
}

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

License:Open Source License

private void doActionAddWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "addWatermark", "source", source);
    if (copyFrom == null && image == null)
        throw engine.getExceptionUtil().createApplicationException(
                "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
        throw engine.getExceptionUtil()
                .createApplicationException("destination file [" + destination + "] already exists");

    // image/*from www  .  ja  v a  2s  . co  m*/
    Image img = null;
    if (image != null) {
        // TODO lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext,image,false,false,true,null);
        // TODO img=Image.getInstance(ri.getBufferedImage(),null,false);
    }
    // copy From
    else {
        byte[] barr;
        try {
            Resource res = copyFrom instanceof String
                    ? engine.getResourceUtil().toResourceExisting(pageContext, (String) copyFrom)
                    : engine.getCastUtil().toResource(copyFrom);
            barr = PDFUtil.toBytes(res);
        } catch (PageException ee) {
            barr = engine.getCastUtil().toBinary(copyFrom);
        }
        img = Image.getInstance(PDFUtil.toImage(barr, 1), null, false);

    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!Util.isEmpty(position)) {
        int index = position.indexOf(',');
        if (index == -1)
            throw engine.getExceptionUtil()
                    .createApplicationException("attribute [position] has an invalid value [" + position + "],"
                            + "value should follow one of the following pattern [40,50], [40,] or [,50]");
        String strX = position.substring(0, index).trim();
        String strY = position.substring(index + 1).trim();
        if (!Util.isEmpty(strX))
            x = engine.getCastUtil().toIntValue(strX);
        if (!Util.isEmpty(strY))
            y = engine.getCastUtil().toIntValue(strY);

    }

    PDFStruct doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null)
        master.addAll(bookmarks);

    // output
    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();
    }

    try {

        int len = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, os);

        if (len > 0) {
            if (x == UNDEFINED || y == UNDEFINED) {
                PdfImportedPage first = stamp.getImportedPage(reader, 1);
                if (y == UNDEFINED)
                    y = (first.getHeight() - img.getHeight()) / 2;
                if (x == UNDEFINED)
                    x = (first.getWidth() - img.getWidth()) / 2;
            }
            img.setAbsolutePosition(x, y);
            // img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte

        }

        // rotation
        if (rotation != 0) {
            img.setRotationDegrees(rotation);
        }

        Set _pages = doc.getPages();
        for (int i = 1; i <= len; i++) {
            if (_pages != null && !_pages.contains(Integer.valueOf(i)))
                continue;
            PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
            PdfGState gs1 = new PdfGState();
            // print.out("op:"+opacity);
            gs1.setFillOpacity(opacity);
            // gs1.setStrokeOpacity(opacity);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        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));
            }
        }
    }
}