Example usage for com.itextpdf.text Image setAbsolutePosition

List of usage examples for com.itextpdf.text Image setAbsolutePosition

Introduction

In this page you can find the example usage for com.itextpdf.text Image setAbsolutePosition.

Prototype


public void setAbsolutePosition(final float absoluteX, final float absoluteY) 

Source Link

Document

Sets the absolute position of the Image.

Usage

From source file:org.kalypso.ogc.gml.map.handlers.utils.PDFExporter.java

License:Open Source License

public IStatus doExport(final File targetFile, IProgressMonitor monitor) {
    /* If no monitor is given, take a null progress monitor. */
    if (monitor == null)
        monitor = new NullProgressMonitor();

    /* The output streams. */
    BufferedOutputStream os = null;

    try {//from  ww w  .  java2  s.c  om
        /* Monitor. */
        monitor.beginTask(Messages.getString("PDFExporter_0"), 1000); //$NON-NLS-1$
        monitor.subTask(Messages.getString("PDFExporter_1")); //$NON-NLS-1$

        /* Create the image. */
        final Insets insets = new Insets(10, 10, 10, 10);
        final BufferedImage image = MapModellHelper.createWellFormedImageFromModel(m_mapPanel,
                (int) PageSize.A4.getHeight(), (int) PageSize.A4.getWidth(), insets, 1);

        /* Convert to an itext image. */
        final Image img = Image.getInstance(image, null);

        /* Monitor. */
        monitor.worked(500);
        monitor.subTask(Messages.getString("PDFExporter_2")); //$NON-NLS-1$

        /* Create the output stream. */
        os = new BufferedOutputStream(new FileOutputStream(targetFile));

        /* Create a new document. */
        final Document document = new Document(
                new com.itextpdf.text.Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth()), 30, 30, 30,
                30);

        /* Create the pdf writter. */
        final PdfWriter writer = PdfWriter.getInstance(document, os);
        writer.setCompressionLevel(0);

        /* Open the document. */
        document.open();

        /* Set the position. */
        img.setAbsolutePosition(0, 0);

        /* Set to the pdf. */
        writer.getDirectContent().addImage(img, true);

        /* Close the document. */
        document.close();

        /* Monitor. */
        monitor.worked(500);

        return new Status(IStatus.OK, KalypsoGisPlugin.getId(), Messages.getString("PDFExporter_3")); //$NON-NLS-1$
    } catch (final Exception ex) {
        return new Status(IStatus.ERROR, KalypsoGisPlugin.getId(), ex.getLocalizedMessage(), ex);
    } finally {
        /* Close the output streams. */
        IOUtils.closeQuietly(os);

        /* Monitor. */
        monitor.done();
    }
}

From source file:org.obiba.mica.PdfUtils.java

License:Open Source License

public static void addImage(byte[] input, OutputStream output, Image image, String placeholder)
        throws IOException, DocumentException {
    try (PdfReaderAutoclosable pdfReader = new PdfReaderAutoclosable(input);
            PdfStamperAutoclosable pdfStamper = new PdfStamperAutoclosable(pdfReader, output)) {
        AcroFields form = pdfStamper.getAcroFields();
        List<AcroFields.FieldPosition> positions = form.getFieldPositions(placeholder);

        positions.forEach(p -> {//from ww  w  .  ja  v  a2  s  .c o m
            image.scaleToFit(p.position.getWidth(), p.position.getHeight());
            image.setAbsolutePosition(
                    p.position.getLeft() + (p.position.getWidth() - image.getScaledWidth()) / 2,
                    p.position.getBottom() + (p.position.getHeight() - image.getScaledHeight()) / 2);
            PdfContentByte cb = pdfStamper.getOverContent(p.page);

            try {
                cb.addImage(image);
            } catch (DocumentException e) {
                throw Throwables.propagate(e);
            }
        });
    }
}

From source file:org.orbisgis.mapcomposer.controller.utils.exportThreads.ExportPDFThread.java

License:Open Source License

