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:bd.gov.forms.web.FormBuilder.java

License:Open Source License

@RequestMapping(value = "/individualpdf", method = RequestMethod.GET)
public String individualpdf(@RequestParam(value = "formId", required = true) String formId,
        @RequestParam(value = "entryId", required = true) String entryId, ModelMap model,
        HttpServletResponse response) throws IOException {

    byte[] fileContent = formDao.getTemplateContent(formId);
    Form form = formDao.getFormWithFields(formId);
    form.setEntryId(entryId);//from  w  ww  .  ja  va  2  s.  co m

    form = formDao.getEntry(form);
    String report = "";

    Document document = new Document();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    if (fileContent != null) {
        report = new String(fileContent, "UTF8");

        for (Field field : form.getFields()) {
            if (fieldTypeIsNotOfFileOrNoteOrSection(field)) {
                report = report.replaceAll("#" + field.getColName() + ":label#", field.getLabel());
                report = report.replaceAll("#" + field.getColName() + ":value#", field.getStrVal());
            }
        }
    }

    else {
        // step 2
        try {
            response.reset();
            response.setContentType("application/pdf");
            response.setHeader("Content-disposition", "inline; filename=test.pdf");

            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Pragma", "No-cache");

            PdfWriter writer = PdfWriter.getInstance(document, baos);
            // step 3
            document.open();

            PdfPCell space;
            space = new PdfPCell();
            space.setBorder(Rectangle.NO_BORDER);
            space.setColspan(2);
            space.setFixedHeight(8);

            PdfPTable table = new PdfPTable(2);
            PdfPCell cell;

            report += "<table cellspacing='0' cellpadding='0' style='border:1px solid #aaa;width:98%;'>";

            for (Field field : form.getFields()) {
                if (fieldTypeIsNotOfFileOrNoteOrSection(field)) {

                    report += field.getLabel();

                    report += field.getStrVal();

                    table.setWidths(new int[] { 1, 2 });
                    table.addCell(field.getLabel());
                    //cell = new PdfPCell();
                    //cell.setCellEvent(new TextFields(1));
                    table.addCell(field.getStrVal());

                }
            }

            document.add(table);
            document.close();
            ServletOutputStream out = response.getOutputStream();
            baos.writeTo(out);
            out.flush();

        }

        catch (Exception ex) {
            System.out.println("Could not print reasone::" + ex.toString());

        }

    }

    return null;

}

From source file:bd.gov.forms.web.FormBuilder.java

License:Open Source License

