Java 类com.lowagie.text.pdf.PdfStamper 实例源码

项目:itext2    文件:XfdfExampleTest.java   
/**
 * Merges an XFDF file with a PDF form.
 */
@Test
public void main() throws Exception {

    // merging the FDF file
    PdfReader pdfreader = new PdfReader(PdfTestBase.RESOURCES_DIR + "SimpleRegistrationForm.pdf");
    PdfStamper stamp = new PdfStamper(pdfreader, PdfTestBase.getOutputStream("registered_xfdf.pdf"));
    XfdfReader fdfreader = new XfdfReader(PdfTestBase.RESOURCES_DIR + "register.xfdf");
    AcroFields form = stamp.getAcroFields();
    form.setFields(fdfreader);
    stamp.close();

}
项目:kansalaisaloite    文件:SupportStatementPdf.java   
public static void modifyPdf(InputStream pdfTemplate, OutputStream modifiedPdf, String name, LocalDate startDate) throws IOException, DocumentException {
        // NOTE: Can we use this?
//        PdfReader.unethicalreading = true;

        PdfReader reader = new PdfReader(pdfTemplate);
        PdfStamper stamper = new PdfStamper(reader, modifiedPdf);

        fill(stamper.getAcroFields(), name, startDate);

        stamper.setFormFlattening(true);
        stamper.partialFormFlattening(INITIATIVE_NAME);
        stamper.partialFormFlattening(INITIATIVE_DAY);
        stamper.partialFormFlattening(INITIATIVE_MONTH);
        stamper.partialFormFlattening(INITIATIVE_YEAR);

        stamper.close();
        reader.close();
    }
项目:kfs    文件:ContractsGrantsInvoiceReportServiceImpl.java   
/**
 *
 * @param template the path to the original form
 * @param list the replacement list
 * @return
 * @throws IOException
 * @throws DocumentException
 */
protected byte[] renameFieldsIn(String template, Map<String, String> list) throws IOException, DocumentException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // Create the stamper
    PdfStamper stamper = new PdfStamper(new PdfReader(template), baos);
    // Get the fields
    AcroFields fields = stamper.getAcroFields();
    // Loop over the fields
    for (String field : list.keySet()) {
        fields.setField(field, list.get(field));
    }
    // close the stamper
    stamper.close();
    return baos.toByteArray();
}
项目:studeasy    文件:PdfGenerator.java   
/**
 * Genera il pdf per la richiesta della tesi
 *
 * @param tesiView Vista con il form per raccogliere i dati
 * @param path     Path del file di destinazione
 * @throws IOException
 * @throws DocumentException
 */
public void generatePdfTesi(FormTesi tesiView, String path) throws IOException, DocumentException {

    // Lettura del template
    PdfReader pdfTemplate = new PdfReader(template);
    // Apertura del file di destinazione
    FileOutputStream fileOutputStream = createOutputStream(path);
    // Popolazione del template con i dati
    PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);

    stamper.setFormFlattening(true);

    stamper.getAcroFields().setField("nome", tesiView.getNome().getText());
    stamper.getAcroFields().setField("cognome", tesiView.getCognome().getText());
    stamper.getAcroFields().setField("matricola", tesiView.getMatricola().getText());
    stamper.getAcroFields().setField("dataNascita", tesiView.getDataNascita().getText());
    stamper.getAcroFields().setField("luogoNascita", tesiView.getLuogoNascita().getText());
    stamper.getAcroFields().setField("eMail", tesiView.getEmail().getText());
    stamper.getAcroFields().setField("annoCorso", tesiView.getAnnoCorso().getText());
    stamper.getAcroFields().setField("professoreRelatore", tesiView.getProfRelatore().getText());
    stamper.getAcroFields().setField("titoloTesi", tesiView.getTitoloTesi().getText());

    pdfTemplate.close();
    stamper.close();
    fileOutputStream.close();
}
项目:PDFTestForAndroid    文件:XfdfExample.java   
/**
 * Merges an XFDF file with a PDF form.
 * 
 * @param args
 *            no arguments needed
 */
