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

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

Introduction

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

Prototype

public void close() throws DocumentException, IOException 

Source Link

Document

Closes the document.

Usage

From source file:controller.DownloadCVServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from   w  w w .j  ava  2 s.c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //protect servlet
    HttpSession session = request.getSession();
    Admin loggedInAdmin = (Admin) session.getAttribute("admin");

    //check if admin is logged in
    if (loggedInAdmin == null) {
        response.sendRedirect("login.jsp");
        return;
    }

    String[] appIDs = request.getParameterValues("download");

    ServletOutputStream sOut = response.getOutputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);

    //prepare fonts
    Font font = FontFactory.getFont("Arial", 10);

    for (String appIDStr : appIDs) {
        int appID = Integer.parseInt(appIDStr);
        Application application = ApplicationDAO.retrieveByAppID(appID);
        Job job = JobDAO.retrieveJobById(application.getJobID());

        ZipEntry entry = new ZipEntry(application.getFullname() + "_CV.pdf");
        zos.putNextEntry(entry);

        String path = System.getenv("OPENSHIFT_DATA_DIR");

        if (path == null) {
            path = getServletContext().getRealPath("/templates/Personal_Particulars_Form.pdf");
        } else {
            path += "Personal_Particulars_Form.pdf";
        }

        try {
            //Prepare PdfStamper
            PdfReader reader = new PdfReader(path);
            PdfStamper stamper = new PdfStamper(reader, zos);
            stamper.setRotateContents(false);
            stamper.getWriter().setCloseStream(false);

            //Get first page
            PdfContentByte canvas = stamper.getOverContent(1);

            //Application ID
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getAppID() + "", font), 110, 555, 0);

            //Date Applied
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getDateApplied(), font), 110, 526, 0);

            //Position Applied
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(job.getPostingTitle(), font), 36,
                    442, 0);

            //Job ID
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getJobID() + "", font), 405, 442, 0);

            //Name
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getFullname(), font),
                    36, 350, 0);

            //Street
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getBlkStreetUnit(), font), 36, 305, 0);

            //Postal Code
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getPostalCode(), font), 377, 305, 0);

            //Nationality
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getNricType(), font),
                    36, 260, 0);

            //NRIC
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getNric(), font), 289,
                    260, 0);

            //DOB
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getDob(), font), 36,
                    215, 0);

            //Gender
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getGender(), font),
                    379, 215, 0);

            //Contact Number
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getContactNo(), font),
                    36, 170, 0);

            //Email Address
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getEmailAddress(), font), 36, 125, 0);

            //Declaration
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("X", font), 50, 80, 0);

            //Generated on
            DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
            dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Singapore"));
            Date date = new Date();
            String today = dateFormat.format(date);
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(today, font), 437, 15, 0);

            stamper.close();
            reader.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    zos.close();
    response.setContentType("application/zip");
    response.addHeader("Content-Disposition", "attachment; filename=CVs.zip");

    sOut.write(baos.toByteArray());
    sOut.close();
}

From source file:cz.muni.pdfjbim.PdfImageExtractor.java

License:Apache License

/**
 * This method extracts images by going through all COSObjects pointed from xref table
 * @param is input stream containing PDF file
 * @param prefix output basename for images
 * @param password password for access to PDF if needed
 * @param pagesToProcess list of pages which should be processed if null given => processed all pages
 *      -- not working yet//from www. j av a  2  s . c  o m
 * @param binarize -- enables processing of nonbitonal images as well (LZW is still not
 *      processed because of output with inverted colors)
 * @throws PdfRecompressionException if problem to extract images from PDF
 */
public void extractImagesUsingPdfParser(InputStream is, String prefix, String password,
        Set<Integer> pagesToProcess, Boolean binarize) throws PdfRecompressionException {
    // checking arguments and setting appropriate variables
    if (binarize == null) {
        binarize = false;
    }

    log.debug("Extracting images (binarize set to {})", binarize);

    InputStream inputStream = null;
    if (password != null) {
        try (ByteArrayOutputStream decryptedOutputStream = new ByteArrayOutputStream()) {
            PdfReader reader = new PdfReader(is, password.getBytes(StandardCharsets.UTF_8));
            PdfStamper stamper = new PdfStamper(reader, decryptedOutputStream);
            if (stamper != null) {
                stamper.close();
            }
            inputStream = new ByteArrayInputStream(decryptedOutputStream.toByteArray());
        } catch (DocumentException ex) {
            throw new PdfRecompressionException(ex);
        } catch (IOException ex) {
            throw new PdfRecompressionException("Reading file caused exception", ex);
        }
    } else {
        inputStream = is;
    }

    PDFParser parser = null;
    COSDocument doc = null;
    try {
        parser = new PDFParser(inputStream);
        parser.parse();
        doc = parser.getDocument();

        List<COSObject> objs = doc.getObjectsByType(COSName.XOBJECT);
        if (objs != null) {
            for (COSObject obj : objs) {
                COSBase subtype = obj.getItem(COSName.SUBTYPE);
                if (subtype.toString().equalsIgnoreCase("COSName{Image}")) {
                    COSBase imageObj = obj.getObject();
                    COSBase cosNameObj = obj.getItem(COSName.NAME);
                    String key;
                    if (cosNameObj != null) {
                        String cosNameKey = cosNameObj.toString();
                        int startOfKey = cosNameKey.indexOf("{") + 1;
                        key = cosNameKey.substring(startOfKey, cosNameKey.length() - 1);
                    } else {
                        key = "im0";
                    }
                    int objectNum = obj.getObjectNumber().intValue();
                    int genNum = obj.getGenerationNumber().intValue();
                    PDXObjectImage image = (PDXObjectImage) PDXObjectImage.createXObject(imageObj);

                    PDStream pdStr = new PDStream(image.getCOSStream());
                    List<COSName> filters = pdStr.getFilters();

                    log.debug("Detected image with color depth: {} bits", image.getBitsPerComponent());
                    if (filters == null) {
                        continue;
                    }
                    log.debug("Detected filters: {}", filters.toString());

                    if ((image.getBitsPerComponent() > 1) && (!binarize)) {
                        log.info("It is not a bitonal image => skipping");
                        continue;
                    }

                    // at this moment for preventing bad output (bad coloring) from LZWDecode filter
                    if (filters.contains(COSName.LZW_DECODE)) {
                        log.info("This is LZWDecoded => skipping");
                        continue;
                    }

                    if (filters.contains(COSName.FLATE_DECODE)) {
                        log.debug("FlateDecoded image detected");
                    }

                    if (filters.contains(COSName.JBIG2_DECODE)) {
                        if (skipJBig2Images) {
                            log.warn("Allready compressed according to JBIG2 standard => skipping");
                            continue;
                        } else {
                            log.debug("JBIG2 image detected");
                        }
                    }

                    // detection of unsupported filters by pdfBox library
                    if (filters.contains(COSName.JPX_DECODE)) {
                        log.warn("Unsupported filter JPXDecode => skipping");
                        continue;
                    }

                    String name = getUniqueFileName(prefix, image.getSuffix());
                    log.info("Writing image: {}", name);
                    image.write2file(name);

                    PdfImageInformation pdfImageInfo = new PdfImageInformation(key, image.getWidth(),
                            image.getHeight(), objectNum, genNum);
                    originalImageInformations.add(pdfImageInfo);

                    namesOfImages.add(name + "." + image.getSuffix());

                }
            }
        }
    } catch (IOException ex) {
        Tools.deleteFilesFromList(namesOfImages);
        throw new PdfRecompressionException("Unable to parse PDF document", ex);
    } catch (Exception ex) {
        Tools.deleteFilesFromList(namesOfImages);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                throw new PdfRecompressionException(ex);
            }
        }
    }
}

