Example usage for com.itextpdf.text Document close

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

Introduction

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

Prototype

boolean close

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

Click Source Link

Document

Has the document already been closed?

Usage

From source file:com.vectorprint.report.itext.TocOutputStream.java

License:Open Source License

@Override
public void secondPass(InputStream firstPass, OutputStream orig) throws IOException {
    PdfReader reader = null;//from  w w  w  . ja  va  2  s .  c  o m
    VectorPrintDocument vpd = (VectorPrintDocument) outer.getDocument();
    try {
        reader = new PdfReader(firstPass);
        prepareToc();
        // init fresh components for second pass styling
        StylerFactory _stylerFactory = outer.getStylerFactory().getClass().newInstance();
        StylerFactoryHelper.SETTINGS_ANNOTATION_PROCESSOR.initSettings(_stylerFactory, outer.getSettings());
        _stylerFactory.setLayerManager(outer.getElementProducer());
        _stylerFactory.setImageLoader(outer.getElementProducer());
        outer.getStyleHelper().setStylerFactory(_stylerFactory);
        EventHelper event = outer.getEventHelper().getClass().newInstance();
        event.setItextStylerFactory(_stylerFactory);
        event.setElementProvider(outer.getElementProducer());
        ((DefaultElementProducer) outer.getElementProducer()).setPh(event);
        Document d = new VectorPrintDocument(event, _stylerFactory, outer.getStyleHelper());
        PdfWriter w = PdfWriter.getInstance(d, orig);
        w.setPageEvent(event);
        outer.getStyleHelper().setVpd((VectorPrintDocument) d);
        _stylerFactory.setDocument(d, w);
        DocumentStyler ds = _stylerFactory.getDocumentStyler();
        outer.getStyleHelper().style(d, null, StyleHelper.toCollection(ds));
        d.open();
        ds.styleAfterOpen(d, null);
        List outline = SimpleBookmark.getBookmark(reader);
        if (!ds.getValue(DocumentSettings.TOCAPPEND, Boolean.class)) {
            printToc(d, w, vpd);
            if (outline != null) {
                int cur = w.getCurrentPageNumber();
                SimpleBookmark.shiftPageNumbers(outline, cur, null);
            }
            d.newPage();
        }
        outer.getSettings().put(ReportConstants.DEBUG, Boolean.FALSE.toString());
        for (int p = 1; p <= reader.getNumberOfPages(); p++) {
            Image page = Image.getInstance(w.getImportedPage(reader, p));
            page.setAbsolutePosition(0, 0);
            d.setPageSize(page);
            d.newPage();
            Chunk i = new Chunk(" ");
            if (vpd.getToc().containsKey(p)) {
                Section s = null;
                for (Map.Entry<Integer, List<Section>> e : vpd.getToc().entrySet()) {
                    if (e.getKey() == p) {
                        s = e.getValue().get(0);
                        break;
                    }
                }
                i.setLocalDestination(s.getTitle().getContent());
            }
            d.add(i);
            w.getDirectContent().addImage(page);
            w.freeReader(reader);
        }
        if (_stylerFactory.getDocumentStyler().getValue(DocumentSettings.TOCAPPEND, Boolean.class)) {
            printToc(d, w, vpd);
        }
        w.setOutlines(outline);
        if (outer.isWasDebug()) {
            event.setLastPage(outer.getWriter().getCurrentPageNumber());
            d.setPageSize(new Rectangle(ItextHelper.mmToPts(297), ItextHelper.mmToPts(210)));
            d.setMargins(5, 5, 5, 5);
            d.newPage();
            outer.getSettings().put(ReportConstants.DEBUG, Boolean.TRUE.toString());
            event.setDebugHereAfter(true);
            DebugHelper.appendDebugInfo(w, d, outer.getSettings(), _stylerFactory);
        }
        d.close();
    } catch (VectorPrintException | DocumentException | InstantiationException | IllegalAccessException ex) {
        throw new VectorPrintRuntimeException(ex);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:com.verbox.PrintHtml.java

public static void RenderPDF_img_too(String inpHtml) throws FileNotFoundException, ParserConfigurationException,
        SAXException, IOException, DocumentException, PrinterException {
    try {//from w ww. jav a 2s .c o  m
        fullhtml = inpHtml;
        String replaceAll = fullhtml.replaceAll("../../image/", "");
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("pdf.pdf"));
        // step 3
        document.open();
        // step 4
        XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
        InputStream is = new ByteArrayInputStream(replaceAll.getBytes(StandardCharsets.UTF_8));
        worker.parseXHtml(writer, document, is, Charset.forName("UTF-8"));
        // step 5
        document.close();
        PreImgPrint();

    } catch (DocumentException | IOException E) {
        JOptionPane.showMessageDialog(null, "Exeption on print or prepare image " + E);
    }
}

From source file:com.vimbox.hr.LicensePDFGenerator.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  ww  .j av  a2s  . c o m*/
 *
 * @param request servlet request
 * @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 {
    response.setContentType("application/pdf");
    String fileName = request.getParameter("license_name");
    String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
    String path = System.getProperty("user.dir") + "/documents/licenses/" + fileName;
    path = path.replaceAll("%20", " ");
    if (ext.equalsIgnoreCase("pdf")) {
        FileInputStream baos = new FileInputStream(path);

        OutputStream os = response.getOutputStream();

        byte buffer[] = new byte[8192];
        int bytesRead;

        while ((bytesRead = baos.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }

        os.flush();
        os.close();
    } else {
        try {
            // Document Settings //
            Document document = new Document();
            PdfWriter.getInstance(document, response.getOutputStream());
            document.open();

            // Loading MC //
            PdfPTable table = new PdfPTable(1);
            table.setWidthPercentage(100);
            // the cell object
            PdfPCell cell;

            Image img = Image.getInstance(path);
            int indentation = 0;
            float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin()
                    - indentation) / img.getWidth()) * 100;
            img.scalePercent(scaler);
            //img.scaleAbsolute(80f, 80f);
            cell = new PdfPCell(img);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
            document.add(table);
            //-----------------------------------//
            document.close();
        } catch (DocumentException de) {
            throw new IOException(de.getMessage());
        }
    }

}