public static void main(String[] args) {
    try {
        // merging the FDF file
        PdfReader pdfreader = new PdfReader(PdfTestRunner.getActivity().getResources().openRawResource(R.raw.simpleregistrationform));
        String path = android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "registered_xfdf.pdf";
           PdfStamper stamp = new PdfStamper(pdfreader, new FileOutputStream(path));
           InputStream inputStream = PdfTestRunner.getActivity().getResources().openRawResource(R.raw.register);
           byte[] buffer = new byte[inputStream.available()];
           inputStream.read(buffer);
        XfdfReader fdfreader = new XfdfReader(buffer);
        AcroFields form = stamp.getAcroFields();
        form.setFields(fdfreader);
        stamp.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}
项目:spring4-understanding    文件:AbstractPdfStamperView.java   
@Override
protected final void renderMergedOutputModel(
        Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

    // IE workaround: write into byte array first.
    ByteArrayOutputStream baos = createTemporaryOutputStream();

    PdfReader reader = readPdfResource();
    PdfStamper stamper = new PdfStamper(reader, baos);
    mergePdfDocument(model, stamper, request, response);
    stamper.close();

    // Flush to HTTP response.
    writeToResponse(response, baos);
}
项目:OSCAR-ConCert    文件:PDFController.java   
private void setStamper(PdfStamper stamper) {
    this.stamper = stamper;
}
项目:camel-spring    文件:PdfController.java   
/**
 * Generate barcode in the form
 *
 * @param pdfStamper
 * @throws DocumentException
 */
private void generateBarcode(PdfStamper pdfStamper, String userId) throws DocumentException {

    // add barcode on the first page
    PdfContentByte cb = pdfStamper.getOverContent(BARCODE_PAGE);

    // barcode format 128C
    Barcode128 code128 = new Barcode128();

    // barcode format e.g. *1502A1234567890
    //  asterisk - * [constant]
    //  WebPOS Transaction - 1502 [constant]
    //  Form Version - A [constant for MyPost 1.5]
    //  10-digit APCN
    code128.setCode(ASTERISK + WEBPOS_TRANSACTIION + MYPOST_FORM_VERSION + userId);

    code128.setCodeType(Barcode128.CODE128);

    // convert barcode into image
    Image code128Image = code128.createImageWithBarcode(cb, null, null);

    // set barcode position x pixel, y pixel
    code128Image.setAbsolutePosition(BARCODE_POSITION_X, BARCODE_POSITION_Y);
    code128Image.scalePercent(BARCODE_SCALE_PERCENTAGE);

    // add barcode image into PDF template
    cb.addImage(code128Image);
}
项目:camel-spring    文件:PdfController.java   
/**
 * Generate a QR code including URL on the page
 * 
 * @param pdfStamper
 * @throws DocumentException
 */
private void generateQRCode(PdfStamper pdfStamper) throws DocumentException {

    // add barcode on the first page
    PdfContentByte pdfContentByte = pdfStamper.getOverContent(APPENDED_PAGE);

    BarcodeQRCode qrcode = new BarcodeQRCode("http://www.vendian.org/mncharity/dir3/paper_rulers/", 200, 200, null);
    Image qrcodeImage = qrcode.getImage();
    qrcodeImage.setAbsolutePosition(360,500);
    qrcodeImage.scalePercent(100);
    pdfContentByte.addImage(qrcodeImage);
}
项目:class-guard    文件:AbstractPdfStamperView.java   
@Override
protected final void renderMergedOutputModel(
        Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

    // IE workaround: write into byte array first.
    ByteArrayOutputStream baos = createTemporaryOutputStream();

    PdfReader reader = readPdfResource();
    PdfStamper stamper = new PdfStamper(reader, baos);
    mergePdfDocument(model, stamper, request, response);
    stamper.close();

    // Flush to HTTP response.
    writeToResponse(response, baos);
}
项目:studeasy    文件:PdfGenerator.java   
/**
 * Genera il pdf per la richiesta di tirocinio
 *
 * @param tirocinioView Vista con il form per raccogliere i dati
 * @param path          Path del file di destinazione
 * @throws IOException
 * @throws DocumentException
 */
public void generatePdfTirocinio(FormTirocinio tirocinioView, String path) throws IOException, DocumentException {

    // Lettura del template
    PdfReader pdfTemplate = new PdfReader(template);
    // Apertura del file di destinazione
    FileOutputStream fileOutputStream = createOutputStream(path);
    // Popolazione del template con i dati
    PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);

    stamper.setFormFlattening(true);

    stamper.getAcroFields().setField("nome", tirocinioView.getNome().getText());
    stamper.getAcroFields().setField("cognome", tirocinioView.getCognome().getText());
    stamper.getAcroFields().setField("matricola", tirocinioView.getMatricola().getText());
    stamper.getAcroFields().setField("luogoNascita", tirocinioView.getLuogonascita().getText());
    stamper.getAcroFields().setField("dataNascita", tirocinioView.getDatanascita().getText());
    stamper.getAcroFields().setField("residenza", tirocinioView.getResidenza().getText());
    stamper.getAcroFields().setField("provincia", tirocinioView.getProvincia().getText());
    stamper.getAcroFields().setField("cap", tirocinioView.getCap().getText());
    stamper.getAcroFields().setField("via", tirocinioView.getVia().getText());
    stamper.getAcroFields().setField("codiceFiscale", tirocinioView.getCodicefiscale().getText());

    pdfTemplate.close();
    stamper.close();
    fileOutputStream.close();
}
项目:studeasy    文件:PdfGenerator.java   
/**
 * Genera il pdf per l'immatricolazione
 *
 * @param immatricolazioneView Vista che contiene il form per raccogliere i dati
 * @param path                 Path del file di destinazione
 * @throws IOException
 * @throws DocumentException
 */
