Example usage for com.lowagie.text.pdf PdfContentByte addTemplate

List of usage examples for com.lowagie.text.pdf PdfContentByte addTemplate

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfContentByte addTemplate.

Prototype

public void addTemplate(PdfTemplate template, float x, float y) 

Source Link

Document

Adds a template to this content.

Usage

From source file:keel.GraphInterKeel.datacf.visualizeData.VisualizePanelCharts2D.java

License:Open Source License

private void topdfjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topdfjButtonActionPerformed
    // Save chart as a PDF file
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Save chart");
    KeelFileFilter fileFilter = new KeelFileFilter();
    fileFilter.addExtension("pdf");
    fileFilter.setFilterName("PDF images (.pdf)");
    chooser.setFileFilter(fileFilter);/*from  w w w .  j a va2  s  .  co m*/
    chooser.setCurrentDirectory(Path.getFilePath());
    int opcion = chooser.showSaveDialog(this);
    Path.setFilePath(chooser.getCurrentDirectory());
    if (opcion == JFileChooser.APPROVE_OPTION) {
        String nombre = chooser.getSelectedFile().getAbsolutePath();
        if (!nombre.toLowerCase().endsWith(".pdf")) {
            // Add correct extension
            nombre += ".pdf";
        }
        File tmp = new File(nombre);
        if (!tmp.exists() || JOptionPane.showConfirmDialog(this,
                "File " + nombre + " already exists. Do you want to replace it?", "Confirm",
                JOptionPane.YES_NO_OPTION, 3) == JOptionPane.YES_OPTION) {
            try {
                Document document = new Document();
                PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(nombre));
                document.addAuthor("KEEL");
                document.addSubject("Attribute comparison");
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(550, 412);
                Graphics2D g2 = tp.createGraphics(550, 412, new DefaultFontMapper());
                Rectangle2D r2D = new Rectangle2D.Double(0, 0, 550, 412);
                chart2.setBackgroundPaint(Color.white);
                chart2.draw(g2, r2D);
                g2.dispose();
                cb.addTemplate(tp, 20, 350);
                document.close();
            } catch (Exception exc) {
            }
        }
    }
}

From source file:managedbean.aas.reportController.java

public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) {

    Document document = new Document();
    try {//from ww  w.  ja  v a2  s  . co  m
        List<InputStream> pdfs = streamOfPDFFiles;
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }
        // Create a writer for the outputstream            
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
        // data

        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, 9);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
                            "" + currentPageNumber + " of " + totalPages, 520, 5, 0);
                    cb.endText();
                }
            }
            pageOfCurrentReaderPDF = 0;
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:mpv5.utils.export.Export.java

License:Open Source License

private static File mergeFiles(List<File> p) {

    Document document = new Document();
    try {//from   w  w w  . j  a va2 s.c  o  m
        List<InputStream> pdfs = new ArrayList<InputStream>();
        for (int i = 0; i < p.size(); i++) {
            File inputStream = p.get(i);
            pdfs.add(new FileInputStream(inputStream));
        }
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }

        File f = FileDirectoryHandler.getTempFile("pdf");
        FileOutputStream outputstream = new FileOutputStream(f);
        PdfWriter writer = PdfWriter.getInstance(document, outputstream);

        document.open();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        PdfContentByte cb = writer.getDirectContent();

        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);

            }
            pageOfCurrentReaderPDF = 0;
        }
        outputstream.flush();
        document.close();
        outputstream.close();

        return f;
    } catch (Exception e) {
        Log.Debug(e);
    } finally {
        if (document.isOpen()) {
            document.close();
        }
    }

    return null;
}

From source file:org.adempiere.pdf.Document.java

License:Open Source License

