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

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

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

/**
 * ?pdf// ww  w  . j  av  a  2s. c om
 *
 * @param srcPdfFile  the original PDF
 * @param descPdfFile the resulting PDF
 * @throws java.io.IOException
 * @throws DocumentException
 */
public static void decompressPdf(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()));
    stamper.getWriter().setCompressionLevel(PdfStream.NO_COMPRESSION);
    int total = reader.getNumberOfPages() + 1;
    for (int i = 1; i < total; i++) {
        reader.setPageContent(i, reader.getPageContent(i));
    }
    stamper.close();
    reader.close();

}

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

/**
 *  pdf /*from  w  ww. j av  a2s . c o m*/
 *
 * @param srcPdfFile       ?
 * @param descPdfFile      
 * @param userPassword     ?? ,null ?
 * @param ownerPassword    ?? ,null ?
 * @param allowHideMenuBar ????
 * @param allowHideToolbar ??
 * @param allowPrinting    ???
 * @param allowCopy        ???
 * @throws java.io.IOException
 * @throws DocumentException
 */
public static void encryptPdf(File srcPdfFile, File descPdfFile, String userPassword, String ownerPassword,
        boolean allowHideMenuBar, boolean allowHideToolbar, boolean allowPrinting, boolean allowCopy)
        throws IOException {

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

    byte[] userByte = null;
    byte[] ownerByte = null;

    /** User password. */
    if (userPassword != null)
        userByte = userPassword.getBytes();
    /** Owner password. */
    if (ownerPassword != null)
        ownerByte = ownerPassword.getBytes();

    try {

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

        // 
        // ???? PdfWriter.setViewerPreferences   addViewerPreference
        // ? api ??? addViewerPreference ?
        // ???"|"()?, ? PdfWriter.HideWindowUI
        // ???, ??

        // ( addViewerPreference )
        stamper.getWriter().addViewerPreference(PdfName.CENTERWINDOW, PdfBoolean.PDFTRUE);
        stamper.getWriter().addViewerPreference(PdfName.DISPLAYDOCTITLE, PdfBoolean.PDFTRUE);
        stamper.getWriter().addViewerPreference(PdfName.FITWINDOW, PdfBoolean.PDFTRUE);
        // writer.addViewerPreference(PdfName.HIDEWINDOWUI,
        // PdfBoolean.PDFTRUE);

        if (!allowHideToolbar)
            stamper.getWriter().addViewerPreference(PdfName.HIDETOOLBAR, PdfBoolean.PDFTRUE);

        if (!allowHideMenuBar)
            stamper.getWriter().addViewerPreference(PdfName.HIDEMENUBAR, PdfBoolean.PDFTRUE);

        //  allow 
        if (allowPrinting && allowCopy)
            stamper.setEncryption(userByte, ownerByte, PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY, true);

        else if (allowPrinting)
            stamper.setEncryption(userByte, ownerByte, PdfWriter.ALLOW_PRINTING, true);

        else if (allowCopy)
            stamper.setEncryption(userByte, ownerByte, PdfWriter.ALLOW_COPY, true);

        else
            stamper.setEncryption(userByte, ownerByte, 0, true);

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

        logger.info(srcPdfFile.getAbsoluteFile() + " encrypt finished.");

    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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

/**
 * http://www.javabeat.net/javascript-in-pdf-documents-using-itext/
 * http://www.javabeat.net/javascript-communication-between-html-and-pdf-in-itext/
 *  PDF  field  javaScript/*from w  w  w  .ja v  a 2 s  . c o m*/
 * <p>
 * pdf ? javaScript?????
 * <p>
 * javaScript ?? filed  filed javaScript ???
 * <p>
 * ?? javaScript 
 * <p>
 *  itext  reader.getJavaScript()? pdf  JavaScript??(adobe pro
 * ????)
 * <p>
 * ??? field ??
 *
 * @param srcPdfFileDir   ?
 * @param descPdfFileDir  
 * @param removeFieldName  javaScript ???
 * @throws java.io.IOException
 */
public static void removeFieldJavaScript(File srcPdfFileDir, File descPdfFileDir, String removeFieldName)
        throws IOException {

    if (!srcPdfFileDir.isDirectory()) {
        logger.info("srcPdfFileDir is not a Directory: " + srcPdfFileDir.getAbsolutePath());
        return;
    }

    File listFiles[] = srcPdfFileDir.listFiles();

    if (listFiles.length == 0) {
        logger.info("srcPdfFileDir has not file. " + srcPdfFileDir.getAbsolutePath());
        return;
    }

    FileUtils.forceMkdir(descPdfFileDir);

    // ??

    // 
    long prefixDiskFreeSize = descPdfFileDir.getFreeSpace();
    // ??
    long srcSize = FileUtils.sizeOf(srcPdfFileDir);

    logger.info(descPdfFileDir.getAbsolutePath() + " " + prefixDiskFreeSize / 1000000.00
            + " M");
    logger.info(srcPdfFileDir.getAbsolutePath() + " ? :" + srcSize / 1000000.00 + " M");

    if (prefixDiskFreeSize < srcSize) {

        logger.info(FilenameUtils.getPrefix(descPdfFileDir.getAbsolutePath()) + " has not enoght disk size .");

        return;
    }

    // logger.info(descPdfFileDir.getAbsolutePath());

    for (File f : listFiles) {
        String fileName = f.getName();
        String extensiion = FilenameUtils.getExtension(fileName).toLowerCase();

        PdfReader reader = null;

        PdfStamper stamper = null;

        if (f.isFile()) {
            if (extensiion.equals("pdf")) {

                reader = getPdfReader(f);

                File fileDesc = new File(descPdfFileDir.getAbsolutePath() + File.separator + fileName);

                try {
                    stamper = new PdfStamper(reader, FileUtils.openOutputStream(fileDesc));

                    /**
                     * ???
                     * **/
                    // reader.removeFields();

                    /**
                     * ??? javaScript ?
                     * **/
                    AcroFields form = stamper.getAcroFields();
                    form.removeField(removeFieldName);

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

                } catch (DocumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            } else
                continue;

        } // end if f.isFile

        else if (f.isDirectory()) {
            removeFieldJavaScript(f, new File(descPdfFileDir.getAbsolutePath() + File.separator + fileName),
                    removeFieldName);
        } // end if f.isDirectory
        else
            continue;

    } // end for

    logger.info("finished !");
}

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

/**
 * ?pdf???//from  w  w w .  j  a  v  a  2s .  co m
 * <p>
 *  javaScript ???? javaScript ?
 * </p>
 *
 * @param srcPdfFileDir  ?
 * @param descPdfFileDir 
 * @param startDate      ? "2011,01,01"
 * @param alerDays       ???
 * @param expiredDays    ?????
 * @throws java.io.IOException
 */
public static void setExpireDateWithJavaScript(File srcPdfFileDir, File descPdfFileDir, String startDate,
        int alerDays, int expiredDays) throws IOException {

    // ??
    if (alerDays >= expiredDays) {
        logger.info(" ' ' " + alerDays + "  '' " + expiredDays);
        return;
    }

    // ??? ?
    if (StringUtils.countMatches(startDate, ",") != 2) {
        logger.info(startDate + " ??  '2011,01,01' ?");
        return;
    }

    if (!isEnoughSpace(srcPdfFileDir, descPdfFileDir))
        return;

    File listFiles[] = srcPdfFileDir.listFiles();

    if (listFiles.length == 0) {
        logger.info("srcPdfFileDir has not file. " + srcPdfFileDir.getAbsolutePath());
        return;
    }

    // ??
    // String[] resources = new String[]{"/pdfexpiration.js"};
    File resPath = MyFileUtils.copyResourceFileFromJarLibToTmpDir("/pdfexpiration.js"); //????
    // ?
    String jsStr = FileUtils.readFileToString(resPath);

    /** ? js ? */
    // ?
    jsStr = StringUtils.replace(jsStr, "2011,01,01", startDate);
    // ?
    jsStr = StringUtils.replace(jsStr, "alertDays = 355", "alertDays = " + Integer.toString(alerDays));
    // ?
    jsStr = StringUtils.replace(jsStr, "expiredDays = 365", "expiredDays = " + Integer.toString(expiredDays));

    System.out.println(jsStr);

    // logger.info(descPdfFileDir.getAbsolutePath());

    for (File f : listFiles) {
        String fileName = f.getName();
        String extensiion = FilenameUtils.getExtension(fileName).toLowerCase();

        if (f.isFile()) {
            if (extensiion.equals("pdf")) {

                PdfReader reader = getPdfReader(f);

                File fileDesc = new File(descPdfFileDir.getAbsolutePath() + File.separator + fileName);

                try {
                    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(fileDesc));
                    // Get the writer (to add actions and annotations)
                    PdfWriter writer = stamper.getWriter();
                    PdfAction action = PdfAction.javaScript(jsStr, writer, true);
                    //  javaScript ?
                    stamper.setPageAction(PdfWriter.PAGE_OPEN, action, 1);
                    // Close the stamper
                    stamper.close();
                    reader.close();

                    logger.info(fileDesc.getAbsolutePath() + " ? !");

                } catch (DocumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            } else
                continue;

        } // end if f.isFile

        else if (f.isDirectory()) {
            setExpireDateWithJavaScript(f,
                    new File(descPdfFileDir.getAbsolutePath() + File.separator + fileName), startDate, alerDays,
                    expiredDays);
        } // end if f.isDirectory
        else
            continue;

    } // end for
}

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

/**
 * //from  www.j av  a 2s . c  o  m
 * <p/>
 * <p>
 * ? iText in Action 2nd EditionChapter 6: Working with existing PDFs
 * SelectPages
 * </p>
 *
 * @param src       ?
 * @param desc      
 * @param beginPage 
 * @param endPage   ?
 * @throws java.io.IOException
 * @throws DocumentException
 */
public static void splitToPages(File src, File desc, int beginPage, int endPage)
        throws IOException, DocumentException {

    PdfReader reader = getPdfReader(src);
    // reader.selectPages("4-8");
    reader.selectPages(Integer.toString(beginPage) + "-" + Integer.toString(endPage));
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(desc));
    stamper.close();
}

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

/**
 *  pdf /* w  ww  . j  a v  a 2s . com*/
 *
 * @param srcPdfFile        ?
 * @param descPdfFile       
 * @param userPassword      ?? ,null ?
 * @param ownerPassword     ?? ,null ?
 * @param allow_HideMenubar ????
 * @param allow_HideToolbar ??
 * @param allow_printing    ???
 * @param allow_copy        ???
 * @throws java.io.IOException
 * @throws DocumentException
 */
public static void encryptPdf(File srcPdfFile, File descPdfFile, String userPassword, String ownerPassword,
        boolean allow_HideMenubar, boolean allow_HideToolbar, boolean allow_printing, boolean allow_copy)
        throws IOException {

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

    byte[] USER = null;
    byte[] OWNER = null;

    /** User password. */
    if (userPassword != null)
        USER = userPassword.getBytes();
    /** Owner password. */
    if (ownerPassword != null)
        OWNER = ownerPassword.getBytes();

    try {

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

        // 
        // ???? PdfWriter.setViewerPreferences   addViewerPreference
        // ? api ??? addViewerPreference ?
        // ???"|"()?, ? PdfWriter.HideWindowUI
        // ???, ??

        // ( addViewerPreference )
        stamper.getWriter().addViewerPreference(PdfName.CENTERWINDOW, PdfBoolean.PDFTRUE);
        stamper.getWriter().addViewerPreference(PdfName.DISPLAYDOCTITLE, PdfBoolean.PDFTRUE);
        stamper.getWriter().addViewerPreference(PdfName.FITWINDOW, PdfBoolean.PDFTRUE);
        // writer.addViewerPreference(PdfName.HIDEWINDOWUI,
        // PdfBoolean.PDFTRUE);

        if (!allow_HideToolbar)
            stamper.getWriter().addViewerPreference(PdfName.HIDETOOLBAR, PdfBoolean.PDFTRUE);

        if (!allow_HideMenubar)
            stamper.getWriter().addViewerPreference(PdfName.HIDEMENUBAR, PdfBoolean.PDFTRUE);

        //  allow 
        if (allow_printing && allow_copy)
            stamper.setEncryption(USER, OWNER, PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY, true);

        else if (allow_printing)
            stamper.setEncryption(USER, OWNER, PdfWriter.ALLOW_PRINTING, true);

        else if (allow_copy)
            stamper.setEncryption(USER, OWNER, PdfWriter.ALLOW_COPY, true);

        else
            stamper.setEncryption(USER, OWNER, 0, true);

        stamper.close();

        logger.info(srcPdfFile.getAbsoluteFile() + " encrypt finished.");

    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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

/**
 * ?pdf???//from w w  w .jav a 2  s. co  m
 * <p>
 *  javaScript ???? javaScript ?
 * </p>
 *
 * @param srcPdfFileDir  ?
 * @param descPdfFileDir 
 * @param startDate      ? "2011,01,01"
 * @param alerDays       ???
 * @param expiredDays    ?????
 * @throws java.io.IOException
 */
public static void setExpireDateWithJavaScript(File srcPdfFileDir, File descPdfFileDir, String startDate,
        int alerDays, int expiredDays) throws IOException {

    // ??
    if (alerDays >= expiredDays) {
        logger.info(" ' ' " + alerDays + "  '' " + expiredDays);
        return;
    }

    // ??? ?
    if (StringUtils.countMatches(startDate, ",") != 2) {
        logger.info(startDate + " ??  '2011,01,01' ?");
        return;
    }

    if (!isEnoughtSpace(srcPdfFileDir, descPdfFileDir))
        return;

    File listFiles[] = srcPdfFileDir.listFiles();

    if (listFiles.length == 0) {
        logger.info("srcPdfFileDir has not file. " + srcPdfFileDir.getAbsolutePath());
        return;
    }

    // ??
    // String[] resources = new String[]{"/pdfexpiration.js"};
    File resPath = MyFileUtils.copyResourceFileFromJarLibToTmpDir("/pdfexpiration.js"); //????
    // ?
    String jsStr = FileUtils.readFileToString(resPath);

    /** ? js ? */
    // ?
    jsStr = StringUtils.replace(jsStr, "2011,01,01", startDate);
    // ?
    jsStr = StringUtils.replace(jsStr, "alertDays = 355", "alertDays = " + Integer.toString(alerDays));
    // ?
    jsStr = StringUtils.replace(jsStr, "expiredDays = 365", "expiredDays = " + Integer.toString(expiredDays));

    System.out.println(jsStr);

    // logger.info(descPdfFileDir.getAbsolutePath());

    for (File f : listFiles) {
        String fileName = f.getName();
        String extensiion = FilenameUtils.getExtension(fileName).toLowerCase();

        if (f.isFile()) {
            if (extensiion.equals("pdf")) {

                PdfReader reader = getPdfReader(f);

                File fileDesc = new File(descPdfFileDir.getAbsolutePath() + File.separator + fileName);

                try {
                    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(fileDesc));
                    // Get the writer (to add actions and annotations)
                    PdfWriter writer = stamper.getWriter();
                    PdfAction action = PdfAction.javaScript(jsStr, writer, true);
                    //  javaScript ?
                    stamper.setPageAction(PdfWriter.PAGE_OPEN, action, 1);
                    // Close the stamper
                    stamper.close();
                    reader.close();

                    logger.info(fileDesc.getAbsolutePath() + " ? !");

                } catch (DocumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            } else
                continue;

        } // end if f.isFile

        else if (f.isDirectory()) {
            setExpireDateWithJavaScript(f,
                    new File(descPdfFileDir.getAbsolutePath() + File.separator + fileName), startDate, alerDays,
                    expiredDays);
        } // end if f.isDirectory
        else
            continue;

    } // end for
}

From source file:org.jfree.chart.swt.ChartPdf.java

License:Open Source License

public static void saveChartAsPDF(File file, JFreeChart chart, int width, int height)
        throws DocumentException, FileNotFoundException, IOException {
    if (chart != null) {
        boolean success = false;
        String old = null;// ww  w.  j  av  a2  s  .com
        File oldFile = null;
        boolean append = file.exists();
        if (append) {
            old = file.getAbsolutePath() + ".old"; //$NON-NLS-1$
            oldFile = new File(old);
            oldFile.delete();
            file.renameTo(oldFile);
        }
        try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
            // convert chart to PDF with iText:
            Rectangle pagesize = new Rectangle(width, height);
            if (append) {
                PdfReader reader = new PdfReader(old);
                PdfStamper stamper = new PdfStamper(reader, out);
                try {
                    int n = reader.getNumberOfPages() + 1;
                    stamper.insertPage(n, pagesize);
                    PdfContentByte overContent = stamper.getOverContent(n);
                    writeChart(chart, width, height, overContent);
                    ColumnText ct = new ColumnText(overContent);
                    ct.setSimpleColumn(width - 50, 50, width - 12, height, 150, Element.ALIGN_RIGHT);
                    Paragraph paragraph = new Paragraph(String.valueOf(n),
                            new Font(FontFamily.HELVETICA, 9, Font.NORMAL, BaseColor.DARK_GRAY));
                    paragraph.setAlignment(Element.ALIGN_RIGHT);
                    ct.addElement(paragraph);
                    ct.go();
                    success = true;
                } finally {
                    stamper.close();
                    reader.close();
                    oldFile.delete();
                }
            } else {
                Document document = new Document(pagesize, 50, 50, 50, 50);
                document.addCreationDate();
                document.addCreator(Constants.APPLICATION_NAME);
                document.addAuthor(System.getProperty("user.name")); //$NON-NLS-1$
                try {
                    PdfWriter writer = PdfWriter.getInstance(document, out);
                    document.open();
                    writeChart(chart, width, height, writer.getDirectContent());
                    success = true;
                } finally {
                    document.close();
                }
            }
        }
        if (!success) {
            file.delete();
            if (oldFile != null)
                oldFile.renameTo(file);
        }
    }
}

From source file:org.roda.common.certification.PDFSignatureUtils.java

public static void runDigitalSignatureStrip(Path input, Path output) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(input.toString());
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(output.toString()));
    stamper.setFormFlattening(true);/*  w  ww  .j a  va2s . c  o m*/
    stamper.close();
    reader.close();
}

From source file:org.sistemafinanciero.rest.impl.CuentaBancariaRESTService.java

License:Apache License

@Override
public Response getCertificado(BigInteger id) {
    OutputStream file;/*from  w  w  w.  ja  v a  2  s.co  m*/

    CuentaBancariaView cuentaBancaria = cuentaBancariaServiceNT.findById(id);
    String codigoAgencia = ProduceObject.getCodigoAgenciaFromNumeroCuenta(cuentaBancaria.getNumeroCuenta());

    Agencia agencia = agenciaServiceNT.findByCodigo(codigoAgencia);

    if (agencia == null) {
        JsonObject model = Json.createObjectBuilder().add("message", "Agencia no encontrado").build();
        return Response.status(Response.Status.NOT_FOUND).entity(model).build();
    }

    try {
        file = new FileOutputStream(new File(certificadoURL + "\\" + id + ".pdf"));
        //Document document = new Document(PageSize.A5.rotate());
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, file);
        document.open();

        //recuperando moneda, redondeando y dando formato
        Moneda moneda = monedaServiceNT.findById(cuentaBancaria.getIdMoneda());
        BigDecimal saldo = cuentaBancaria.getSaldo();
        BigDecimal decimalValue = saldo.subtract(saldo.setScale(0, RoundingMode.FLOOR))
                .movePointRight(saldo.scale());
        Long integerValue = saldo.longValue();

        String decimalString = decimalValue.toString();
        if (decimalString.length() < 2)
            decimalString = "0" + decimalString;

        NumberFormat df1 = NumberFormat.getCurrencyInstance();
        DecimalFormatSymbols dfs = new DecimalFormatSymbols();
        dfs.setCurrencySymbol("");
        dfs.setGroupingSeparator(',');
        dfs.setMonetaryDecimalSeparator('.');
        ((DecimalFormat) df1).setDecimalFormatSymbols(dfs);

        //recuperando el plazo en dias
        Date fechaApertura = cuentaBancaria.getFechaApertura();
        Date fechaCierre = cuentaBancaria.getFechaCierre();
        LocalDate localDateApertura = new LocalDate(fechaApertura);
        LocalDate localDateCierre = new LocalDate(fechaCierre);
        Days days = Days.daysBetween(localDateApertura, localDateCierre);

        //fuentes
        Font fontTitulo = FontFactory.getFont("Times New Roman", 14, Font.BOLD);
        Font fontSubTitulo = FontFactory.getFont("Times New Roman", 8);
        Font fontContenidoNegrita = FontFactory.getFont("Times New Roman", 10, Font.BOLD);
        Font fontContenidoNormal = FontFactory.getFont("Times New Roman", 10);

        //dando formato a las fechas
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        String fechaAperturaString = df.format(cuentaBancaria.getFechaApertura());
        String fechaVencimientoString = df.format(cuentaBancaria.getFechaCierre());

        //ingresando datos al documento
        document.add(new Paragraph("\n"));
        document.add(new Paragraph("\n"));

        //parrafo titulo
        Paragraph parrafoTitulo = new Paragraph();
        parrafoTitulo.setFont(fontTitulo);
        parrafoTitulo.setSpacingBefore(30);
        parrafoTitulo.setAlignment(Element.ALIGN_CENTER);

        //parrafo subtitulo
        Paragraph parrafoSubTitulo = new Paragraph();
        parrafoSubTitulo.setFont(fontSubTitulo);
        parrafoSubTitulo.setSpacingAfter(30);
        parrafoSubTitulo.setAlignment(Element.ALIGN_CENTER);

        //parrafo contenido
        Paragraph parrafoContenido = new Paragraph();
        parrafoContenido.setIndentationLeft(50);
        parrafoContenido.setAlignment(Element.ALIGN_LEFT);

        //parrafo firmas
        Paragraph parrafoFirmas = new Paragraph();
        parrafoFirmas.setAlignment(Element.ALIGN_CENTER);

        //agregar titulo al documento
        Chunk titulo = new Chunk("CERTIFICADO DE PLAZO FIJO");
        parrafoTitulo.add(titulo);

        //agregar titulo al documento
        Chunk subTitulo;
        if (cuentaBancaria.getIdMoneda().compareTo(BigInteger.ZERO) == 0) {
            subTitulo = new Chunk("DEPSITO A PLAZO FIJO - DOLARES AMERICANOS");
        } else if (cuentaBancaria.getIdMoneda().compareTo(BigInteger.ONE) == 0) {
            subTitulo = new Chunk("DEPSITO A PLAZO FIJO - NUEVOS SOLES");
        } else {
            subTitulo = new Chunk("DEPSITO A PLAZO FIJO - EUROS");
        }
        parrafoSubTitulo.add(subTitulo);

        //agregando contenido al documento
        //Agencia
        Chunk agencia1 = new Chunk("AGENCIA", fontContenidoNegrita);
        Chunk agencia2 = new Chunk(": " + agencia.getCodigo() + " - " + agencia.getDenominacion().toUpperCase(),
                fontContenidoNormal);
        parrafoContenido.add(agencia1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(agencia2);
        parrafoContenido.add("\n");

        //cuenta
        Chunk numeroCuenta1 = new Chunk("N CUENTA", fontContenidoNegrita);
        Chunk numeroCuenta2 = new Chunk(": " + cuentaBancaria.getNumeroCuenta(), fontContenidoNormal);
        parrafoContenido.add(numeroCuenta1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(numeroCuenta2);
        parrafoContenido.add("\n");

        //codigo cliente
        Chunk codigoSocio1 = new Chunk("CODIGO CLIENTE", fontContenidoNegrita);
        Chunk codigoSocio2 = new Chunk(": " + cuentaBancaria.getIdSocio().toString(), fontContenidoNormal);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(codigoSocio1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(codigoSocio2);
        parrafoContenido.add("\n");

        //cliente
        Chunk socio1 = new Chunk("CLIENTE", fontContenidoNegrita);
        Chunk socio2 = new Chunk(": " + cuentaBancaria.getSocio(), fontContenidoNormal);
        parrafoContenido.add(socio1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(socio2);
        parrafoContenido.add("\n");

        //tipo cuenta
        Chunk tipoCuenta1 = new Chunk("TIPO CUENTA", fontContenidoNegrita);
        Chunk tipoCuenta2 = new Chunk(": " + "INDIVIDUAL", fontContenidoNormal);
        parrafoContenido.add(tipoCuenta1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(tipoCuenta2);
        parrafoContenido.add("\n");

        //tipo moneda
        Chunk tipoMoneda1 = new Chunk("TIPO MONEDA", fontContenidoNegrita);
        Chunk tipoMoneda2;
        if (cuentaBancaria.getIdMoneda().compareTo(BigInteger.ZERO) == 0) {
            tipoMoneda2 = new Chunk(": " + "DOLARES AMERICANOS", fontContenidoNormal);
        } else if (cuentaBancaria.getIdMoneda().compareTo(BigInteger.ONE) == 0) {
            tipoMoneda2 = new Chunk(": " + "NUEVOS SOLES", fontContenidoNormal);
        } else {
            tipoMoneda2 = new Chunk(": " + "EUROS", fontContenidoNormal);
        }
        parrafoContenido.add(tipoMoneda1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(tipoMoneda2);
        parrafoContenido.add("\n");

        //Monto
        Chunk monto1 = new Chunk("MONTO", fontContenidoNegrita);
        Chunk monto2 = new Chunk(": " + moneda.getSimbolo() + df1.format(saldo) + " - "
                + NumLetrasJ.Convierte(integerValue.toString() + "", Tipo.Pronombre).toUpperCase() + " Y "
                + decimalString + "/100 " + moneda.getDenominacion(), fontContenidoNormal);
        parrafoContenido.add(monto1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(monto2);
        parrafoContenido.add("\n");

        //Plazo
        Chunk plazo1 = new Chunk("PLAZO", fontContenidoNegrita);
        Chunk plazo2 = new Chunk(": " + days.getDays() + " D?AS", fontContenidoNormal);
        parrafoContenido.add(plazo1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(plazo2);
        parrafoContenido.add("\n");

        //Fecha Apertura
        Chunk fechaApertura1 = new Chunk("FEC. APERTURA", fontContenidoNegrita);
        Chunk fechaApertura2 = new Chunk(": " + fechaAperturaString, fontContenidoNormal);
        parrafoContenido.add(fechaApertura1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(fechaApertura2);
        parrafoContenido.add("\n");

        //Fecha Vencimiento
        Chunk fechaVencimiento1 = new Chunk("FEC. VENCIMIENTO", fontContenidoNegrita);
        Chunk fechaVencimiento2 = new Chunk(": " + fechaVencimientoString, fontContenidoNormal);
        parrafoContenido.add(fechaVencimiento1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(fechaVencimiento2);
        parrafoContenido.add("\n");

        //tasa efectiva anual
        Chunk tasaEfectivaAnual1 = new Chunk("TASA EFECTIVA ANUAL", fontContenidoNegrita);
        Chunk tasaEfectivaAnual2 = new Chunk(
                ": " + cuentaBancaria.getTasaInteres().multiply(new BigDecimal(100)).toString() + "%",
                fontContenidoNormal);
        parrafoContenido.add(tasaEfectivaAnual1);
        parrafoContenido.add(tasaEfectivaAnual2);
        parrafoContenido.add("\n");

        //frecuencia de capitalizacion
        Chunk frecuenciaCapitalizacion1 = new Chunk("FREC. CAPITALIZACION", fontContenidoNegrita);
        Chunk frecuenciaCapitalizacion2 = new Chunk(": " + "DIARIA", fontContenidoNormal);
        parrafoContenido.add(frecuenciaCapitalizacion1);
        parrafoContenido.add(frecuenciaCapitalizacion2);
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");

        //importante
        Chunk importante = new Chunk("IMPORTANTE: ", fontContenidoNegrita);
        Chunk importanteDetalle1 = new Chunk(
                "DEPSITO CUBIERTO POR EL FONDO DE SEGURO DE DEPOSITOS ESTABLECIDO POR EL BANCO CENTRAL DE RESERVA DEL PER HASTA S/.82,073.00.",
                fontSubTitulo);
        Chunk importanteDetalle2 = new Chunk(
                "LAS PERSONAS JUR?DICAS SIN FINES DE LUCRO SON CUBIERTAS POR EL FONDO DE SEGURO DE DEPSITOS.",
                fontSubTitulo);
        parrafoContenido.add(importante);
        parrafoContenido.add(importanteDetalle1);
        parrafoContenido.add("\n");
        parrafoContenido.add(importanteDetalle2);
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");

        //certificado intranferible
        Chunk certificadoIntransferible = new Chunk("CERTIFICADO INTRANSFERIBLE.", fontContenidoNegrita);
        parrafoContenido.add(certificadoIntransferible);
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");

        //Firmas
        Chunk subGion = new Chunk("___________________", fontContenidoNormal);
        Chunk firmaCajero = new Chunk("CAJERO", fontContenidoNormal);
        Chunk firmaCliente = new Chunk("CLIENTE", fontContenidoNormal);

        parrafoFirmas.add(subGion);
        parrafoFirmas.add(Chunk.SPACETABBING);
        parrafoFirmas.add(Chunk.SPACETABBING);
        parrafoFirmas.add(subGion);
        parrafoFirmas.add("\n");
        parrafoFirmas.add(firmaCajero);
        parrafoFirmas.add(Chunk.SPACETABBING);
        parrafoFirmas.add(Chunk.SPACETABBING);
        parrafoFirmas.add(Chunk.SPACETABBING);
        parrafoFirmas.add(firmaCliente);

        //agregando los parrafos al documento
        document.add(parrafoTitulo);
        document.add(parrafoSubTitulo);
        document.add(parrafoContenido);
        document.add(parrafoFirmas);
        document.close();
        file.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    PdfReader reader;
    try {
        reader = new PdfReader(certificadoURL + "\\" + id + ".pdf");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PdfStamper pdfStamper = new PdfStamper(reader, out);
        AcroFields acroFields = pdfStamper.getAcroFields();
        acroFields.setField("field_title", "test");
        pdfStamper.close();
        reader.close();
        return Response.ok(out.toByteArray()).type("application/pdf").build();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(Jsend.getErrorJSend("No encontrado"))
            .build();
}