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

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

Introduction

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

Prototype

public void close() throws DocumentException, IOException 

Source Link

Document

Closes the document.

Usage

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

License:Apache License

/**
 * //  www . j ava2s .  c  o m
 * @param ruleAction
 * @param actionedUponNodeRef
 * @param actionedUponContentReader
 */
protected void doSignature(Action ruleAction, NodeRef actionedUponNodeRef,
        ContentReader actionedUponContentReader) {

    NodeRef privateKey = (NodeRef) ruleAction.getParameterValue(PARAM_PRIVATE_KEY);
    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    String position = (String) ruleAction.getParameterValue(PARAM_POSITION);
    String reason = (String) ruleAction.getParameterValue(PARAM_REASON);
    String visibility = (String) ruleAction.getParameterValue(PARAM_VISIBILITY);
    String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD);
    String keyType = (String) ruleAction.getParameterValue(PARAM_KEY_TYPE);
    int height = getInteger(ruleAction.getParameterValue(PARAM_HEIGHT));
    int width = getInteger(ruleAction.getParameterValue(PARAM_WIDTH));
    int pageNumber = getInteger(ruleAction.getParameterValue(PARAM_PAGE));

    // New keystore parameters
    String alias = (String) ruleAction.getParameterValue(PARAM_ALIAS);
    String storePassword = (String) ruleAction.getParameterValue(PARAM_STORE_PASSWORD);

    int locationX = getInteger(ruleAction.getParameterValue(PARAM_LOCATION_X));
    int locationY = getInteger(ruleAction.getParameterValue(PARAM_LOCATION_Y));

    File tempDir = null;
    ContentWriter writer = null;
    KeyStore ks = null;

    try {
        // get a keystore instance by
        if (keyType == null || keyType.equalsIgnoreCase(KEY_TYPE_DEFAULT)) {
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
        } else if (keyType.equalsIgnoreCase(KEY_TYPE_PKCS12)) {
            ks = KeyStore.getInstance("pkcs12");
        } else {
            throw new AlfrescoRuntimeException("Unknown key type " + keyType + " specified");
        }

        // open the reader to the key and load it
        ContentReader keyReader = getReader(privateKey);
        ks.load(keyReader.getContentInputStream(), storePassword.toCharArray());

        // set alias
        // String alias = (String) ks.aliases().nextElement();

        PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassword.toCharArray());
        Certificate[] chain = ks.getCertificateChain(alias);

        // open original pdf
        ContentReader pdfReader = getReader(actionedUponNodeRef);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());

        // create temp dir to store file
        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());

        FileOutputStream fout = new FileOutputStream(file);
        PdfStamper stamp = PdfStamper.createSignature(reader, fout, '\0');
        PdfSignatureAppearance sap = stamp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);

        // set reason for signature and location of signer
        sap.setReason(reason);
        sap.setLocation(location);

        if (visibility.equalsIgnoreCase(PDFSignatureActionExecuter.VISIBILITY_VISIBLE)) {
            //create the signature rectangle using either the provided position or
            //the exact coordinates, if provided
            if (position != null && !position.trim().equalsIgnoreCase("")) {
                Rectangle pageRect = reader.getPageSizeWithRotation(pageNumber);
                sap.setVisibleSignature(positionSignature(position, pageRect, width, height), pageNumber, null);
            } else {
                sap.setVisibleSignature(
                        new Rectangle(locationX, locationY, locationX + width, locationY - height), pageNumber,
                        null);
            }
        }

        stamp.close();

        //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);
        writer.putContent(file);

        file.delete();

        //if useAspect is true, store some additional info about the signature in the props
        if (useAspect) {
            serviceRegistry.getNodeService().addAspect(destinationNode, PDFToolkitModel.ASPECT_SIGNED,
                    new HashMap<QName, Serializable>());
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_REASON, reason);
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_LOCATION,
                    location);
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_SIGNATUREDATE,
                    new java.util.Date());
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_SIGNEDBY,
                    AuthenticationUtil.getRunAsUser());
        }

    } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (KeyStoreException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (ContentIOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (CertificateException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (UnrecoverableKeyException 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);
            }
        }
    }
}

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

