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:gui.TransHistory.java

public void Convertpdf() throws Exception {
    display();/* w ww .  j ava  2  s  . c o  m*/

    Document document = new Document(PageSize.A4.rotate());
    try {
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Table.pdf"));

        document.open();
        PdfContentByte cb = writer.getDirectContent();

        cb.saveState();
        Graphics2D g2 = cb.createGraphics(500, 500);

        Shape oldClip = g2.getClip();
        g2.clipRect(20, 20, 500, 500);

        jTable1.print(g2);
        jTable1.getTableHeader().paint(g2);
        g2.setClip(oldClip);

        g2.dispose();
        cb.restoreState();
        cb.saveState();
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    document.close();

    //send mail
    query = "select email from profile_id where user_id = ?";
    psmt = con.prepareStatement(query);
    psmt.setString(1, t.user);
    rs = psmt.executeQuery();
    rs.next();
    SendMailWithAttachment smail = new SendMailWithAttachment();
    String message = "hereby is the requested transction report of account " + "no. = " + t.accNo
            + " from date " + fDate + " to " + toDate;

    smail.send(rs.getString(1), "Table.pdf", message);

}

From source file:ilarkesto.integration.itext.PdfBuilder.java

License:Open Source License

public void write(OutputStream out) {
    Document document = new Document();
    try {//from  ww  w . j a v  a2s . c o m
        PdfWriter.getInstance(document, out);
    } catch (DocumentException ex) {
        throw new RuntimeException(ex);
    }
    document.setMargins(mmToPoints(marginLeft), mmToPoints(marginRight), mmToPoints(marginTop),
            mmToPoints(marginBottom));
    document.open();
    for (ItextElement element : elements) {
        try {
            if (element instanceof PageBreak) {
                document.newPage();
            } else {
                Element iTextElement = element.getITextElement();
                if (iTextElement != null)
                    document.add(iTextElement);
            }
        } catch (DocumentException ex) {
            throw new RuntimeException(ex);
        }
    }
    document.close();
}

From source file:include.nseer_cookie.MakePdf.java

License:Open Source License

public void make(String database, String tablename, String sql1, String sql2, String filename, int everypage,
        HttpSession session) {/*from w ww . jav  a 2  s . c om*/
    try {

        nseer_db aaa = new nseer_db(database);
        nseer_db demo_db = new nseer_db(database);

        ServletContext context = session.getServletContext();
        String path = context.getRealPath("/");

        Masking reader = new Masking(configFile);
        Vector columnNames = new Vector();
        Vector tables = reader.getTableNicks();
        Iterator loop = tables.iterator();
        while (loop.hasNext()) {
            String tablenick = (String) loop.next();
            columnNames = reader.getColumnNames(tablenick);
        }

        int cpage = 1; //? 

        int spage = 1;
        int ipage = everypage;
        String pagesql = sql1;

        //? 
        ResultSet pagers = demo_db.executeQuery(pagesql);
        pagers.next();
        int allCol = pagers.getInt("A");

        allpage = (int) Math.ceil((allCol + ipage - 1) / ipage);
        //
        for (int m = 1; m <= allpage; m++) {
            spage = (m - 1) * ipage;
            String sql = sql2 + " limit " + spage + "," + ipage;

            ResultSet bbb = aaa.executeQuery(sql);
            //ResultSetMetaData tt=bbb.getMetaData();       //
            int b = columnNames.size(); //
            int a = 0;
            while (bbb.next()) {
                a++;
            } //
            bbb.first(); //    ??
            Rectangle rectPageSize = new Rectangle(PageSize.A4);// 
            rectPageSize = rectPageSize.rotate();
            Document document = new Document(rectPageSize, 20, 20, 20, 20); //? Document
            PdfWriter writer = PdfWriter.getInstance(document,
                    new FileOutputStream(path + filename + m + ".pdf")); //?PDF??
            document.open(); //
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); //?
            com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 8,
                    com.lowagie.text.Font.NORMAL); //

            Paragraph title1 = new Paragraph("nseer ERP",
                    FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLDITALIC));
            Chapter chapter1 = new Chapter(title1, 1); // ? 
            chapter1.setNumberDepth(0);

            Paragraph title11 = new Paragraph(tablename,
                    FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD));
            Section section1 = chapter1.addSection(title11); //?                                                                                            

            Table t = new Table(b, a); // ? 
            t.setPadding(1); //  
            t.setSpacing(0); //  ?
            t.setBorderWidth(1); //

            do { //
                 //
                for (int k = 0; k < b; k++) { //
                    Cell cell = new Cell(
                            new Paragraph(bbb.getString((String) columnNames.elementAt(k)), FontChinese)); //?                                    //
                    t.addCell(cell); //   ?
                    //
                } //
            } while (bbb.next()); //

            section1.add(t); //
            document.add(chapter1); // 
            document.close();

        } // ?
    } catch (Exception pp) {
        pp.printStackTrace();
    }
}

