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:be.fedict.eid.applet.service.impl.PdfGenerator.java

License:Open Source License

/**
 * Generate a Code128C barcode/*from   w w  w . j  a  v a 2 s .  c o m*/
 *
 * @param rrn unique Rijksregister number
 * @param cardNumber number of the card
 * @return Image containing barcode
 * @throws IOException
 * @throws BadElementException
 */
private Image createBarcodeImage(String rrn, String cardNumber) throws IOException, BadElementException {
    if (null == rrn || rrn.length() != 11 || null == cardNumber || cardNumber.length() < 9) {
        throw new IllegalArgumentException("Missing or invalid length for RRN or Card Number");
    }

    String lastDigits = cardNumber.substring(cardNumber.length() - 9);
    String code = rrn + lastDigits;

    Barcode128 barcode = new Barcode128();
    barcode.setCodeType(Barcode128.CODE_C);
    barcode.setCode(code);
    barcode.setFont(null);

    return Image.getInstance(barcode.createAwtImage(Color.BLACK, Color.WHITE), null, true);
}

From source file:de.intranda.test_ics.ImageHelper.java

License:Apache License

@SuppressWarnings("unused")
private void addPage(File imageFile, PdfWriter pdfWriter, Document pdfDocument, float shrinkRatio,
        float rotationDegree) throws DocumentException, IOException {

    float pointsPerInch = 200.0f;
    Image pageImage = null;/*from  w w w . j a  v a 2  s.co  m*/
    float pageImageHeight = 0, pageImageWidth = 0;
    boolean lowMemory = (shrinkRatio == 1 ? false : true);

    URL inputImage = imageFile.toURI().toURL();

    pdfWriter.setFullCompression();
    pdfWriter.setStrictImageSequence(true);
    pdfWriter.setLinearPageMode();

    LOGGER.debug("Out of memory on loading image for pdf generation");
    // ByteArrayOutputStream stream = new ByteArrayOutputStream();
    BufferedImage bitmap = ImageIO.read(imageFile);
    // LOGGER.debug( "Size of temporary image bitmap: Width = " + bitmap.getWidth() + "; Height = " + bitmap.getHeight());
    LOGGER.debug("Reading file " + imageFile.getAbsolutePath());
    pageImage = Image.getInstance(bitmap, null, false);
    bitmap.flush();
    // stream.close();

    pageImage.setRotationDegrees(-rotationDegree);
    LOGGER.debug("Image dimensions: Width = " + pageImage.getWidth() + "; Height = " + pageImage.getHeight());
    pageImageHeight = pageImage.getHeight();
    pageImageWidth = pageImage.getWidth();
    pageImage.setAbsolutePosition(0, 0);
    // Rectangle pageRect = new Rectangle(pageImageWidth/shrinkRatio, pageImageHeight/shrinkRatio);
    com.lowagie.text.Rectangle pageRect = new com.lowagie.text.Rectangle(pageImageWidth, pageImageHeight);
    LOGGER.debug("Creating rectangle: Width = " + pageRect.getWidth() + "; Height = " + pageRect.getHeight());
    pdfDocument.setPageSize(pageRect);

    if (pdfDocument.isOpen()) {
        pdfDocument.newPage();
        pdfWriter.getDirectContent().addImage(pageImage);

    } else {
        pdfDocument.open();
        pdfWriter.getDirectContent().addImage(pageImage);
    }
    pdfWriter.flush();
    System.gc();
}

From source file:jp.ac.utokyo.rcast.karkinos.graph.output.PdfReport.java

License:Apache License