From source file:cz.muni.pdfjbim.PdfImageExtractor.java

License:Apache License

/**
 * @deprecated -- do not use doesn't work properly yet
 * This method extracts images by going through PDF tree structure
 * @param pdfFile name of input PDF file
 * @param prefix //w  w w . java 2  s .co m
 * @param password password for access to PDF if needed
 * @param pagesToProcess list of pages which should be processed if null given => processed all pages
 *      -- not working yet
//    * @param silent -- if true error messages are not written to output otherwise they are
 * @param binarize -- enables processing of nonbitonal images as well (LZW is still not
 *      processed because of output with inverted colors)
 * @throws PdfRecompressionException if problem to extract images from PDF
 */
public void extractImagesUsingPdfObjectAccess(String pdfFile, String prefix, String password,
        Set<Integer> pagesToProcess, Boolean binarize) throws PdfRecompressionException {
    if (binarize == null) {
        binarize = false;
    }
    // checking arguments and setting appropriate variables
    if (pdfFile == null) {
        throw new IllegalArgumentException("pdfFile must be defined");
    }

    InputStream inputStream = null;
    if (password != null) {
        try {
            log.debug("PDF probably encrypted, trying to decrypt using given password {}", password);
            ByteArrayOutputStream decryptedOutputStream = new ByteArrayOutputStream();
            PdfReader reader = new PdfReader(pdfFile, password.getBytes(StandardCharsets.UTF_8));
            PdfStamper stamper = new PdfStamper(reader, decryptedOutputStream);
            stamper.close();
            inputStream = new ByteArrayInputStream(decryptedOutputStream.toByteArray());
        } catch (DocumentException ex) {
            throw new PdfRecompressionException(ex);
        } catch (IOException ex) {
            throw new PdfRecompressionException("Reading file caused exception", ex);
        }
    } else {
        try {
            inputStream = new FileInputStream(pdfFile);
        } catch (FileNotFoundException ex) {
            throw new PdfRecompressionException("File wasn't found", ex);
        }
    }

    // if prefix is not set then prefix set to name of pdf without .pdf
    // if pdfFile has unconsistent name (without suffix .pdf) and name longer than 4 chars then last for chars are removed
    // and this string set as prefix
    if ((prefix == null) && (pdfFile.length() > 4)) {
        prefix = pdfFile.substring(0, pdfFile.length() - 4);
    }

    PDFParser parser = null;
    PDDocument doc = null;
    try {
        parser = new PDFParser(inputStream);
        parser.parse();
        doc = parser.getPDDocument();

        AccessPermission accessPermissions = doc.getCurrentAccessPermission();

        if (!accessPermissions.canExtractContent()) {
            throw new PdfRecompressionException("Error: You do not have permission to extract images.");
        }

        // going page by page
        List pages = doc.getDocumentCatalog().getAllPages();
        for (int pageNumber = 0; pageNumber < pages.size(); pageNumber++) {
            if ((pagesToProcess != null) && (!pagesToProcess.contains(pageNumber + 1))) {
                continue;
            }
            PDPage page = (PDPage) pages.get(pageNumber);
            PDResources resources = page.getResources();
            Map xobjs = resources.getXObjects();

            if (xobjs != null) {
                Iterator xobjIter = xobjs.entrySet().iterator();
                while (xobjIter.hasNext()) {
                    Map.Entry entry = (Map.Entry) xobjIter.next();
                    String key = (String) entry.getKey();
                    PDXObject xobj = (PDXObject) entry.getValue();
                    Map images;
                    if (xobj instanceof PDXObjectForm) {
                        PDXObjectForm xform = (PDXObjectForm) xobj;
                        images = xform.getResources().getImages();
                    } else {
                        images = resources.getImages();
                    }

                    // reading images from each page and saving them to file
                    if (images != null) {
                        Iterator imageIter = images.entrySet().iterator();
                        while (imageIter.hasNext()) {
                            Map.Entry imEntry = (Map.Entry) imageIter.next();
                            String imKey = (String) imEntry.getKey();
                            PDXObjectImage image = (PDXObjectImage) imEntry.getValue();

                            PDStream pdStr = new PDStream(image.getCOSStream());
                            List<COSName> filters = pdStr.getFilters();

                            if (image.getBitsPerComponent() > 1 && !binarize) {
                                log.info("It is not a bitonal image => skipping");
                                continue;
                            }

                            // at this moment for preventing bad output (bad coloring) from LZWDecode filter
                            if (filters.contains(COSName.LZW_DECODE)) {
                                log.info("This is LZWDecoded => skipping");
                                continue;

                            }

                            if (filters.contains(COSName.JBIG2_DECODE)) {
                                if (skipJBig2Images) {
                                    log.warn("Allready compressed according to JBIG2 standard => skipping");
                                    continue;
                                } else {
                                    log.debug("JBIG2 image detected");
                                }
                            }

                            // detection of unsupported filters by pdfBox library
                            if (filters.contains(COSName.JPX_DECODE)) {
                                log.info("Unsupported filter JPXDecode => skipping");
                                continue;
                            }

                            COSObject cosObj = new COSObject(image.getCOSObject());
                            int objectNum = cosObj.getObjectNumber().intValue();
                            int genNum = cosObj.getGenerationNumber().intValue();
                            log.debug(objectNum + " " + genNum + " obj");

                            String name = getUniqueFileName(prefix + imKey, image.getSuffix());
                            log.debug("Writing image:" + name);
                            image.write2file(name);

                            PdfImageInformation pdfImageInfo = new PdfImageInformation(key, image.getWidth(),
                                    image.getHeight(), objectNum, genNum);
                            originalImageInformations.add(pdfImageInfo);
                            log.debug(pdfImageInfo.toString());

                            namesOfImages.add(name + "." + image.getSuffix());
                        }
                    }
                }
            }
        }
    } catch (IOException ex) {
        Tools.deleteFilesFromList(namesOfImages);
        throw new PdfRecompressionException("Unable to parse PDF document", ex);
    } catch (RuntimeException ex) {
        Tools.deleteFilesFromList(namesOfImages);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                throw new PdfRecompressionException(ex);
            }
        }
    }
}

From source file:cz.muni.pdfjbim.PdfImageProcessor.java

License:Apache License

