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

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

Introduction

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

Prototype

public PdfAction(int named) 

Source Link

Document

Implements name actions.

Usage

From source file:app.App.java

private void setLink(int pageId, PdfStamper stamper) throws ClassNotFoundException, IOException {
    // load the sqlite-JDBC driver using the current class loader
    Class.forName("org.sqlite.JDBC");

    Connection connection = null;
    try {//www  .  j av  a 2  s. c om
        // create a database connection
        connection = DriverManager.getConnection("jdbc:sqlite:" + DATABASE);
        Statement statement = connection.createStatement();
        statement.setQueryTimeout(30); // set timeout to 30 sec.

        ResultSet rs = statement.executeQuery(
                "select * from page_annotations " + "where annotation_type = 'goto' and page_id = " + pageId);
        float spendX = 0;
        float spendY = 0;
        float coordX = 0;
        float coordY = 0;
        int pageDest = 0;
        Rectangle rect;
        PdfAnnotation annotation;
        while (rs.next()) {
            spendX = rs.getFloat("pdf_width");
            spendY = rs.getFloat("pdf_height");
            coordX = rs.getFloat("pdf_x");// + rs.getFloat("pdf_width");
            coordY = rs.getFloat("pdf_y");
            pageDest = rs.getInt("annotation_target");

            Font font = FontFactory.getFont(FontFactory.COURIER, 10, Font.UNDERLINE);
            // Blue
            font.setColor(0, 0, 255);
            Chunk chunk = new Chunk("GOTO", font);
            Anchor anchor = new Anchor(chunk);
            ColumnText.showTextAligned(stamper.getUnderContent(pageId), Element.ALIGN_LEFT, anchor,
                    coordX + spendX, coordY, 0);

            rect = new Rectangle(coordX, coordY, spendX, spendY);
            annotation = PdfAnnotation.createLink(stamper.getWriter(), rect, PdfAnnotation.HIGHLIGHT_INVERT,
                    new PdfAction("#" + pageDest));
            stamper.addAnnotation(annotation, pageId);
        }
    } catch (SQLException e) {
        // if the error message is "out of memory", 
        // it probably means no database file is found
        System.err.println(e.getMessage());
    } finally {
        try {
            if (connection != null)
                connection.close();
        } catch (SQLException e) {
            // connection close failed.
            System.err.println(e);
        }
    }
}

From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java

License:Open Source License

private PdfPTable buildModelPricingTables(Contact contact, Model model) {

    final PdfPTable table = new PdfPTable(1);

    final List<Pricing> validPricings = model.validPricings(contact);

    if (CollectionUtils.isEmpty(validPricings)) {
        final Chunk chunk = new Chunk("Contact us for pricing on this model", iTextUtil.getFontContactUs());
        chunk.setAction(new PdfAction(contactUsUrl));
        table.addCell(cell(new Phrase(chunk)));
    } else {//from w  w  w. ja va2  s  .c om
        for (Pricing pricing : validPricings) {
            table.addCell(cell(buildModelPricingTable(pricing)));
        }
    }

    return table;

}

From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java

License:Open Source License

private PdfPTable buildModelDetailSection(Model model, PdfWriter pdfWriter)
        throws IOException, BadElementException {

    final Phrase p = processHtmlCodes(model.getProductNameProcessed(), iTextUtil.getFontModelTitle(),
            iTextUtil.getFontModelSymbol());
    for (Chunk c : p.getChunks()) {
        c.setAction(new PdfAction(model.getUrl()));
    }/*from w w  w .j  av  a  2  s .co  m*/

    final StringBuilder strAppList = new StringBuilder();
    for (String application : model.getApplicationsSorted()) {
        if (strAppList.length() != 0) {
            strAppList.append(", ");
        }
        strAppList.append(application);
    }

    final PdfPTable table = new PdfPTable(1);

    table.addCell(cell(p));

    table.addCell(createRow("Model Number", model.getModelNumber(), null));
    table.addCell(createRow("Animal Type", model.getAnimalType(), null));
    table.addCell(createRow("Nomenclature", model.getNomenclatureParsed(), null));
    table.addCell(createRow("Application(s)", strAppList.toString(), null));
    table.addCell(createRow("Health Report", model.getHealthReport(), model.getHealthReport()));
    table.addCell(createRow("Species", model.getSpecies(), null));

    table.addCell(cell(createOrderButton(model)));

    return table;

}

