Example usage for com.lowagie.text Document close

List of usage examples for com.lowagie.text Document close

Introduction

In this page you can find the example usage for com.lowagie.text Document close.

Prototype

boolean close

To view the source code for com.lowagie.text Document close.

Click Source Link

Document

Has the document already been closed?

Usage

From source file:de.japes.text.PdfCreator.java

License:Open Source License

public String exportToPdf(byte[] imgArray) {

    String filename;/*from  w  ww  .  j av  a2s  . c  o m*/
    Document document = new Document();
    Image img = null;

    Calendar cal = Calendar.getInstance();

    filename = "chart_" + cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH) + cal.get(Calendar.DAY_OF_MONTH)
            + "_" + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.MINUTE) + ".pdf";

    try {
        img = Image.getInstance(imgArray);
    } catch (MalformedURLException e) {
        return e.getMessage();
    } catch (IOException e) {
        return e.getMessage();
    } catch (BadElementException e) {
        return e.getMessage();
    }

    img.setAlignment(Image.ALIGN_CENTER);

    try {

        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file

        PdfWriter.getInstance(document, new FileOutputStream(filename));

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

        // step 4: we add a paragraph to the document
        document.add(img);

    } catch (DocumentException de) {
        return de.getMessage();
    } catch (IOException ioe) {
        return ioe.getMessage();
    }

    // step 5: we close the document
    document.close();

    return filename;
}

From source file:de.jdufner.sudoku.generator.pdf.PdfPrinterImpl.java

License:Open Source License

private Document writeDocument(Document document, List<SudokuData> sudokus) throws DocumentException {
    document.open();/*www.j ava 2  s.  c  o  m*/
    // TODO Von auen konfigurieren
    document.addAuthor("Jrgen Dufner");
    document.addCreationDate();
    document.addCreator("de.jdufner.sudoku.Generator");
    document.addKeywords("Sudoku");
    document.addTitle("Sudokus in unterschiedlichen Schwierigkeitsgraden");
    document.add(writePdfMetaTable(sudokus));
    document.close();
    return document;
}

From source file:de.jdufner.sudoku.generator.pdf.PdfPrinterImpl.java

License:Open Source License