License:Apache License

/**
 * Applies an image watermark// w  w w  . j av  a  2  s  . c  o m
 * 
 * @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)/* ww w  .j  av  a  2  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);
            }
        }
    }
}

From source file:org.cejug.footprint.FootPrint.java

License:Open Source License

public byte[] generate() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/*  ww w  . j a  v  a2s  . c  om*/
        PdfStamper stamper = new PdfStamper(reader, baos);
        AcroFields fields = stamper.getAcroFields();
        Set<String> keys = fields.getFields().keySet();
        for (String k : keys) {
            fields.setField(k, values.get(k));
        }
        stamper.close();
    } catch (DocumentException | IOException e) {
        e.printStackTrace();
    }
    return baos.toByteArray();
}

From source file:org.crossref.pdfmark.Main.java

License:Open Source License

public Main(String[] args) {
    if (args.length == 0) {
        printUsage();//from w  w  w  . j a  va 2s .c o  m
        System.exit(2);
    }

    CmdLineParser parser = new CmdLineParser();
    Option provideXmpOp = parser.addStringOption('p', "xmp-file");
    Option overwriteOp = parser.addBooleanOption('f', "force");
    Option outputOp = parser.addStringOption('o', "output-dir");
    Option doiOp = parser.addStringOption('d', "doi");
    Option searchOp = parser.addBooleanOption('s', "search-for-doi");
    Option copyrightOp = parser.addBooleanOption("no-copyright");
    Option rightsOp = parser.addStringOption("rights-agent");
    Option apiKeyOp = parser.addStringOption("api-key");

    try {
        parser.parse(args);
    } catch (CmdLineParser.OptionException e) {
        printUsage();
        System.exit(2);
    }

    String optionalXmpPath = (String) parser.getOptionValue(provideXmpOp, "");
    String outputDir = (String) parser.getOptionValue(outputOp, "");
    String explicitDoi = (String) parser.getOptionValue(doiOp, "");
    boolean useTheForce = (Boolean) parser.getOptionValue(overwriteOp, Boolean.FALSE);
    boolean searchForDoi = (Boolean) parser.getOptionValue(searchOp, Boolean.FALSE);
    boolean noCopyright = (Boolean) parser.getOptionValue(copyrightOp, Boolean.FALSE);
    String rightsAgent = (String) parser.getOptionValue(rightsOp, "");
    String apiKey = (String) parser.getOptionValue(apiKeyOp, ApiKey.DEFAULT);

    if (!explicitDoi.equals("") && searchForDoi) {
        exitWithError(2, "-d and -s are mutually exclusive options.");
    }

    if (!outputDir.isEmpty() && !new File(outputDir).exists()) {
        exitWithError(2, "The output directory, '" + outputDir + "' does not exist.");
    }

    byte[] optionalXmpData = null;

    if (!optionalXmpPath.equals("")) {
        /* We will take XMP data from a file. */
        FileInfo xmpFile = FileInfo.readFileFully(optionalXmpPath);
        if (xmpFile.missing) {
            exitWithError(2, "Error: File '" + xmpFile.path + "' does not exist.");
        } else if (xmpFile.error != null) {
            exitWithError(2, "Error: Could not read '" + xmpFile.path + "' because of:\n" + xmpFile.error);
        }

        optionalXmpData = xmpFile.data;
    }

    grabber = new MetadataGrabber(apiKey);

    /* Now we're ready to merge our imported or generated XMP data with what
     * is already in each PDF. */

    for (String pdfFilePath : parser.getRemainingArgs()) {
        String outputPath = getOutFileName(pdfFilePath);

        /* Grab the leaf. */
        if (outputPath.contains(File.separator)) {
            String[] split = outputPath.split(File.separator);
            outputPath = split[split.length - 1];
        }

        if (!outputDir.isEmpty()) {
            outputPath = outputDir + File.separator + outputPath;
        } else {
            /* Output to the working directory. */
        }

        File pdfFile = new File(pdfFilePath);
        File outputFile = new File(outputPath);

        byte[] resolvedXmpData = null;

        if (!pdfFile.exists()) {
            exitWithError(2, "Error: File '" + pdfFilePath + "' does not exist.");
        }

        if (outputFile.exists() && !useTheForce) {
            exitWithError(2, "Error: File '" + outputPath + "' already exists.\nTry using -f (force).");
        }

        try {
            if (!useTheForce && isLinearizedPdf(new FileInputStream(pdfFile))) {
                exitWithError(2,
                        "Error: '" + pdfFilePath + "' is a" + " linearized PDF and force is not specified."
                                + " This tool will output non-linearized PDF."
                                + "\nIf you don't mind that, use -f (force).");
            }
        } catch (IOException e) {
            exitWithError(2, "Error: Could not determine linearization" + " because of:\n" + e);
        }

        if (!explicitDoi.equals("")) {
            resolvedXmpData = getXmpForDoi(explicitDoi, !noCopyright, rightsAgent);
        }

        try {
            new File(outputFile.getPath() + ".tmp").deleteOnExit();

            FileInputStream fileIn = new FileInputStream(pdfFile);
            FileOutputStream fileOut = new FileOutputStream(outputFile.getPath() + ".tmp");
            PdfReader reader = new PdfReader(fileIn);
            PdfStamper stamper = new PdfStamper(reader, fileOut);

            byte[] merged = reader.getMetadata();

            if (optionalXmpData != null) {
                merged = XmpUtils.mergeXmp(merged, optionalXmpData);
            }

            if (resolvedXmpData != null) {
                merged = XmpUtils.mergeXmp(merged, resolvedXmpData);
            }

            stamper.setXmpMetadata(merged);

            stamper.close();
            reader.close();

            fileIn = new FileInputStream(outputFile.getPath() + ".tmp");
            writeInfoDictionary(fileIn, outputFile.getPath(), merged);
        } catch (IOException e) {
            exitWithError(2, "Error: Couldn't handle '" + pdfFilePath + "' because of:\n" + e);
        } catch (DocumentException e) {
            exitWithError(2, "Error: Couldn't handle '" + pdfFilePath + "' because of:\n" + e);
        } catch (XmpException e) {
            exitWithError(2, "Error: Couldn't handle '" + pdfFilePath + "' because of:\n" + e);
        } catch (COSVisitorException e) {
            exitWithError(2, "Error: Couldn't write document info dictionary" + " because of:\n" + e);
        }
    }

    shutDown();
}