/**
 * This method extracts images by going through all COSObjects pointed from xref table
 * @param is input stream containing PDF file
 * @param password password for access to PDF if needed
 * @param pagesToProcess list of pages which should be processed if null given => processed all pages
 *      -- not working yet/*from   w w  w .j  a  va  2  s  . com*/
 * @param binarize -- enables processing of nonbitonal images as well (LZW is still not
 *      processed because of output with inverted colors)
 * @throws PdfRecompressionException if problem to extract images from PDF
 */
public void extractImagesUsingPdfParser(InputStream is, String prefix, String password,
        Set<Integer> pagesToProcess, Boolean binarize) throws PdfRecompressionException {
    // checking arguments and setting appropriate variables
    if (binarize == null) {
        binarize = false;
    }

    InputStream inputStream = null;
    if (password != null) {
        try {
            ByteArrayOutputStream decryptedOutputStream = null;
            PdfReader reader = new PdfReader(is, password.getBytes());
            PdfStamper stamper = new PdfStamper(reader, decryptedOutputStream);
            stamper.close();
            inputStream = new ByteArrayInputStream(decryptedOutputStream.toByteArray());
        } catch (DocumentException ex) {
            throw new PdfRecompressionException(ex);
        } catch (IOException ex) {
            throw new PdfRecompressionException("Reading file caused exception", ex);
        }
    } else {
        inputStream = is;
    }

    PDFParser parser = null;
    COSDocument doc = null;
    try {
        parser = new PDFParser(inputStream);
        parser.parse();
        doc = parser.getDocument();

        List<COSObject> objs = doc.getObjectsByType(COSName.XOBJECT);
        if (objs != null) {
            for (COSObject obj : objs) {
                COSBase subtype = obj.getItem(COSName.SUBTYPE);
                if (subtype.toString().equalsIgnoreCase("COSName{Image}")) {
                    COSBase imageObj = obj.getObject();
                    COSBase cosNameObj = obj.getItem(COSName.NAME);
                    String key;
                    if (cosNameObj != null) {
                        String cosNameKey = cosNameObj.toString();
                        int startOfKey = cosNameKey.indexOf("{") + 1;
                        key = cosNameKey.substring(startOfKey, cosNameKey.length() - 1);
                    } else {
                        key = "im0";
                    }
                    int objectNum = obj.getObjectNumber().intValue();
                    int genNum = obj.getGenerationNumber().intValue();
                    PDXObjectImage image = (PDXObjectImage) PDXObjectImage.createXObject(imageObj);

                    PDStream pdStr = new PDStream(image.getCOSStream());
                    List filters = pdStr.getFilters();

                    if ((image.getBitsPerComponent() > 1) && (!binarize)) {
                        log.info("It is not a bitonal image => skipping");

                        continue;
                    }

                    // at this moment for preventing bad output (bad coloring) from LZWDecode filter
                    if (filters.contains(COSName.LZW_DECODE.getName())) {
                        log.info("This is LZWDecoded => skipping");
                        continue;

                    }

                    // detection of unsupported filters by pdfBox library
                    if (filters.contains("JBIG2Decode")) {
                        log.warn("Allready compressed according to JBIG2 standard => skipping");
                        continue;
                    }

                    if (filters.contains("JPXDecode")) {
                        log.warn("Unsupported filter JPXDecode => skipping");
                        continue;
                    }

                    String name = getUniqueFileName(prefix, image.getSuffix());
                    log.info("Writing image:" + name);
                    image.write2file(name);

                    PdfImageInformation pdfImageInfo = new PdfImageInformation(key, image.getWidth(),
                            image.getHeight(), objectNum, genNum);
                    originalImageInformations.add(pdfImageInfo);

                    namesOfImages.add(name + "." + image.getSuffix());

                }
                //                    }
            }
        }
    } catch (IOException ex) {
        throw new PdfRecompressionException("Unable to parse PDF document", ex);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                throw new PdfRecompressionException(ex);
            }
        }
    }
}

From source file:cz.muni.pdfjbim.PdfImageProcessor.java

License:Apache License

/**
 * @deprecated -- do not use doesn't work properly yet
 * This method extracts images by going through PDF tree structure
 * @param pdfFile name of input PDF file
 * @param password password for access to PDF if needed
 * @param pagesToProcess list of pages which should be processed if null given => processed all pages
 *      -- not working yet// w w w  .  j  ava  2s.  c  o m
 * @param silent -- if true error messages are not written to output otherwise they are
 * @param binarize -- enables processing of nonbitonal images as well (LZW is still not
 *      processed because of output with inverted colors)
 * @throws PdfRecompressionException if problem to extract images from PDF
 */
public void extractImagesUsingPdfObjectAccess(String pdfFile, String password, Set<Integer> pagesToProcess,
        Boolean silent, Boolean binarize) throws PdfRecompressionException {
    if (binarize == null) {
        binarize = false;
    }
    // checking arguments and setting appropriate variables
    if (pdfFile == null) {
        throw new IllegalArgumentException(pdfFile);
    }

    String prefix = null;

    InputStream inputStream = null;
    if (password != null) {
        try {
            ByteArrayOutputStream decryptedOutputStream = null;
            PdfReader reader = new PdfReader(pdfFile, password.getBytes());
            PdfStamper stamper = new PdfStamper(reader, decryptedOutputStream);
            stamper.close();
            inputStream = new ByteArrayInputStream(decryptedOutputStream.toByteArray());
        } catch (DocumentException ex) {
            throw new PdfRecompressionException(ex);
        } catch (IOException ex) {
            throw new PdfRecompressionException("Reading file caused exception", ex);
        }
    } else {
        try {
            inputStream = new FileInputStream(pdfFile);
        } catch (FileNotFoundException ex) {
            throw new PdfRecompressionException("File wasn't found", ex);
        }
    }

    // if prefix is not set then prefix set to name of pdf without .pdf
    // if pdfFile has unconsistent name (without suffix .pdf) and name longer than 4 chars then last for chars are removed
    // and this string set as prefix
    if ((prefix == null) && (pdfFile.length() > 4)) {
        prefix = pdfFile.substring(0, pdfFile.length() - 4);
    }

    PDFParser parser = null;
    PDDocument doc = null;
    try {
        parser = new PDFParser(inputStream);
        parser.parse();
        doc = parser.getPDDocument();

        AccessPermission accessPermissions = doc.getCurrentAccessPermission();

        if (!accessPermissions.canExtractContent()) {
            throw new PdfRecompressionException("Error: You do not have permission to extract images.");
        }

        // going page by page
        List pages = doc.getDocumentCatalog().getAllPages();
        for (int pageNumber = 0; pageNumber < pages.size(); pageNumber++) {
            if ((pagesToProcess != null) && (!pagesToProcess.contains(pageNumber + 1))) {
                continue;
            }
            PDPage page = (PDPage) pages.get(pageNumber);
            PDResources resources = page.getResources();
            Map xobjs = resources.getXObjects();

            if (xobjs != null) {
                Iterator xobjIter = xobjs.keySet().iterator();
                while (xobjIter.hasNext()) {
                    String key = (String) xobjIter.next();
                    PDXObject xobj = (PDXObject) xobjs.get(key);
                    Map images;
                    if (xobj instanceof PDXObjectForm) {
                        PDXObjectForm xform = (PDXObjectForm) xobj;
                        images = xform.getResources().getImages();
                    } else {
                        images = resources.getImages();
                    }

                    // reading images from each page and saving them to file
                    if (images != null) {
                        Iterator imageIter = images.keySet().iterator();
                        while (imageIter.hasNext()) {
                            String imKey = (String) imageIter.next();
                            PDXObjectImage image = (PDXObjectImage) images.get(imKey);

                            PDStream pdStr = new PDStream(image.getCOSStream());
                            List filters = pdStr.getFilters();

                            if (image.getBitsPerComponent() > 1) {
                                log.info("It is not a bitonal image => skipping");
                                continue;
                            }

                            // at this moment for preventing bad output (bad coloring) from LZWDecode filter
                            if (filters.contains(COSName.LZW_DECODE.getName())) {
                                log.info("This is LZWDecoded => skipping");
                                continue;

                            }

                            // detection of unsupported filters by pdfBox library
                            if (filters.contains("JBIG2Decode")) {
                                log.info("Allready compressed according to JBIG2 standard => skipping");
                                continue;
                            }
                            if (filters.contains("JPXDecode")) {
                                log.info("Unsupported filter JPXDecode => skipping");
                                continue;
                            }

                            COSObject cosObj = new COSObject(image.getCOSObject());
                            int objectNum = cosObj.getObjectNumber().intValue();
                            int genNum = cosObj.getGenerationNumber().intValue();
                            log.debug(objectNum + " " + genNum + " obj");

                            String name = getUniqueFileName(prefix + imKey, image.getSuffix());
                            log.debug("Writing image:" + name);
                            image.write2file(name);

                            PdfImageInformation pdfImageInfo = new PdfImageInformation(key, image.getWidth(),
                                    image.getHeight(), objectNum, genNum);
                            originalImageInformations.add(pdfImageInfo);
                            log.debug(pdfImageInfo.toString());

                            namesOfImages.add(name + "." + image.getSuffix());
                        }
                    }

                }
            }

        }
    } catch (IOException ex) {
        throw new PdfRecompressionException("Unable to parse PDF document", ex);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                throw new PdfRecompressionException(ex);
            }
        }
    }
}

