Example usage for com.lowagie.text Image getInstance

List of usage examples for com.lowagie.text Image getInstance

Introduction

In this page you can find the example usage for com.lowagie.text Image getInstance.

Prototype

public static Image getInstance(PdfContentByte cb, java.awt.Image awtImage, float quality)
        throws BadElementException, IOException 

Source Link

Document

Gets an instance of a Image from a java.awt.Image.

Usage

From source file:org.goobi.presentation.contentservlet.controller.GetPdfMultiMetsAction.java

License:Apache License

/************************************************************************************
 * exectute multiple mets handling and generation of one pdf file from it to send it back to output stream of the servlet, after setting correct
 * mime type/*from  ww  w .  ja  va2s .  com*/
 * 
 * @param request {@link HttpServletRequest} of ServletRequest
 * @param response {@link HttpServletResponse} for writing to response output stream
 * @throws IOException
 * @throws ServletException
 * @throws ContentLibException
 * @throws URISyntaxException
 * @throws CacheException
 ************************************************************************************/
@Override
public void run(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ContentLibException, URISyntaxException, CacheException {

    /* first of all validation */
    validateParameters(request);

    /*
     * -------------------------------- get central configuration and --------------------------------
     */
    ContentServerConfiguration config = ContentServerConfiguration.getInstance();
    OutputStream myOutStream = response.getOutputStream();
    setTargetNameAndMimeType(request, response, config);
    Watermark myWatermark = null;
    /* get mets filegroup from request or from configuration */
    String strMetsFileGroup = request.getParameter("metsFileGroup");
    if (strMetsFileGroup == null) {
        strMetsFileGroup = config.getDefaultMetsFileGroup();
    }

    try {
        if (config.getWatermarkUse()) {

            File watermarkfile = new File(new URI(config.getWatermarkConfigFilePath()));
            if (request.getParameterMap().containsKey("watermarkText")) {
                myWatermark = new Watermark(watermarkfile, request.getParameter("watermarkText"));
            } else {
                myWatermark = new Watermark(watermarkfile);
            }

        }
        // defining the DocumentPart-List
        LinkedList<DocumentPart> documentparts = new LinkedList<DocumentPart>();

        /* define title page, if configured */
        PDFTitlePage titlepage = new PDFTitlePage();
        if (config.getPdfTitlePageUse()) {
            titlepage.readConfiguration(config.getPdfTitlePageConfigFile());
        }

        /* run through all Documentparts in parameter 'files' */
        StrTokenizer stdocuments = new StrTokenizer(request.getParameter("files"), "$$");
        while (stdocuments.hasNext()) {
            /* get all parameters from each Documentpart */
            StrTokenizer docparams = new StrTokenizer(stdocuments.nextToken(), "$");

            /* create DocumentPart */
            String doctype = docparams.nextToken();
            URL url = new URL(config.getRepositoryPathMets() + docparams.nextToken());
            // URL url2 = new URL("http://gdz.sub.uni-goettingen.de/mets_export.php?PPN=PPN271629789");
            DocumentPart dp;
            if (doctype.equals("pdf")) {
                dp = new DocumentPart(url, DocumentPartType.PDF);
            } else {
                dp = new DocumentPart(url, DocumentPartType.METS);
                dp.setMetsFileGroup(strMetsFileGroup);
            }

            /* possibly a divid */
            if (docparams.size() == 3) {
                dp.setDivid(docparams.nextToken());
            }

            /* if titlepage should be used, add it now to documentpart */
            if (config.getPdfTitlePageUse()) {
                dp.setTitlepage(titlepage.clone());
            }

            /* add documentpart to list */
            documentparts.add(dp);
        }

        // create metadata extractor
        SimplePDFMetadataExtractor spme = new SimplePDFMetadataExtractor();
        // create bookmark extractor
        StructureMetadataExtractor bmke = new SimpleStructureMetadataExtractor();
        // create PDF Manager
        PDFCreator pdfcreator = new PDFCreator();

        PDFConfiguration pdfconfig = new PDFConfiguration();
        File iccfile = new File(Util.getBaseFolderAsFile(), "sRGB.icc");
        pdfconfig.setIccinputfilename(iccfile.getAbsolutePath());
        pdfconfig.setPagesize(getPageSize(request));
        pdfconfig.setPdfDefaultAlwaysCompressToJPEG(config.getPdfDefaultAlwaysCompressToJPEG());
        pdfconfig.setPdfDefaultAlwaysUseRenderedImage(config.getPdfDefaultAlwaysUseRenderedImage());
        boolean pdfa = Boolean.parseBoolean(getParameterFromRequestOrConfig("writeAsPdfA", request));
        pdfconfig.setWriteAsPdfA(pdfa);

        pdfcreator.createPDF(myOutStream, documentparts, pdfconfig, spme, bmke, myWatermark);
    } catch (Exception e) {
        LOGGER.error("error while multiple files to pdf generation (" + e.getClass().getName() + ")", e);
        Document pdfdoc = new Document();
        PdfWriter writer;
        try {
            writer = PdfWriter.getInstance(pdfdoc, myOutStream);
        } catch (DocumentException e1) {
            throw new ContentLibException("wrapped DocumentException", e1);
        }
        pdfdoc.open();

        /*---------------------------------
         * Generate Watermark
         *---------------------------------*/
        String errorString = e.getClass().getName() + ": " + e.getMessage();
        String jpgfile = new File(Util.getBaseFolderAsFile(), "errorfile.jpg").getAbsolutePath();
        LOGGER.debug("errorfile to embedd: " + jpgfile);
        FileInputStream inputFileStream = new FileInputStream(jpgfile);
        RenderedImage ri = ServletWatermark.generateErrorWatermark(inputFileStream, errorString)
                .getRenderedImage();

        /*
         * -------------------------------- prepare target and read created image --------------------------------
         */
        BufferedImage buffImage = ImageManipulator.fromRenderedToBuffered(ri);
        Image pdfImage;
        try {
            pdfImage = Image.getInstance(buffImage, null, false);
            pdfdoc.add(pdfImage);
        } catch (BadElementException e1) {
            LOGGER.error("error while adding pdfImage", e);
            throw new ContentLibException("wrapped BadElementException", e1);
        } catch (DocumentException e2) {
            LOGGER.error("error while adding pdfImage", e);
            throw new ContentLibException("wrapped DocumentException", e2);
        }
        /*
         * -------------------------------- close all --------------------------------
         */
        try {
            inputFileStream.close();
            pdfdoc.close();
            writer.close();
        } catch (Error e2) {
            LOGGER.warn("Caught unknown error when closing the pdf writer. Probably due to a broken pipe");
        } finally {
            myOutStream.flush();
            myOutStream.close();
        }
    } finally {
        if (myOutStream != null) {
            myOutStream.flush();
            myOutStream.close();
        }
    }
}

From source file:org.lucee.extension.pdf.tag.PDF.java

License:Open Source License

private void doActionAddWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "addWatermark", "source", source);
    if (copyFrom == null && image == null)
        throw engine.getExceptionUtil().createApplicationException(
                "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
        throw engine.getExceptionUtil()
                .createApplicationException("destination file [" + destination + "] already exists");

    // image/*from  w  w  w .  jav a2  s .  c  om*/
    Image img = null;
    if (image != null) {
        // TODO lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext,image,false,false,true,null);
        // TODO img=Image.getInstance(ri.getBufferedImage(),null,false);
    }
    // copy From
    else {
        byte[] barr;
        try {
            Resource res = copyFrom instanceof String
                    ? engine.getResourceUtil().toResourceExisting(pageContext, (String) copyFrom)
                    : engine.getCastUtil().toResource(copyFrom);
            barr = PDFUtil.toBytes(res);
        } catch (PageException ee) {
            barr = engine.getCastUtil().toBinary(copyFrom);
        }
        img = Image.getInstance(PDFUtil.toImage(barr, 1), null, false);

    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!Util.isEmpty(position)) {
        int index = position.indexOf(',');
        if (index == -1)
            throw engine.getExceptionUtil()
                    .createApplicationException("attribute [position] has an invalid value [" + position + "],"
                            + "value should follow one of the following pattern [40,50], [40,] or [,50]");
        String strX = position.substring(0, index).trim();
        String strY = position.substring(index + 1).trim();
        if (!Util.isEmpty(strX))
            x = engine.getCastUtil().toIntValue(strX);
        if (!Util.isEmpty(strY))
            y = engine.getCastUtil().toIntValue(strY);

    }

    PDFStruct doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null)
        master.addAll(bookmarks);

    // output
    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    OutputStream os = null;
    if (!Util.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }

    try {

        int len = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, os);

        if (len > 0) {
            if (x == UNDEFINED || y == UNDEFINED) {
                PdfImportedPage first = stamp.getImportedPage(reader, 1);
                if (y == UNDEFINED)
                    y = (first.getHeight() - img.getHeight()) / 2;
                if (x == UNDEFINED)
                    x = (first.getWidth() - img.getWidth()) / 2;
            }
            img.setAbsolutePosition(x, y);
            // img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte

        }

        // rotation
        if (rotation != 0) {
            img.setRotationDegrees(rotation);
        }

        Set _pages = doc.getPages();
        for (int i = 1; i <= len; i++) {
            if (_pages != null && !_pages.contains(Integer.valueOf(i)))
                continue;
            PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
            PdfGState gs1 = new PdfGState();
            // print.out("op:"+opacity);
            gs1.setFillOpacity(opacity);
            // gs1.setStrokeOpacity(opacity);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        Util.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
                        destination, true);// MUST overwrite
            if (!Util.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:org.lucee.extension.pdf.tag.PDF.java

License:Open Source License

private void doActionRemoveWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "removeWatermark", "source", source);

    if (destination != null && destination.exists() && !overwrite)
        throw engine.getExceptionUtil()
                .createApplicationException("destination file [" + destination + "] already exists");

    BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    g.setBackground(Color.BLACK);
    g.clearRect(0, 0, 1, 1);//w  ww.  j ava2 s. co  m

    Image img = Image.getInstance(bi, null, false);
    img.setAbsolutePosition(1, 1);

    PDFStruct doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();

    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null)
        master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!Util.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }

    try {
        int len = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, os);

        Set _pages = doc.getPages();
        for (int i = 1; i <= len; i++) {
            if (_pages != null && !_pages.contains(Integer.valueOf(i)))
                continue;
            PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
            PdfGState gs1 = new PdfGState();
            gs1.setFillOpacity(0);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        Util.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
                        destination, true);// MUST overwrite
            if (!Util.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:ugh.fileformats.pdf.PortableDocumentFormat.java

License:Open Source License

/***************************************************************************
 * @param document/*from   www  .  j  av  a2s. co m*/
 * @param cf
 * @return
 **************************************************************************/
private boolean writeTIFFImage(com.lowagie.text.Document document, ContentFile cf) {
    RenderedOp inImage = null;
    RenderedOp outImage = null;
    Image itextimg = null;

    // Read metadata.
    String xresolution_string = null;
    String yresolution_string = null;
    String samples_string = null;
    String bitspersamples_string = null;
    String height_string = null;
    String width_string = null;

    long orig_width = 0;
    long orig_height = 0;

    List<Metadata> allMD = cf.getAllMetadata();
    // No metadata available.
    if (allMD == null) {
        return false;
    }
    Iterator<Metadata> it = allMD.iterator();
    while (it.hasNext()) {
        Metadata md = it.next();
        if (md.getType().getName().equals("ugh_height")) {
            height_string = md.getValue();
        }
        if (md.getType().getName().equals("ugh_width")) {
            width_string = md.getValue();
        }
        if (md.getType().getName().equals("ugh_xresolution")) {
            xresolution_string = md.getValue();
        }
        if (md.getType().getName().equals("ugh_yresolution")) {
            yresolution_string = md.getValue();
        }
        if (md.getType().getName().equals("ugh_samples")) {
            samples_string = md.getValue();
        }
        if (md.getType().getName().equals("ugh_bitspersamples")) {
            bitspersamples_string = md.getValue();
        }
    }
    if (xresolution_string == null || yresolution_string == null || height_string == null
            || width_string == null || samples_string == null || bitspersamples_string == null) {
        System.err
                .println("ERROR: Can't get all needed technical metadata for contentfile " + cf.getLocation());
        return false;
    }

    int xresolution = Integer.parseInt(xresolution_string);
    int yresolution = Integer.parseInt(yresolution_string);

    // Read tiff file and convert it to Buffered Images.
    try {
        FileSeekableStream ffs = new FileSeekableStream(cf.getLocation());
        // Create an image for Java Advanced Imaging.
        inImage = JAI.create("stream", ffs);
        orig_width = inImage.getWidth();
        orig_height = inImage.getHeight();
    } catch (IOException ioe) {
        System.err.println("Can't read contentfile " + cf.getLocation());
        return false;
    }

    // Set scaling factor; usually we had to calculate it.
    int scale = 100;
    ParameterBlock params = new ParameterBlock();
    params.addSource(inImage);
    params.add(scale);
    params.add(scale);
    params.add(0.0F);
    params.add(0.0F);
    params.add(new InterpolationNearest());

    outImage = JAI.create("scale", params);
    // Create buffered image.
    BufferedImage newbi = outImage.getAsBufferedImage();

    try {
        itextimg = Image.getInstance(newbi, null, true);
    } catch (IOException ioe) {
    } catch (BadElementException bee) {
    }

    // Define page size.
    int page_w = 210;
    int page_h = 297;

    // Scale image, if it doesn't fit on page.
    float page_w_pixel = (float) (page_w * xresolution / 25.4);
    float page_h_pixel = (float) (page_h * yresolution / 25.4);

    // Calculate actual scale factor.
    //
    // Check, if image will fit on page.
    if ((orig_width > page_w_pixel) || (orig_height > page_h_pixel)) {
        // Does not fit on page.
        float scalefactor = 0;
        float scalefactor_w = page_w_pixel / orig_width;
        float scalefactor_h = page_h_pixel / orig_height;

        if (scalefactor_h < scalefactor_w) {
            scalefactor = scalefactor_h;
        } else {
            scalefactor = scalefactor_w;
        }
        // orig_width = (long) (orig_width * scalefactor);
        // orig_height = (long) (orig_height * scalefactor);
        // Do scaling.
        itextimg.scalePercent((72f / xresolution * 100) * scalefactor, (72f / yresolution * 100) * scalefactor);
    } else {
        // Do scaling.
        itextimg.scalePercent((72f / xresolution * 100), (72f / yresolution * 100));
    }

    // Add page.
    try {
        document.add(itextimg);
        // Create new page.
        document.newPage();
    } catch (DocumentException de) {
        System.err.println("PortableDocumentFormat: DocumentException for Contentfile " + cf.getLocation());
    }

    return true;
}