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

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

Introduction

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

Prototype

public PdfStamper(PdfReader reader, OutputStream os) throws DocumentException, IOException 

Source Link

Document

Starts the process of adding extra content to an existing PDF document.

Usage

From source file:docx4j.TextSubstitution.java

License:Apache License

private String addWaterMark() throws IOException, DocumentException {
    String result = null;//from   w  w w. j  a v  a2  s.  co  m
    String newFileName = this.getFolderPath() + "wm" + this.fileName;

    try {
        // try to delete the file if it already exists so that we refresh the watermark
        // if it fails then at least we have the existing version which can be deleted manually
        File target = new File(newFileName);
        if (target.exists()) {
            if (!target.delete()) {
                return "existing";
            }
        }

        // add the watermark
        PdfReader reader = new PdfReader(this.filePath);
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(newFileName));
        Image watermark_image = Image.getInstance(this.getFolderPath() + "doc-watermark.png");
        watermark_image.setAbsolutePosition(5, 5);
        int i = 0;
        PdfContentByte add_watermark;

        // loop the pages adding the watermark
        while (i < reader.getNumberOfPages()) {
            i++;
            add_watermark = stamp.getUnderContent(i);
            add_watermark.addImage(watermark_image);
        }
        stamp.close();
        reader.close();
    } catch (Exception e) {
        result = e.getMessage();
    }
    return result;
}

From source file:dynamicform.Stamper.java

License:Apache License

public Stamper(InputStream inputPath, OutputStream outputPath) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(inputPath);
    stamper = new PdfStamper(reader, outputPath);
    reader.close();//from  w w  w .  ja v  a 2  s .  c  o m
    fields = stamper.getAcroFields();
}

From source file:erando.controllers.InterfaceRandoController.java

void genererpdf() throws IOException, FileNotFoundException, DocumentException {

    PdfReader pdfTemplate = new PdfReader("templatefacture.pdf");
    RandonneService rando = new RandonneService();
    Randonne r = new Randonne();
    r = rando.findById(RecupererIdRando.getIdRando());
    FileOutputStream fileOutputStream = new FileOutputStream("test.pdf");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);
    stamper.setFormFlattening(true);/*from ww  w . j av  a  2  s .  c  o  m*/

    stamper.getAcroFields().setField("name", r.getTitre());
    stamper.getAcroFields().setField("montant", String.valueOf(r.getPrix()));
    stamper.getAcroFields().setField("depart", r.getPointDepart());
    stamper.getAcroFields().setField("arrivee", r.getDestination());
    stamper.getAcroFields().setField("date", String.valueOf(r.getDate()));
    stamper.close();
    pdfTemplate.close();

}

From source file:erando.controllers.ReservationByuserController.java

void genererpdf() throws IOException, FileNotFoundException, DocumentException {

    PdfReader pdfTemplate = new PdfReader("templatefacture.pdf");
    FileOutputStream fileOutputStream = new FileOutputStream("test.pdf");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);
    stamper.setFormFlattening(true);/*from  w w w.j  av a 2s  .  c  o  m*/

    stamper.getAcroFields().setField("name", titre);
    stamper.getAcroFields().setField("montant", String.valueOf(prix));
    stamper.getAcroFields().setField("depart", depart);
    stamper.getAcroFields().setField("arrivee", destination);
    stamper.getAcroFields().setField("date", String.valueOf(date));
    stamper.close();
    pdfTemplate.close();

}

From source file:erando.services.impl.pdfCreation.java

public void genererpdf(String titre, float prix, String imageName, int id, String description)
        throws IOException, FileNotFoundException, DocumentException {

    PdfReader pdfTemplate = new PdfReader("template.pdf");
    FileOutputStream fileOutputStream = new FileOutputStream(id + ".pdf");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);
    stamper.setFormFlattening(true);/*  w ww.jav  a2s  .  c o m*/
    stamper.getAcroFields().setField("titre", titre.toUpperCase());
    stamper.getAcroFields().setField("description", description);
    stamper.getAcroFields().setField("prix", "" + prix);

    stamper.close();
    pdfTemplate.close();

}

From source file:fr.opensagres.odfdom.converter.pdf.internal.BackgroundImage.java

License:Open Source License