public void generatePdfImmatricolazione(FormImmatricolazione immatricolazioneView, String path) throws IOException, DocumentException {

    // Lettura del template
    PdfReader pdfTemplate = new PdfReader(template);
    // Apertura del file di destinazione
    FileOutputStream fileOutputStream = createOutputStream(path);
    // Popolazione del template con i dati
    PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);

    stamper.setFormFlattening(true);

    stamper.getAcroFields().setField("nome", immatricolazioneView.getNome().getText());
    stamper.getAcroFields().setField("cognome", immatricolazioneView.getCognome().getText());
    stamper.getAcroFields().setField("matricola", immatricolazioneView.getMatricola().getText());
    stamper.getAcroFields().setField("luogoNascita", immatricolazioneView.getLuogonascita().getText());
    stamper.getAcroFields().setField("dataNascita", immatricolazioneView.getDatanascita().getText());
    stamper.getAcroFields().setField("provinciaNascita", immatricolazioneView.getProvincia().getText());
    stamper.getAcroFields().setField("codiceFiscale", immatricolazioneView.getCodicefiscale().getText());
    stamper.getAcroFields().setField("tipologiaScuolaSuperiore", immatricolazioneView.getDiploma().getText());
    stamper.getAcroFields().setField("voto", immatricolazioneView.getVoto().getText());
    String primaParteAnnoScolastico = immatricolazioneView.getAnnoConseguimento1().getText();
    stamper.getAcroFields().setField("anno1", primaParteAnnoScolastico);
    stamper.getAcroFields().setField("anno2", Integer.toString(Integer.parseInt(primaParteAnnoScolastico) + 1));

    pdfTemplate.close();
    stamper.close();
    fileOutputStream.close();
}
项目:wichtel    文件:HelperPdf.java   
/**
 * Modifies the meta data of given PDF and stores it in a new {@link File}.
 * <strong>Meta data example:"</strong> metadata.put("Title", "Example");
 * metadata.put("Author", "Stefan Laubenberger"); metadata.put("Subject",
 * "Example PDF meta data"); metadata.put("Keywords", "Example, PDF");
 * metadata.put("Creator", "http://www.laubenberger.net/");
 * metadata.put("Producer", "Silvan Spross");
 * 
 * @param source
 *           {@link File}
 * @param dest
 *           {@link File} for the modified PDF
 * @param metadata
 *           list with the new meta data informations
 * @throws DocumentException
 * @throws IOException
 * @since 0.0.1
 */