From source file:cz.muni.pdfjbim.PdfImageProcessor.java

License:Apache License

/**
 * replace images by they recompressed version according to JBIG2 standard
 * positions and image data given in imagesData
 * @param pdfName represents name of original PDF file
 * @param os represents output stream for writing changed PDF file
 * @param imagesData contains compressed images according to JBIG2 standard and informations about them
 * @throws PdfRecompressionException if version of PDF is lower than 1.4 or was catch DocumentException or IOException
 *//*from   ww  w.j av  a 2  s . com*/
public void replaceImageUsingIText(String pdfName, OutputStream os, Jbig2ForPdf imagesData)
        throws PdfRecompressionException {
    if (pdfName == null) {
        throw new NullPointerException("pdfName");
    }

    if (os == null) {
        throw new NullPointerException("os");
    }

    if (imagesData == null) {
        throw new NullPointerException("imagesData is null => nothing to recompress");
    }

    Map<PdfObjId, PdfImage> jbig2Images = imagesData.getMapOfJbig2Images();

    PdfReader pdf;
    PdfStamper stp = null;
    try {
        pdf = new PdfReader(pdfName);
        stp = new PdfStamper(pdf, os);
        PdfWriter writer = stp.getWriter();

        int version;
        if ((version = Integer.parseInt(String.valueOf(pdf.getPdfVersion()))) < 4) {
            writer.setPdfVersion(PdfWriter.PDF_VERSION_1_4);
        }

        Iterator itImages = jbig2Images.values().iterator();
        String key;
        if (itImages.hasNext()) {
            PdfImage myImg = (PdfImage) itImages.next();
            key = myImg.getPdfImageInformation().getKey();
        } else {
            key = "im0";
        }

        for (int pageNum = 1; pageNum <= pdf.getNumberOfPages(); pageNum++) {

            PdfDictionary pg = pdf.getPageN(pageNum);
            PdfDictionary resPg = (PdfDictionary) PdfReader.getPdfObject(pg.get(PdfName.RESOURCES));

            PdfDictionary xobjResPg = (PdfDictionary) PdfReader.getPdfObject(resPg.get(PdfName.XOBJECT));

            PdfObject obj = null;
            if (xobjResPg != null) {
                for (Iterator it = xobjResPg.getKeys().iterator(); it.hasNext();) {
                    PdfObject pdfObjIndirect = xobjResPg.get((PdfName) it.next());
                    if (pdfObjIndirect.isIndirect()) {
                        PdfDictionary pdfObj2 = (PdfDictionary) PdfReader.getPdfObject(pdfObjIndirect);
                        PdfDictionary xobj2Res = (PdfDictionary) PdfReader
                                .getPdfObject(pdfObj2.get(PdfName.RESOURCES));
                        if (xobj2Res != null) {
                            for (Iterator it2 = xobj2Res.getKeys().iterator(); it2.hasNext();) {
                                PdfObject resObj = xobj2Res.get((PdfName) it2.next());
                            }
                            PdfDictionary xobj = (PdfDictionary) PdfReader
                                    .getPdfObject(xobj2Res.get(PdfName.XOBJECT));
                            if (xobj == null) {
                                continue;
                            }
                            obj = xobj.get(new PdfName(key));
                        } else {
                            obj = xobjResPg.get(new PdfName(key));
                            if (obj == null) {
                                obj = pdfObjIndirect;
                            }
                        }
                    }
                }
            }

            if ((obj != null) && (obj.isIndirect())) {

                PdfDictionary tg = (PdfDictionary) PdfReader.getPdfObject(obj);
                if (tg == null) {
                    continue;
                }
                PdfName type = (PdfName) PdfReader.getPdfObject(tg.get(PdfName.SUBTYPE));
                if (PdfName.IMAGE.equals(type)) {
                    PRIndirectReference ref = (PRIndirectReference) obj;
                    PdfObjId imId = new PdfObjId(ref.getNumber(), ref.getGeneration());
                    PdfImage jbImage = jbig2Images.get(imId);
                    if (jbImage == null) {
                        continue;
                    }
                    PdfImageInformation jbImageInfo = jbImage.getPdfImageInformation();
                    Image img = Image.getInstance(jbImageInfo.getWidth(), jbImageInfo.getHeight(),
                            jbImage.getImageData(), imagesData.getGlobalData());

                    PdfReader.killIndirect(obj);
                    Image maskImage = img.getImageMask();

                    if (maskImage != null) {
                        writer.addDirectImageSimple(maskImage);
                    }
                    writer.addDirectImageSimple(img, (PRIndirectReference) obj);
                }
            }
        }
        stp.close();
    } catch (IOException ioEx) {
        throw new PdfRecompressionException(ioEx);
    } catch (DocumentException dEx) {
        throw new PdfRecompressionException(dEx);
    } finally {
        Tools.deleteFilesFromList(imagesData.getJbFiles().toArray(new File[0]));
    }
}