From source file:io.github.autsia.crowly.controllers.DashboardController.java

License:Apache License

@RequestMapping(value = "/campaigns/export/{campaignId}", method = RequestMethod.GET)
public ResponseEntity<byte[]> export(@PathVariable("campaignId") String campaignId, ModelMap model)
        throws DocumentException {
    Document document = new Document();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, byteArrayOutputStream);
    document.open();/*from  w  ww  .ja  v  a2 s. c o m*/
    Gson gson = new Gson();
    String json = gson.toJson(mentionRepository.findByCampaignId(campaignId));
    document.add(new Paragraph(json));
    document.close();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers,
            HttpStatus.OK);
    return response;
}

From source file:io.vertigo.dynamo.plugins.export.pdfrtf.AbstractExporterIText.java

License:Apache License

/**
 * Mthode principale qui gre l'export d'un tableau vers un fichier ODS.
 *
 * @param export paramtres du document  exporter
 * @param out flux de sortie/*from   ww w. ja va  2  s  . com*/
 * @throws DocumentException Exception
 */
public final void exportData(final Export export, final OutputStream out) throws DocumentException {
    // step 1: creation of a document-object
    final boolean landscape = export.getOrientation() == Export.Orientation.Landscape;
    final Rectangle pageSize = landscape ? PageSize.A4.rotate() : PageSize.A4;
    final Document document = new Document(pageSize, 20, 20, 50, 50); // left,
    // right,
    // top,
    // bottom
    // step 2: we create a writer that listens to the document and directs a
    // PDF-stream to out
    createWriter(document, out);

    // we add some meta information to the document, and we open it
    final String title = export.getTitle();
    if (title != null) {
        final HeaderFooter header = new HeaderFooter(new Phrase(title), false);
        header.setAlignment(Element.ALIGN_LEFT);
        header.setBorder(Rectangle.NO_BORDER);
        document.setHeader(header);
        document.addTitle(title);
    }

    final String author = export.getAuthor();
    document.addAuthor(author);
    document.addCreator(CREATOR);
    document.open();
    try {
        // pour ajouter l'ouverture automatique de la bote de dialogue
        // imprimer
        // (print(false) pour imprimer directement)
        // ((PdfWriter) writer).addJavaScript("this.print(true);", false);

        for (final ExportSheet exportSheet : export.getSheets()) {
            final Table datatable;
            if (exportSheet.hasDtObject()) {
                // table
                datatable = new Table(2);
                datatable.setCellsFitPage(true);
                datatable.setPadding(4);
                datatable.setSpacing(0);

                // data rows
                renderObject(exportSheet, datatable);
            } else {
                // table
                datatable = new Table(exportSheet.getExportFields().size());
                datatable.setCellsFitPage(true);
                datatable.setPadding(4);
                datatable.setSpacing(0);

                // headers
                renderHeaders(exportSheet, datatable);

                // data rows
                renderList(exportSheet, datatable);
            }
            document.add(datatable);
        }
    } finally {
        // we close the document
        document.close();
    }
}

From source file:io.vertigo.quarto.plugins.export.pdfrtf.AbstractExporterIText.java

License:Apache License

/**
 * Mthode principale qui gre l'export d'un tableau vers un fichier ODS.
 *
 * @param export paramtres du document  exporter
 * @param out flux de sortie/*  w  ww  .  j a  va 2  s .  c o  m*/
 * @throws DocumentException Exception
 */