@SuppressWarnings("unchecked")
public static void setMetaData(final File source, final File dest, final Map<String, String> metadata)
        throws IOException, DocumentException { // $JUnit$
    if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(source, dest, metadata));
    if (null == source) {
        throw new RuntimeExceptionIsNull("source"); //$NON-NLS-1$
    }
    if (null == dest) {
        throw new RuntimeExceptionIsNull("dest"); //$NON-NLS-1$
    }
    if (HelperObject.isEquals(source, dest)) {
        throw new RuntimeExceptionIsEquals("source", "dest"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    if (null == metadata) {
        throw new RuntimeExceptionIsNull("metadata"); //$NON-NLS-1$
    }

    try (FileOutputStream fos = new FileOutputStream(dest)){
        final PdfReader reader = new PdfReader(source.getAbsolutePath());
        final PdfStamper stamper = new PdfStamper(reader, fos);

        final HashMap<String, String> info = reader.getInfo();
        info.putAll(metadata);

        stamper.setMoreInfo(info);

        stamper.close();
        reader.close();
    }
    if (log.isDebugEnabled()) log.debug(HelperLog.methodExit());
}
项目:itext2    文件:AddWatermarkPageNumbersTest.java   
/**
    * Reads the pages of an existing PDF file, adds pagenumbers and a watermark.

    */
@Test
   public  void main() throws Exception {
           // we create a reader for a certain document
           PdfReader reader = new PdfReader(PdfTestBase.RESOURCES_DIR +"ChapterSection.pdf");
           int n = reader.getNumberOfPages();
           // we create a stamper that will copy the document to a new file
           PdfStamper stamp = new PdfStamper(reader,PdfTestBase.getOutputStream("watermark_pagenumbers.pdf"));
           // adding some metadata
           HashMap<String, String> moreInfo = new HashMap<String, String>();
           moreInfo.put("Author", "Bruno Lowagie");
           stamp.setMoreInfo(moreInfo);
           // adding content to each page
           int i = 0;
           PdfContentByte under;
           PdfContentByte over;
           Image img = Image.getInstance(PdfTestBase.RESOURCES_DIR +"watermark.jpg");
           BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
           img.setAbsolutePosition(200, 400);
           while (i < n) {
            i++;
            // watermark under the existing page
            under = stamp.getUnderContent(i);
            under.addImage(img);
            // text over the existing page
            over = stamp.getOverContent(i);
            over.beginText();
            over.setFontAndSize(bf, 18);
            over.setTextMatrix(30, 30);
            over.showText("page " + i);
            over.setFontAndSize(bf, 32);
            over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);
            over.endText();
           }
           // adding an extra page
           stamp.insertPage(1, PageSize.A4);
           over = stamp.getOverContent(1);
        over.beginText();
        over.setFontAndSize(bf, 18);
           over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE OF AN EXISTING PDF DOCUMENT", 30, 600, 0);
           over.endText();
           // adding a page from another document
           PdfReader reader2 = new PdfReader(PdfTestBase.RESOURCES_DIR +"SimpleAnnotations1.pdf");
           under = stamp.getUnderContent(1);
           under.addTemplate(stamp.getImportedPage(reader2, 3), 1, 0, 0, 1, 0, 0);
           // closing PdfStamper will generate the new PDF file
           stamp.close();
   }
项目:sistra    文件:PDFDocumentTemplate.java   
/**
 * Inicia objeto PDF (Uso interno)
 * @throws Exception
 */
private void iniciarPdf() throws Exception
{
    ostream = new ByteArrayOutputStream();
    pdfs = new PdfStamper(pdfr, ostream);
    pdfs.getWriter().setPdfVersion(PdfWriter.VERSION_1_3);
    afields = pdfs.getAcroFields();
}
项目:sistra    文件:PDFDocumentTemplate.java   
/**
 * @return Devuelve pdfs.
 */
public PdfStamper getPdfs() {
    return pdfs;
}
项目:OSCAR-ConCert    文件:PDFController.java   
public PdfStamper getStamper() {
    return stamper;
}
项目:camel-spring    文件:PdfController.java   
/**
 * Inspect PDF, find input / editable fields in the interactive form
 *
 * @param pdfReader
 * @param pdfStamper
 */
private void inspect(PdfReader pdfReader, PdfStamper pdfStamper) {

    // Get the fields from the reader (read-only!!!)
    AcroFields form = pdfReader.getAcroFields();

    // Loop over the fields and get info about them
    Set<String> fields = form.getFields().keySet();

    for (String field : fields) {
        switch (form.getFieldType(field)) {
            case AcroFields.FIELD_TYPE_CHECKBOX:
                LOG.debug("[" + field + "] : Check box");
                break;
            case AcroFields.FIELD_TYPE_COMBO:
                LOG.debug("[" + field + "] : Combo box");
                break;
            case AcroFields.FIELD_TYPE_LIST:
                LOG.debug("[" + field + "] : List");
                break;
            case AcroFields.FIELD_TYPE_NONE:
                LOG.debug("[" + field + "] : None");
                break;
            case AcroFields.FIELD_TYPE_PUSHBUTTON:
                LOG.debug("[" + field + "] : Push button");
                break;
            case AcroFields.FIELD_TYPE_RADIOBUTTON:
                LOG.debug("[" + field + "] : Radio button");
                break;
            case AcroFields.FIELD_TYPE_SIGNATURE:
                LOG.debug("[" + field + "] : Signature");
                break;
            case AcroFields.FIELD_TYPE_TEXT:
                LOG.debug("[" + field + "] : Text");
                break;
            default:
                LOG.debug("[" + field + "] : ?");
        }

        findPossibleValues(pdfStamper, field);
    }
}
项目:camel-spring    文件:PdfController.java   
/**
 * find out input field name in the interactive form
 *
 * @param pdfStamper
 * @param field
 */