private ByteArrayOutputStream insertImage(ByteArrayOutputStream out, Image image) {

    try {/*from  ww  w .  ja  v  a  2 s  .c om*/
        ByteArrayOutputStream os = new ByteArrayOutputStream(out.size());
        PdfReader reader = new PdfReader(out.toByteArray());
        PdfStamper stamper = new PdfStamper(reader, os);

        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            PdfContentByte canvas = stamper.getUnderContent(i);
            canvas.addImage(image);
        }
        reader.close();
        stamper.close();
        return os;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:gov.anl.aps.cdb.portal.plugins.support.icmsLink.IcmsWatermarkUtility.java

License:Open Source License

/**
 * Adds a stamp of some metadata to ICMS documents.
 *
 * Function Credit: Thomas Fors/*from   ww w .  jav  a2 s  .  co  m*/
 *     
 * @return byte array ologgerf the stamped PDF file
 * @throws DocumentException - Error loading pdfstamper or creating font
 * @throws IOException - Error performing IO operation 
 * @throws Base64DecodingException - Error converting downloadContent string to byte[]
 */
private byte[] addWatermarkToPDFFile() throws Base64DecodingException, DocumentException, IOException {
    byte[] pdfBytes = Base64.decode(downloadContentBase64Encoded);

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yy hh:mm:ss a");
    LocalDateTime now = LocalDateTime.now();
    String downloadTime = dtf.format(now);

    UserInfo user = (UserInfo) SessionUtility.getUser();
    String username = null;
    if (user != null) {
        username = user.getUsername();
    } else {
        username = "unknown user";
    }
    String bottomMessage = "Downloaded via APS CDB by: " + username + " at " + downloadTime;

    controlledRev = updateOptionalValue(controlledRev);
    dnsCollectionId = updateOptionalValue(dnsCollectionId);
    dnsDocNumber = updateOptionalValue(dnsDocNumber);

    String watermarkContents = "Content ID: " + docName;
    watermarkContents += "      Rev: " + controlledRev;
    watermarkContents += "      Released: " + date;
    watermarkContents += "      DNS Collection ID: " + dnsCollectionId;
    watermarkContents += "      DNS Document ID: " + dnsDocNumber;

    PdfReader pdfReader = new PdfReader(pdfBytes);
    int n = pdfReader.getNumberOfPages();

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PdfStamper stamp = new PdfStamper(pdfReader, out);

    PdfContentByte over;
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);

    for (int i = 0; i < n; i++) {
        over = stamp.getOverContent(i + 1);
        over.beginText();
        over.setTextMatrix(30, 30);
        over.setFontAndSize(bf, 10);
        over.setColorFill(new Color(0x80, 0x80, 0x80));
        over.showTextAligned(Element.ALIGN_LEFT, watermarkContents, 25, 25, 90);
        over.showTextAligned(Element.ALIGN_LEFT, bottomMessage, 50, 10, 0);
        if (status.equals(ICMS_UNDER_REV_STATUS)) {
            over.setColorFill(new Color(0xFF, 0x00, 0x00));
        }
        //over.showTextAligned(Element.ALIGN_LEFT, status, 25, 25 + bf.getWidthPoint(watermarkContents + " - ", 10), 90);

        over.endText();
    }
    stamp.close();

    return out.toByteArray();
}

From source file:hornet.framework.export.fdf.FDF.java

License:CeCILL license

/**
 * Thread-safe utility method for PDF generation, based on a FDF template stream and a data object to
 * merge. Fields defined in FDF that can't be merged (not corresponding field in data object) are stored
 * in FDF Result./*  ww w  . ja v a 2  s .  c o  m*/
 *
 * @param in
 *            input stream of PDF/FDF (template)
 * @param out
 *            output stream of final PDF
 * @param data
 *            a javabean or a java.util.Map. Nested properties are allowed this field names access pattern
 *            : "propA:propB:propC".
 * @return FDF result object (not null)
 */
public static FDFRes export(final InputStream in, final OutputStream out, final Object data) {

    PdfReader pdfIn = null;
    PdfStamper stamper = null;
    final FDFRes res = new FDFRes();

    try {
        pdfIn = new PdfReader(in);
        stamper = new PdfStamper(pdfIn, out);
        final AcroFields form = stamper.getAcroFields();

        // fusion champs FDF avec le bean
        for (final Object nomField : form.getFields().keySet()) {
            fusionChamp(data, stamper, res, form, nomField);
        }

        // la ligne suivante supprime le formulaire
        stamper.setFormFlattening(true);

    } catch (final IOException ex) {
        throw new FDFExportException(ex);
    } catch (final DocumentException ex) {
        throw new FDFExportException(ex);
    } finally {
        try {
            stamper.close();
        } catch (final Exception ex) {
            LOG.error("Erreur", ex);
        }
    }

    return res;
}

From source file:ispyb.common.util.PDFFormFiller.java

License:Open Source License

/**
 * Initialize the PDF document/* w  w  w.  j  a va 2s . c o m*/
 * 
 * @param pdfForm
 *            the path to the PDF form to be filled
 * @param os
 *            the output stream object
 * @param pageOrientation
 *            the page orientation (Portrait or Landscape)
 * @throws Exception
 */
public void init(String pdfForm, OutputStream os, int pageOrientation) throws Exception {
    if (LOG.isDebugEnabled())
        LOG.debug("Initializing with template: " + pdfForm);
    try {
        this.reader = new PdfReader(pdfForm);
        this.stamper = new PdfStamper(this.reader, os);
        this.writer = this.stamper.getWriter();
        this.writer.setPdfVersion(PdfWriter.VERSION_1_3);
        this.setPageOrientation(pageOrientation);
        this.formFields = this.stamper.getAcroFields();
    } catch (Exception e) {
        LOG.error("init", e);
        throw new Exception("Error initializing the PDF objects for file \"" + pdfForm + "\".");
    }
}

From source file:ispyb.common.util.PDFFormFiller.java

License:Open Source License

/**
 * Initialize the PDF document/* w  w w  .  jav  a  2  s  .c o  m*/
 * 
 * @param pdfForm
 *            the path to the PDF form to be filled
 * @param os
 *            the output stream object
 * @param pageOrientation
 *            the page orientation (Portrait or Landscape)
 * @throws Exception
 */
private void init(byte[] bs, OutputStream os, int pageOrientation) throws Exception {
    try {
        this.reader = new PdfReader(bs);
        this.stamper = new PdfStamper(this.reader, os);
        this.writer = this.stamper.getWriter();
        this.writer.setPdfVersion(PdfWriter.VERSION_1_3);
        this.setPageOrientation(pageOrientation);
        this.formFields = this.stamper.getAcroFields();
    } catch (Exception e) {
        LOG.error("init", e);
        throw new Exception("Error initializing the PDF objects for file bytes.");
    }
}