From source file:cz.muni.pdfjbim.PdfImageReplacer.java

License:Apache License

/**
 * replace images by they recompressed version according to JBIG2 standard positions and image
 * data given in imagesData/*  w ww .  j  a  v a  2  s  . c o  m*/
 *
 * @param originalPdf represents name of original PDF file
 * @param os represents output stream for writing changed PDF file
 * @param imagesData contains compressed images according to JBIG2 standard and informations
 * about them
 * @throws PdfRecompressionException if version of PDF is lower than 1.4 or was catch
 * DocumentException or IOException
 */
public void replaceImageUsingIText(InputStream originalPdf, OutputStream os, List<Jbig2ForPdf> imagesDataList)
        throws PdfRecompressionException {
    if (originalPdf == null) {
        throw new NullPointerException("pdfName");
    }

    if (os == null) {
        throw new NullPointerException("os");
    }

    if (imagesDataList == null) {
        throw new NullPointerException("imagesData is null => nothing to recompress");
    }

    log.info("Replacing old images in PDF with their equivalent encoded according to standard JBIG2");
    PdfReader pdf;
    PdfStamper stp = null;
    try {
        pdf = new PdfReader(originalPdf);
        stp = new PdfStamper(pdf, os);
        PdfWriter writer = stp.getWriter();

        int version;
        if ((version = Integer.parseInt(String.valueOf(pdf.getPdfVersion()))) < 4) {
            log.debug("PDF version of original PDF was {} => changing to PDF version 1.4", pdf.getPdfVersion());
            writer.setPdfVersion(PdfWriter.PDF_VERSION_1_4);
        }

        for (Jbig2ForPdf imagesData : imagesDataList) {

            Map<PdfObjId, PdfImage> jbig2Images = imagesData.getMapOfJbig2Images();

            Iterator itImages = jbig2Images.values().iterator();
            String key;
            if (itImages.hasNext()) {
                PdfImage myImg = (PdfImage) itImages.next();
                key = myImg.getPdfImageInformation().getKey();
            } else {
                key = "im0";
            }

            for (int pageNum = 1; pageNum <= pdf.getNumberOfPages(); pageNum++) {

                PdfDictionary pg = pdf.getPageN(pageNum);
                PdfDictionary resPg = (PdfDictionary) PdfReader.getPdfObject(pg.get(PdfName.RESOURCES));

                PdfDictionary xobjResPg = (PdfDictionary) PdfReader.getPdfObject(resPg.get(PdfName.XOBJECT));

                PdfObject obj = null;
                if (xobjResPg != null) {
                    for (Iterator it = xobjResPg.getKeys().iterator(); it.hasNext();) {
                        PdfObject pdfObjIndirect = xobjResPg.get((PdfName) it.next());
                        if (pdfObjIndirect.isIndirect()) {
                            PdfDictionary pdfObj2 = (PdfDictionary) PdfReader.getPdfObject(pdfObjIndirect);
                            PdfDictionary xobj2Res = (PdfDictionary) PdfReader
                                    .getPdfObject(pdfObj2.get(PdfName.RESOURCES));
                            if (xobj2Res != null) {
                                for (Iterator it2 = xobj2Res.getKeys().iterator(); it2.hasNext();) {
                                    PdfObject resObj = xobj2Res.get((PdfName) it2.next());
                                }
                                PdfDictionary xobj = (PdfDictionary) PdfReader
                                        .getPdfObject(xobj2Res.get(PdfName.XOBJECT));
                                if (xobj == null) {
                                    continue;
                                }
                                obj = xobj.get(new PdfName(key));
                            } else {
                                obj = xobjResPg.get(new PdfName(key));
                                if (obj == null) {
                                    obj = pdfObjIndirect;
                                }
                            }
                        }
                    }
                }

                if ((obj != null) && (obj.isIndirect())) {

                    PdfDictionary tg = (PdfDictionary) PdfReader.getPdfObject(obj);
                    if (tg == null) {
                        continue;
                    }
                    PdfName type = (PdfName) PdfReader.getPdfObject(tg.get(PdfName.SUBTYPE));
                    if (PdfName.IMAGE.equals(type)) {
                        PRIndirectReference ref = (PRIndirectReference) obj;
                        PdfObjId imId = new PdfObjId(ref.getNumber(), ref.getGeneration());
                        PdfImage jbImage = jbig2Images.get(imId);
                        if (jbImage == null) {
                            continue;
                        }

                        log.debug("Replacing image {}", jbImage);
                        PdfImageInformation jbImageInfo = jbImage.getPdfImageInformation();
                        Image img = Image.getInstance(jbImageInfo.getWidth(), jbImageInfo.getHeight(),
                                jbImage.getImageData(), imagesData.getGlobalData());

                        PdfReader.killIndirect(obj);
                        Image maskImage = img.getImageMask();

                        if (maskImage != null) {
                            writer.addDirectImageSimple(maskImage);
                        }
                        writer.addDirectImageSimple(img, (PRIndirectReference) obj);
                    }
                }
            }
        }
    } catch (IOException ioEx) {
        throw new PdfRecompressionException(ioEx);
    } catch (DocumentException dEx) {
        throw new PdfRecompressionException(dEx);
    } finally {
        log.debug("Deleting temporary files created during process of PDF recompression");
        for (Jbig2ForPdf imagesData : imagesDataList) {
            Tools.deleteFilesFromList(imagesData.getJbFiles().toArray(new File[0]));
        }
        try {
            if (stp != null) {
                stp.close();
            }
        } catch (DocumentException ex) {
            log.error("Exception thrown while closing stream", ex);
        } catch (IOException ex) {
            log.error("Exception thrown while closing stream", ex);
        }
    }

}

From source file:de.drippinger.cytricHelper.CytricHelper.java

License:Open Source License

public void manipulatePdf(String sourceFile, String expenseID) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(sourceFile);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(getOutputName(sourceFile)));

    PdfContentByte over = stamper.getOverContent(1);
    Phrase p = new Phrase(String.format("Cytric ID: %s", expenseID));
    ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, 500, reader.getPageSize(1).getHeight() - 30, 0);
    over.saveState();//w  w w . j  a v a 2 s  .  c o  m

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

From source file:de.earthdawn.ECEPdfExporter.java

License:Open Source License