@RequestMapping(value = "/pdfExport", method = RequestMethod.GET)
public String pdfExport(@RequestParam(value = "formId", required = true) String formId,
        @RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "colName", required = false) String colName,
        @RequestParam(value = "colVal", required = false) String colVal,
        @RequestParam(value = "sortCol", required = false) String sortCol,
        @RequestParam(value = "sortDir", required = false) String sortDir, ModelMap model,
        HttpServletResponse response, HttpServletRequest request) throws IOException {

    Document document = new Document();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // step 2//from w w w . ja v a  2s .  c o  m
    try {
        response.reset();
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "inline; filename=test.pdf");

        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Pragma", "No-cache");

        PdfWriter writer = PdfWriter.getInstance(document, baos);
        // step 3
        document.open();

        Form form = null;
        //System.out.println("The form id is 1:"+formId);
        if (formId != null) {
            form = formDao.getFormWithFields(formId);
        }

        if (form != null) {
            if (form.getStatus() != 2) {//2-active, 3-deactive
                model.put("doneMessage", "msg.access.denied");
                model.put("doneMsgType", "failed");

                return "redirect:done.htm";
            }
            initForm(form);
        }

        List<Field> fieldList = form.getFields();

        if (fieldList.isEmpty()) {
            System.out.println("The list size is zero");
        }

        PdfPCell space;
        space = new PdfPCell();
        space.setBorder(Rectangle.NO_BORDER);
        space.setColspan(2);
        space.setFixedHeight(8);

        PdfPTable table = new PdfPTable(2);
        PdfPCell cell;

        //PdfPCell cell;                
        table.setWidths(new int[] { 1, 2 });

        int i = 0;
        for (Field f : fieldList) {
            if ("text".equals(f.getType())) {

                table.addCell(f.getLabel());
                cell = new PdfPCell();
                cell.setCellEvent(new TextFields(1, i));
                table.addCell(cell);

            } else if ("textarea".equals(f.getType())) {
                table.addCell(f.getLabel());
                cell = new PdfPCell();
                cell.setCellEvent(new TextFields(1, i));
                cell.setFixedHeight(60);
                table.addCell(cell);

            } else if ("select".equals(f.getType())) {
                table.addCell(f.getType());
                cell = new PdfPCell();
                cell.setCellEvent(new ChoiceFields(3, f.getList().toArray()));
                table.addCell(cell);
                //table.addCell(space);
                System.out.println("ajsdhd");
            }
            i++;
        }

        /*
          for(Field f : fieldList)
          {  
                
        if( "radio".equals(f.getType()) )
        {    
            System.out.println("List "+f.getList()+"  Oppt"+f.getOptions()+ "    df"+f.getColName());
                    
            writer = PdfWriter.getInstance(document, new FileOutputStream("TextFieldForm.pdf"));
                 
            //writer.addJavaScript(Utilities.readFileToString(""));
            // add the radio buttons
            PdfContentByte canvas = writer.getDirectContent();
            Font font = new Font(FontFamily.HELVETICA, 14);
            Rectangle rect;
            PdfFormField field;
            PdfFormField radiogroup = PdfFormField.createRadioButton(writer, true);
            radiogroup.setFieldName("language");
            RadioCheckField radio;
            for (int i = 0; i < 2; i++) 
            {
                rect = new Rectangle(40, 806 - i * 40, 60, 788 - i * 40);
                radio = new RadioCheckField(writer, rect, null, f.getLabel());
                radio.setBorderColor(GrayColor.GRAYBLACK);
                radio.setBackgroundColor(GrayColor.GRAYWHITE);
                radio.setCheckType(RadioCheckField.TYPE_CIRCLE);
                field = radio.getRadioField();
                radiogroup.addKid(field);
                        
                writer.addAnnotation(field);
                       
                ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(f.getLabel(), font), 70, 790 - i * 40, 0);
            }
            //table.addCell(f.getLabel());
            //cell = new PdfPCell();
                    
            //document.add(radiogroup);
            //writer.addAnnotation(radiogroup);
                    
                
        }
                
          }       */

        // Add submit button   
        PushbuttonField submitBtn = new PushbuttonField(writer, new Rectangle(400, 700, 370, 670),
                "submitPOST");
        //submitBtn.setBackgroundColor(Color.GRAY);
        submitBtn.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
        submitBtn.setText("Submit");
        submitBtn.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
        PdfFormField submitField = submitBtn.getField();
        submitField.setAction(
                PdfAction.createSubmitForm("http://localhost:8084/GovForm-07-02/formBuilder/pdfresponse.htm",
                        null, PdfAction.SUBMIT_HTML_FORMAT));

        writer.addAnnotation(submitField);

        document.add(table);

        System.out.println("Pdf creation successful");

        document.close();

        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();

    } catch (Exception ex) {
        System.out.println("Could not print reasone::" + ex.toString());

    }

    //////////////////////////////////////// email part////////////////////////////  
    //email functionalities
    // Recipient's email ID needs to be mentioned.
    String to = "tanviranik@gmail.com";

    // Sender's email ID needs to be mentioned
    String from = "tanvir_cse@yahoo.com";

    // Assuming you are sending email from localhost
    String host = "localhost";

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Set Subject: header field
        message.setSubject("This is the Subject Line!");

        // Now set the actual message
        message.setText("This is actual message");

        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
        mex.printStackTrace();
    }
    //////////////////////////////////////// email part////////////////////////////

    return null;

}

From source file:be.kcbj.placemat.Placemat.java

License:Open Source License

private void createPdf(File file, List<Sponsor> sponsors) throws IOException, DocumentException {
    System.out.println("Generating PDF file " + file.getAbsolutePath());
    Layout layout = new Layout(sponsors);
    System.out.println("Layout = " + layout);

    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(file));
    document.setPageSize(PageSize.A4.rotate());
    document.setMargins(PADDING_DOC, PADDING_DOC, PADDING_DOC, PADDING_DOC);
    document.open();//from   w  ww .  ja  v a 2 s  . c  om

    PdfPTable table = new PdfPTable(layout.getColumnCount());
    table.setWidthPercentage(100);
    table.setSpacingBefore(0f);
    table.setSpacingAfter(0f);
    for (int i = 0; i < sponsors.size(); i++) {
        table.addCell(generateCell(sponsors.get(i), layout.getCellHeight()));
    }
    for (int i = 0; i < layout.getEmptyCellCount(); i++) {
        table.addCell(generateCell(new Sponsor(), layout.getCellHeight()));
    }
    document.add(table);

    document.close();
}