From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java

License:Open Source License

private PdfPTable createOrderButton(Model model) throws IOException, BadElementException {

    final Chunk chunk = new Chunk("Order on taconic.com", iTextUtil.getFontButton());
    chunk.setAction(/*from   www  .  ja v  a  2 s . co  m*/
            new PdfAction("http://www.taconic.com/start-an-order?modelNumber=" + model.getModelNumber()));

    final PdfPCell cell = cell(new Phrase(chunk));
    cell.setBackgroundColor(iTextUtil.getTaconicRed());
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setPaddingTop(5);
    cell.setPaddingBottom(8);

    final PdfPTable button = new PdfPTable(new float[] { 80f, 20f });
    button.addCell(cell(new Phrase(" "), 2));
    button.addCell(cell);
    button.addCell(cell(new Phrase(" ")));
    button.addCell(cell(new Phrase(" "), 2));

    return button;
}

From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java

License:Open Source License

private PdfPCell createRow(String key, String value, String url) {
    final Paragraph paragraph = new Paragraph();
    paragraph.add(new Chunk(key, iTextUtil.getFontModelKey()));
    paragraph.add(new Chunk(": ", iTextUtil.getFontModelKey()));

    if (value == null) {
        value = "";
    }/*from   www .  ja  v a2  s. c  o m*/

    final Phrase valuePhrase = processHtmlCodes(value.trim(), iTextUtil.getFontModelValue(),
            iTextUtil.getFontModelSymbol());
    if (!StringUtils.isEmpty(url)) {
        for (Chunk chunk : valuePhrase.getChunks()) {
            chunk.setAction(new PdfAction(url));
        }
    }
    for (Chunk chunk : valuePhrase.getChunks()) {
        chunk.setLineHeight(13f);
    }
    paragraph.add(valuePhrase);

    final PdfPCell cell = cell(paragraph);
    cell.setPaddingBottom(5f);
    return cell;
}

From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java

License:Open Source License

private byte[] enableLinkToWebsite(byte[] pdf, Toc tableOfContents) throws IOException, DocumentException {

    try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

        final PdfReader reader = new PdfReader(pdf);

        final PdfStamper stamper = new PdfStamper(reader, bos);

        for (int i = tableOfContents.getFirstPageOfToc(); i <= tableOfContents
                .getLastPageNumberOfModelPages(); i++) {

            final Chunk websiteChunk = new Chunk("..................");
            websiteChunk.setAction(new PdfAction(websiteLink));

            ColumnText ct = new ColumnText(stamper.getUnderContent(i));
            ct.setSimpleColumn(335, 10, 400, 35);
            ct.addText(new Phrase(websiteChunk));
            ct.go();/*from w  ww.jav  a2s  . c o m*/

            final Chunk emailChunk = new Chunk(".........................................");
            emailChunk.setAction(new PdfAction(emailLink));

            ct = new ColumnText(stamper.getUnderContent(i));
            ct.setSimpleColumn(240, 10, 330, 35);
            ct.addText(new Phrase(emailChunk));
            ct.go();

        }

        stamper.close();
        reader.close();
        return bos.toByteArray();

    }

}

From source file:com.athena.chameleon.engine.core.PDFDocGenerator.java

License:Apache License