private void findPossibleValues(PdfStamper pdfStamper, String field) {

    String[] states;
    String values = "";

    AcroFields form = pdfStamper.getAcroFields();

    states = form.getAppearanceStates(field);

    for (int i = 0; i < states.length; i++) {
        values += states[i] + ", ";
    }

    LOG.debug("Possible values for [" + field + "] : " + values);
}
项目:Lucee4    文件:PDF.java   
private void doActionSetInfo() throws PageException, IOException, DocumentException {
    required("pdf", "setInfo", "info", info);
    required("pdf", "getInfo", "source", source);

    PDFDocument doc = toPDFDocument(source,password,null);
    PdfReader pr = doc.getPdfReader();
    OutputStream os=null;
    try {
        if(destination==null){
            if(doc.getResource()==null)
                throw new ApplicationException("source is not based on a resource, destination file is required");
            destination=doc.getResource();
        }
        else if(destination.exists() && !overwrite)
            throw new ApplicationException("destination file ["+destination+"] already exists");

        PdfStamper stamp = new PdfStamper(pr, os=destination.getOutputStream());
        HashMap moreInfo = new HashMap();

        //Key[] keys = info.keys();
        Iterator<Entry<Key, Object>> it = info.entryIterator();
        Entry<Key, Object> e;
        while(it.hasNext()) {
            e = it.next();
            moreInfo.put(StringUtil.ucFirst(e.getKey().getLowerString()), Caster.toString(e.getValue()));
        }
        // author
        Object value = info.get(KeyConstants._author, null);    
        if(value!=null)moreInfo.put("Author", Caster.toString(value));
        // keywords
        value = info.get("keywords", null); 
        if(value!=null)moreInfo.put("Keywords", Caster.toString(value));
        // title
        value = info.get(KeyConstants._title, null);    
        if(value!=null)moreInfo.put("Title", Caster.toString(value));
        // subject
        value = info.get(KeyConstants._subject, null);  
        if(value!=null)moreInfo.put("Subject", Caster.toString(value));
        // creator
        value = info.get("creator", null);  
        if(value!=null)moreInfo.put("Creator", Caster.toString(value));
        // trapped
        value = info.get("Trapped", null);  
        if(value!=null)moreInfo.put("Trapped", Caster.toString(value));
        // Created
        value = info.get("Created", null);  
        if(value!=null)moreInfo.put("Created", Caster.toString(value));
        // Language
        value = info.get("Language", null); 
        if(value!=null)moreInfo.put("Language", Caster.toString(value));


        stamp.setMoreInfo(moreInfo);
        stamp.close();

    }
    finally {
        IOUtil.closeEL(os);
        pr.close();
    }
}
项目:OLE-INST    文件:CashReceiptCoverSheetServiceImpl.java   
/**
 * Use iText <code>{@link PdfStamper}</code> to stamp information from <code>{@link CashReceiptDocument}</code> into field
 * values on a PDF Form Template.
 * 
 * @param document The cash receipt document the values will be pulled from.
 * @param searchPath The directory path of the template to be used to generate the cover sheet.
 * @param returnStream The output stream the cover sheet will be written to.
 */
protected void stampPdfFormValues(CashReceiptDocument document, String searchPath, OutputStream returnStream) throws Exception {
    String templateName = CR_COVERSHEET_TEMPLATE_NM;

    try {
        // populate form with document values

        //KFSMI-7303
        //The PDF template is retrieve through web static URL rather than file path, so the File separator is unnecessary
        final boolean isWebResourcePath = StringUtils.containsIgnoreCase(searchPath, "HTTP");

        //skip the File.separator if reference by web resource
        PdfStamper stamper = new PdfStamper(new PdfReader(searchPath + (isWebResourcePath? "" : File.separator) + templateName), returnStream);
        AcroFields populatedCoverSheet = stamper.getAcroFields();

        populatedCoverSheet.setField(DOCUMENT_NUMBER_FIELD, document.getDocumentNumber());
        populatedCoverSheet.setField(INITIATOR_FIELD, document.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId());
        populatedCoverSheet.setField(CREATED_DATE_FIELD, document.getDocumentHeader().getWorkflowDocument().getDateCreated().toString());
        populatedCoverSheet.setField(AMOUNT_FIELD, document.getTotalDollarAmount().toString());
        populatedCoverSheet.setField(ORG_DOC_NUMBER_FIELD, document.getDocumentHeader().getOrganizationDocumentNumber());
        populatedCoverSheet.setField(CAMPUS_FIELD, document.getCampusLocationCode());
        if (document.getDepositDate() != null) {
            // This value won't be set until the CR document is
            // deposited. A CR document is deposited only when it has
            // been associated with a Cash Management Document (CMD)
            // and with a Deposit within that CMD. And only when the
            // CMD is submitted and FINAL, will the CR documents
            // associated with it, be "deposited." So this value will
            // fill in at an arbitrarily later point in time. So your
            // code shouldn't expect it, but if it's there, then
            // display it.
            populatedCoverSheet.setField(DEPOSIT_DATE_FIELD, document.getDepositDate().toString());
        }
        populatedCoverSheet.setField(DESCRIPTION_FIELD, document.getDocumentHeader().getDocumentDescription());
        populatedCoverSheet.setField(EXPLANATION_FIELD, document.getDocumentHeader().getExplanation());
        populatedCoverSheet.setField(CHECKS_FIELD, document.getTotalCheckAmount().toString());
        populatedCoverSheet.setField(CURRENCY_FIELD, document.getTotalCashAmount().toString());
        populatedCoverSheet.setField(COIN_FIELD, document.getTotalCoinAmount().toString());
        populatedCoverSheet.setField(CHANGE_OUT_FIELD, document.getTotalChangeAmount().toString());

        populatedCoverSheet.setField(TOTAL_RECONCILIATION_FIELD, document.getTotalDollarAmount().toString());

        stamper.setFormFlattening(true);
        stamper.close();
    }
    catch (Exception e) {
        LOG.error("Error creating coversheet for: " + document.getDocumentNumber() + ". ::" + e);
        throw e;
    }
}
项目:kfs    文件:CashReceiptCoverSheetServiceImpl.java   
/**
 * Use iText <code>{@link PdfStamper}</code> to stamp information from <code>{@link CashReceiptDocument}</code> into field
 * values on a PDF Form Template.
 *
 * @param document The cash receipt document the values will be pulled from.
 * @param searchPath The directory path of the template to be used to generate the cover sheet.
 * @param returnStream The output stream the cover sheet will be written to.
 */