From source file:be.rheynaerde.poolsheets.AbstractPoolSheet.java

License:Open Source License

protected void buildSheet() throws DocumentException {
    Rectangle pageSize = configuration.isLandscape(AbstractPoolSheetConfiguration.TITLE_PAGE)
            ? PageSize.A4.rotate()/*from  w  w  w . j a v  a2 s . co m*/
            : PageSize.A4;
    Document document = new Document(pageSize);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);

    document.open();
    document.addTitle(configuration.getTitle());
    document.addCreator(CREATOR);

    buildTitle(document);
    buildTable(document);

    if (configuration.includeOrderOfBouts()) {
        if (configuration.putBoutOrderOnNewPage()) {
            pageSize = configuration.isLandscape(AbstractPoolSheetConfiguration.BOUT_ORDER_PAGE)
                    ? PageSize.A4.rotate()
                    : PageSize.A4;
            document.setPageSize(pageSize);
            document.newPage();
        }

        buildBoutOrder(document);
    }

    document.close();
    sheet = baos.toByteArray();
}

From source file:be.rheynaerde.pufmanager.gui.workers.ExportFullPdfWorker.java

License:Open Source License

@Override
protected byte[] doInBackground() throws Exception {
    ByteArrayOutputStream largeBaos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfCopy copy = new PdfCopy(document, largeBaos);
    document.open();/*from   w  w  w .  j  a v a  2  s .c om*/

    String stampText = ResourceBundle
            .getBundle("be.rheynaerde.pufmanager.gui.export", competition.getSettings().getLocale())
            .getString("ExportFullPdf.poolsheet.stamp");

    for (int i = 0; i < competition.getRoundCount(); i++) {
        publish(i);
        Round round = competition.getRound(i);
        int piste = 1;
        for (Match match : round.getMatches()) {
            final Match currentMatch = match;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if (match.getRound().includeInternalBouts()) {
                PufCompletePoolSheetConfiguration config = new NamedPufCompletePoolSheetConfiguration(
                        match.getFirstTeam().getFencerNames(), match.getSecondTeam().getFencerNames(), 20f,
                        competition.getSettings().getImage(), competition.getSettings().getLocale(),
                        competition.getSettings().getTitle(), competition.getSettings().getSubtitle()) {

                    @Override
                    public String getResult(int team1, int player1, int team2, int player2) {
                        Fencer player = (team1 == 0 ? currentMatch.getFirstTeam()
                                : currentMatch.getSecondTeam()).getFencer(player1);
                        Fencer opponent = (team2 == 0 ? currentMatch.getFirstTeam()
                                : currentMatch.getSecondTeam()).getFencer(player2);
                        PoolResult result = competition.getCompetitionPool().getResult(player, opponent);
                        return result == null ? null : result.toString();
                    }

                };
                PufCompletePoolSheet sheet = new PufCompletePoolSheet(config);
                sheet.export(baos);
            } else {
                PufTeamPoolSheetConfiguration config = new NamedPufTeamPoolSheetConfiguration(
                        match.getFirstTeam().getFencerNames(), match.getSecondTeam().getFencerNames(), 20f,
                        competition.getSettings().getImage(), competition.getSettings().getLocale(),
                        competition.getSettings().getTitle(), competition.getSettings().getSubtitle()) {

                    @Override
                    public String getResult(int team1, int player1, int team2, int player2) {
                        Fencer player = (team1 == 0 ? currentMatch.getFirstTeam()
                                : currentMatch.getSecondTeam()).getFencer(player1);
                        Fencer opponent = (team2 == 0 ? currentMatch.getFirstTeam()
                                : currentMatch.getSecondTeam()).getFencer(player2);
                        PoolResult result = competition.getCompetitionPool().getResult(player, opponent);
                        return result == null ? null : result.toString();
                    }

                };
                PufTeamPoolSheet sheet = new PufTeamPoolSheet(config);
                sheet.export(baos);

            }
            addPdfToDocument(baos, copy, String.format(stampText, i + 1, piste));
            piste++;
        }
        if (i == 0) {
            for (Team team : round.getRestingTeams()) {
                final Team currentTeam = team;
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                PufSingleTeamPoolSheetConfiguration config = new NamedPufSingleTeamPoolSheetConfiguration(
                        team.getFencerNames(), 20f, competition.getSettings().getImage(),
                        competition.getSettings().getLocale(), competition.getSettings().getTitle(),
                        competition.getSettings().getSubtitle()) {

                    @Override
                    public String getResult(int player, int opponent) {
                        Fencer playerFencer = currentTeam.getFencer(player);
                        Fencer opponentFencer = currentTeam.getFencer(opponent);
                        PoolResult result = competition.getCompetitionPool().getResult(playerFencer,
                                opponentFencer);
                        return result == null ? null : result.toString();
                    }

                };
                PufSingleTeamPoolSheet sheet = new PufSingleTeamPoolSheet(config);
                sheet.export(baos);
                addPdfToDocument(baos, copy, String.format(stampText, i + 1, piste));
                piste++;
            }
        }
    }

    document.close();
    publish(competition.getRoundCount());

    return largeBaos.toByteArray();
}