public static void setLastPageInfo(Document doc, PdfWriter writer, int cNum) throws Exception {
    Chapter chapter = PDFWriterUtil.getChapter(MessageUtil.getMessage("pdf.message.chapter.confirm.title"),
            cNum);/*from  ww w  .  ja  v  a2s  .  co m*/

    Paragraph preP = new Paragraph();
    preP.add(new Phrase(MessageUtil.getMessage("pdf.message.chapter.confirm.prepared1"),
            PDFWriterUtil.fnNormalBold));
    preP.add(new Phrase("                                                           ",
            new Font(bfKorean, 10, Font.UNDERLINE)));
    preP.setSpacingBefore(15);
    preP.setSpacingAfter(2);
    chapter.add(preP);

    preP = new Paragraph();
    preP.add(new Phrase(MessageUtil.getMessage("pdf.message.chapter.confirm.prepared2"),
            PDFWriterUtil.fnNormal));
    preP.setIndentationLeft(65);
    preP.setSpacingAfter(14);
    chapter.add(preP);

    preP = new Paragraph();
    preP.add(new Phrase(MessageUtil.getMessage("pdf.message.chapter.confirm.approved1"),
            PDFWriterUtil.fnNormalBold));
    preP.add(new Phrase("                                                           ",
            new Font(bfKorean, 10, Font.UNDERLINE)));
    preP.setSpacingBefore(15);
    preP.setSpacingAfter(2);
    chapter.add(preP);

    preP = new Paragraph();
    preP.add(new Phrase(MessageUtil.getMessage("pdf.message.chapter.confirm.approved2"),
            PDFWriterUtil.fnNormal));
    preP.setIndentationLeft(65);
    preP.setSpacingAfter(14);
    chapter.add(preP);

    cNum++;
    doc.add(chapter);

    chapter = PDFWriterUtil.getChapter(MessageUtil.getMessage("pdf.message.chapter.appendices.title"), cNum);
    Section section = PDFWriterUtil.getSection(chapter,
            MessageUtil.getMessage("pdf.message.chapter.appendices.label1"));

    Chunk url = new Chunk(MessageUtil.getMessage("pdf.message.chapter.appendices.text1"), PDFWriterUtil.fnURL);
    url.setAction(new PdfAction(new URL(MessageUtil.getMessage("pdf.message.chapter.appendices.text1"))));

    preP = new Paragraph(url);
    preP.setIndentationLeft(23);
    preP.setSpacingAfter(14);
    section.add(preP);

    section = PDFWriterUtil.getSection(chapter,
            MessageUtil.getMessage("pdf.message.chapter.appendices.label2"));

    doc.add(chapter);
}

From source file:com.athena.chameleon.engine.utils.PDFWriterUtil.java

License:Apache License

/**
 * /*from  w w  w  . ja  va  2s .c o  m*/
 * url Mapping
 *
 * @param e url   element
 * @return Chunk
 * @throws Exception
 */
public static Chunk getUrl(Element e) throws Exception {
    Chunk url = new Chunk(e.getText(), fnURL);
    url.setAction(new PdfAction(new URL(e.getText())));

    return url;
}

From source file:com.pdi.util.PdfGenerator.java