protected void stampPdfFormValues(CashReceiptDocument document, String searchPath, OutputStream returnStream) throws Exception {
    String templateName = CR_COVERSHEET_TEMPLATE_NM;

    try {
        // populate form with document values

        //KFSMI-7303
        //The PDF template is retrieved through web static URL rather than file path, so the File separator is unnecessary
        final boolean isWebResourcePath = StringUtils.containsIgnoreCase(searchPath, "HTTP");

        //skip the File.separator if reference by web resource
        PdfStamper stamper = new PdfStamper(new PdfReader(searchPath + (isWebResourcePath? "" : File.separator) + templateName), returnStream);
        AcroFields populatedCoverSheet = stamper.getAcroFields();

        populatedCoverSheet.setField(DOCUMENT_NUMBER_FIELD, document.getDocumentNumber());
        populatedCoverSheet.setField(INITIATOR_FIELD, document.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId());
        populatedCoverSheet.setField(CREATED_DATE_FIELD, document.getDocumentHeader().getWorkflowDocument().getDateCreated().toString());
        populatedCoverSheet.setField(AMOUNT_FIELD, document.getTotalDollarAmount().toString());
        populatedCoverSheet.setField(ORG_DOC_NUMBER_FIELD, document.getDocumentHeader().getOrganizationDocumentNumber());
        populatedCoverSheet.setField(CAMPUS_FIELD, document.getCampusLocationCode());

        if (document.getDepositDate() != null) {
            // This value won't be set until the CR document is
            // deposited. A CR document is deposited only when it has
            // been associated with a Cash Management Document (CMD)
            // and with a Deposit within that CMD. And only when the
            // CMD is submitted and FINAL, will the CR documents
            // associated with it, be "deposited." So this value will
            // fill in at an arbitrarily later point in time. So your
            // code shouldn't expect it, but if it's there, then
            // display it.
            populatedCoverSheet.setField(DEPOSIT_DATE_FIELD, document.getDepositDate().toString());
        }
        populatedCoverSheet.setField(DESCRIPTION_FIELD, document.getDocumentHeader().getDocumentDescription());
        populatedCoverSheet.setField(EXPLANATION_FIELD, document.getDocumentHeader().getExplanation());

        /*
         * We should print original amounts before cash manager approves the CR; after that, we should print confirmed amounts.
         * Note that, in CashReceiptAction.printCoverSheet, it always retrieves the CR from DB, rather than from the current form.
         * Since during CashManagement route node, the CR can't be saved until CM approves/disapproves the document; this means
         * that if CM prints during this route node, he will get the original amounts. This is consistent with our logic here.
         */
        boolean isConfirmed = document.isConfirmed();
        KualiDecimal totalCheckAmount = !isConfirmed ? document.getTotalCheckAmount() : document.getTotalConfirmedCheckAmount();
        KualiDecimal totalCurrencyAmount = !isConfirmed ? document.getTotalCurrencyAmount() : document.getTotalConfirmedCurrencyAmount();
        KualiDecimal totalCoinAmount = !isConfirmed ? document.getTotalCoinAmount() : document.getTotalConfirmedCoinAmount();
        KualiDecimal totalCashInAmount = !isConfirmed ? document.getTotalCashInAmount() : document.getTotalConfirmedCashInAmount();
        KualiDecimal totalMoneyInAmount = !isConfirmed ? document.getTotalMoneyInAmount() : document.getTotalConfirmedMoneyInAmount();
        KualiDecimal totalChangeCurrencyAmount = !isConfirmed ? document.getTotalChangeCurrencyAmount() : document.getTotalConfirmedChangeCurrencyAmount();
        KualiDecimal totalChangeCoinAmount = !isConfirmed ? document.getTotalChangeCoinAmount() : document.getTotalConfirmedChangeCoinAmount();
        KualiDecimal totalChangeAmount = !isConfirmed ? document.getTotalChangeAmount() : document.getTotalConfirmedChangeAmount();
        KualiDecimal totalNetAmount = !isConfirmed ? document.getTotalNetAmount() : document.getTotalConfirmedNetAmount();

        populatedCoverSheet.setField(CHECKS_FIELD, totalCheckAmount.toString());
        populatedCoverSheet.setField(CURRENCY_FIELD, totalCurrencyAmount.toString());
        populatedCoverSheet.setField(COIN_FIELD, totalCoinAmount.toString());
        populatedCoverSheet.setField(CASH_IN_FIELD, totalCashInAmount.toString());
        populatedCoverSheet.setField(MONEY_IN_FIELD, totalMoneyInAmount.toString());
        populatedCoverSheet.setField(CHANGE_CURRENCY_FIELD, totalChangeCurrencyAmount.toString());
        populatedCoverSheet.setField(CHANGE_COIN_FIELD, totalChangeCoinAmount.toString());
        populatedCoverSheet.setField(CHANGE_OUT_FIELD, totalChangeAmount.toString());
        populatedCoverSheet.setField(RECONCILIATION_TOTAL_FIELD, totalNetAmount.toString());

        stamper.setFormFlattening(true);
        stamper.close();
    }
    catch (Exception e) {
        LOG.error("Error creating coversheet for: " + document.getDocumentNumber() + ". ::" + e);
        throw e;
    }
}
项目:Open-ePlatform    文件:PDFGeneratorModule.java   
private File addAttachments(File basePDF, List<PDFManagerResponse> managerResponses, FlowInstanceManager instanceManager, FlowInstanceEvent event) throws IOException, DocumentException {

        File pdfWithAttachments = File.createTempFile("pdf-with-attachments", instanceManager.getFlowInstanceID() + "-" + getFileSuffix(event) + ".pdf", getTempDir());

        OutputStream outputStream = null;
        InputStream inputStream = null;

        try{
            outputStream = new FileOutputStream(pdfWithAttachments);
            inputStream = new FileInputStream(basePDF);

            PdfReader reader = new PdfReader(inputStream);
            PdfStamper stamper = new PdfStamper(reader, outputStream);
            PdfWriter writer = stamper.getWriter();

            for(PDFManagerResponse managerResponse : managerResponses){

                for(PDFQueryResponse queryResponse : managerResponse.getQueryResponses()){

                    if(queryResponse.getAttachments() != null){

                        for(PDFAttachment attachment : queryResponse.getAttachments()){

                            try {
                                PdfFileSpecification fs = StreamPdfFileSpecification.fileEmbedded(writer, attachment.getInputStream(), attachment.getName());
                                writer.addFileAttachment(attachment.getDescription(), fs);
                            } catch (Exception e) {

                                log.error("Error appending attachment " + attachment.getName() + " from query " + queryResponse.getQueryDescriptor(), e);
                            }
                        }
                    }
                }
            }

            stamper.close();

        }finally{

            StreamUtils.closeStream(inputStream);
            StreamUtils.closeStream(outputStream);
        }

        return pdfWithAttachments;
    }