public void exportRedbrickSimple(EDCHARACTER edCharakter, File outFile) throws DocumentException, IOException {
    PdfReader reader = new PdfReader(new FileInputStream(new File("./templates/ed3_character_sheet.pdf")));
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outFile));
    acroFields = stamper.getAcroFields();
    CharacterContainer character = new CharacterContainer(edCharakter);
    // +++ DEBUG +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
    //Set<String> fieldNames = acroFields.getFields().keySet();
    //fieldNames = new TreeSet<String>(fieldNames);
    //for( String fieldName : fieldNames ) {
    //   acroFields.setField( fieldName, fieldName );
    //}// w w w  .  jav  a2 s  .  c o  m
    // +++ ~DEBUG ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    exportCommonFields(character, 16, 41);
    acroFields.setField("Shield", "none");
    acroFields.setField("ShieldDeflectionBonus", "na");
    int armor_max = 0;
    int shield_max = 0;
    for (ARMORType armor : character.getProtection().getARMOROrSHIELD()) {
        if (!armor.getUsed().equals(YesnoType.YES))
            continue;
        if (armor.getClass().getSimpleName().equals("ARMORType")) {
            if (armor.getPhysicalarmor() > armor_max) {
                armor_max = armor.getPhysicalarmor();
                acroFields.setField("Armor", armor.getName());
            }
        } else if (armor.getClass().getSimpleName().equals("SHIELDType")) {
            SHIELDType shield = (SHIELDType) armor;
            if (shield.getPhysicalarmor() > shield_max) {
                shield_max = armor.getPhysicalarmor();
                acroFields.setField("Shield", shield.getName());
                acroFields.setField("ShieldDeflectionBonus",
                        shield.getPhysicaldeflectionbonus() + "/" + shield.getMysticdeflectionbonus());
            }
        } else {
            System.err.println("Unbekannte Rstungstyp: " + armor.getClass().getSimpleName());
        }
    }
    acroFields.setField("Discipline", concat(" / ", character.getDisciplineNames()));
    acroFields.setField("Circle", concat(" / ", character.getDisciplineCircles()));
    int counterKarmaritual = 0;
    for (String karmaritual : character.getAllKarmaritual()) {
        for (String description : wrapString(50, karmaritual)) {
            if (counterKarmaritual > 11) {
                System.err.println("Karmaritual description is to long. Only first 12 lines were displayed.");
                break;
            }
            acroFields.setField("KarmaRitual." + counterKarmaritual, description);
            counterKarmaritual++;
        }
    }
    List<DISCIPLINEType> disciplines = character.getDisciplines();
    if (disciplines.size() > 0) {
        DISCIPLINEType discipline1 = disciplines.get(0);
        List<TALENTType> disziplinetalents = discipline1.getDISZIPLINETALENT();
        Collections.sort(disziplinetalents, new TalentComparator());
        HashMap<String, ATTRIBUTEType> attributes = character.getAttributes();
        int counter = 0;
        for (TALENTType talent : disziplinetalents) {
            if ((talent.getCircle() > 4) && (counter < 9)) {
                counter = 9;
            }
            setTalent(counter, talent, attributes);
            counter++;
        }
        List<TALENTType> optionaltalents = discipline1.getOPTIONALTALENT();
        Collections.sort(optionaltalents, new TalentComparator());
        counter = 0;
        for (TALENTType talent : optionaltalents) {
            if ((talent.getCircle() > 4) && (counter < 4)) {
                counter = 4;
            }
            setTalent(13 + counter, talent, attributes);
            // Optionale Talente knnen Karma erfordern
            if (talent.getKarma().equals(YesnoType.YES)) {
                acroFields.setField("KarmaRequired." + counter, "Yes");
            } else {
                acroFields.setField("KarmaRequired." + counter, "");
            }
            counter++;
        }
    }
    List<WEAPONType> weapons = character.getWeapons();
    if (weapons != null) {
        int counter = 0;
        for (WEAPONType weapon : weapons) {
            acroFields.setField("Weapon." + counter, weapon.getName());
            acroFields.setField("WeaponDmgStep." + counter, String.valueOf(weapon.getDamagestep()));
            acroFields.setField("Weapon Size." + counter, String.valueOf(weapon.getSize()));
            acroFields.setField("WeaponTimesForged." + counter, String.valueOf(weapon.getTimesforged()));
            acroFields.setField("WeaponShortRange." + counter, String.valueOf(weapon.getShortrange()));
            acroFields.setField("Weapon Long Range." + counter, String.valueOf(weapon.getLongrange()));
            counter++;
        }
    }

    List<List<SPELLType>> spellslist = new ArrayList<List<SPELLType>>();
    spellslist.add(character.getOpenSpellList());
    for (DISCIPLINEType discipline : disciplines)
        spellslist.add(discipline.getSPELL());
    setSpellRedbrick(spellslist);

    counterEquipment = 0;
    for (ITEMType item : listArmorAndWeapon(character))
        addEquipment(item.getName(), item.getWeight());
    for (ITEMType item : character.getItems())
        addEquipment(item.getName(), item.getWeight());
    for (MAGICITEMType item : character.getMagicItem()) {
        StringBuffer text = new StringBuffer(item.getName());
        text.append(" (");
        text.append(item.getBlooddamage());
        text.append("/");
        text.append(item.getDepatterningrate());
        text.append("/");
        text.append(item.getEnchantingdifficultynumber());
        text.append(")");
        addEquipment(text.toString(), item.getWeight());
    }

    int copperPieces = 0;
    int goldPieces = 0;
    int silverPieces = 0;
    for (COINSType coins : character.getAllCoins()) {
        addEquipment(coinsToString(coins), coins.getWeight());
        copperPieces += coins.getCopper();
        silverPieces += coins.getSilver();
        goldPieces += coins.getGold();
    }
    acroFields.setField("CopperPieces", String.valueOf(copperPieces));
    acroFields.setField("SilverPieces", String.valueOf(silverPieces));
    acroFields.setField("GoldPieces", String.valueOf(goldPieces));

    int counterDescription = 0;
    for (String description : wrapString(50, character.getDESCRIPTION())) {
        acroFields.setField("ShortDescription." + counterDescription, description);
        counterDescription++;
        if (counterDescription > 7) {
            System.err.println("Character description to long. Only first 8 lines were displayed.");
            break;
        }
    }

    List<THREADITEMType> magicitems = character.getThreadItem();
    if (!magicitems.isEmpty()) {
        THREADITEMType magicitem = character.getThreadItem().get(0);
        if (magicitem != null) {
            int counterThreadItem = 0;
            int weaventhreadrank = magicitem.getWeaventhreadrank();
            acroFields.setField("MagicalTreasureName", magicitem.getName());
            acroFields.setField("MagicalTreasureSpellDefense", String.valueOf(magicitem.getSpelldefense()));
            acroFields.setField("MagicalTreasureMaxThreads", String.valueOf(magicitem.getMaxthreads()));
            int counterMagicItemDescription = 0;
            for (String description : wrapString(50, magicitem.getDESCRIPTION())) {
                acroFields.setField("MagicalTreasureDesc." + counterMagicItemDescription, description);
                counterMagicItemDescription++;
                if (counterMagicItemDescription > 2) {
                    System.err.println("MagicItem description to long. Only first 3 lines were displayed.");
                    break;
                }
            }
            int counterMagicItemRank = 0;
            for (THREADRANKType rank : magicitem.getTHREADRANK()) {
                acroFields.setField("MagicalTreasureRank." + counterMagicItemRank,
                        String.valueOf(counterMagicItemRank + 1));
                acroFields.setField("MagicalTreasureLPCost." + counterMagicItemRank,
                        String.valueOf(rank.getLpcost()));
                acroFields.setField("MagicalTreasureKeyKnowledge." + counterMagicItemRank,
                        rank.getKeyknowledge());
                acroFields.setField("MagicalTreasureEffect." + counterMagicItemRank, rank.getEffect());
                if (counterMagicItemRank < weaventhreadrank) {
                    acroFields.setField("ThreadMagicTarget." + counterThreadItem, magicitem.getName());
                    acroFields.setField("ThreadMagicEffect." + counterThreadItem, rank.getEffect());
                    acroFields.setField("ThreadMagicLPCost." + counterThreadItem,
                            String.valueOf(rank.getLpcost()));
                    acroFields.setField("ThreadMagicRank." + counterThreadItem,
                            String.valueOf(counterMagicItemRank + 1));
                    counterThreadItem++;
                }
                counterMagicItemRank++;
            }
        }
    }

    int counterBloodCharms = 0;
    for (MAGICITEMType item : character.getBloodCharmItem()) {
        acroFields.setField("BloodMagicType." + counterBloodCharms, item.getName());
        if (item.getUsed().equals(YesnoType.YES)) {
            acroFields.setField("BloodMagicDamage." + counterBloodCharms,
                    String.valueOf(item.getBlooddamage()));
        } else {
            acroFields.setField("BloodMagicDamage." + counterBloodCharms, "(" + item.getBlooddamage() + ")");
        }
        acroFields.setField("BloodMagicDR." + counterBloodCharms, String.valueOf(item.getDepatterningrate()));
        acroFields.setField("BloodMagicEffect." + counterBloodCharms, item.getEffect());
        counterBloodCharms++;
    }

    stamper.close();
}