From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java

License:Open Source License

private byte[] createModelPages(Contact contact, List<Model> models, Toc tableOfContents)
        throws IOException, DocumentException {

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    Document document = iTextUtil.createNewDocument();
    PdfWriter writer = PdfWriter.getInstance(document, bos);

    document.open();//from   w w w .  ja  v  a2  s  . co  m

    // create a PdfPTable for every model (so we can measure the height)
    final List<PdfPTable> modelPageTables = new ArrayList<>();
    Collections.sort(models);
    for (Model model : models) {
        if (model != null) {
            modelPageTables.add(createModelPage(contact, model, writer));
        }
    }

    // put the PdfPTable Models tables on PDF pages (multiple per page if possible)
    byte[] pages = new byte[] {};

    int height = 0;
    List<String> pageNames = new ArrayList<>();

    int i = 0;
    for (PdfPTable modelPageTable : modelPageTables) {

        // create a new pdf page, if necessary
        if (height != 0 && (height + modelPageTable.getTotalHeight()
                + 20 /* for the line separator */ ) >= iTextUtil.PAGE_HEIGHT) {

            writer.close();
            document.close();
            bos.close();

            byte[] page = bos.toByteArray();
            tableOfContents.addEntries(2, pageNames, page, true,
                    Toc.MODEL_SORT_PREFIX + "___" + IntUtil.format(++i));
            pages = iTextUtil.merge(pages, page);

            height = 0;
            pageNames.clear();
            bos = new ByteArrayOutputStream();
            document = iTextUtil.createNewDocument();
            writer = PdfWriter.getInstance(document, bos);

            document.open();

        } else if (height != 0) {
            // if not the first model on the page, draw a separator

            document.add(new Paragraph(
                    new Chunk(new LineSeparator(.25f, 80f, BaseColor.LIGHT_GRAY, Element.ALIGN_CENTER, -2))));
            document.add(new Paragraph(new Chunk("   ")));
        }

        // rerender the table (with a valid pdfWriter)
        document.add(createModelPage(contact, models.get(modelPageTables.indexOf(modelPageTable)), writer));
        height += modelPageTable.getTotalHeight();
        pageNames.add(models.get(modelPageTables.indexOf(modelPageTable)).getProductNameProcessed());

    }
    writer.close();
    document.close();

    byte[] page = bos.toByteArray();
    tableOfContents.addEntries(2, pageNames, page, true, Toc.MODEL_SORT_PREFIX + "___" + IntUtil.format(++i));
    pages = iTextUtil.merge(pages, page);

    return pages;

}

From source file:be.roots.taconic.pricingguide.util.iTextUtil.java

License:Open Source License

public static byte[] emptyPage() throws DocumentException, IOException {

    try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        final Document document = createNewDocument();

        final PdfWriter pdfWriter = PdfWriter.getInstance(document, baos);
        document.open();//from w w w . ja  v a  2s . c o  m
        document.newPage();
        pdfWriter.setPageEmpty(false);
        document.close();
        return baos.toByteArray();
    }
}

From source file:be.thomasmore.controller.InputBean.java

public void createPdf(String filename) throws DocumentException, IOException {
    // step 1//from   w  w  w.  ja v  a  2s  . c o  m
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    document.open();
    // step 4
    document.add(new Paragraph("Hello World!"));
    // step 5
    document.close();
}