public static void generarPresupuesto(String lugar, Date fecha, float cantidad, String tipo, Cliente cliente,
        float precio, Aliado aliado, String path) {

    try {//from www.  j  a  v a2s.  co m

        NEGRITA_12_VERDE.setColor(145, 189, 57);

        long miliSemana = System.currentTimeMillis() + (86400 * 7 * 1000);
        Date vtoPresup = new Date(miliSemana);
        float precioPers = precio / cantidad;
        int precioTotalInt = Math.round(precio);
        int precioPersInt = Math.round(precioPers);
        int cantPersonasInt = Math.round(cantidad);

        //Referencia al objeto Doc
        Document document = new Document(PageSize.A4, //Dimensiones
                36, //margIzq
                36, //margDer
                36, //margenSup
                36); // margenInf

        //Creamos el archivo fisico
        FileOutputStream salida = new FileOutputStream(path);

        //Referencia e inicializacion del objeto que "escribe" el PDF
        PdfWriter writer = PdfWriter.getInstance(document, salida);
        writer.setInitialLeading(0);

        //Imagen Logo
        Image logoPDI = Image.getInstance("Logo PDI.png");
        logoPDI.scaleToFit(215, 205);
        logoPDI.setAlignment(Chunk.ALIGN_LEFT);
        //image.setAbsolutePosition(200, 200);

        //Imagen QR
        Image qr = Image.getInstance("QR PDI.png");
        qr.scaleToFit(211, 165);
        qr.setAbsolutePosition(295, PageSize.A4.getHeight() - 390);

        //Parrafo info evento
        Paragraph infoEvento = new Paragraph();
        infoEvento.add(new Chunk("Informacin del Evento", NEGRITA_SUB_12));
        infoEvento.add(Chunk.NEWLINE);
        infoEvento.add(negritaNormal("Solicitante: ", cliente.toString()));
        infoEvento.add(negritaNormal("Evento: ", tipo));
        infoEvento.add(negritaNormal("Cantidad de personas: ", Integer.toString(cantPersonasInt)));
        infoEvento.add(negritaNormal("Fecha: ", General.formatoFecha.format(fecha)));
        infoEvento.add(negritaNormal("Lugar:  ", lugar));
        infoEvento.add(Chunk.NEWLINE);
        infoEvento.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Modalidad del Servicio
        Paragraph modalidadServicio = new Paragraph();
        modalidadServicio.add(new Chunk("Modalidad Servicio Integral", NEGRITA_SUB_12));
        modalidadServicio.add(Chunk.NEWLINE);
        modalidadServicio.add(new Chunk("Nuestro servicio incluye la totalidad de lo referido a"
                + " los elementos necesarios para el despacho de bebidas: Barras, Bartenders,"
                + " Artculos de Coctelera, Insumos de calidad para los tragos y Mucha Buena Onda."
                + " Con esta modalidad aseguramos la expedicin de "
                + "los tragos desde las 00hs hasta las 05hs, para que se desentiendan del asunto "
                + "y disfruten al mximo.", NORMAL_12));
        modalidadServicio.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Ver Carta
        Paragraph verCarta = new Paragraph();
        verCarta.add(negritaNormal("\u2022 Carta de Tragos: ", "Ver archivo adjunto."));
        verCarta.setIndentationLeft(20);
        verCarta.add(Chunk.NEWLINE);
        verCarta.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Titulo Info Contratacion
        Paragraph infoContratacionTitulo = new Paragraph();
        infoContratacionTitulo.add(new Chunk("Informacin de Contratacin", NEGRITA_SUB_12));
        infoContratacionTitulo.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Inf de Contratacion
        Paragraph infoContratacion = new Paragraph();
        infoContratacion.add(negritaNormal("\u2022 Mtodo de contratacin y reserva de la fecha: ",
                "A travs de contrato firmado por ambas partes. "));
        Phrase lineaCosto = new Phrase();
        lineaCosto.add(new Chunk("\u2022 Costo: ", NEGRITA_12));
        lineaCosto.add(new Chunk("$" + Integer.toString(precioPersInt) + " ", NEGRITA_14));
        lineaCosto.add(new Chunk("por persona ", NEGRITA_12));
        lineaCosto.add(new Chunk("(Total: $" + Integer.toString(precioTotalInt) + ")", NEGRITA_14));
        infoContratacion.add(lineaCosto);
        infoContratacion.add(Chunk.NEWLINE);
        infoContratacion.add(negritaNormal("\u2022 Forma de Pago : ",
                "50% al momento de la firma del contrato y 50% como mximo una semana antes del evento. "));
        infoContratacion.add(Chunk.NEWLINE);
        infoContratacion.setIndentationLeft(20);
        infoContratacion.setFirstLineIndent(0);
        infoContratacion.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Despedida
        Paragraph despedida = new Paragraph();
        despedida.add(new Phrase("Quedamos al aguardo de tus comentarios,", NEGRITA_14));
        despedida.add(Chunk.NEWLINE);
        despedida.add(new Phrase("Muchas Gracias.", NEGRITA_14));
        despedida.add(Chunk.NEWLINE);
        despedida.add(Chunk.NEWLINE);
        despedida.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Firma
        Paragraph firma = new Paragraph();
        firma.add(new Phrase("Piel de Iguana Tragos.-", NEGRITA_CUR_14));
        firma.add(Chunk.NEWLINE);
        firma.add(new Phrase("Cel.: 3462-15337860", NEGRITA_12_VERDE));
        firma.setAlignment(Paragraph.ALIGN_RIGHT);

        float llxLink = 279;
        float llyLink = PageSize.A4.getHeight() - 145;
        float anchoLink = 199;
        float altoLink = 16;

        //Link al facebook
        URL urlPDI = new URL("https://www.facebook.com/pieldeiguanatragos.vt");
        PdfAction irAlFace = new PdfAction(urlPDI);
        Rectangle linkLocation = new Rectangle(llxLink, llyLink, llxLink + anchoLink, llyLink + altoLink);
        PdfAnnotation link = PdfAnnotation.createLink(writer, linkLocation, PdfAnnotation.HIGHLIGHT_NONE,
                irAlFace);
        link.setBorder(new PdfBorderArray(0, 0, 0));
        writer.addAnnotation(link);

        //Espacios Vacios
        Paragraph dosEspacios = new Paragraph();
        dosEspacios.add(Chunk.NEWLINE);
        dosEspacios.add(Chunk.NEWLINE);

        //Hay que abrir el Documento, llenarlo con los elemntos creados
        //en el orden que queremos y cerrarlo
        document.open();

        PdfContentByte cb = writer.getDirectContent();

        ColumnText ct = new ColumnText(cb);
        Phrase recuadro = new Phrase();
        recuadro.add(new Chunk("Piel de Iguana Tragos", NEGRITA_SUB_14));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("Servicio de tragos para eventos", NEGRITA_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("\"Piel de Iguana, para que tu noche nica sea inigualable.\"", NORMAL_CUR_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        Image logoFB = Image.getInstance("Icono FB.png");
        logoFB.scaleToFit(13, 13);
        recuadro.add(new Chunk(logoFB, 0, -3));
        recuadro.add(new Chunk("/pieldeiguanatragos.vt  -> Click Aqu!", NORMAL_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("Vencimiento del Prepuesto " + General.formatoFecha.format(vtoPresup),
                NORMAL_SUB_12));

        float llx = 279;
        float lly = PageSize.A4.getHeight() - 185;
        float ancho = 228;
        float alto = 150;

        ct.setSimpleColumn(recuadro, //Texto
                llx, //punta inf izquierda (x)
                lly, //punta inf izquierda (y) PageSize.A4.getHeight() - 185
                llx + ancho, //ancho del cuadro
                lly + alto, // alto del cuadro
                15, //espaciado
                Element.ALIGN_LEFT // Alineacion
        );

        ct.go();

        document.add(logoPDI);
        document.add(qr);
        document.add(dosEspacios);
        document.add(infoEvento);
        document.add(modalidadServicio);
        document.add(verCarta);
        document.add(infoContratacionTitulo);
        document.add(infoContratacion);
        document.add(despedida);
        document.add(firma);
        document.close();
        System.out.println("Archivo creado");
        int rta = JOptionPane.showConfirmDialog(VentanaMaestra.eventosCurrent,
                "Se guard el presupesto en:\n" + path + "\nDesea abrirlo?", "Presupuesto guardado",
                JOptionPane.YES_NO_OPTION);

        if (rta == JOptionPane.YES_OPTION) {
            if (Desktop.isDesktopSupported()) {
                try {
                    File myFile = new File(path);
                    Desktop.getDesktop().open(myFile);
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(VentanaMaestra.eventosCurrent,
                            "No se puede abrir el archivo. Ubiquelo en su equipo" + "y abralo manualmente.",
                            "Error al abrir el archivo", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(VentanaMaestra.eventosCurrent,
                        "No se puede abrir el archivo. Ubiquelo en su equipo" + "y abralo manualmente.",
                        "Error al abrir el archivo", JOptionPane.ERROR_MESSAGE);
            }

        }

    } catch (FileNotFoundException ex) {
        System.out.println("Error: " + ex.toString());
    } catch (DocumentException ex) {
        System.out.println("Error: " + ex.toString());
    } catch (IOException ex) {
        System.out.println("Error: " + ex.toString());
    }

}