private static void addObj(Document document, Object obj, int width, int hight, int size, PdfWriter writer,
        int figcount) throws Exception, IOException {
    if (obj instanceof JFreeChart) {

        JFreeChart chart = (JFreeChart) obj;
        BufferedImage bufferedImage = chart.createBufferedImage(width * size, hight * size);
        Image image = Image.getInstance(writer, bufferedImage, 1.0f);
        image.scalePercent(20);/*from  w  ww .j a v a  2  s  .  c o m*/
        image.setAnnotation(new Annotation("fig" + figcount, "karkinos fig" + figcount));
        document.add(image);

    } else if (obj instanceof Element) {

        document.add((Element) obj);

    } else if (obj instanceof java.awt.Image) {

        java.awt.Image aim = (java.awt.Image) obj;
        Image image = Image.getInstance(writer, aim, 1.0f);
        image.scalePercent(50);
        document.add(image);

    } else {

        document.add(new Paragraph(String.valueOf(obj)));

    }

}

From source file:jp.ac.utokyo.rcast.karkinos.summary.RegionGraph.java

License:Apache License

/**
 * @param args/*from  w  ww.ja  v a2  s  .c  o m*/
 */
public static void main(String[] args) {

    String indir = "/GLUSTER_DIST/data/users/ueda/ICGC/ICGCkarkinos4.0/HCC_exome_rcast,"
            + "/GLUSTER_DIST/data/users/ueda/ICGC/ICGCkarkinos4.0/HCC_NCC/karkinosver4.0.25,"
            + "/GLUSTER_DIST/data/users/ueda/ICGC/ICGCkarkinos4.0/HCC_exome_baylor/HCC-JP-453-T-HCC-JP-453-N/HCC-JP-453-T-HCC-JP-453-N,"
            + "/GLUSTER_DIST/data/users/ueda/ICGC/bcmtest/tcga,"
            + "/GLUSTER_DIST/data/users/ueda/ICGC/bcmtest/goss,";

    //
    // String indir =
    // "/GLUSTER_DIST/data/users/ueda/ICGC/ICGCkarkinos4.0/HCC_exome_rcast/THCC_167T-THCC_167N/THCC_167T-THCC_167N/";
    String out = "/GLUSTER_DIST/data/users/ueda/ICGC/ICGCkarkinos4.0/chr5Graprh.pdf";
    String outpng = "/GLUSTER_DIST/data/users/ueda/ICGC/ICGCkarkinos4.0/chr1Graprh.jpeg";

    List<File> list = new ArrayList<File>();

    for (String s : indir.split(",")) {
        File f = new File(s);
        // chage to reccursive file search
        searchRecursive(f, list);
    }

    String chr = "chr5";
    int start = 0;
    int end = 50000000;

    // String chr = "chr11";
    // int start = 0;
    // int end = 135000000;

    //      String chr = "chr1";
    //      int start = 0;
    //      int end = 247000000;
    int[][] target = new int[][] { { 1278756, 1295162 } };

    Document document = null;
    PdfWriter writer = null;
    int width = 1200;
    int hight = 500;
    int size = 1;
    try {

        FileOutputStream fileOutputStream = new FileOutputStream(out);
        document = new Document();

        writer = PdfWriter.getInstance(document, fileOutputStream);
        document.open();

        for (File f : list) {

            document.add(new Paragraph(String.valueOf(f.getName())));
            Object[] obj = getChart(f, chr, start, end, target);
            document.add(new Paragraph("mean=" + toStr(obj[1]) + "\t mean original=" + toStr(obj[2])));
            JFreeChart chart = (JFreeChart) obj[0];

            // try {
            // File jpn = new File(outpng);
            // ChartUtilities.saveChartAsJPEG(jpn, chart, 300, 300);
            //
            // } catch (Exception ex) {
            //
            // }

            BufferedImage bufferedImage = chart.createBufferedImage(width * size, hight * size);
            Image image = Image.getInstance(writer, bufferedImage, 1.0f);
            image.scalePercent(20);
            document.add(image);

        }

        document.close();
        document = null;
        writer.close();
        writer = null;

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }
        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:jp.ac.utokyo.rcast.karkinos.summary.RegionGraph2.java

License:Apache License

/**
 * @param args//from   www .  j  ava 2s.co  m
 */
public static void main(String[] args) {

    String indir = "/GLUSTER_DIST/data/users/ueda/ICGC/ICGCkarkinos4.0/HCC_exome_rcast,"
            + "/GLUSTER_DIST/data/users/ueda/ICGC/ICGCkarkinos4.0/HCC_NCC/karkinosver4.0.25,"
            + "/GLUSTER_DIST/data/users/ueda/ICGC/ICGCkarkinos4.0/HCC_exome_baylor/HCC-JP-453-T-HCC-JP-453-N/HCC-JP-453-T-HCC-JP-453-N,"
            + "/GLUSTER_DIST/data/users/ueda/ICGC/bcmtest/tcga,"
            + "/GLUSTER_DIST/data/users/ueda/ICGC/bcmtest/goss,";

    //
    // String indir =
    // "/GLUSTER_DIST/data/users/ueda/ICGC/ICGCkarkinos4.0/HCC_exome_rcast/THCC_167T-THCC_167N/THCC_167T-THCC_167N/";
    String out = "/GLUSTER_DIST/data/users/ueda/ICGC/ICGCkarkinos4.0/chr4allelicGraprh.pdf";
    // String outpng =
    // "/GLUSTER_DIST/data/users/ueda/ICGC/ICGCkarkinos4.0/chr1Graprh.jpeg";

    List<File> list = new ArrayList<File>();

    for (String s : indir.split(",")) {
        File f = new File(s);
        // chage to reccursive file search
        searchRecursive(f, list);
    }

    // String chr = "chr5";
    // int start = 0;
    // int end = 300000;

    // String chr = "chr11";
    // int start = 0;
    // int end = 135000000;

    String chr = "chr4";
    int start = 0;
    int end = 247000000;
    int[][] target = new int[][] { { 190328975, 190903950 } };

    Document document = null;
    PdfWriter writer = null;
    int width = 1200;
    int hight = 500;
    int size = 1;
    try {

        FileOutputStream fileOutputStream = new FileOutputStream(out);
        document = new Document();

        writer = PdfWriter.getInstance(document, fileOutputStream);
        document.open();

        for (File f : list) {

            document.add(new Paragraph(String.valueOf(f.getName())));
            Object[] obj = getChart(f, chr, start, end, target, 1);
            document.add(new Paragraph("mean=" + toStr(obj[1]) + "\t mean original=" + toStr(obj[2])));
            JFreeChart chart = (JFreeChart) obj[0];

            // try {
            // File jpn = new File(outpng);
            // ChartUtilities.saveChartAsJPEG(jpn, chart, 300, 300);
            //
            // } catch (Exception ex) {
            //
            // }

            BufferedImage bufferedImage = chart.createBufferedImage(width * size, hight * size);
            Image image = Image.getInstance(writer, bufferedImage, 1.0f);
            image.scalePercent(20);
            document.add(image);

            obj = getChart(f, chr, start, end, target, 2);
            chart = (JFreeChart) obj[0];

            // try {
            // File jpn = new File(outpng);
            // ChartUtilities.saveChartAsJPEG(jpn, chart, 300, 300);
            //
            // } catch (Exception ex) {
            //
            // }

            bufferedImage = chart.createBufferedImage(width * size, hight * size);
            image = Image.getInstance(writer, bufferedImage, 1.0f);
            image.scalePercent(20);
            document.add(image);

        }

        document.close();
        document = null;
        writer.close();
        writer = null;

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }
        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:jp.ac.utokyo.rcast.karkinos.summary.TextToGraph.java

License:Apache License

/**
 * @param args//from   w ww . j  ava2  s . c o m
 */
public static void main(String[] args) {

    // String s =
    // "/GLUSTER_DIST/data/users/ueda/ICGC/bcmtest/TCGA-MR-A520-01A-11D-A25V-10.vs-10_cnvAllelicDepth.txt";
    // String s2 =
    // "/GLUSTER_DIST/data/users/ueda/ICGC/bcmtest/TCGA-MR-A520-01A-11D-A25V-10.vs-10_cnvdepth.txt";
    // String sout = "/GLUSTER_DIST/data/users/ueda/ICGC/bcmtest/out.pdf";

    String s = "/GLUSTER_DIST/data/users/ueda/ICGC/bcmtest/HCC-JP-468-T.vs-N_cnvAllelicDepth.txt";
    String s2 = "/GLUSTER_DIST/data/users/ueda/ICGC/bcmtest/HCC-JP-468-T.vs-N_cnvdepth.txt";
    String sout = "/GLUSTER_DIST/data/users/ueda/ICGC/bcmtest/468out.pdf";

    Document document = null;
    PdfWriter writer = null;
    //
    try {

        int width = 1200;
        int hight = 500;
        int size = 1;
        FileOutputStream fileOutputStream = new FileOutputStream(sout);
        document = new Document();

        writer = PdfWriter.getInstance(document, fileOutputStream);
        document.open();

        JFreeChart chart0 = getChart(new File(s2), 0);
        JFreeChart chart1 = getChart(new File(s2), 1);
        JFreeChart chart2 = getChart(new File(s2), 2);
        JFreeChart chart3 = getChart(new File(s2), 3);
        JFreeChart chart4 = getChart(new File(s), 4);
        JFreeChart chart5 = getChart(new File(s), 5);
        JFreeChart chart6 = getChart(new File(s), 6);

        BufferedImage bufferedImage = chart0.createBufferedImage(width * size, hight * size);
        Image image = Image.getInstance(writer, bufferedImage, 1.0f);
        image.scalePercent(20);
        document.add(image);

        BufferedImage bufferedImage1 = chart1.createBufferedImage(width * size, hight * size);
        Image image1 = Image.getInstance(writer, bufferedImage1, 1.0f);
        image1.scalePercent(20);
        document.add(image1);

        BufferedImage bufferedImage2 = chart2.createBufferedImage(width * size, hight * size);
        Image image2 = Image.getInstance(writer, bufferedImage2, 1.0f);
        image2.scalePercent(20);
        document.add(image2);

        BufferedImage bufferedImage3 = chart3.createBufferedImage(width * size, hight * size);
        Image image3 = Image.getInstance(writer, bufferedImage3, 1.0f);
        image3.scalePercent(20);
        document.add(image3);

        BufferedImage bufferedImage4 = chart4.createBufferedImage(width * size, hight * size);
        Image image4 = Image.getInstance(writer, bufferedImage4, 1.0f);
        image4.scalePercent(20);
        document.add(image4);

        BufferedImage bufferedImage5 = chart5.createBufferedImage(width * size, hight * size);
        Image image5 = Image.getInstance(writer, bufferedImage5, 1.0f);
        image5.scalePercent(20);
        document.add(image5);

        BufferedImage bufferedImage6 = chart6.createBufferedImage(width * size, hight * size);
        Image image6 = Image.getInstance(writer, bufferedImage6, 1.0f);
        image6.scalePercent(20);
        document.add(image6);

        document.close();
        document = null;
        writer.close();
        writer = null;

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }
        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:lucee.runtime.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 new ApplicationException(
                "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
        throw new ApplicationException("destination file [" + destination + "] already exists");

    // image//  w w w  . j a  va  2s. co  m
    Image img = null;
    if (image != null) {
        lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext, image, false, false, true,
                null);
        img = Image.getInstance(ri.getBufferedImage(), null, false);
    }
    // copy From
    else {
        byte[] barr;
        try {
            Resource res = Caster.toResource(pageContext, copyFrom, true);
            barr = IOUtil.toBytes(res);
        } catch (ExpressionException ee) {
            barr = Caster.toBinary(copyFrom);
        }
        img = Image.getInstance(PDFUtil.toImage(barr, 1).getBufferedImage(), null, false);

    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!StringUtil.isEmpty(position)) {
        int index = position.indexOf(',');
        if (index == -1)
            throw new ApplicationException("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 (!StringUtil.isEmpty(strX))
            x = Caster.toIntValue(strX);
        if (!StringUtil.isEmpty(strY))
            y = Caster.toIntValue(strY);

    }

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    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 (!StringUtil.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 {
        IOUtil.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                IOUtil.copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination,
                        true);// MUST overwrite
            if (!StringUtil.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:lucee.runtime.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 new ApplicationException("destination file [" + destination + "] already exists");

    lucee.runtime.img.Image ri = new lucee.runtime.img.Image(1, 1, BufferedImage.TYPE_INT_RGB, Color.BLACK);
    Image img = Image.getInstance(ri.getBufferedImage(), null, false);
    img.setAbsolutePosition(1, 1);//from   w w  w .j  a va2s  .  c o m

    PDFDocument 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 (!StringUtil.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 {
        IOUtil.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                IOUtil.copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination,
                        true);// MUST overwrite
            if (!StringUtil.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:org.andrill.coretools.graphics.driver.pdf.PDFDriver.java

License:Apache License

protected Image getImage(final URL url) {
    String key = url.toExternalForm();
    if (!imageCache.containsKey(key)) {
        try {/*from  w w  w.  j a  va  2 s.c o m*/
            // Image image = Image.getInstance(url);
            Image image = Image.getInstance(content, ImageIO.read(url), 0);
            imageCache.put(key, image);
        } catch (BadElementException e) {
            // TODO log
            e.printStackTrace();
        } catch (MalformedURLException e) {
            // TODO log
            e.printStackTrace();
        } catch (IOException e) {
            // TODO log
            e.printStackTrace();
        }
    }
    return imageCache.get(key);
}

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

License:Apache License

/************************************************************************************
 * exectute mets handling and generation of pdf file and send pdf back to output stream of the servlet, after setting correct mime type
 * /*from w  w  w.j a va 2  s. c o  m*/
 * @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 retrieve source image from url --------------------------------
     */
    ContentServerConfiguration config = ContentServerConfiguration.getInstance();
    if (config.getWatermarkUse()) {
        File watermarkfile = new File(new URI(config.getWatermarkConfigFilePath()));
        myWatermark = Watermark.generateWatermark(request, watermarkfile);
    }
    OutputStream myOutStream = response.getOutputStream();
    ContentCache cc = ContentServer.getPdfCache();
    String myUniqueID = getContentCacheIdForRequest(request, config);
    setTargetNameAndMimeType(request, response, config);
    try {
        /*
         * -------------------------------- ask ContentCache, if object already exists --------------------------------
         */
        PDFManager pdfmanager = null;
        try {
            boolean ignoreCache = false;
            /* check if cache should be ignored */
            if (request.getParameter("ignoreCache") != null) {
                String ignore = request.getParameter("ignoreCache").trim();
                ignoreCache = Boolean.parseBoolean(ignore);
            }
            if (cc == null || !config.getPdfCacheUse()) {
                ignoreCache = true;
                cc = null;
                LOGGER.debug("cache deactivated via configuration");
            }

            /* if cache should not be ignored and cache contains file, write it back to stream */
            if (!ignoreCache && cc.cacheContains(myUniqueID, "pdf")) {
                LOGGER.debug("get file from cache: " + myUniqueID);
                cc.writeToStream(response.getOutputStream(), myUniqueID, "pdf");
                return;
            } else if (ignoreCache == false) {
                LOGGER.debug("file not found in cache: " + myUniqueID);
            }

            /*
             * -------------------------------- if Cache is not used, parse mets file name and add it to repository path
             * --------------------------------
             */
            String metsFile = request.getParameter("metsFile");
            if (!metsFile.endsWith(".xml")) {
                metsFile += ".xml";
            }
            URL fullMetsPath = new URL(config.getRepositoryPathMets() + metsFile);
            LOGGER.debug("mets file to parse: " + fullMetsPath);

            /*
             * -------------------------------- open METS file --------------------------------
             */
            METSParser metsparser = new METSParser(fullMetsPath, true);
            SimplePDFMetadataExtractor spme = new SimplePDFMetadataExtractor();
            spme.activateDFGConfiguration();

            // set the Metadata extractor and the Bookmark metadata extractor
            metsparser.setMetadataextractor(spme);
            metsparser.setStructureMetadataExtractor(new SimpleStructureMetadataExtractor());

            /*
             * -------------------------------- check if filegroup is defined in request parameter, else take it from config file
             * --------------------------------
             */
            String strMetsFileGroup = request.getParameter("metsFileGroup");
            if (strMetsFileGroup == null) {
                strMetsFileGroup = config.getDefaultMetsFileGroup();
            }
            metsparser.setFilegroupsuseattributevalue(strMetsFileGroup);
            LOGGER.debug("Using METS file group: " + strMetsFileGroup);

            /*
             * -------------------------------- check divID as parameter, else use upper most divID --------------------------------
             */
            String divID = request.getParameter("divID");
            DivType pdfdiv = null;
            if (StringUtils.isNotBlank(divID)) {
                pdfdiv = metsparser.getDIVbyID(divID);
                // check if the METS file is a monograph, volume or multivolume file
            } else {
                DivType uplogdiv = metsparser.getUppermostLogicalDiv();
                if (uplogdiv == null) {
                    throw new ContentLibPdfException("Can't create PDF; div seems to be an anchor.");
                }

                // check, if we have <mptr> as children
                List<Mptr> mptrs = uplogdiv.getMptrList();
                if ((mptrs == null) || (mptrs.size() == 0)) {
                    // no mptr - must be a monograph
                    // in this case the uppermost logical id is the one we are looking for
                    pdfdiv = uplogdiv;
                } else {
                    // check, if we have a physical structmap
                    DivType physDiv = metsparser.getUppermostPhysicalDiv();
                    if (physDiv == null) {
                        // it is a multivolume or a periodical or anything like this
                        // in this case the uppermost logical div is the one for which we create the PDF
                        pdfdiv = uplogdiv;
                    } else {
                        // it is the first child div; this represents the volume

                        List<DivType> children = uplogdiv.getDivList();
                        if ((children == null) || (children.size() == 0)) {
                            throw new ContentLibPdfException("Can't create PDF; can't find a div");
                        }
                        pdfdiv = children.get(0); // the first child
                    }
                }
            }
            spme.calculateMetadata(pdfdiv, metsparser);
            metsparser.getAllFilesForRelatedDivs(pdfdiv.getID()); // get page names

            /*
             * -------------------------------- get list of files and pagenames --------------------------------
             */
            Map<Integer, UrlImage> myPages = metsparser.getImageMap();
            // HashMap<Integer, URL> myURLs = metsparser.getPageUrls();
            Map<Integer, String> myNames = metsparser.getPageNames();
            List<? extends Structure> pDFBookmarks = metsparser.getStructureList();
            // PDFManager pdfmanager = new PDFManager(myURLs);
            pdfmanager = new PDFManager(myPages, true);

            setPdfManagerDefaults(request, config, pdfmanager);

            /*
             * -------------------------------- set pdf meta data --------------------------------
             */
            if (spme.getPdftitle() != null) {
                String title = spme.getPdftitle().trim();
                pdfmanager.setTitle(title);
            }
            if (spme.getPdfcreator() != null) {
                String creator = spme.getPdfcreator().trim();
                pdfmanager.setCreator(creator);
                pdfmanager.setAuthor(creator);
            }
            if (spme.getPdfkeywords() != null) {
                pdfmanager.setSubject(spme.getPdfkeywords());
            }

            /*
             * -------------------------------- if configured create PDF title page - either read its path from config file and fill it with mets
             * content - or if given as url parameter use it directly without any change --------------------------------
             */
            if (config.getPdfTitlePageUse()) {
                PDFTitlePage pdftp = new PDFTitlePage();

                String pdfconfigurl = request.getParameter("pdftitlepage");
                if (StringUtils.isNotBlank(pdfconfigurl)) {
                    pdftp.readConfiguration(new URI(pdfconfigurl));
                } else {
                    pdftp.readConfiguration(config.getPdfTitlePageConfigFile());
                    if (spme.getPdfTitlepageLine1() != null) {
                        PDFTitlePageLine ptl = new PDFTitlePageLine(spme.getPdfTitlepageLine1());
                        ptl.setLinetype(2);
                        ptl.setFontsize(14);
                        pdftp.addPDFTitlePageLine(ptl);
                    }

                    if (spme.getPdfTitlepageLine2() != null) {
                        PDFTitlePageLine ptl = new PDFTitlePageLine(spme.getPdfTitlepageLine2());
                        ptl.setLinetype(2);
                        ptl.setFontsize(10);
                        pdftp.addPDFTitlePageLine(ptl);
                    }

                    if (spme.getPdfTitlepageLine3() != null) {
                        PDFTitlePageLine ptl = new PDFTitlePageLine(spme.getPdfTitlepageLine3());
                        ptl.setLinetype(2);
                        ptl.setFontsize(10);
                        pdftp.addPDFTitlePageLine(ptl);
                    }

                    if (spme.getPdfTitlepageLine4() != null) {
                        PDFTitlePageLine ptl = new PDFTitlePageLine(spme.getPdfTitlepageLine4());
                        ptl.setLinetype(2);
                        ptl.setFontsize(10);
                        pdftp.addPDFTitlePageLine(ptl);
                    }
                }
                pdfmanager.setPdftitlepage(pdftp);
            }

            /*
             * -------------------------------- set page names and bookmarks --------------------------------
             */
            if ((myNames != null) && (myNames.size() > 0)) {
                pdfmanager.setImageNames(myNames);
            }
            if ((pDFBookmarks != null) && (pDFBookmarks.size() > 0)) {
                pdfmanager.setStructureList(pDFBookmarks);
            }

            /*
             * -------------------------------- write pdf to response stream (and cache) --------------------------------
             */
            /* remove file from cache, if cache should be used and file present */
            if (cc != null) {
                cc.delete(myUniqueID, "pdf");
            }
            /* if cache size is exceeded write it to response stream only */
            if (cc != null && !cc.isCacheSizeExceeded()) {
                LOGGER.info("write file to cache and servlet response: " + cc.getFileForId(myUniqueID, "pdf"));
                myOutStream = new CacheOutputStream(cc.getFileForId(myUniqueID, "pdf"),
                        response.getOutputStream());
            } else if (cc == null) {
                LOGGER.info("file will not be written to cache, cache is deactivated in configuration");
            } else if (cc.isCacheSizeExceeded()) {
                LOGGER.info(
                        "file will not be written to cache, maximum cache size exceeded defined configuration");
            }
        } catch (NullPointerException e) {
            throw new NullPointerException("Nullpointer occured before pdf-generation");
        }
        /* write to stream */
        if (pdfmanager != null) {
            pdfmanager.createPDF(myOutStream, getPageSize(request), myWatermark);
        }
    } catch (Exception e) {
        LOGGER.error("error during 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);
        } finally {
            /*
             * -------------------------------- close all --------------------------------
             */
            try {
                if (inputFileStream != null) {
                    inputFileStream.close();
                }
                if (pdfdoc != null) {
                    pdfdoc.close();
                }
                if (writer != null) {
                    writer.close();
                }
            } catch (ExceptionConverter e2) {
                LOGGER.warn("Caught ExceptionConverter object");
            } finally {

                /* on errors remove incomplete file from cache */
                try {
                    if (myOutStream != null) {
                        myOutStream.flush();
                        myOutStream.close();
                    }
                } catch (Exception e2) {
                    LOGGER.debug("Caught unknown Exception");
                }
                if (cc != null && cc.cacheContains(myUniqueID, "pdf")) {
                    cc.delete(myUniqueID, "pdf");
                }
            }
        }
    } finally {
        if (myOutStream != null) {
            myOutStream.flush();
            myOutStream.close();
        }
    }
}