From source file:com.wabacus.system.assistant.PdfAssistant.java

License:Open Source License

public ByteArrayOutputStream showReportDataOnPdfWithTpl(ReportRequest rrequest, IComponentConfigBean ccbean) {
    boolean ispdfprint = rrequest.isPdfPrintAction();
    PDFExportBean pdfbean = null;/*from   www. j  a  v a2s . c  o  m*/
    if (ispdfprint) {
        pdfbean = ccbean.getPdfPrintBean();
    } else if (ccbean.getDataExportsBean() != null) {//PDF?PDF<dataexport/>
        pdfbean = (PDFExportBean) ccbean.getDataExportsBean().getDataExportBean(Consts.DATAEXPORT_PDF);
    }
    if (pdfbean == null || pdfbean.getPdftemplate() == null || pdfbean.getPdftemplate().trim().equals(""))
        return null;
    if (pdfbean.getLstIncludeApplicationids() == null || pdfbean.getLstIncludeApplicationids().size() == 0)
        return null;
    Map<String, AbsReportType> mReportTypeObjs = new HashMap<String, AbsReportType>();
    IComponentType cctypeObj;
    AbsReportType reportTypeObjTmp;
    int maxrowcount = 0;
    for (String appidTmp : pdfbean.getLstIncludeApplicationids()) {//?PDF
        if (mReportTypeObjs.containsKey(appidTmp))
            continue;
        cctypeObj = rrequest.getComponentTypeObj(appidTmp, null, false);
        if (cctypeObj == null || !(cctypeObj instanceof AbsReportType))
            continue;
        reportTypeObjTmp = (AbsReportType) cctypeObj;
        mReportTypeObjs.put(appidTmp, reportTypeObjTmp);
        if (reportTypeObjTmp.getLstReportData() != null
                && reportTypeObjTmp.getLstReportData().size() > maxrowcount) {
            maxrowcount = reportTypeObjTmp.getLstReportData().size();
        }
    }
    if (mReportTypeObjs.size() == 0 || maxrowcount == 0)
        return null;
    try {
        Document document = new Document();
        ByteArrayOutputStream baosResult = new ByteArrayOutputStream();
        PdfCopy pdfCopy = new PdfCopy(document, baosResult);
        document.open();
        for (int i = 0; i < maxrowcount; i++) {
            addPdfPageToDocument(pdfCopy,
                    showReportOneRowDataOnPdf(rrequest, mReportTypeObjs, ccbean, pdfbean, i));
        }
        document.close();
        return baosResult;
    } catch (Exception e) {
        throw new WabacusRuntimeException("" + ccbean.getPath() + "?pdf", e);
    }
}