From source file:org.dihedron.crypto.operations.sign.pdf.PDFSigner.java

License:Open Source License

@Override
public void sign(InputStream input, OutputStream output) throws CryptoException {
    try {/*from   ww  w  .  ja v  a  2s. c o  m*/
        PdfReader reader = new PdfReader(input);
        PdfStamper stamper = PdfStamper.createSignature(reader, output, '\0');
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        //appearance.setVisibleSignature("mySig");
        appearance.setReason("Signed with Dihedron WebSign - Digital Signature for the Web ver. "
                + Crypto.valueOf(Traits.VERSION));
        appearance.setLocation("Hidden Signature");

        appearance.setCrypto((PrivateKey) key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        if (mode == Mode.EXCLUSIVE) {
            appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
        }
        // TODO: no graphic signature mode enabled yet
        //      if (graphic) {
        //         appearance.setAcro6Layers(true);
        //         appearance.setSignatureGraphic(Image.getInstance(RESOURCE));
        //         appearance.setRenderingMode(
        //         PdfSignatureAppearance.RenderingMode.GRAPHIC);
        //      }      
        stamper.close();
    } catch (IOException e) {
        logger.error("I/O exception writing the PDF", e);
        throw new CryptoException("I/O exception writing the PDF", e);
    } catch (DocumentException e) {
        logger.error("invalid document: exception writing the PDF", e);
        throw new CryptoException("document exception writing the PDF", e);
    }
}

From source file:org.freemedsoftware.util.CompositePdfForm.java

License:Open Source License

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;/* w  w w  . j  a v a2 s.co  m*/
    try {
        line = parser.parse(getOptions(), args);
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        System.exit(1);
    }

    String dataFile = line.getOptionValue("i");
    String templateFile = line.getOptionValue("t");
    String outputFile = line.getOptionValue("o");

    if (dataFile == null || templateFile == null || outputFile == null) {
        System.err.println("options:");
        System.err.println("\t[-i|--input]     Input file name");
        System.err.println("\t[-t|--template]  PDF template");
        System.err.println("\t[-o|--output]    Output file name");
        System.exit(1);
    }

    if (!(new File(dataFile).exists())) {
        System.err.println("Could not open input data file " + dataFile);
        System.exit(1);
    }

    if (!(new File(templateFile).exists())) {
        System.err.println("Could not open template file " + templateFile);
        System.exit(1);
    }

    Serializer serializer = new Persister();
    FormElementList elementList = serializer.read(FormElementList.class, new File(dataFile));

    PdfReader templateReader = new PdfReader(templateFile);
    PdfStamper stamper = new PdfStamper(templateReader, new FileOutputStream(outputFile));

    // Iterate
    fillForm(stamper.getAcroFields(), elementList);

    stamper.close();
    System.exit(0);
}