@Override
public void run() {
    try {//w  w  w  .j  ava 2 s .com
        Document pdfDocument = null;
        //Find the Document GE to create the BufferedImage where all the GE will be drawn
        for (GraphicalElement ge : geIsVectorMap.keySet()) {
            if (ge instanceof org.orbisgis.mapcomposer.model.graphicalelement.element.Document) {
                pdfDocument = new Document(new Rectangle(ge.getWidth(), ge.getHeight()));
                height = ge.getHeight();
            }
        }
        //If no Document was created, throw an exception
        if (pdfDocument == null) {
            throw new IllegalArgumentException(i18n.tr(
                    "Error on export : The list of GraphicalElement to export does not contain any Document GE."));
        }
        //Open the document
        PdfWriter writer = PdfWriter.getInstance(pdfDocument, new FileOutputStream(path));
        writer.setUserProperties(true);
        writer.setRgbTransparencyBlending(true);
        writer.setTagged();
        pdfDocument.open();

        PdfContentByte cb = writer.getDirectContent();

        progressBar.setIndeterminate(true);
        progressBar.setStringPainted(true);
        progressBar.setString(i18n.tr("Exporting the document ..."));

        int geCount = 0;
        int numberOfGe[] = new int[geManager.getRegisteredGEClasses().size()];
        for (int i = 0; i < numberOfGe.length; i++) {
            numberOfGe[i] = 0;
        }
        //Draw each GraphicalElement in the BufferedImage
        for (GraphicalElement ge : geStack) {
            if ((ge instanceof org.orbisgis.mapcomposer.model.graphicalelement.element.Document))
                continue;

            double rad = Math.toRadians(ge.getRotation());
            double newHeight = Math.abs(sin(rad) * ge.getWidth()) + Math.abs(cos(rad) * ge.getHeight());
            double newWidth = Math.abs(sin(rad) * ge.getHeight()) + Math.abs(cos(rad) * ge.getWidth());

            int maxWidth = Math.max((int) newWidth, ge.getWidth());
            int maxHeight = Math.max((int) newHeight, ge.getHeight());

            String layerName = ge.getGEName()
                    + numberOfGe[geManager.getRegisteredGEClasses().indexOf(ge.getClass())];

            if (geIsVectorMap.get(ge)) {
                PdfTemplate pdfTemplate = cb.createTemplate(maxWidth, maxHeight);
                Graphics2D g2dTemplate = pdfTemplate.createGraphics(maxWidth, maxHeight);
                PdfLayer layer = new PdfLayer(layerName, writer);
                cb.beginLayer(layer);
                ((RendererVector) geManager.getRenderer(ge.getClass())).drawGE(g2dTemplate, ge);
                cb.addTemplate(pdfTemplate, ge.getX() + (ge.getWidth() - maxWidth) / 2,
                        -ge.getY() + height - ge.getHeight() + (ge.getHeight() - maxHeight) / 2);
                g2dTemplate.dispose();
                cb.endLayer();
            }

            else {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedImage bi = ((RendererRaster) geManager.getRenderer(ge.getClass())).createGEImage(ge,
                        null);
                ImageIO.write(bi, "png", baos);
                Image image = Image.getInstance(baos.toByteArray());
                image.setAbsolutePosition(ge.getX() + (ge.getWidth() - maxWidth) / 2,
                        -ge.getY() + height - ge.getHeight() + (ge.getHeight() - maxHeight) / 2);

                PdfTemplate pdfTemplate = cb.createTemplate(maxWidth, maxHeight);
                Graphics2D g2dTemplate = pdfTemplate.createGraphics(maxWidth, maxHeight);
                PdfLayer layer = new PdfLayer(layerName, writer);
                cb.beginLayer(layer);
                g2dTemplate.drawImage(bi, 0, 0, null);
                cb.addTemplate(pdfTemplate, ge.getX() + (ge.getWidth() - maxWidth) / 2,
                        -ge.getY() + height - ge.getHeight() + (ge.getHeight() - maxHeight) / 2);
                g2dTemplate.dispose();
                cb.endLayer();
            }
            numberOfGe[geManager.getRegisteredGEClasses().indexOf(ge.getClass())]++;

            progressBar.setIndeterminate(false);
            progressBar.setValue((geCount * 100) / geIsVectorMap.keySet().size());
            progressBar.revalidate();
            geCount++;
        }

        pdfDocument.close();
        //Wait a bit before erasing the progress bar
        progressBar.setValue(progressBar.getMaximum());
        progressBar.setString(i18n.tr("Document successfully exported."));
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            LoggerFactory.getLogger(ExportPDFThread.class).error(e.getMessage());
        }
        progressBar.setValue(0);
        progressBar.setStringPainted(false);

    } catch (IllegalArgumentException | IOException | DocumentException ex) {
        LoggerFactory.getLogger(ExportPDFThread.class).error(ex.getMessage());
    }
}