From source file:be.thomasmore.controller.PdfController.java

public void createPdfKlas() {

    Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext()
            .getRequestParameterMap();/*  w  ww  .j  ava  2 s. co  m*/
    String KlasId = params.get("klasId");
    int id = Integer.parseInt(KlasId);
    Document document = new Document();
    Klas klas = service.getKlas(id);
    List<Klastest> klastesten = klas.getKlastestList();
    List<Test> testen = new ArrayList<Test>();

    HttpServletResponse res = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext()
            .getResponse();
    res.setHeader("Content-Disposition", "attachement; filename=" + klas.getNummer() + "-resultaten.pdf");
    res.setContentType("application/pdf");

    try {
        PdfWriter.getInstance(document, res.getOutputStream());

        document.open();

        Font font = FontFactory.getFont("Calibri");
        Font fontbold = FontFactory.getFont("Calibri", Font.BOLD);

        PdfPTable table = new PdfPTable(3); // 3 columns.

        PdfPCell cell1 = new PdfPCell(new Paragraph("Vak", font));
        PdfPCell cell2 = new PdfPCell(new Paragraph("Student", font));
        PdfPCell cell3 = new PdfPCell(new Paragraph("Behaald", font));

        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);

        for (Klastest klastest : klastesten) {
            Test test = klastest.getTestId();
            testen.add(service.getTest(test.getId()));
        }

        for (Test test : testen) {
            List<Score> scores = test.getScoreList();
            Vak vak = test.getVakId();
            for (Score score : scores) {
                Student student = score.getStudentId();
                PdfPCell cellVak = new PdfPCell(new Paragraph(vak.getNaam(), font));
                PdfPCell cellStudent = new PdfPCell(new Paragraph(student.getVoornaam(), font));
                PdfPCell cellScore = new PdfPCell(new Paragraph(score.getScore().toString(), font));

                table.addCell(cellVak);
                table.addCell(cellStudent);
                table.addCell(cellScore);
            }
        }

        document.add(new Phrase("Klas: ", font));
        document.add(new Phrase(klas.getNummer(), font));
        document.add(table);

        document.close();
    } catch (Exception e) {

    }

}

From source file:be.thomasmore.controller.PdfController.java

public void createPdfTest() {
    Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext()
            .getRequestParameterMap();/*from w w w  . j  a va2 s .  co m*/
    String KlasId = params.get("klasId3");
    String TestId = params.get("testId");
    int klasId = Integer.parseInt(KlasId);
    int id = Integer.parseInt(TestId);
    Document document = new Document();
    Test test = service.getTest(id);
    List<Score> scores = test.getScoreList();
    Klas klas = service.getKlas(klasId);
    Vak vak = test.getVakId();

    HttpServletResponse res = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext()
            .getResponse();
    res.setHeader("Content-Disposition", "attachement; filename=" + test.getBeschrijving() + "-resultaten.pdf");
    res.setContentType("application/pdf");

    try {
        PdfWriter.getInstance(document, res.getOutputStream());

        document.open();

        Font font = FontFactory.getFont("Calibri");
        Font fontbold = FontFactory.getFont("Calibri", Font.BOLD);

        PdfPTable table = new PdfPTable(3); // 3 columns.

        PdfPCell cell1 = new PdfPCell(new Paragraph("Test", font));
        PdfPCell cell2 = new PdfPCell(new Paragraph("Student", font));
        PdfPCell cell3 = new PdfPCell(new Paragraph("Score", font));

        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);

        for (Score score : scores) {
            Student student = score.getStudentId();
            PdfPCell cellTest = new PdfPCell(new Paragraph(test.getBeschrijving(), font));
            PdfPCell cellStudent = new PdfPCell(new Paragraph(student.getVoornaam(), font));
            PdfPCell cellScore = new PdfPCell(new Paragraph(score.getScore().toString()));

            table.addCell(cellTest);
            table.addCell(cellStudent);
            table.addCell(cellScore);
        }

        document.add(new Phrase("Klas: ", font));
        document.add(new Phrase(klas.getNummer(), font));
        document.add(new Phrase("  Vak: ", font));
        document.add(new Phrase(vak.getNaam(), font));
        document.add(table);

        document.close();
    } catch (Exception e) {

    }

}