From source file:com.wabacus.WabacusFacade.java

License:Open Source License

private static void exportReportDataOnPDF(String pageid, ReportRequest rrequest, WabacusResponse wresponse) {
    boolean success = true;
    try {/* w ww  . j  a v  a2  s  .co  m*/
        rrequest.setWResponse(wresponse);
        wresponse.setRRequest(rrequest);
        rrequest.init(pageid);
        if (rrequest.getLstAllReportBeans() == null || rrequest.getLstAllReportBeans().size() == 0) {
            throw new WabacusRuntimeException("?" + pageid
                    + "?plainexcel???");
        }
        Document document = new Document();
        ByteArrayOutputStream baosResult = new ByteArrayOutputStream();
        PdfCopy pdfCopy = new PdfCopy(document, baosResult);
        document.open();
        boolean ispdfprint = rrequest.isPdfPrintAction();
        for (IComponentConfigBean ccbeanTmp : rrequest.getLstComponentBeans()) {//??PDF?
            PDFExportBean pdfbeanTmp = null;
            if (ispdfprint) {
                pdfbeanTmp = ccbeanTmp.getPdfPrintBean();
            } else if (ccbeanTmp.getDataExportsBean() != null) {
                pdfbeanTmp = (PDFExportBean) ccbeanTmp.getDataExportsBean()
                        .getDataExportBean(Consts.DATAEXPORT_PDF);
            }
            if (pdfbeanTmp != null && pdfbeanTmp.getPdftemplate() != null
                    && !pdfbeanTmp.getPdftemplate().trim().equals("")) {
                PdfAssistant.getInstance().addPdfPageToDocument(pdfCopy,
                        PdfAssistant.getInstance().showReportDataOnPdfWithTpl(rrequest, ccbeanTmp));
            }
        }
        AbsReportType reportTypeObjTmp;
        for (ReportBean rbTmp : rrequest.getLstAllReportBeans()) {
            reportTypeObjTmp = (AbsReportType) rrequest.getComponentTypeObj(rbTmp, null, false);
            if (rrequest.isReportInPdfTemplate(rbTmp.getId()))
                continue;//??PDF???
            PdfAssistant.getInstance().addPdfPageToDocument(pdfCopy, reportTypeObjTmp.displayOnPdf());
        }
        document.close();
        BufferedOutputStream bos = null;
        if (rrequest.isExportToLocalFile()) {
            bos = new BufferedOutputStream(new FileOutputStream(new File(rrequest.getDataExportFilepath())));
        } else {
            if (!ispdfprint) {
                String title = WabacusAssistant.getInstance().encodeAttachFilename(rrequest.getRequest(),
                        rrequest.getDataExportFilename());
                wresponse.getResponse().setHeader("Content-disposition",
                        "attachment;filename=" + title + ".pdf");
            }
            wresponse.getResponse().setContentLength(baosResult.size());
            bos = new BufferedOutputStream(wresponse.getResponse().getOutputStream());
        }
        baosResult.writeTo(bos);
        bos.close();
        baosResult.close();
        if (rrequest.isExportToLocalFile() && rrequest.isDataexport_localstroagezip()) {
            tarDataFile(rrequest);
        }
    } catch (WabacusRuntimeTerminateException wrwe) {
        if (wresponse.getStatecode() == Consts.STATECODE_FAILED) {
            success = false;
        }
    } catch (Exception wre) {
        wresponse.setStatecode(Consts.STATECODE_FAILED);
        log.error("?" + rrequest.getPagebean().getId() + "", wre);
        success = false;
    } finally {
        rrequest.destroy(success);
    }
    doPostDataExport(rrequest, wresponse);
}