public final void exportData(final Export export, final OutputStream out) throws DocumentException {
    // step 1: creation of a document-object
    final boolean landscape = export.getOrientation() == Export.Orientation.Landscape;
    final Rectangle pageSize = landscape ? PageSize.A4.rotate() : PageSize.A4;
    final Document document = new Document(pageSize, 20, 20, 50, 50); // left, right, top, bottom
    // step 2: we create a writer that listens to the document and directs a PDF-stream to out
    createWriter(document, out);

    // we add some meta information to the document, and we open it
    final String title = export.getTitle();
    if (title != null) {
        final HeaderFooter header = new HeaderFooter(new Phrase(title), false);
        header.setAlignment(Element.ALIGN_LEFT);
        header.setBorder(Rectangle.NO_BORDER);
        document.setHeader(header);
        document.addTitle(title);
    }

    final String author = export.getAuthor();
    document.addAuthor(author);
    document.addCreator(CREATOR);
    document.open();
    try {
        // pour ajouter l'ouverture automatique de la bote de dialogue imprimer (print(false) pour imprimer directement)
        // ((PdfWriter) writer).addJavaScript("this.print(true);", false);

        for (final ExportSheet exportSheet : export.getSheets()) {
            final Table datatable;
            if (exportSheet.hasDtObject()) {
                // table
                datatable = new Table(2);
                datatable.setCellsFitPage(true);
                datatable.setPadding(4);
                datatable.setSpacing(0);

                // data rows
                renderObject(exportSheet, datatable);
            } else {
                // table
                datatable = new Table(exportSheet.getExportFields().size());
                datatable.setCellsFitPage(true);
                datatable.setPadding(4);
                datatable.setSpacing(0);

                // headers
                renderHeaders(exportSheet, datatable);

                // data rows
                renderList(exportSheet, datatable);
            }
            document.add(datatable);
        }
    } finally {
        // we close the document
        document.close();
    }
}

From source file:is.idega.idegaweb.egov.cases.business.CaseWriter.java

License:Open Source License