From source file:org.primaresearch.pdf.PageToPdfConverter.java

License:Apache License

/**
 * Adds the document page image to the current PDF page (spanning the whole page). 
 *///from   ww  w .j  a v a  2s .c  o m
private void addImage(String filepath, PdfWriter writer, Document doc, Page page)
        throws MalformedURLException, IOException, DocumentException {

    PdfContentByte cb = writer.getDirectContentUnder();
    cb.saveState();

    Image img = Image.getInstance(filepath);
    img.setAbsolutePosition(0f, 0f);
    //if (img.getScaledWidth() > 300 || img.getScaledHeight() > 300) {
    //img.scaleToFit(300, 300);
    //}
    img.scaleToFit(page.getLayout().getWidth(), page.getLayout().getHeight());

    cb.addImage(img);

    cb.restoreState();

}

From source file:org.smap.sdal.managers.PDFSurveyManager.java

License:Open Source License

private void fillTemplate(GlobalVariables gv, AcroFields pdfForm, ArrayList<Result> record, String basePath,
        String formName, int repeatIndex, String serverRoot, PdfStamper stamper, int oId)
        throws IOException, DocumentException {
    try {/*from   ww w . j a  v  a 2 s.  c o  m*/

        for (Result r : record) {

            String value = "";
            boolean hideLabel = false;
            String fieldName = getFieldName(formName, repeatIndex, r.name);
            String fieldNameQR = getFieldName(formName, repeatIndex, r.name + "_qr");

            DisplayItem di = new DisplayItem();
            try {
                Form form = survey.forms.get(r.fIdx);
                Question question = getQuestionFromResult(sd, r, form);
                setQuestionFormats(question.appearance, di);
            } catch (Exception e) {
                // If we can't get the question details for this data then that is ok
            }

            /*
             * Set the value based on the result
             * Process subforms if this is a repeating group
             */
            if (r.type.equals("form")) {
                for (int k = 0; k < r.subForm.size(); k++) {
                    fillTemplate(gv, pdfForm, r.subForm.get(k), basePath, fieldName, k, serverRoot, stamper,
                            oId);
                }
            } else if (r.type.equals("select1")) {

                Form form = survey.forms.get(r.fIdx);
                Question question = form.questions.get(r.qIdx);

                ArrayList<String> matches = new ArrayList<String>();
                matches.add(r.value);
                value = choiceManager.getLabel(sd, cResults, user, oId, survey.id, question.id, question.l_id,
                        question.external_choices, question.external_table,
                        survey.languages.get(languageIdx).name, languageIdx, matches, survey.ident);

            } else if (r.type.equals("select")) {

                String nameValue = r.value;
                if (nameValue != null) {
                    String vArray[] = nameValue.split(" ");
                    ArrayList<String> matches = new ArrayList<String>();
                    if (vArray != null) {
                        for (String v : vArray) {
                            matches.add(v);
                        }
                    }
                    Form form = survey.forms.get(r.fIdx);
                    Question question = form.questions.get(r.qIdx);
                    value = choiceManager.getLabel(sd, cResults, user, oId, survey.id, question.id,
                            question.l_id, question.external_choices, question.external_table,
                            survey.languages.get(languageIdx).name, languageIdx, matches, survey.ident);
                }

            } else if (r.type.equals("dateTime") || r.type.equals("timestamp")) {

                value = null;
                if (r.value != null) {
                    // Convert date to local time
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    df.setTimeZone(TimeZone.getTimeZone("UTC"));
                    Date date = df.parse(r.value);
                    df.setTimeZone(TimeZone.getTimeZone(tz));
                    value = df.format(date);
                    log.info("Convert date to local time (template): " + r.name + " : " + r.value + " : "
                            + " : " + value + " : " + r.type + " : " + tz);
                }

            } else {
                value = r.value;
            }

            /*
             * Add the value to the form
             * Alternatively remove the fieldName if the value is empty.
             */
            if (value == null || value.trim().equals("")) {
                try {
                    pdfForm.removeField(fieldName);
                } catch (Exception e) {
                    log.info("Error removing field: " + fieldName + ": " + e.getMessage());
                }

            } else if (r.type.equals("geopoint") || r.type.equals("geoshape") || r.type.equals("geotrace")
                    || r.type.startsWith("geopolygon_") || r.type.startsWith("geolinestring_")) {

                PushbuttonField ad = pdfForm.getNewPushbuttonFromField(fieldName);
                if (ad != null) {
                    Image img = PdfUtilities.getMapImage(sd, di.map, r.value, di.location, di.zoom,
                            gv.mapbox_key, survey.id, user, di.markerColor);
                    PdfUtilities.addMapImageTemplate(pdfForm, ad, fieldName, img);
                } else {
                    log.info("No field for image (Mapbox not called: " + fieldName);
                }

            } else if (r.type.equals("image") || r.type.equals("video") || r.type.equals("audio")) {
                PdfUtilities.addImageTemplate(pdfForm, fieldName, basePath, value, serverRoot, stamper,
                        defaultFontLink);

            } else {
                if (hideLabel) {
                    try {
                        pdfForm.removeField(fieldName);
                    } catch (Exception e) {
                        log.info("Error removing field: " + fieldName + ": " + e.getMessage());
                    }
                } else {
                    if (di.isBarcode) {
                        PushbuttonField ad = pdfForm.getNewPushbuttonFromField(fieldName);
                        if (ad != null) {
                            BarcodeQRCode qrcode = new BarcodeQRCode(value.trim(), 1, 1, null);
                            Image qrcodeImage = qrcode.getImage();
                            qrcodeImage.setAbsolutePosition(10, 500);
                            qrcodeImage.scalePercent(200);
                            PdfUtilities.addMapImageTemplate(pdfForm, ad, fieldName, qrcodeImage);
                        }
                    } else {
                        pdfForm.setField(fieldName, value);

                    }
                }
            }

            /*
             * Add any QR code values to fields that have been identified using the QR suffix
             */
            if (fieldNameQR != null && value != null && value.trim().length() > 0) {
                PushbuttonField ad = pdfForm.getNewPushbuttonFromField(fieldName);
                if (ad != null) {
                    BarcodeQRCode qrcode = new BarcodeQRCode(value.trim(), 1, 1, null);
                    Image qrcodeImage = qrcode.getImage();
                    qrcodeImage.setAbsolutePosition(10, 500);
                    qrcodeImage.scalePercent(200);
                    PdfUtilities.addMapImageTemplate(pdfForm, ad, fieldNameQR, qrcodeImage);
                }
            }

        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Error filling template", e);
    }
}

From source file:org.smap.sdal.managers.PDFSurveyManager.java

License:Open Source License

private void updateValueCell(Parser parser, String remoteUser, PdfPCell valueCell, DisplayItem di,
        boolean generateBlank, String basePath, String serverRoot, GlobalVariables gv, int oId)
        throws Exception {

    // Questions that append their values to this question
    ArrayList<String> deps = gv.addToList.get(di.fIdx + "_" + di.rec_number + "_" + di.name);

    if (di.type.startsWith("select")) {
        processSelect(parser, remoteUser, valueCell, di, generateBlank, gv, oId);
    } else if (di.type.equals("image")) {
        if (di.value != null && !di.value.trim().equals("") && !di.value.trim().equals("Unknown")) {
            if (di.isHyperlink) {
                Anchor anchor = new Anchor(serverRoot + di.value);
                anchor.setReference(serverRoot + di.value);

                valueCell.addElement(getPara("", di, gv, deps, anchor));
            } else {
                try {
                    Image img = Image.getInstance(basePath + "/" + di.value);
                    valueCell.addElement(img);
                } catch (Exception e) {
                    log.info("Error: image " + basePath + "/" + di.value + " not added: " + e.getMessage());
                    log.log(Level.SEVERE, "Adding image to pdf", e);
                }//  ww w  . j av  a 2  s  . c o  m
            }

        } else {
            // TODO add empty image
        }

    } else if (di.type.equals("video") || di.type.equals("audio")) {
        if (di.value != null && !di.value.trim().equals("") && !di.value.trim().equals("Unknown")) {
            Anchor anchor = new Anchor(serverRoot + di.value);
            anchor.setReference(serverRoot + di.value);

            valueCell.addElement(getPara("", di, gv, deps, anchor));

        } else {
            // TODO add empty image
        }

    } else if (di.type.equals("geopoint") || di.type.equals("geoshape") || di.type.equals("geotrace")
            || di.type.startsWith("geopolygon_") || di.type.startsWith("geolinestring_")) {

        Image img = PdfUtilities.getMapImage(sd, di.map, di.value, di.location, di.zoom, gv.mapbox_key,
                survey.id, user, di.markerColor);

        if (img != null) {
            valueCell.addElement(img);
        } else {
            valueCell.addElement(getPara(" ", di, gv, deps, null));
        }

    } else if (di.isBarcode) {
        BarcodeQRCode qrcode = new BarcodeQRCode(di.value.trim(), 1, 1, null);
        Image qrcodeImage = qrcode.getImage();
        qrcodeImage.setAbsolutePosition(10, 500);
        qrcodeImage.scalePercent(200);

        valueCell.addElement((qrcodeImage));

    } else {
        // Todo process other question types
        String value = null;

        if (di.value == null || di.value.trim().length() == 0) {
            value = " "; // Need a space to show a blank row
        } else {
            if (di.value != null && di.value.length() > 0) {
                if (GeneralUtilityMethods.isRtlLanguage(di.value)) {
                    valueCell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
                }
            }

            if (di.type.equals("dateTime") || di.type.equals("timestamp")) { // Set date time to local time

                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                df.setTimeZone(TimeZone.getTimeZone("UTC"));
                Date date = df.parse(di.value);
                df.setTimeZone(TimeZone.getTimeZone(tz));
                value = df.format(date);
                log.info("Convert date to local time: " + di.name + " : " + di.value + " : " + " : " + value
                        + " : " + di.type + " : " + tz);
            } else {
                value = di.value;
            }

        }
        valueCell.addElement(getPara(value, di, gv, deps, null));
    }
}

From source file:org.smap.sdal.managers.PDFTableManager.java

License:Open Source License

private PdfPCell addDisplayItem(Parser parser, KeyValue kv, String basePath, boolean barcode, String type)
        throws BadElementException, MalformedURLException, IOException {

    PdfPCell valueCell = new PdfPCell();
    valueCell.setBorderColor(BaseColor.LIGHT_GRAY);

    // Set the content of the value cell
    try {//  www. j a  v  a2s . c  o m
        if (type != null && type.equals("image")) {
            Image img = Image.getInstance(kv.v);
            valueCell.addElement(img);
        } else if (barcode && kv.v.trim().length() > 0) {
            BarcodeQRCode qrcode = new BarcodeQRCode(kv.v.trim(), 1, 1, null);
            Image qrcodeImage = qrcode.getImage();
            qrcodeImage.setAbsolutePosition(10, 500);
            qrcodeImage.scalePercent(200);
            valueCell.addElement((qrcodeImage));
        } else {
            valueCell.addElement(getPara(kv.v));
        }
    } catch (Exception e) {
        log.info("Error updating value cell, continuing: " + basePath + " : " + kv.v);
        log.log(Level.SEVERE, "Exception", e);
    }

    return valueCell;
}

From source file:org.yale.cs.graphics.gephi.imagepreview.ImageNodes.java

License:Open Source License

public void renderImagePDF(ImageItem item, PDFTarget target, PreviewProperties properties, File directory) {

    Image image = item.renderPDF(directory);

    if (image == null) {
        logger.log(Level.WARNING, "Unable to load image: {0}", item.getSource());
        return;/*from w  w  w.  ja v a2 s.c om*/
    }

    Float x = item.getData(NodeItem.X);
    Float y = item.getData(NodeItem.Y);
    Float size = item.getData(NodeItem.SIZE);

    float alpha = properties.getFloatValue(IMAGE_OPACITY) / 100f;

    PdfContentByte cb = target.getContentByte();

    if (alpha < 1f) {
        cb.saveState();
        PdfGState gState = new PdfGState();
        gState.setFillOpacity(alpha);
        gState.setStrokeOpacity(alpha);
        cb.setGState(gState);
    }

    image.setAbsolutePosition(x - size / 2, -y - size / 2);
    image.scaleToFit(size, size);
    try {
        cb.addImage(image);
    } catch (DocumentException ex) {
        logger.log(Level.SEVERE, "Unable to add image to document: " + item.getSource(), ex);
    }

    if (alpha < 1f) {
        cb.restoreState();
    }
}

From source file:PDF.CrearPDF_Ficha.java

public void generarPDF(ServletOutputStream sops, DatosPDF datos, String url) {

    try {/* w w  w .  ja  v  a  2  s. co m*/

        Document documento = new Document();
        //            ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(documento, sops);
        documento.open();

        Image itt_logo;
        try {
            itt_logo = Image.getInstance(url);
            Image Logo_itt = Image.getInstance(itt_logo);
            Logo_itt.setAbsolutePosition(50f, 698f);
            Logo_itt.scaleAbsolute(90, 100);
            documento.add(Logo_itt);
        } catch (BadElementException | IOException ex) {
            Logger.getLogger(CrearPDF_Ficha.class.getName()).log(Level.SEVERE, null, ex);
        }

        PdfContentByte rectangulo_info = writer.getDirectContentUnder();
        drawRectangle(rectangulo_info, 430, 648, 90, 100);
        Paragraph leyendaFoto = new Paragraph("\nFOTO:\n", FontFactory.getFont("arial", 14, Font.BOLD));
        leyendaFoto.setIndentationLeft(200f);
        Paragraph titulo = new Paragraph("INSTITUTO TECNOLGICO DE TOLUCA", FontFactory.getFont("arial", 14));
        titulo.setAlignment(Element.ALIGN_CENTER);

        Paragraph asunto = new Paragraph("FICHA DE EXAMEN", FontFactory.getFont("arial", 12));
        asunto.setAlignment(Element.ALIGN_CENTER);

        Chunk folio1 = new Chunk("FICHA PARA EL EXAMEN DE ADMISIN: ", FontFactory.getFont("arial", 10));
        Chunk folio2 = new Chunk(datos.getFicha(), FontFactory.getFont("arial", 10, Font.BOLD));

        Phrase fol = new Phrase();
        fol.add(folio1);
        fol.add(folio2);

        Paragraph noFicha = new Paragraph(fol);
        noFicha.setAlignment(Element.ALIGN_LEFT);

        Chunk nombre1 = new Chunk("NOMBRE DEL SOLICITANTE: ", FontFactory.getFont("arial", 10));
        Chunk nombre2 = new Chunk(datos.getNombre(), FontFactory.getFont("arial", 10, Font.BOLD));

        Phrase nom = new Phrase();
        nom.add(nombre1);
        nom.add(nombre2);

        Paragraph nombre = new Paragraph(nom);
        nombre.setAlignment(Element.ALIGN_LEFT);

        Chunk in1 = new Chunk("PROCESO PARA EL REGISTRO DE ASPIRANTES EN EL PERIODO: ",
                FontFactory.getFont("arial", 10));
        Chunk in2 = new Chunk(datos.getPeriodoConcursa().toUpperCase(),
                FontFactory.getFont("arial", 10, Font.BOLD));

        Phrase in = new Phrase();
        in.add(in1);
        in.add(in2);

        Paragraph instrucciones = new Paragraph(in);
        instrucciones.setAlignment(Element.ALIGN_LEFT);

        Chunk folCen1 = new Chunk("1.- NMERO DE FOLIO CENEVAL: ", FontFactory.getFont("arial", 10));
        Chunk folCen2 = new Chunk(datos.getFolioCENEVAL(), FontFactory.getFont("arial", 10, Font.BOLD));

        Phrase folC = new Phrase();
        folC.add(folCen1);
        folC.add(folCen2);

        Paragraph folioCENEVAL = new Paragraph(folC);
        folioCENEVAL.setAlignment(Element.ALIGN_LEFT);

        Chunk fechas1 = new Chunk("2.- LOS EX?MENES DE ADMISIN SE APLICAR?N LOS D?AS: ",
                FontFactory.getFont("arial", 10));
        Chunk fechas2 = new Chunk(datos.getFechaExamenCeneval() + " (" + datos.getLugarExamenCeneval() + ")",
                FontFactory.getFont("arial", 10, Font.BOLD));
        Chunk fechas3 = new Chunk(" Y ", FontFactory.getFont("arial", 10));
        Chunk fechas4 = new Chunk(datos.getFechaExamenMate() + " (" + datos.getLugarExamenMate() + ")",
                FontFactory.getFont("arial", 10, Font.BOLD));

        Phrase fechas = new Phrase();
        fechas.add(fechas1);
        fechas.add(fechas2);
        fechas.add(fechas3);
        fechas.add(fechas4);

        Paragraph fechaExamenes = new Paragraph(fechas);
        fechaExamenes.setAlignment(Element.ALIGN_LEFT);

        Phrase lugar = new Phrase();

        Paragraph lugarYhora = new Paragraph(lugar);
        lugarYhora.setAlignment(Element.ALIGN_LEFT);

        Chunk paginaPub1 = new Chunk(
                "3.- LA PUBLICACIN DE LOS RESULTADOS SER? NICAMENTE EN LA P?GINA WEB: ",
                FontFactory.getFont("arial", 10));

        Anchor url_itt = new Anchor(datos.getPagResultados());
        url_itt.setReference(datos.getPagResultados());

        Phrase pag = new Phrase();
        pag.add(paginaPub1);
        pag.add(url_itt);

        Paragraph pagWeb = new Paragraph(pag);

        Chunk diaPub1 = new Chunk("EL D?A: ", FontFactory.getFont("arial", 10));
        Chunk diaPub2 = new Chunk(convertir(datos.getDiaPublicacion() + "-"),
                FontFactory.getFont("arial", 10, Font.BOLD));

        Phrase dia = new Phrase();
        dia.add(diaPub1);
        dia.add(diaPub2);

        Paragraph diaResultados = new Paragraph(dia);
        diaResultados.setAlignment(Element.ALIGN_LEFT);

        Chunk notas = new Chunk("\nNOTAS:\n", FontFactory.getFont("arial", 14, Font.BOLD));

        Chunk uno = new Chunk("1.- ", FontFactory.getFont("arial", 10, Font.BOLD));

        Chunk guias = new Chunk("Guas de estudio:\n   - (CENEVAL) \n", FontFactory.getFont("arial", 10));

        Anchor url_guia_cen = new Anchor("     " + datos.getEstudioCeneval());
        // url_guia_cen.setReference(datos.getEstudioCeneval());

        Chunk ceneval_inter = new Chunk("\n   - (CENEVAL INTERACTIVA) \n", FontFactory.getFont("arial", 10));

        Anchor url_guia_cen_inter = new Anchor("     " + datos.getEstudioCenevalInt());
        url_guia_cen_inter.setReference(datos.getEstudioCenevalInt());

        Chunk tem_mate_itt = new Chunk("\n   - Temario de Matemticas (TECNOLGICO DE TOLUCA)\n\n",
                FontFactory.getFont("arial", 10));
        Chunk dos = new Chunk("2.- ", FontFactory.getFont("arial", 10, Font.BOLD));
        Chunk veri = new Chunk("Verifique que el nmero de folio de Ceneval de esta ficha, coincida con el",
                FontFactory.getFont("arial", 10));
        Chunk fol_ceneval = new Chunk(" FOLIO CENEVAL ", FontFactory.getFont("arial", 10, Font.BOLD));
        Chunk capturado = new Chunk("capturado en la informacin proporcionada por el Tecnlogico.\n\n",
                FontFactory.getFont("arial", 10));
        Chunk tres = new Chunk("3.- ", FontFactory.getFont("arial", 10, Font.BOLD));
        Chunk dia_exam = new Chunk(
                "El da del examen deber presentarse con el presente documento, pase de ingreso al examen(Ceneval), una identificacin con fotografa reciente(credencial escolar, IMSS, ISSSTE, ISSEMYM, licencia, pasaporte), lpiz del nmero 2 y goma.\n\n",
                FontFactory.getFont("arial", 10));
        Chunk cuatro = new Chunk("4.- ", FontFactory.getFont("arial", 10, Font.BOLD));
        Chunk curso = new Chunk(
                "Si curs sus estudios de secundaria o bachillerato en el extranjero deber presentar revalidacin de estudios correspondientes al momento de la inscripcin.\n",
                FontFactory.getFont("arial", 10));
        Chunk cinco = new Chunk("\n5.- ", FontFactory.getFont("arial", 10, Font.BOLD));
        Chunk examenes = new Chunk(
                "Los exmenes que se evaluarn son:       1) ADMISIN Y DIAGNSTICO.     2) MATEM?TICAS.",
                FontFactory.getFont("arial", 10));

        Phrase ulti = new Phrase();
        ulti.add(notas);
        ulti.add(uno);
        ulti.add(guias);
        ulti.add(url_guia_cen);
        ulti.add(ceneval_inter);
        ulti.add(url_guia_cen_inter);
        ulti.add(tem_mate_itt);
        ulti.add(dos);
        ulti.add(veri);
        ulti.add(fol_ceneval);
        ulti.add(capturado);
        ulti.add(tres);
        ulti.add(dia_exam);
        ulti.add(cuatro);
        ulti.add(curso);
        ulti.add(cinco);
        ulti.add(examenes);

        Paragraph ultimo = new Paragraph(ulti);
        ultimo.setAlignment(Element.ALIGN_LEFT);

        documento.addTitle("Ficha de Examen");
        documento.addSubject("Instituto Tecnolgico de Toluca");
        documento.addKeywords("Instituto Tecnolgico de Toluca");
        documento.addAuthor("Departamento de Servicios escolares");
        documento.addCreator("Departamento de Servicios escolares");
        documento.add(titulo);
        documento.add(asunto);
        documento.add(new Paragraph(" "));
        documento.add(new Paragraph(" "));
        documento.add(new Paragraph(" "));
        documento.add(new Paragraph(" "));
        documento.add(new Paragraph(" "));

        documento.add(noFicha);
        documento.add(nombre);
        documento.add(new Paragraph(" "));
        documento.add(instrucciones);
        documento.add(new Paragraph(" "));
        documento.add(folioCENEVAL);
        documento.add(fechaExamenes);
        documento.add(lugarYhora);
        documento.add(pagWeb);
        documento.add(diaResultados);
        documento.add(new Paragraph(" "));
        documento.add(ultimo);

        documento.close();
    } catch (DocumentException ex) {
        Logger.getLogger(CrearPDF_Ficha.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:pdf.watermark.java

License:Open Source License

public watermark() {
    try {//  w w  w .ja  v  a2  s .  co m
        PdfReader Read_PDF_To_Watermark = new PdfReader(
                "D:\\Dropbox\\Studium\\Bachelor Thesis\\Resourcen\\pdfexport\\xmltopdf\\test.pdf");
        int number_of_pages = Read_PDF_To_Watermark.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(Read_PDF_To_Watermark, new FileOutputStream(
                "D:\\Dropbox\\Studium\\Bachelor Thesis\\Resourcen\\pdfexport\\xmltopdf\\New_PDF_With_Watermark_Image.pdf"));
        int i = 0;
        Image watermark_image = Image
                .getInstance("D:\\Dropbox\\Studium\\Bachelor Thesis\\Resourcen\\pdfexport\\xmltopdf\\desy.png");
        watermark_image.setAbsolutePosition(50, 150);
        watermark_image.scaleToFit(500, 500);
        PdfContentByte add_watermark;
        while (i < number_of_pages) {
            i++;
            add_watermark = stamp.getUnderContent(i);
            add_watermark.addImage(watermark_image);
        }
        stamp.close();
    } catch (IOException | DocumentException i1) {
        i1.printStackTrace();
    }
}