项目:PDFTestForAndroid    文件:AddWatermarkPageNumbers.java   
/**
     * Reads the pages of an existing PDF file, adds pagenumbers and a
     * watermark.
     * 
     * @param args
     *            no arguments needed
     */
    public static void main(String[] args) {
        System.out.println("Add watermarks and pagenumbers");
        try {
            // we create a reader for a certain document
            //Can't use filename directly
            //PdfReader reader = new PdfReader("chaptersection.pdf");
            PdfReader reader = new PdfReader(PdfTestRunner.getActivity().getResources().openRawResource(R.raw.chaptersection));
            int n = reader.getNumberOfPages();
            // we create a stamper that will copy the document to a new file
            PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "watermark_pagenumbers.pdf"));
            // adding some metadata
            HashMap moreInfo = new HashMap();
            moreInfo.put("Author", "Bruno Lowagie");
            stamp.setMoreInfo(moreInfo);
            // adding content to each page
            int i = 0;
            PdfContentByte under;
            PdfContentByte over;
            //Can't use filename => use byte[] instead
//          Image img = Image.getInstance("watermark.jpg");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            Bitmap bitmap = BitmapFactory.decodeResource(PdfTestRunner.getActivity().getResources(), R.drawable.watermark);
            bitmap.compress(Bitmap.CompressFormat.JPEG /* FileType */,
                                    100 /* Ratio */, stream);
            Image img = Image.getInstance(stream.toByteArray());

            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            img.setAbsolutePosition(200, 400);
            while (i < n) {
                i++;
                // watermark under the existing page
                under = stamp.getUnderContent(i);
                under.addImage(img);
                // text over the existing page
                over = stamp.getOverContent(i);
                over.beginText();
                over.setFontAndSize(bf, 18);
                over.setTextMatrix(30, 30);
                over.showText("page " + i);
                over.setFontAndSize(bf, 32);
                over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);
                over.endText();
            }
            // adding an extra page
            stamp.insertPage(1, PageSize.A4);
            over = stamp.getOverContent(1);
            over.beginText();
            over.setFontAndSize(bf, 18);
            over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE OF AN EXISTING PDF DOCUMENT", 30, 600, 0);
            over.endText();
            // adding a page from another document
            //Can't use filename directly