From source file:de.earthdawn.ECEPdfExporter.java

License:Open Source License

public void exportRedbrickExtended(EDCHARACTER edCharakter, File outFile)
        throws DocumentException, IOException {
    PdfReader reader = new PdfReader(
            new FileInputStream(new File("./templates/ed3_extended_character_sheet.pdf")));
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outFile));
    acroFields = stamper.getAcroFields();
    CharacterContainer character = new CharacterContainer(edCharakter);
    // +++ DEBUG +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
    //Set<String> fieldNames = acroFields.getFields().keySet();
    //fieldNames = new TreeSet<String>(fieldNames);
    //for( String fieldName : fieldNames ) {
    //   acroFields.setField( fieldName, fieldName );
    //   System.out.println( fieldName );
    //}//  w  w  w.j  a v  a 2 s.c o  m
    // +++ ~DEBUG ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    exportCommonFields(character, 16, 55);
    setButtons(character.getWound().getNormal(), "WoundPenalties.", 9);
    acroFields.setField("Shield", "none");
    acroFields.setField("ShieldDeflectionBonus", "na");

    // Charakter Potrait-Bild einfgen
    List<Base64BinaryType> potraits = character.getPortrait();
    if (!potraits.isEmpty()) {
        Image image = Image.getInstance(potraits.get(0).getValue());
        image.setAbsolutePosition(35f, 517f);
        image.scaleAbsolute(165f, 200f);
        PdfContentByte overContent = stamper.getOverContent(2);
        overContent.addImage(image);
    }

    int armor_max = 0;
    int shield_max = 0;
    for (ARMORType armor : character.getProtection().getARMOROrSHIELD()) {
        if (!armor.getUsed().equals(YesnoType.YES))
            continue;
        if (armor.getClass().getSimpleName().equals("ARMORType")) {
            if (armor.getPhysicalarmor() > armor_max) {
                armor_max = armor.getPhysicalarmor();
                acroFields.setField("Armor", armor.getName());
            }
        } else if (armor.getClass().getSimpleName().equals("SHIELDType")) {
            SHIELDType shield = (SHIELDType) armor;
            if (shield.getPhysicalarmor() > shield_max) {
                shield_max = armor.getPhysicalarmor();
                acroFields.setField("Shield", shield.getName());
                acroFields.setField("ShieldDeflectionBonus",
                        shield.getPhysicaldeflectionbonus() + "/" + shield.getMysticdeflectionbonus());
            }
        } else {
            System.err.println("Unbekannte Rstungstyp: " + armor.getClass().getSimpleName());
        }
    }
    acroFields.setField("Discipline", concat(" / ", character.getDisciplineNames()));
    acroFields.setField("Circle", concat(" / ", character.getDisciplineCircles()));
    int counterKarmaritual = 0;
    for (String karmaritual : character.getAllKarmaritual()) {
        for (String description : wrapString(50, karmaritual)) {
            if (counterKarmaritual > 11) {
                System.err.println("Karmaritual description is to long. Only first 12 lines were displayed.");
                break;
            }
            acroFields.setField("KarmaRitual." + counterKarmaritual, description);
            counterKarmaritual++;
        }
    }
    List<DISCIPLINEType> disciplines = character.getDisciplines();
    if (!disciplines.isEmpty()) {
        DISCIPLINEType discipline1 = disciplines.get(0);
        int counter = 0;
        List<TALENTType> disziplinetalents = discipline1.getDISZIPLINETALENT();
        Collections.sort(disziplinetalents, new TalentComparator());
        HashMap<String, ATTRIBUTEType> attributes = character.getAttributes();
        for (TALENTType talent : disziplinetalents) {
            if ((talent.getCircle() > 4) && (counter < 9))
                counter = 9;
            if ((talent.getCircle() > 8) && (counter < 13))
                counter = 13;
            if ((talent.getCircle() > 12) && (counter < 17))
                counter = 17;
            setTalent(counter, talent, attributes);
            counter++;
        }
        List<TALENTType> optionaltalents = discipline1.getOPTIONALTALENT();
        Collections.sort(optionaltalents, new TalentComparator());
        counter = 0;
        for (TALENTType talent : optionaltalents) {
            if ((talent.getCircle() > 4) && (counter < 7))
                counter = 7;
            if ((talent.getCircle() > 8) && (counter < 13))
                counter = 13;
            setTalent(20 + counter, talent, attributes);
            // Optionale Talente knnen Karma erfordern
            if (talent.getKarma().equals(YesnoType.YES)) {
                acroFields.setField("KarmaRequired." + counter, "Yes");
            } else {
                acroFields.setField("KarmaRequired." + counter, "");
            }
            counter++;
        }
    }
    if (disciplines.size() > 1) {
        DISCIPLINEType discipline2 = disciplines.get(1);
        int counter = 36;
        List<TALENTType> disziplinetalents = discipline2.getDISZIPLINETALENT();
        Collections.sort(disziplinetalents, new TalentComparator());
        HashMap<String, ATTRIBUTEType> attributes = character.getAttributes();
        for (TALENTType talent : disziplinetalents) {
            if ((talent.getCircle() > 4) && (counter < 44))
                counter = 44;
            if ((talent.getCircle() > 8) && (counter < 48))
                counter = 48;
            if ((talent.getCircle() > 12) && (counter < 52))
                counter = 52;
            setTalent(counter, talent, attributes);
            counter++;
        }
        List<TALENTType> optionaltalents = discipline2.getOPTIONALTALENT();
        Collections.sort(optionaltalents, new TalentComparator());
        counter = 16;
        for (TALENTType talent : optionaltalents) {
            if ((talent.getCircle() > 4) && (counter < 22))
                counter = 22;
            if ((talent.getCircle() > 8) && (counter < 26))
                counter = 26;
            setTalent(39 + counter, talent, attributes);
            // Optionale Talente knnen Karma erfordern
            if (talent.getKarma().equals(YesnoType.YES)) {
                acroFields.setField("KarmaRequired." + counter, "Yes");
            } else {
                acroFields.setField("KarmaRequired." + counter, "");
            }
            counter++;
        }
    }
    List<WEAPONType> weapons = character.getWeapons();
    if (weapons != null) {
        int counter_melee = 0;
        int counter_range = 0;
        for (WEAPONType weapon : weapons) {
            if (weapon.getShortrange() > 0) {
                acroFields.setField("RangedWeapon." + counter_range, weapon.getName());
                acroFields.setField("RangedWeaponDmgStep." + counter_range,
                        String.valueOf(weapon.getDamagestep()));
                acroFields.setField("RangedWeapon Size." + counter_range, String.valueOf(weapon.getSize()));
                acroFields.setField("RangedWeaponTimesForged." + counter_range,
                        String.valueOf(weapon.getTimesforged()));
                acroFields.setField("WeaponShortRange." + counter_range,
                        String.valueOf(weapon.getShortrange()));
                acroFields.setField("Weapon Long Range." + counter_range,
                        String.valueOf(weapon.getLongrange()));
                counter_range++;
            } else {
                acroFields.setField("Weapon." + counter_melee, weapon.getName());
                acroFields.setField("WeaponDmgStep." + counter_melee, String.valueOf(weapon.getDamagestep()));
                acroFields.setField("Weapon Size." + counter_melee, String.valueOf(weapon.getSize()));
                acroFields.setField("WeaponTimesForged." + counter_melee,
                        String.valueOf(weapon.getTimesforged()));
                counter_melee++;
            }
        }
    }

    List<List<SPELLType>> spellslist = new ArrayList<List<SPELLType>>();
    spellslist.add(character.getOpenSpellList());
    for (DISCIPLINEType discipline : disciplines)
        spellslist.add(discipline.getSPELL());
    setSpellRedbrick(spellslist);

    counterEquipment = 0;
    for (ITEMType item : listArmorAndWeapon(character))
        addEquipment(item.getName(), item.getWeight());
    for (ITEMType item : character.getItems())
        addEquipment(item.getName(), item.getWeight());
    for (MAGICITEMType item : character.getMagicItem()) {
        StringBuffer text = new StringBuffer(item.getName());
        text.append(" (");
        text.append(item.getBlooddamage());
        text.append("/");
        text.append(item.getDepatterningrate());
        text.append("/");
        text.append(item.getEnchantingdifficultynumber());
        text.append(")");
        addEquipment(text.toString(), item.getWeight());
    }

    int copperPieces = 0;
    int goldPieces = 0;
    int silverPieces = 0;
    for (COINSType coins : character.getAllCoins()) {
        addEquipment(coinsToString(coins), coins.getWeight());
        copperPieces += coins.getCopper();
        silverPieces += coins.getSilver();
        goldPieces += coins.getGold();
    }
    acroFields.setField("CopperPieces", String.valueOf(copperPieces));
    acroFields.setField("SilverPieces", String.valueOf(silverPieces));
    acroFields.setField("GoldPieces", String.valueOf(goldPieces));

    int counterDescription = 0;
    for (String description : wrapString(60, character.getDESCRIPTION())) {
        acroFields.setField("ShortDescription." + counterDescription, description);
        counterDescription++;
        if (counterDescription > 7) {
            System.err.println("Character description to long. Only first 8 lines were displayed.");
            break;
        }
    }

    int counterMagicItem = 0;
    int counterThreadItem = 0;
    for (THREADITEMType item : character.getThreadItem()) {
        int weaventhreadrank = item.getWeaventhreadrank();
        acroFields.setField("MagicalTreasureName." + counterMagicItem, item.getName());
        acroFields.setField("MagicalTreasureSpellDefense." + counterMagicItem,
                String.valueOf(item.getSpelldefense()));
        acroFields.setField("MagicalTreasureMaxThreads." + counterMagicItem,
                String.valueOf(item.getMaxthreads()));
        int counterMagicItemDescription = 0;
        for (String description : wrapString(55, item.getDESCRIPTION())) {
            acroFields.setField("MagicalTreasureDesc." + counterMagicItemDescription + "." + counterMagicItem,
                    description);
            counterMagicItemDescription++;
            if (counterMagicItemDescription > 2) {
                System.err.println("MagicItem description to long. Only first 3 lines were displayed.");
                break;
            }
        }
        int counterMagicItemRank = 0;
        for (THREADRANKType rank : item.getTHREADRANK()) {
            acroFields.setField("MagicalTreasureRank." + counterMagicItemRank + "." + counterMagicItem,
                    String.valueOf(counterMagicItemRank + 1));
            acroFields.setField("MagicalTreasureLPCost." + counterMagicItemRank + "." + counterMagicItem,
                    String.valueOf(rank.getLpcost()));
            acroFields.setField("MagicalTreasureKeyKnowledge." + counterMagicItemRank + "." + counterMagicItem,
                    rank.getKeyknowledge());
            acroFields.setField("MagicalTreasureEffect." + counterMagicItemRank + "." + counterMagicItem,
                    rank.getEffect());
            if (counterMagicItemRank < weaventhreadrank) {
                acroFields.setField("ThreadMagicTarget." + counterThreadItem, item.getName());
                acroFields.setField("ThreadMagicEffect." + counterThreadItem, rank.getEffect());
                acroFields.setField("ThreadMagicLPCost." + counterThreadItem, String.valueOf(rank.getLpcost()));
                acroFields.setField("ThreadMagicRank." + counterThreadItem,
                        String.valueOf(counterMagicItemRank + 1));
                counterThreadItem++;
            }
            counterMagicItemRank++;
        }
        counterMagicItem++;
    }

    int counterBloodCharms = 0;
    for (MAGICITEMType item : character.getBloodCharmItem()) {
        acroFields.setField("BloodMagicType." + counterBloodCharms, item.getName());
        if (item.getUsed().equals(YesnoType.YES)) {
            acroFields.setField("BloodMagicDamage." + counterBloodCharms,
                    String.valueOf(item.getBlooddamage()));
        } else {
            acroFields.setField("BloodMagicDamage." + counterBloodCharms, "(" + item.getBlooddamage() + ")");
        }
        acroFields.setField("BloodMagicDR." + counterBloodCharms, String.valueOf(item.getDepatterningrate()));
        acroFields.setField("BloodMagicEffect." + counterBloodCharms, item.getEffect());
        counterBloodCharms++;
    }

    stamper.close();
}