private static void writePDF(Pageable pageable, OutputStream output) {
    try {/*from   w ww . ja  va  2  s. c o  m*/
        final PageFormat pf = pageable.getPageFormat(0);

        final com.lowagie.text.Document document = new com.lowagie.text.Document(
                new Rectangle((int) pf.getWidth(), (int) pf.getHeight()));
        final PdfWriter writer = PdfWriter.getInstance(document, output);
        writer.setPdfVersion(PdfWriter.VERSION_1_2);
        document.open();
        final DefaultFontMapper mapper = new DefaultFontMapper();

        //Elaine 2009/02/17 - load additional font from directory set in PDF_FONT_DIR of System Configurator 
        String pdfFontDir = MSysConfig.getValue(PDF_FONT_DIR, "");
        if (pdfFontDir != null && pdfFontDir.trim().length() > 0) {
            pdfFontDir = pdfFontDir.trim();
            File dir = new File(pdfFontDir);
            if (dir.exists() && dir.isDirectory())
                mapper.insertDirectory(pdfFontDir);
        }
        //

        final float w = (float) pf.getWidth();
        final float h = (float) pf.getHeight();
        final PdfContentByte cb = writer.getDirectContent();
        for (int page = 0; page < pageable.getNumberOfPages(); page++) {
            if (page != 0) {
                document.newPage();
            }

            final PdfTemplate tp = cb.createTemplate(w, h);
            final Graphics2D g2 = tp.createGraphics(w, h, mapper);
            tp.setWidth(w);
            tp.setHeight(h);
            pageable.getPrintable(page).print(g2, pf, page);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
        }
        document.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.adempiere.util.Document.java

private static void writePDF(Pageable pageable, OutputStream output) {
    try {//from ww w . j a  v a  2s  . c  o m
        final PageFormat pf = pageable.getPageFormat(0);

        Rectangle pageSize = new Rectangle((int) pf.getWidth(), (int) pf.getHeight());
        final com.lowagie.text.Document document = new com.lowagie.text.Document(pageSize);
        final PdfWriter writer = PdfWriter.getInstance(document, output);
        writer.setPdfVersion(PdfWriter.VERSION_1_2);
        document.open();
        final DefaultFontMapper mapper = new DefaultFontMapper();

        String pdfFontDir = /* MSysConfig.getValue( */PDF_FONT_DIR/* , "") */;
        if (pdfFontDir != null && pdfFontDir.trim().length() > 0) {
            pdfFontDir = pdfFontDir.trim();
            File dir = new File(pdfFontDir);
            if (dir.exists() && dir.isDirectory())
                mapper.insertDirectory(pdfFontDir);
        }
        final float w = (float) pf.getWidth();
        final float h = (float) pf.getHeight();
        final PdfContentByte cb = writer.getDirectContent();
        for (int page = 0; page < pageable.getNumberOfPages(); page++) {
            if (page != 0) {
                document.newPage();
            }

            final PdfTemplate tp = cb.createTemplate(w, h);
            final Graphics2D g2 = tp.createGraphics(w, h, mapper);
            tp.setWidth(w);
            tp.setHeight(h);
            pageable.getPrintable(page).print(g2, pf, page);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
        }
        document.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.adempiere.webui.apps.AEnv.java

License:Open Source License

/**
 *
 * @param pdfList//  w w w. jav a 2s .c  o m
 * @param outFile
 * @throws IOException
 * @throws DocumentException
 * @throws FileNotFoundException
 */
public static void mergePdf(List<File> pdfList, File outFile)
        throws IOException, DocumentException, FileNotFoundException {
    Document document = null;
    PdfWriter copy = null;
    for (File f : pdfList) {
        PdfReader reader = new PdfReader(f.getAbsolutePath());
        if (document == null) {
            document = new Document(reader.getPageSizeWithRotation(1));
            copy = PdfWriter.getInstance(document, new FileOutputStream(outFile));
            document.open();
        }
        int pages = reader.getNumberOfPages();
        PdfContentByte cb = copy.getDirectContent();
        for (int i = 1; i <= pages; i++) {
            document.newPage();
            PdfImportedPage page = copy.getImportedPage(reader, i);
            cb.addTemplate(page, 0, 0);
        }
    }
    document.close();
}

From source file:org.adempiere.webui.apps.ProcessDialog.java

License:Open Source License

public void onPrintShipments() {
    //   Loop through all items
    List<File> pdfList = new ArrayList<File>();
    for (int i = 0; i < m_ids.length; i++) {
        int M_InOut_ID = m_ids[i];
        ReportEngine re = ReportEngine.get(Env.getCtx(), ReportEngine.SHIPMENT, M_InOut_ID);
        pdfList.add(re.getPDF());/*www  . ja  v a 2s .c o  m*/
    }

    if (pdfList.size() > 1) {
        try {
            File outFile = File.createTempFile("PrintShipments", ".pdf");
            Document document = null;
            PdfWriter copy = null;
            for (File f : pdfList) {
                String fileName = f.getAbsolutePath();
                PdfReader reader = new PdfReader(fileName);
                reader.consolidateNamedDestinations();
                if (document == null) {
                    document = new Document(reader.getPageSizeWithRotation(1));
                    copy = PdfWriter.getInstance(document, new FileOutputStream(outFile));
                    document.open();
                }
                int pages = reader.getNumberOfPages();
                PdfContentByte cb = copy.getDirectContent();
                for (int i = 1; i <= pages; i++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, i);
                    cb.addTemplate(page, 0, 0);
                }
            }
            document.close();

            hideBusyDialog();
            Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(outFile));
            SessionManager.getAppDesktop().showWindow(win, "center");
        } catch (Exception e) {
            log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    } else if (pdfList.size() > 0) {
        hideBusyDialog();
        try {
            Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(pdfList.get(0)));
            SessionManager.getAppDesktop().showWindow(win, "center");
        } catch (Exception e) {
            log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }
}

From source file:org.adempiere.webui.apps.ProcessDialog.java

License:Open Source License

public void onPrintInvoices() {
    //   Loop through all items
    List<File> pdfList = new ArrayList<File>();
    for (int i = 0; i < m_ids.length; i++) {
        int C_Invoice_ID = m_ids[i];
        ReportEngine re = ReportEngine.get(Env.getCtx(), ReportEngine.INVOICE, C_Invoice_ID);
        pdfList.add(re.getPDF());//from   ww  w  .jav a  2  s  . c om
    }

    if (pdfList.size() > 1) {
        try {
            File outFile = File.createTempFile("PrintInvoices", ".pdf");
            Document document = null;
            PdfWriter copy = null;
            for (File f : pdfList) {
                PdfReader reader = new PdfReader(f.getAbsolutePath());
                if (document == null) {
                    document = new Document(reader.getPageSizeWithRotation(1));
                    copy = PdfWriter.getInstance(document, new FileOutputStream(outFile));
                    document.open();
                }
                PdfContentByte cb = copy.getDirectContent(); // Holds the PDF
                int pages = reader.getNumberOfPages();
                for (int i = 1; i <= pages; i++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, i);
                    cb.addTemplate(page, 0, 0);
                }
            }
            document.close();

            hideBusyDialog();
            Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(outFile));
            SessionManager.getAppDesktop().showWindow(win, "center");
        } catch (Exception e) {
            log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    } else if (pdfList.size() > 0) {
        try {
            Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(pdfList.get(0)));
            SessionManager.getAppDesktop().showWindow(win, "center");
        } catch (Exception e) {
            log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }
}

From source file:org.alchemy.core.AlcSession.java

License:Open Source License

/** Save the canvas to a single paged PDF file
 * /*  w  w w.  j  av  a 2s  .  c  om*/
 * @param file  The file object to save the pdf to
 * @return      True if save worked, otherwise false
 */
boolean saveSinglePdf(File file) {
    // Get the current 'real' size of the canvas without margins/borders
    java.awt.Rectangle bounds = Alchemy.canvas.getVisibleRect();
    //int singlePdfWidth = Alchemy.window.getWindowSize().width;
    //int singlePdfHeight = Alchemy.window.getWindowSize().height;
    com.lowagie.text.Document document = new com.lowagie.text.Document(
            new com.lowagie.text.Rectangle(bounds.width, bounds.height), 0, 0, 0, 0);
    System.out.println("Save Single Pdf Called: " + file.toString());
    boolean noError = true;

    try {

        PdfWriter singleWriter = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.addTitle("Alchemy Session");
        document.addAuthor(USER_NAME);
        document.addCreator("Alchemy <http://al.chemy.org>");

        // Add metadata and open the document
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        XmpWriter xmp = new XmpWriter(os);
        PdfSchema pdf = new PdfSchema();
        pdf.setProperty(PdfSchema.KEYWORDS, "Alchemy <http://al.chemy.org>");
        //pdf.setProperty(PdfSchema.VERSION, "1.4");
        xmp.addRdfDescription(pdf);
        xmp.close();
        singleWriter.setXmpMetadata(os.toByteArray());

        // To avoid transparent colurs being converted from RGB>CMYK>RGB
        // We have to add everything to a transparency group
        PdfTransparencyGroup transGroup = new PdfTransparencyGroup();
        transGroup.put(PdfName.CS, PdfName.DEVICERGB);

        document.open();

        PdfContentByte cb = singleWriter.getDirectContent();
        PdfTemplate tp = cb.createTemplate(bounds.width, bounds.height);

        document.newPage();

        cb.getPdfWriter().setGroup(transGroup);
        // Make sure the color space is Device RGB
        cb.setDefaultColorspace(PdfName.CS, PdfName.DEVICERGB);

        // Draw into the template and add it to the PDF 
        Graphics2D g2pdf = tp.createGraphics(bounds.width, bounds.height);
        Alchemy.canvas.setGuide(false);
        Alchemy.canvas.vectorCanvas.paintComponent(g2pdf);
        Alchemy.canvas.setGuide(true);
        g2pdf.dispose();
        cb.addTemplate(tp, 0, 0);

    } catch (DocumentException ex) {
        System.err.println(ex);
        noError = false;
    } catch (IOException ex) {
        System.err.println(ex);
        noError = false;
    }

    document.close();

    return noError;
}

From source file:org.allcolor.yahp.cl.converter.CDocumentReconstructor.java

License:Open Source License

/**
 * construct a pdf document from pdf parts.
 * /*from w ww . j a v  a 2s .  c o m*/
 * @param files
 *            list containing the pdf to assemble
 * @param properties
 *            converter properties
 * @param fout
 *            outputstream to write the new pdf
 * @param base_url
 *            base url of the document
 * @param producer
 *            producer of the pdf
 * 
 * @throws CConvertException
 *             if an error occured while reconstruct.
 */
public static void reconstruct(final List files, final Map properties, final OutputStream fout,
        final String base_url, final String producer, final PageSize[] size, final List hf)
        throws CConvertException {
    OutputStream out = fout;
    OutputStream out2 = fout;
    boolean signed = false;
    OutputStream oldOut = null;
    File tmp = null;
    File tmp2 = null;
    try {
        tmp = File.createTempFile("yahp", "pdf");
        tmp2 = File.createTempFile("yahp", "pdf");
        oldOut = out;
        if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) {
            signed = true;
            out2 = new FileOutputStream(tmp2);
        } // end if
        else {
            out2 = oldOut;
        }
        out = new FileOutputStream(tmp);
        com.lowagie.text.Document document = null;
        PdfCopy writer = null;
        boolean first = true;

        Map mapSizeDoc = new HashMap();

        int totalPage = 0;

        for (int i = 0; i < files.size(); i++) {
            final File fPDF = (File) files.get(i);
            final PdfReader reader = new PdfReader(fPDF.getAbsolutePath());
            reader.consolidateNamedDestinations();

            final int n = reader.getNumberOfPages();

            if (first) {
                first = false;
                // step 1: creation of a document-object
                // set title/creator/author
                document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, out);
                // use pdf version 1.5
                writer.setPdfVersion(PdfWriter.VERSION_1_3);
                // compress the pdf
                writer.setFullCompression();

                // check if encryption is needed
                if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                    final String password = (String) properties
                            .get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
                    final int securityType = CDocumentReconstructor.getSecurityFlags(properties);
                    writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, securityType);
                } // end if

                final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE);

                if (title != null) {
                    document.addTitle(title);
                } // end if
                else if (base_url != null) {
                    document.addTitle(base_url);
                } // end else if

                final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR);

                if (creator != null) {
                    document.addCreator(creator);
                } // end if
                else {
                    document.addCreator(IHtmlToPdfTransformer.VERSION);
                } // end else

                final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR);

                if (author != null) {
                    document.addAuthor(author);
                } // end if

                final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER);

                if (sproducer != null) {
                    document.add(new Meta("Producer", sproducer));
                } // end if
                else {
                    document.add(new Meta("Producer", (IHtmlToPdfTransformer.VERSION
                            + " - http://www.allcolor.org/YaHPConverter/ - " + producer)));
                } // end else

                // step 3: we open the document
                document.open();
            } // end if

            PdfImportedPage page;

            for (int j = 0; j < n;) {
                ++j;
                totalPage++;
                mapSizeDoc.put("" + totalPage, "" + i);
                page = writer.getImportedPage(reader, j);
                writer.addPage(page);
            } // end for
        } // end for

        document.close();
        out.flush();
        out.close();
        {
            final PdfReader reader = new PdfReader(tmp.getAbsolutePath());
            ;
            final int n = reader.getNumberOfPages();
            final PdfStamper stp = new PdfStamper(reader, out2);
            int i = 0;
            BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer();
            while (i < n) {
                i++;
                int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i));
                final int[] dsize = size[indexSize].getSize();
                final int[] dmargin = size[indexSize].getMargin();
                for (final Iterator it = hf.iterator(); it.hasNext();) {
                    final CHeaderFooter chf = (CHeaderFooter) it.next();
                    if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) {
                        continue;
                    } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) {
                        continue;
                    }
                    final String text = chf.getContent().replaceAll("<pagenumber>", "" + i)
                            .replaceAll("<pagecount>", "" + n);
                    // text over the existing page
                    final PdfContentByte over = stp.getOverContent(i);
                    final ByteArrayOutputStream bbout = new ByteArrayOutputStream();
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(),
                                properties, bbout);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(),
                                properties, bbout);
                    }
                    final PdfReader readerHF = new PdfReader(bbout.toByteArray());
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0);
                    }
                    readerHF.close();
                }
            }
            stp.close();
        }
        try {
            out2.flush();
        } catch (Exception ignore) {
        } finally {
            try {
                out2.close();
            } catch (Exception ignore) {
            }
        }
        if (signed) {

            final String keypassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD);
            final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
            final String keyStorepassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD);
            final String privateKeyFile = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE);
            final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON);
            final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION);
            final boolean selfSigned = !"false"
                    .equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING));
            PdfReader reader = null;

            if (password != null) {
                reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes());
            } // end if
            else {
                reader = new PdfReader(tmp2.getAbsolutePath());
            } // end else

            final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType())
                    : KeyStore.getInstance("pkcs12");
            ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray());

            final String alias = (String) ks.aliases().nextElement();
            final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray());
            final Certificate chain[] = ks.getCertificateChain(alias);
            final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0');

            if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                stp.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null,
                        CDocumentReconstructor.getSecurityFlags(properties));
            } // end if

            final PdfSignatureAppearance sap = stp.getSignatureAppearance();

            if (selfSigned) {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
            } // end if
            else {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            } // end else

            if (reason != null) {
                sap.setReason(reason);
            } // end if

            if (location != null) {
                sap.setLocation(location);
            } // end if

            stp.close();
            oldOut.flush();
        } // end if
    } // end try
    catch (final Exception e) {
        throw new CConvertException(
                "ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e);
    } // end catch
    finally {
        try {
            tmp.delete();
        } // end try
        catch (final Exception ignore) {
        }
        try {
            tmp2.delete();
        } // end try
        catch (final Exception ignore) {
        }
    } // end finally
}