//          PdfReader reader2 = new PdfReader("SimpleAnnotations1.pdf");
            PdfReader reader2 = new PdfReader(PdfTestRunner.getActivity().getResources().openRawResource(R.raw.simpleannotations1));
            under = stamp.getUnderContent(1);
            under.addTemplate(stamp.getImportedPage(reader2, 3), 1, 0, 0, 1, 0, 0);
            // closing PdfStamper will generate the new PDF file
            stamp.close();
        } catch (Exception de) {
            de.printStackTrace();
        }
    }
项目:spring4-understanding    文件:AbstractPdfStamperView.java   
/**
 * Subclasses must implement this method to merge the PDF form
 * with the given model data.
 * <p>This is where you are able to set values on the AcroForm.
 * An example of what can be done at this level is:
 * <pre class="code">
 * // get the form from the document
 * AcroFields form = stamper.getAcroFields();
 *
 * // set some values on the form
 * form.setField("field1", "value1");
 * form.setField("field2", "Vvlue2");
 *
 * // set the disposition and filename
 * response.setHeader("Content-disposition", "attachment; FILENAME=someName.pdf");</pre>
 * <p>Note that the passed-in HTTP response is just supposed to be used
 * for setting cookies or other HTTP headers. The built PDF document itself
 * will automatically get written to the response after this method returns.
 * @param model the model Map
 * @param stamper the PdfStamper instance that will contain the AcroFields.
 * You may also customize this PdfStamper instance according to your needs,
 * e.g. setting the "formFlattening" property.
 * @param request in case we need locale etc. Shouldn't look at attributes.
 * @param response in case we need to set cookies. Shouldn't write to it.
 * @throws Exception any exception that occurred during document building
    */
protected abstract void mergePdfDocument(Map<String, Object> model, PdfStamper stamper,
        HttpServletRequest request, HttpServletResponse response) throws Exception;
项目:class-guard    文件:AbstractPdfStamperView.java   
/**
 * Subclasses must implement this method to merge the PDF form
 * with the given model data.
 * <p>This is where you are able to set values on the AcroForm.
 * An example of what can be done at this level is:
 * <pre class="code">
 * // get the form from the document
 * AcroFields form = stamper.getAcroFields();
 *
 * // set some values on the form
 * form.setField("field1", "value1");
 * form.setField("field2", "Vvlue2");
 *
 * // set the disposition and filename
 * response.setHeader("Content-disposition", "attachment; FILENAME=someName.pdf");</pre>
 * <p>Note that the passed-in HTTP response is just supposed to be used
 * for setting cookies or other HTTP headers. The built PDF document itself
 * will automatically get written to the response after this method returns.
 * @param model the model Map
 * @param stamper the PdfStamper instance that will contain the AcroFields.
 * You may also customize this PdfStamper instance according to your needs,
 * e.g. setting the "formFlattening" property.
 * @param request in case we need locale etc. Shouldn't look at attributes.
 * @param response in case we need to set cookies. Shouldn't write to it.
 * @throws Exception any exception that occured during document building
    */
protected abstract void mergePdfDocument(Map<String, Object> model, PdfStamper stamper,
        HttpServletRequest request, HttpServletResponse response) throws Exception;