private void writeFrontpage(String name, Document document, List<PdfSolution> solutions)
        throws DocumentException {
    document.open();// www .ja  v a2 s .  com
    Paragraph p = new Paragraph(name);
    p.setAlignment(Element.ALIGN_CENTER);
    p.setSpacingBefore(20f);
    p.setSpacingAfter(20f);
    document.add(p);
    PdfPTable table = new PdfPTable(17);
    table.setWidthPercentage(100);
    int[] width = { 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
    table.setWidths(width);
    PdfPCell cell;
    table.addCell(buildHeaderCell("Name", 90, true, false));
    table.addCell(buildHeaderCell("Schwierigkeitsgrad", 90, false, false));
    table.addCell(buildHeaderCell("Besetzte Zellen", 90, false, false));
    table.addCell(buildHeaderCell("Simple", 90, false, false));
    table.addCell(buildHeaderCell("Hidden Single", 90, false, false));
    table.addCell(buildHeaderCell("Naked Pair", 90, false, false));
    table.addCell(buildHeaderCell("Naked Triple", 90, false, false));
    table.addCell(buildHeaderCell("Naked Quad", 90, false, false));
    table.addCell(buildHeaderCell("Hidden Pair", 90, false, false));
    table.addCell(buildHeaderCell("Hidden Triple", 90, false, false));
    table.addCell(buildHeaderCell("Hidden Quad", 90, false, false));
    table.addCell(buildHeaderCell("Intersection Removal", 90, false, false));
    table.addCell(buildHeaderCell("Y-Wing", 90, false, false));
    table.addCell(buildHeaderCell("X-Wing", 90, false, false));
    table.addCell(buildHeaderCell("Jellyfish", 90, false, false));
    table.addCell(buildHeaderCell("Swordfish", 90, false, false));
    table.addCell(buildHeaderCell("Backtracking", 90, false, true));
    boolean even = false;
    for (PdfSolution solution : solutions) {
        table.addCell(buildBodyNumberCell(solution.getId(), even, true, false));
        table.addCell(buildBodyTextCell(solution.getLevel().toString(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getFixed(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategySimple(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyHiddenSingle(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyNakedPair(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyNakedTriple(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyNakedQuad(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyHiddenPair(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyHiddenTriple(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyHiddenQuad(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyIntersectionRemoval(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyYwing(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyXwing(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyJellyfish(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategySwordfish(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyBacktracking(), even, false, true));
        even = (even ? false : true);
    }
    document.add(table);
    document.close();
}

From source file:de.maklerpoint.office.Schnittstellen.PDF.ExportListePDF.java

License:Open Source License

public void write() throws DocumentException, FileNotFoundException {

    SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm");

    Document doc = null;

    if (titles.length > 7)
        doc = new Document(PageSize.A4.rotate(), 20, 20, 20, 20);
    else/*from www . jav a  2  s.c o m*/
        doc = new Document(PageSize.A4, 20, 20, 20, 20);

    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(filename));
    doc.addAuthor("MaklerPoint - www.maklerpoint.de");
    doc.addCreator("MaklerPoint - www.maklerpoint.de");
    doc.addCreationDate();
    doc.addTitle(title);

    doc.open();

    doc.add(new Paragraph(title, FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, Color.BLACK)));

    Table t = new Table(titles.length, data.length + 1);
    t.setPadding(3);
    t.setSpacing(0);
    t.setBorderWidth(1);

    for (int i = 0; i < titles.length; i++) {
        Cell c1 = new Cell(titles[i]);
        c1.setHeader(true);
        t.addCell(c1);
    }
    t.endHeaders();

    for (int i = 0; i < data.length; i++) {
        for (int j = 0; j < data[i].length; j++) {
            Cell c1 = null;
            if (data[i][j] != null)
                c1 = new Cell(data[i][j].toString());
            else
                c1 = new Cell("");
            t.addCell(c1);
        }
    }

    doc.add(t);

    if (footer == null) {
        doc.add(new Paragraph(
                ("Export " + title + " - Genereriert am " + df.format(new Date(System.currentTimeMillis())))
                        + " von MaklerPoint",
                FontFactory.getFont(FontFactory.TIMES, 10, Font.NORMAL, Color.black)));
    } else {
        doc.add(new Paragraph(footer, FontFactory.getFont(FontFactory.TIMES, 10, Font.NORMAL, Color.black)));
    }

    doc.close();
}

From source file:de.offis.health.icardea.cied.pdf.extractor.PDFiText2Extractor.java

License:LGPL

public byte[] getPDFPages(int fromPageNumber, int toPageNumber) {
    ByteArrayOutputStream byteArrayOutputStream = null;
    boolean extractionSuccessful = false;

    if (pdfReader != null) {
        int numberOfPages = getNumberOfPages();

        /*//from   www. java  2s  .c  om
         * Check if the given page numbers are in the allowed range.
         */
        if (fromPageNumber > 0 && fromPageNumber <= numberOfPages && toPageNumber > 0
                && toPageNumber <= numberOfPages) {
            /*
             * Now check if the given fromPageNumber is smaller
             * as the given toPageNumber. If not swap the numbers.
             */
            if (fromPageNumber > toPageNumber) {
                int tmpPageNumber = toPageNumber;
                toPageNumber = fromPageNumber;
                fromPageNumber = tmpPageNumber;
            }

            Document newDocument = new Document();

            try {
                byteArrayOutputStream = new ByteArrayOutputStream();
                PdfSmartCopy pdfCopy = new PdfSmartCopy(newDocument, byteArrayOutputStream);
                newDocument.open();
                for (int currentPage = fromPageNumber; currentPage <= toPageNumber; currentPage++) {
                    pdfCopy.addPage(pdfCopy.getImportedPage(pdfReader, currentPage));
                } // end for
                pdfCopy.flush();
                pdfCopy.close();
                newDocument.close();
                extractionSuccessful = true;
            } catch (DocumentException ex) {
                // TODO: Create an own exception for PDF processing errors.
                logger.error("An exception occurred while extracting " + "pages from the input PDF file.", ex);
            } catch (IOException ex) {
                // TODO: Create an own exception for PDF processing errors.
                logger.error("An exception occurred while extracting " + "pages from the input PDF file.", ex);
            } finally {
                if (!extractionSuccessful) {
                    byteArrayOutputStream = null;
                }
            } // end try..catch..finally
        } // end if checking range of given pages
    } // end if (pdfReader != null)

    if (byteArrayOutputStream != null) {
        return byteArrayOutputStream.toByteArray();
    }
    return null;
}

From source file:de.sub.goobi.forms.ProzessverwaltungForm.java

License:Open Source License

/**
 * Generate result as PDF.//from w  w  w . j ava  2s  .  c o m
 */
public void generateResultAsPdf() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.getResponseComplete()) {

        /*
         * Vorbereiten der Header-Informationen
         */
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        try {
            ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
            String contentType = servletContext.getMimeType("search.pdf");
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment;filename=\"search.pdf\"");
            ServletOutputStream out = response.getOutputStream();

            SearchResultGeneration sr = new SearchResultGeneration(this.filter, this.showClosedProcesses,
                    this.showArchivedProjects);
            HSSFWorkbook wb = sr.getResult();
            List<List<HSSFCell>> rowList = new ArrayList<>();
            HSSFSheet mySheet = wb.getSheetAt(0);
            Iterator<Row> rowIter = mySheet.rowIterator();
            while (rowIter.hasNext()) {
                HSSFRow myRow = (HSSFRow) rowIter.next();
                Iterator<Cell> cellIter = myRow.cellIterator();
                List<HSSFCell> row = new ArrayList<>();
                while (cellIter.hasNext()) {
                    HSSFCell myCell = (HSSFCell) cellIter.next();
                    row.add(myCell);
                }
                rowList.add(row);
            }
            Document document = new Document();
            Rectangle a4quer = new Rectangle(PageSize.A3.getHeight(), PageSize.A3.getWidth());
            PdfWriter.getInstance(document, out);
            document.setPageSize(a4quer);
            document.open();
            if (rowList.size() > 0) {
                Paragraph p = new Paragraph(rowList.get(0).get(0).toString());
                document.add(p);
                PdfPTable table = new PdfPTable(9);
                table.setSpacingBefore(20);
                for (List<HSSFCell> row : rowList) {
                    for (HSSFCell hssfCell : row) {
                        // TODO aufhbschen und nicht toString() nutzen
                        String stringCellValue = hssfCell.toString();
                        table.addCell(stringCellValue);
                    }
                }
                document.add(table);
            }

            document.close();
            out.flush();
            facesContext.responseComplete();
        } catch (Exception e) {
            logger.error(e);
        }
    }
}

From source file:de.thorstenberger.examServer.webapp.action.SystemConfigSubmitAction.java

License:Open Source License

/**
 * @param mapping//w ww  .java 2 s .  c o m
 * @param request
 * @param response
 * @param configManager
 * @return
 */
private ActionForward createSignedPDF(final ActionMapping mapping, final HttpServletRequest request,
        final HttpServletResponse response, final ConfigManager configManager) {
    final ActionErrors errors = new ActionErrors();
    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        final Document pdf = new Document();
        PdfWriter.getInstance(pdf, baos);
        pdf.open();
        pdf.add(new Paragraph("Signaturtest."));
        pdf.close();

        final InputStream pdfIn = new ByteArrayInputStream(baos.toByteArray());
        baos.reset();
        SignPdf.signAndTimestamp(pdfIn, baos, configManager.getPDFSignatureInfos());
        // write signed pdf to response
        response.setContentType("application/pdf");
        // set an appropriate filename
        response.setHeader("Content-Disposition", "attachment; filename=signaturetest.pdf");
        response.getOutputStream().write(baos.toByteArray());
        return null;
    } catch (final DocumentException e) {
        addError(errors, e);
    } catch (final IOException e) {
        addError(errors, e);
    } catch (final SignatureException e) {
        addError(errors, e);
    } catch (final KeyStoreException e) {
        addError(errors, e);
    }
    saveMessages(request, errors);
    return mapping.findForward("success");
}

From source file:de.tr1.cooperator.manager.web.CreateSubscriberListAction.java

License:Open Source License

/**
 * This method is called by the struts-framework if the submit-button is pressed.
 * It creates a PDF-File and puts in into the output-stream of the response.
 *//* w w w .  j  a v a 2  s. c  o m*/
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    CreateSubscriberListForm myForm = (CreateSubscriberListForm) form;
    boolean bSortByName;

    if (myForm.getSortBy().equals(myForm.SORTBYPN))
        bSortByName = false;
    else
        bSortByName = true;

    //create Collection for the results...
    Event eEvent = EventManager.getInstance().getEventByID(myForm.getEventID());
    Collection cSubscriberList = UserManager.getInstance().getUsersByCollection(eEvent.getSubscriberList());
    Collection cExamResults = EventResultManager.getInstance().getResults(eEvent.getID());

    Iterator cSubscriberListIT = cSubscriberList.iterator();
    Collection cSubscriberResultList = new ArrayList();

    while (cSubscriberListIT.hasNext()) {
        User CurUser = (User) cSubscriberListIT.next();
        String UserPNR = CurUser.getPersonalNumber();

        Iterator cExamResultsIT = cExamResults.iterator();
        ExamResult curExamResult = null;
        String ResultUserPNR = null;
        while (cExamResultsIT.hasNext()) {
            curExamResult = (ExamResult) cExamResultsIT.next();

            ResultUserPNR = curExamResult.getUserPersonalNumber();
            if (UserPNR.equals(ResultUserPNR))
                break;
        }

        if (UserPNR.equals(ResultUserPNR)) {
            if (bSortByName) {
                UserResultSortByName URS = new UserResultSortByName(CurUser, "" + curExamResult.getResult());
                cSubscriberResultList.add(URS);
            } else {
                UserResultSortByPersonalNumber URS = new UserResultSortByPersonalNumber(CurUser,
                        "" + curExamResult.getResult());
                cSubscriberResultList.add(URS);
            }
        } else {
            if (bSortByName) {
                UserResultSortByName URS = new UserResultSortByName(CurUser, "-");
                cSubscriberResultList.add(URS);
            } else {
                UserResultSortByPersonalNumber URS = new UserResultSortByPersonalNumber(CurUser, "-");
                cSubscriberResultList.add(URS);
            }
        }

    }

    //sort List
    Collections.sort((List) cSubscriberResultList);

    BaseFont bf;
    //36pt = 0.5inch
    Document document = new Document(PageSize.A4, 36, 36, 72, 72);

    try {
        bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    } catch (Exception e) {
        Log.addLog("CreateSubscriberListAction: Error creating BaseFont: " + e);
        //2do: add ErrorMessage and return to inputFormular!
        return mapping.findForward("GeneralFailure");
    }

    //calculate the number of cols and their width
    int cols = 0;
    ArrayList alWidth = new ArrayList();
    float boldItalicFactor = 1.2f;
    if (myForm.getShowNumber())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_NUMBER, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowPersonalNumber())
        alWidth.add(new Float(
                boldItalicFactor * bf.getWidthPoint(TABLEHEADER_PERSONALNUMBER, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowName())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_NAME, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowEmail())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_EMAIL, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowResult())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_RESULT, TABLEHEADER_FONTSIZE)));

    if (myForm.getAddInfoField())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_INFO, TABLEHEADER_FONTSIZE)));

    if (myForm.getAddSignField())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_SIGN, TABLEHEADER_FONTSIZE)));

    cols = alWidth.size();

    float totalWidth = 0;
    //calculate the whole length
    Iterator alIterator = alWidth.iterator();
    for (; alIterator.hasNext(); totalWidth += ((Float) alIterator.next()).floatValue())
        ;

    //calculate relativ width for the table
    float[] width = new float[cols];
    alIterator = alWidth.iterator();
    int i = 0;
    while (alIterator.hasNext()) {
        float pixLength = ((Float) alIterator.next()).floatValue();
        //alWidthRelativ.add( new Float( pixLength/totalWidth ) );
        width[i] = pixLength / totalWidth;
        i++;
    }

    //needed for the shrink (enlarge?)
    float shrinkFactor;

    try {
        //1st: set correct outputstream
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());

        //1.5st: set content-stuff
        response.setContentType("application/pdf");

        //2nd: set EventManager for PageEvents to Helper
        writer.setPageEvent(
                new CreateSubscriberListActionHelper(myForm.getHeaderLeft(), myForm.getHeaderRight()));

        //3rd: open document for editing the content
        document.open();

        //4th: add content
        Phrase pInfoText = new Phrase(myForm.getInfoText(), new Font(bf, 12, Font.BOLD));
        document.add(pInfoText);

        //PdfPTable( cols )
        PdfPTable table = new PdfPTable(width);

        float documentWidth = document.right() - document.left();
        if (documentWidth < totalWidth) {
            table.setTotalWidth(documentWidth);
            shrinkFactor = documentWidth / totalWidth;
        } else {
            table.setTotalWidth(totalWidth);
            shrinkFactor = 1;
        }
        table.setLockedWidth(true);

        Font headerFont = new Font(bf, TABLEHEADER_FONTSIZE * shrinkFactor, Font.BOLDITALIC);
        Font cellFont = new Font(bf, TABLECELL_FONTSIZE * shrinkFactor, Font.NORMAL);

        if (myForm.getShowNumber())
            table.addCell(new Phrase(TABLEHEADER_NUMBER, headerFont));
        if (myForm.getShowPersonalNumber())
            table.addCell(new Phrase(TABLEHEADER_PERSONALNUMBER, headerFont));
        if (myForm.getShowName())
            table.addCell(new Phrase(TABLEHEADER_NAME, headerFont));
        if (myForm.getShowEmail())
            table.addCell(new Phrase(TABLEHEADER_EMAIL, headerFont));
        if (myForm.getShowResult())
            table.addCell(new Phrase(TABLEHEADER_RESULT, headerFont));
        if (myForm.getAddInfoField())
            table.addCell(new Phrase(TABLEHEADER_INFO, headerFont));
        if (myForm.getAddSignField())
            table.addCell(new Phrase(TABLEHEADER_SIGN, headerFont));

        //fill table
        Iterator iSRL = cSubscriberResultList.iterator();
        int counter = 1;
        while (iSRL.hasNext()) {
            UserResult curResult = (UserResult) iSRL.next();

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            if (myForm.getShowNumber())
                table.addCell(new Phrase("" + counter++, cellFont));

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            if (myForm.getShowPersonalNumber())
                table.addCell(new Phrase(curResult.getPersonalNumber(), cellFont));

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            if (myForm.getShowName())
                table.addCell(new Phrase(curResult.getSurname() + ", " + curResult.getFirstName(), cellFont));
            if (myForm.getShowEmail())
                table.addCell(new Phrase(curResult.getEmailAddress(), cellFont));
            if (myForm.getShowResult())
                table.addCell(new Phrase(curResult.getResult(), cellFont));
            if (myForm.getAddInfoField())
                table.addCell(new Phrase("", cellFont));
            if (myForm.getAddSignField())
                table.addCell(new Phrase("", cellFont));
        }

        //set how many rows are header...
        table.setHeaderRows(1);

        document.add(table);

        //5th: close document, write the output to the stream...
        document.close();
    } catch (Exception de) {
        Log.addLog("CreateSubscriberListAction: Error creating PDF: " + de);
    }

    //we dont need to return a forward, because we write directly to the outputstream!
    return null;
}