From source file:com.warehouse.abstractController.OrderMenuAbstractController.java

public void handleGeneratePDF() {
    try {//  w ww.jav  a  2  s .  com
        OutputStream file = new FileOutputStream(new File("./Test.pdf"));
        Document document = new Document();
        PdfWriter.getInstance(document, file);
        document.open();

        document.add(new Paragraph("Order information"));

        for (Order o : orderDao.getOrderList())
            if (o.getId() == Integer.parseInt(Cookie.getInstance().get("orderID")))
                document.add(new Paragraph("Order (" + o.getId() + ") " + o.getItems() + " " + o.getDate() + " "
                        + o.getClient().getPhone()));

        document.add(new Paragraph(new Date().toString()));
        document.close();

        file.close();

        AlertBox.getInstance().display(getClass().getSimpleName(), "Successful generated *.PDF file !");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.wesley.creche.services.pdf.createHrPdf.java

public void writePdfHrReport() throws DocumentException, IOException, SQLException {

    createFolderIfNotExist();//from  w  w w .j  ava 2s  . c o m

    Date date = new Date();
    DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
    String today = df.format(date);
    String fileName = "C:\\creche\\reports\\HRReport" + today + "_.pdf";

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));

    document.open();

    addTitle(document);
    addLine(document);
    addEmptyLine(document, 2);

    try {
        document.add(new Paragraph(getEmpName()));
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(createHrPdf.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        document.add(new Paragraph(getEmpLastName()));
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(createHrPdf.class.getName()).log(Level.SEVERE, null, ex);
    }

    document.close();
}

From source file:com.wesley.creche.services.pdf.createPdf.java

public void writePdfFinancialReport(String name, String startDate, String accStatus, String amountDue)
        throws DocumentException, IOException {

    createFolderIfNotExist();/*from w  w w .j  a  v  a 2s  .com*/
    SQLQueries s = new SQLQueries();

    String lastName = "";

    try {
        lastName = s.getChildSurnameByName(name);
    } catch (SQLException | ClassNotFoundException ex) {
        System.out.println(ex);
    }

    Date date = new Date();
    DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
    String today = df.format(date);
    String fileName = "C:\\creche\\reports\\" + name + today + "_.pdf";

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));

    document.open();

    addTitle(document);
    addLine(document);

    document.add(new Paragraph("Name : " + name + " " + lastName, italic));
    addEmptyLine(document, 2);

    Paragraph paragraph = new Paragraph();
    paragraph.add("Start Date :");
    paragraph.setTabSettings(new TabSettings());
    paragraph.add(Chunk.TABBING);
    paragraph.add(new Chunk(startDate));
    document.add(paragraph);

    addEmptyLine(document, 1);
    document.add(new Paragraph("Account Status : " + accStatus));
    addEmptyLine(document, 1);

    document.add(new Paragraph("Total Amount Outstanding : R" + amountDue));
    addEmptyLine(document, 3);

    addLine(document);
    document.add(new Paragraph("For any queries, please contact Administration : 10111"));

    document.close();
}

From source file:com.wipro.srs.service.PrintTicket.java

@Transactional
public void generatePDF(String res) {
    try {//from  w  w  w  .  j av  a  2  s .  co  m

        ReservationBean rb = resDao.findByResID(res);

        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(FILE));
        document.open();
        addMetaData(document);
        addTitlePage(document);
        addContent(document, rb);
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.workhub.utils.PDFUtils.java

public static void createPDF(String title, String creator, List<ElementModel> models,
        FileOutputStream outputStream) {

    try {/*from w  w  w.j  a  v  a  2 s . c om*/
        Document document = new Document();
        PdfWriter.getInstance(document, outputStream);
        document.open();

        addMetaData(document, title, creator);
        addTitlePage(document, title, models, creator);
        addContent(document, models);
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}