From source file:org.h819.commons.file.MyPDFUtils.java

/**
 * ??//from  ww w .  ja va  2  s.  co m
 *
 * @param srcPdf         ?
 * @param destPdf        
 * @param waterMarkText  ?
 * @param waterMarkImage ?
 */
public static void addWaterMarkFile(File srcPdf, File destPdf, String waterMarkText, File waterMarkImage)
        throws IOException, DocumentException {

    if (waterMarkText == null && waterMarkImage == null)
        throw new FileNotFoundException(waterMarkText + " " + waterMarkImage + " all null.");

    if (srcPdf == null || !srcPdf.exists() || !srcPdf.isFile())
        throw new FileNotFoundException("pdf file :  '" + srcPdf + "' does not exsit.");

    if (!FilenameUtils.getExtension(srcPdf.getAbsolutePath()).toLowerCase().equals("pdf"))
        return;

    if (waterMarkImage != null) {
        if (!waterMarkImage.exists() || !waterMarkImage.isFile())
            throw new FileNotFoundException("img file :  '" + srcPdf + "' does not exsit.");

        if (!FilenameUtils.getExtension(waterMarkImage.getAbsolutePath()).toLowerCase().equals("png"))
            throw new FileNotFoundException("image file '" + srcPdf
                    + "'  not png.(???? pdf )");
    }

    PdfReader reader = getPdfReader(srcPdf);

    int n = reader.getNumberOfPages();
    PdfStamper stamper = getPdfStamper(srcPdf, destPdf);

    //
    //        HashMap<String, String> moreInfo = new HashMap<String, String>();
    //        moreInfo.put("Author", "H819 create");
    //        moreInfo.put("Producer", "H819 Producer");
    //        Key = CreationDate, Value = D:20070425182920
    //        Key = Producer, Value = TH-OCR 2000 (C++/Win32)
    //        Key = Author, Value = TH-OCR 2000
    //        Key = Creator, Value = TH-OCR PDF Writer

    // stamp.setMoreInfo(moreInfo);

    // text
    Phrase text = null;
    if (waterMarkText != null) {
        //
        Font bfont = getPdfFont();
        bfont.setSize(35);
        bfont.setColor(new BaseColor(192, 192, 192));
        text = new Phrase(waterMarkText, bfont);
    }
    // image watermark
    Image img = null;
    float w = 0;
    float h = 0;
    if (waterMarkImage != null) {
        img = Image.getInstance(waterMarkImage.getAbsolutePath());
        w = img.getScaledWidth();
        h = img.getScaledHeight();
        //  img.
        img.setRotationDegrees(45);

    }

    // transparency
    PdfGState gs1 = new PdfGState();
    gs1.setFillOpacity(0.5f);
    // properties
    PdfContentByte over;
    Rectangle pageSize;
    float x, y;
    // loop over every page
    for (int i = 1; i <= n; i++) {
        pageSize = reader.getPageSizeWithRotation(i);
        x = (pageSize.getLeft() + pageSize.getRight()) / 2;
        y = (pageSize.getTop() + pageSize.getBottom()) / 2;
        //  pdf pdf ???
        over = stamper.getOverContent(i);
        // ?
        // over = stamp.getUnderContent(i);
        // ?? over.beginText(); over.endText(); ?
        // ,?,:????
        over.saveState(); //??
        over.setGState(gs1);

        if (waterMarkText != null && waterMarkImage != null) { // 
            if (i % 2 == 1) {
                ColumnText.showTextAligned(over, Element.ALIGN_CENTER, text, x, y, 45);
            } else
                over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
        } else if (waterMarkText != null) { //?

            ColumnText.showTextAligned(over, Element.ALIGN_CENTER, text, x, y, 45);
            //?? ,?, :?????
            // ...

        } else { //?
            over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
        }

        over.restoreState();//???
    }

    stamper.close();
    reader.close();

}