From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java

License:Apache License

/***************************************************************************
 * Creates a PDF, which is streams to the OutputStream out.
 * /*from  w  w w.j  a va2  s .co  m*/
 * @param out {@link OutputStream}
 * @param pagesizemode {@link PdfPageSize}
 * 
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws FileNotFoundException the file not found exception
 * @throws ImageManagerException the image manager exception
 * @throws PDFManagerException the PDF manager exception
 * @throws ImageInterpreterException the image interpreter exception
 * @throws URISyntaxException
 ****************************************************************************/
public void createPDF(OutputStream out, PdfPageSize pagesizemode, Watermark myWatermark)
        throws ImageManagerException, FileNotFoundException, IOException, PDFManagerException,
        ImageInterpreterException, URISyntaxException {

    Document pdfdoc = null;
    PdfWriter writer = null;

    Rectangle pagesize = null; // pagesize of the first page
    PdfPageLabels pagelabels = null; // object to store all page labels

    try {
        if ((imageURLs == null) || (imageURLs.isEmpty())) {
            throw new PDFManagerException("No URLs for images available, HashMap is null or empty");
        }

        // set the page sizes & pdf document
        pdfdoc = setPDFPageSizeForFirstPage(pagesizemode, pagesize);

        // writer for creating the PDF
        writer = createPDFWriter(out, pdfdoc);

        // set metadata for PDF as author and title
        // ------------------------------------------------------------------------------------
        if (this.title != null) {
            pdfdoc.addTitle(this.title);
        }
        if (this.author != null) {
            pdfdoc.addAuthor(this.author);
        }
        if (this.keyword != null) {
            pdfdoc.addKeywords(this.keyword);
        }
        if (this.subject != null) {
            pdfdoc.addSubject(this.subject);
        }
        // add title page to PDF
        if (pdftitlepage != null) {
            // create a title page
            pdftitlepage.render(pdfdoc);
        }

        // iterate over all files, they must be ordered by the key
        // the key contains the page number (as integer), the String
        // contains the Page name
        // ----------------------------------------------------------------------

        pagelabels = addAllPages(pagesizemode, writer, pdfdoc, myWatermark);

        // add page labels
        if (pagelabels != null) {
            writer.setPageLabels(pagelabels);
        }

        // create the required xmp metadata
        // for pdfa
        if (pdfa) {
            writer.createXmpMetadata();
        }
    } catch (ImageManagerException e) {
        if (pdfdoc != null) {
            pdfdoc.close();
        }
        if (writer != null) {
            writer.close();
        }
        throw e;
    } catch (PDFManagerException e) {
        if (pdfdoc != null) {
            pdfdoc.close();
        }
        if (writer != null) {
            writer.close();
        }
        throw e;
    } catch (ImageInterpreterException e) {
        if (pdfdoc != null) {
            pdfdoc.close();
        }
        if (writer != null) {
            writer.close();
        }
        throw e;
    } catch (IOException e) {
        if (pdfdoc != null) {
            pdfdoc.close();
        }
        if (writer != null) {
            writer.close();
        }
        throw e;
    }
    // close documents and writer
    try {
        if (pdfdoc != null && pdfdoc.isOpen()) {
            pdfdoc.close();
        }
        if (writer != null) {
            writer.close();
        }
    } catch (IllegalStateException e) {
        LOGGER.warn("Caught IllegalStateException when closing pdf document.");
    } catch (NullPointerException e) {
        throw new PDFManagerException("Nullpointer occured while closing pdfwriter");
    }
    LOGGER.debug("PDF document and writer closed");
}

From source file:de.xirp.chart.ChartUtil.java

License:Open Source License

/**
 * Exports the given chart as PDF in the specified size. The
 * export is written to the given path.//w ww . j a  v a  2 s  . co  m
 * 
 * @param chart
 *            The chart to export.
 * @param width
 *            The desired width of the PDF.
 * @param height
 *            The desired height of the PDF.
 * @param path
 *            The path to write the PDF to.
 * @see org.jfree.chart.JFreeChart
 */
private static void exportPDF(JFreeChart chart, int width, int height, String path) {
    Document document = new Document(new Rectangle(width, height));
    try {
        PdfWriter writer;
        writer = PdfWriter.getInstance(document, new FileOutputStream(path));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2d, r2d);
        g2d.dispose();
        cb.addTemplate(tp, 0, 0);
    } catch (Exception e) {
        logClass.error("Error: " + e.getMessage() //$NON-NLS-1$
                + Constants.LINE_SEPARATOR, e);
    }
    document.close();
}