protected MemoryFileBuffer writePDF(IWContext iwc) {
    Font titleFont = new Font(Font.HELVETICA, 14, Font.BOLD);
    Font labelFont = new Font(Font.HELVETICA, 11, Font.BOLD);
    Font textFont = new Font(Font.HELVETICA, 11, Font.NORMAL);

    try {//from w w w.  j  a  v a 2s  .  c o  m
        MemoryFileBuffer buffer = new MemoryFileBuffer();
        MemoryOutputStream mos = new MemoryOutputStream(buffer);

        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        PdfWriter.getInstance(document, mos);
        document.addAuthor("Idegaweb eGov");
        document.addSubject("Case");
        document.open();
        document.newPage();

        String title = iwrb.getLocalizedString("case_overview", "Case overview");
        Paragraph cTitle = new Paragraph(title, titleFont);
        cTitle.setSpacingAfter(24);
        document.setPageCount(1);
        document.add(cTitle);

        int[] widths = { 25, 75 };
        PdfPTable table = new PdfPTable(2);
        table.setWidths(widths);
        table.getDefaultCell().setBorder(0);
        table.getDefaultCell().setPaddingBottom(8);

        CaseCategory category = theCase.getCaseCategory();
        CaseCategory parentCategory = category.getParent();
        CaseType type = theCase.getCaseType();
        User user = theCase.getOwner();
        Address address = user != null ? getUserBusiness(iwc).getUsersMainAddress(user) : null;
        PostalCode postal = null;
        if (address != null) {
            postal = address.getPostalCode();
        }
        Phone phone = null;
        if (user != null) {
            try {
                phone = getUserBusiness(iwc).getUsersHomePhone(user);
            } catch (NoPhoneFoundException e) {
                //No phone found...
            }
        }
        Email email = null;
        if (user != null) {
            try {
                email = getUserBusiness(iwc).getUsersMainEmail(user);
            } catch (NoEmailFoundException e) {
                //No email found...
            }
        }

        IWTimestamp created = new IWTimestamp(theCase.getCreated());

        if (user != null) {
            table.addCell(new Phrase(iwrb.getLocalizedString("name", "Name"), labelFont));
            table.addCell(new Phrase(
                    new Name(user.getFirstName(), user.getMiddleName(), user.getLastName()).getName(locale),
                    textFont));

            table.addCell(new Phrase(iwrb.getLocalizedString("personal_id", "Personal ID"), labelFont));
            table.addCell(new Phrase(PersonalIDFormatter.format(user.getPersonalID(), locale), textFont));

            table.addCell(new Phrase(iwrb.getLocalizedString("address", "Address"), labelFont));
            table.addCell(new Phrase(address != null ? address.getStreetAddress() : "-", textFont));

            table.addCell(new Phrase(iwrb.getLocalizedString("zip_code", "Postal code"), labelFont));
            table.addCell(new Phrase(postal != null ? postal.getPostalAddress() : "-", textFont));

            table.addCell(new Phrase(iwrb.getLocalizedString("home_phone", "Home phone"), labelFont));
            table.addCell(new Phrase(phone != null ? phone.getNumber() : "-", textFont));

            table.addCell(new Phrase(iwrb.getLocalizedString("email", "Email"), labelFont));
            table.addCell(new Phrase(email != null ? email.getEmailAddress() : "-", textFont));

            table.addCell(new Phrase(""));
            table.addCell(new Phrase(""));
            table.addCell(new Phrase(""));
            table.addCell(new Phrase(""));
        }

        table.addCell(new Phrase(iwrb.getLocalizedString("case_nr", "Case nr."), labelFont));
        table.addCell(new Phrase(theCase.getPrimaryKey().toString(), textFont));

        if (getCasesBusiness(iwc).useTypes()) {
            table.addCell(new Phrase(iwrb.getLocalizedString("case_type", "Case type"), labelFont));
            table.addCell(new Phrase(type.getName(), textFont));
        }

        if (parentCategory != null) {
            table.addCell(new Phrase(iwrb.getLocalizedString("case_category", "Case category"), labelFont));
            table.addCell(new Phrase(parentCategory.getLocalizedCategoryName(locale), textFont));

            table.addCell(new Phrase(iwrb.getLocalizedString("sub_case_category", "Case category"), labelFont));
            table.addCell(new Phrase(category.getLocalizedCategoryName(locale), textFont));
        } else {
            table.addCell(new Phrase(iwrb.getLocalizedString("case_category", "Case category"), labelFont));
            table.addCell(new Phrase(category.getLocalizedCategoryName(locale), textFont));
        }

        table.addCell(new Phrase(iwrb.getLocalizedString("created_date", "Created date"), labelFont));
        table.addCell(new Phrase(created.getLocaleDateAndTime(locale, IWTimestamp.SHORT, IWTimestamp.SHORT),
                textFont));

        if (theCase.getSubject() != null) {
            table.addCell(new Phrase(iwrb.getLocalizedString("subject", "Subject"), labelFont));
            table.addCell(new Phrase(theCase.getSubject(), textFont));
        }

        table.addCell(new Phrase(iwrb.getLocalizedString("message", "Message"), labelFont));
        table.addCell(new Phrase(theCase.getMessage(), textFont));

        if (theCase.getReference() != null) {
            table.addCell(new Phrase(iwrb.getLocalizedString("reference", "Reference"), labelFont));
            table.addCell(new Phrase(theCase.getReference(), textFont));
        }

        table.setWidthPercentage(100);
        document.add(table);

        document.close();
        try {
            mos.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        buffer.setMimeType("application/pdf");
        return buffer;

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

    return null;
}

From source file:is.idega.idegaweb.egov.printing.business.DocumentBusinessBean.java

License:Open Source License

public int writeBulkPDF(Collection messages, User performer, String fileName, Locale locale, String type,
        boolean areAddressMessages, boolean flagMessages, boolean registerBulkData) {
    int fileId = -1;
    try {/* ww  w .j av a 2  s.  co  m*/
        Iterator iter = messages.iterator();
        PrintMessage msg = null;
        PdfTemplate template = null;
        if (registerBulkData) {
            MemoryFileBuffer outerBuf = new MemoryFileBuffer();
            OutputStream outerDocOS = new MemoryOutputStream(outerBuf);
            InputStream outerDocIS = new MemoryInputStream(outerBuf);
            Document outerDocument = getLetterDocumentTemplate();
            PdfWriter writer = PdfWriter.getInstance(outerDocument, outerDocOS);
            outerDocument.open();

            ICFile bulkFile = getICFileHome().create();
            bulkFile.store();

            if (!areAddressMessages) {
                template = getLetterTemplate(type, writer);
            }
            int contentReturn = 0;
            int lettersProcessed = 0;
            DocumentPrintContext dpc = new DocumentPrintContext();
            dpc.setLocale(locale);
            dpc.setDocument(outerDocument);
            dpc.setPdfWriter(writer);
            dpc.setIWApplicationContext(getIWApplicationContext());
            while (iter.hasNext()) {
                msg = (PrintMessage) iter.next();
                dpc.setMessage(msg);
                if (!areAddressMessages) {
                    addTemplateToPage(template, writer, type);
                }
                // contentReturn = createContent(outerDocument, msg,
                // performer,writer,locale);
                // contentReturn = createContent(dpc);
                createHandlerContent(dpc);

                // System.err.println("letter content returns : "+contentReturn+" for
                // msg: "+msg.getPrimaryKey().toString());
                if (contentReturn != ADDRESS_ERROR) {
                    outerDocument.newPage();
                    try {
                        // System.err.println("bulk id =
                        // "+bulkFile.getPrimaryKey().toString());
                        msg.setMessageBulkData(bulkFile);

                        if (areAddressMessages) {
                            writePDF(msg, performer, fileName, locale, flagMessages);
                        } else if (flagMessages) {
                            getMessageBusiness().flagMessageAsPrinted(performer, msg);
                        } else {
                            msg.store();
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    lettersProcessed++;
                }
            }

            outerDocument.close();
            if (lettersProcessed > 0) {
                if (registerBulkData) {
                    bulkFile.setFileValue(outerDocIS);
                    bulkFile.setMimeType(MimeTypeUtil.MIME_TYPE_PDF_2);
                    bulkFile.setName(fileName + ".pdf");
                    bulkFile.setFileSize(outerBuf.length());
                    bulkFile.store();
                    PrintDocuments pdocs = getPrintDocumentsHome().create();
                    pdocs.setDocument(bulkFile);
                    pdocs.setNumberOfSubDocuments(lettersProcessed);
                    pdocs.setCreator(performer);
                    pdocs.setType(type);
                    pdocs.store();
                    fileId = pdocs.getDocumentFileID();
                }
            }
            try {
                outerDocOS.close();
                outerDocIS.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else {
            while (iter.hasNext()) {
                msg = (PrintMessage) iter.next();
                writePDF(msg, performer, fileName, locale, flagMessages);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return fileId;
}

From source file:is.idega.idegaweb.egov.printing.business.DocumentBusinessBean.java

License:Open Source License

public int writePDF(PrintMessage msg, User performer, String fileName, Locale locale, boolean flagPrinted)
        throws Exception {
    MemoryFileBuffer buffer = new MemoryFileBuffer();
    OutputStream mos = new MemoryOutputStream(buffer);
    InputStream mis = new MemoryInputStream(buffer);
    Document document = getLetterDocumentTemplate();

    PdfWriter writer = PdfWriter.getInstance(document, mos);

    document.open();//  w  w  w.j  ava 2s. c  o m
    document.newPage();

    DocumentPrintContext dpc = new DocumentPrintContext();
    dpc.setDocument(document);
    dpc.setPdfWriter(writer);
    dpc.setUser(performer);
    dpc.setLocale(locale);
    dpc.setMessage(msg);
    dpc.setIWApplicationContext(getIWApplicationContext());

    // int contentReturn = createContent(document, msg,
    // performer,writer,locale);

    // int contentReturn = createContent(dpc);
    createHandlerContent(dpc);

    /*
     * if(contentReturn==ADDRESS_ERROR){ document.close(); try { mos.close(); mis.close(); } catch (Exception ex) { } return -1; }
     */
    document.close();
    ICFile file = getICFileHome().create();

    if (!fileName.endsWith(".pdf") && !fileName.endsWith(".PDF")) {
        fileName += ".pdf";
    }

    /* *** writing pdf to cachefolder manually */
    String folder = getIWApplicationContext().getIWMainApplication()
            .getRealPath(getIWApplicationContext().getIWMainApplication().getCacheDirectoryURI() + "/prints");
    java.io.File tfile = com.idega.util.FileUtil.getFileAndCreateIfNotExists(folder, fileName);
    java.io.FileOutputStream fos = new java.io.FileOutputStream(tfile);
    java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
    while (mis.available() > 0) {
        baos.write(mis.read());
    }
    baos.writeTo(fos);
    baos.flush();
    baos.close();
    mis.reset();

    file.setFileValue(mis);
    file.setMimeType(MimeTypeUtil.MIME_TYPE_PDF_2);
    file.setName(fileName);
    file.setFileSize(buffer.length());
    file.store();
    msg.setMessageData(file);
    try {
        if (flagPrinted) {
            getMessageBusiness().flagMessageAsPrinted(performer, msg);
        } else {
            msg.store();
        }
        return msg.getMessageDataFileID();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    try {
        mos.close();
        mis.close();
    } catch (Exception ex) {
    }
    return -1;

}

From source file:is.idega.idegaweb.egov.printing.business.DocumentServiceBean.java

License:Open Source License

/**
 * Creates a pdf letter from a template which is chosen from the message type. Returns a primaryKey to a file in database
 *//* w w  w.  j  av a2 s .c  o  m*/
public Integer createPDF(IWUserContext iwuc, Collection msgs, String type, String fileName,
        boolean flagPrinted) {
    OutputStream outerOs = null;
    InputStream outerIs = null;
    try {
        MemoryFileBuffer outerBuf = new MemoryFileBuffer();
        outerOs = new MemoryOutputStream(outerBuf);
        outerIs = new MemoryInputStream(outerBuf);

        //
        // step 1: creation of a document-object
        Document document = new Document();
        // step 2: we create a writer that listens to the document
        PdfCopy writer = new PdfCopy(document, outerOs);
        // step 3: we open the document
        document.open();

        ICFile bulkFile = getICFileHome().create();
        bulkFile.store();

        PrintingService pserv = getPrintingService();

        CommuneMessageBusiness msgBuiz = getMessageService();
        int lettersProcessed = 0;
        for (Iterator iter = msgs.iterator(); iter.hasNext();) {
            PrintMessage msg = (PrintMessage) iter.next();
            MemoryFileBuffer buffer = new MemoryFileBuffer();
            OutputStream mos = new MemoryOutputStream(buffer);
            InputStream mis = new MemoryInputStream(buffer);

            PrintingContext pcx = getPrintingContext(iwuc, msg);
            if (pcx != null) {
                pcx.setDocumentStream(mos);
                pserv.printDocument(pcx);

                PdfReader reader = new PdfReader(buffer.buffer());
                PdfImportedPage page;
                int n = reader.getNumberOfPages();
                for (int i = 0; i < n;) {
                    ++i;
                    page = writer.getImportedPage(reader, i);
                    writer.addPage(page);
                }
                lettersProcessed++;
                storeStreamToICFile(iwuc, msgBuiz, msg, mis, fileName, buffer.length(), flagPrinted);
                msg.setMessageBulkData(bulkFile);
                msg.store();
            }
        }
        document.close();
        bulkFile = createFile(bulkFile, fileName, outerIs, outerBuf.length());

        PrintDocuments pdocs = getPrintDocumentsHome().create();
        pdocs.setDocument(bulkFile);
        pdocs.setNumberOfSubDocuments(lettersProcessed);
        pdocs.setCreator(iwuc.getCurrentUser());
        pdocs.setType(type);
        pdocs.store();

        return (Integer) bulkFile.getPrimaryKey();
    } catch (Exception e) {
        e.printStackTrace();
        throw new ContentCreationException(e);
    } finally {
        try {
            outerOs.close();
            outerIs.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}