From source file:org.h819.commons.file.MyPDFUtils.java

/**
 * ? pdf ??/* w ww .j a  v  a 2s.  com*/
 *
 * @param srcPdfFile  the original PDF
 * @param descPdfFile the resulting PDF
 * @throws java.io.IOException
 * @throws DocumentException
 */
public static void compressPdf(File srcPdfFile, File descPdfFile) throws IOException, DocumentException {

    if (srcPdfFile == null || !srcPdfFile.exists())
        throw new IOException("src pdf file '" + srcPdfFile + "' does not exsit.");

    PdfReader reader = getPdfReader(srcPdfFile);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(descPdfFile.getAbsoluteFile()),
            PdfWriter.VERSION_1_7);

    stamper.getWriter().setCompressionLevel(9);
    int total = reader.getNumberOfPages() + 1;
    for (int i = 1; i < total; i++) {
        reader.setPageContent(i, reader.getPageContent(i));
    }
    stamper.setFullCompression();
    stamper.close();
    reader.close();
}

From source file:org.h819.commons.file.MyPDFUtils.java

/**
 *  pdf ? pdf//from www .  j a  v a  2s .  c o m
 *
 * @param srcPdf      the original PDF
 * @param destPdf     the resulting PDF
 * @param imageFactor The multiplication factor for the image (?  imageFacto =0.5f)
 * @throws IOException
 * @throws DocumentException
 */
public static void compressPdf(File srcPdf, File destPdf, float imageFactor)
        throws IOException, DocumentException {

    PdfReader reader = new PdfReader(srcPdf.getAbsolutePath());
    int n = reader.getXrefSize();
    PdfObject object;
    PRStream stream;
    // Look for image and manipulate image stream
    for (int i = 0; i < n; i++) {
        object = reader.getPdfObject(i);
        if (object == null || !object.isStream())
            continue;
        stream = (PRStream) object;
        if (!PdfName.IMAGE.equals(stream.getAsName(PdfName.SUBTYPE)))
            continue;
        if (!PdfName.DCTDECODE.equals(stream.getAsName(PdfName.FILTER)))
            continue;
        PdfImageObject image = new PdfImageObject(stream);
        BufferedImage bi = image.getBufferedImage();
        if (bi == null)
            continue;
        int width = (int) (bi.getWidth() * imageFactor);
        int height = (int) (bi.getHeight() * imageFactor);
        if (width <= 0 || height <= 0)
            continue;
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        AffineTransform at = AffineTransform.getScaleInstance(imageFactor, imageFactor);
        Graphics2D g = img.createGraphics();
        g.drawRenderedImage(bi, at);
        ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
        ImageIO.write(img, "JPG", imgBytes);
        stream.clear();
        stream.setData(imgBytes.toByteArray(), false, PRStream.NO_COMPRESSION);
        stream.put(PdfName.TYPE, PdfName.XOBJECT);
        stream.put(PdfName.SUBTYPE, PdfName.IMAGE);
        stream.put(PdfName.FILTER, PdfName.DCTDECODE);
        stream.put(PdfName.WIDTH, new PdfNumber(width));
        stream.put(PdfName.HEIGHT, new PdfNumber(height));
        stream.put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
        stream.put(PdfName.COLORSPACE, PdfName.DEVICERGB);
    }
    reader.removeUnusedObjects();
    // Save altered PDF
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destPdf.getAbsolutePath()));
    stamper.setFullCompression();
    stamper.close();
    reader.close();
}