Example usage for com.lowagie.text Document open

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

Introduction

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

Prototype

boolean open

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

Click Source Link

Document

Is the document open or not?

Usage

From source file:gov.noaa.pfel.coastwatch.sgt.SgtUtil.java

License:Open Source License

/**
 * This creates a file to capture the pdf output generated by calls to 
 * graphics2D (e.g., use makeMap).//from ww  w  . j a  v  a2s  .c om
 * This will overwrite an existing file.
 * 
 * @param pageSize e.g, PageSize.LETTER or PageSize.LETTER.rotate() (or A4, or, ...)
 * @param width the bounding box width, in 1/144ths of an inch
 * @param height the bounding box height, in 1/144ths of an inch
 * @param outputStream
 * @return an object[] with 0=g2D, 1=document, 2=pdfContentByte, 3=pdfTemplate
 * @throws Exception if trouble
 */
public static Object[] createPdf(com.lowagie.text.Rectangle pageSize, int bbWidth, int bbHeight,
        OutputStream outputStream) throws Exception {
    //currently, this uses itext
    //see the sample program:
    //  file://localhost/C:/programs/iText/examples/com/lowagie/examples/directcontent/graphics2D/G2D.java
    //Document.compress = false; //for test purposes only
    Document document = new Document(pageSize);
    document.addCreationDate();
    document.addCreator("gov.noaa.pfel.coastwatch.SgtUtil.createPdf");

    document.setPageSize(pageSize);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.open();

    //create contentByte and template and Graphics2D objects
    PdfContentByte pdfContentByte = writer.getDirectContent();
    PdfTemplate pdfTemplate = pdfContentByte.createTemplate(bbWidth, bbHeight);
    Graphics2D g2D = pdfTemplate.createGraphics(bbWidth, bbHeight);

    return new Object[] { g2D, document, pdfContentByte, pdfTemplate };
}

From source file:gov.utah.dts.det.ccl.documents.templating.templates.AbstractCaseloadTemplate.java

@Override
public void render(Map<String, Object> context, OutputStream outputStream, FileDescriptor descriptor)
        throws TemplateException {
    Long specialistId = (Long) context.get("specId");
    if (specialistId == null) {
        throw new TemplateException("Specialist id is required.");
    }/* ww w .  j  a  v a2s.  c  om*/

    CaseloadSortBy sortBy = CaseloadSortBy.getDefaultSortBy();
    String sortByStr = (String) context.get("sortBy");
    if (sortByStr != null) {
        sortBy = CaseloadSortBy.valueOf(sortByStr);
    }

    Person specialist = personService.getPerson(specialistId);
    context.put(SPECIALIST_KEY, specialist);

    List<FacilityCaseloadView> caseload = getCaseload(specialistId, sortBy);

    setFileName(context, descriptor);

    try {
        Document document = new Document(PageSize.LETTER.rotate(), MARGIN, MARGIN, MARGIN, MARGIN);
        PdfWriter.getInstance(document, outputStream);

        document.open();

        document.add(new Paragraph(getReportTitle() + " for " + specialist.getFirstAndLastName(), FONT));
        //columns: name, facility id, address, phone, 1st director(s), status, type, capacity (<2)

        PdfPTable table = new PdfPTable(8);
        table.setWidths(new float[] { 23f, 25f, 11f, 13f, 5f, 9f, 7f, 7f });
        table.setWidthPercentage(100);
        table.setSpacingBefore(FONT_SIZE);

        table.getDefaultCell().setPadding(TABLE_CELL_PADDING);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setBorderWidthBottom(.5f);
        table.setHeaderRows(1);

        table.addCell(new Phrase("Facility Name", HEADER_FONT));
        table.addCell(new Phrase("Address", HEADER_FONT));
        table.addCell(new Phrase("Phone", HEADER_FONT));
        table.addCell(new Phrase("1st Director(s)", HEADER_FONT));
        table.addCell(new Phrase("Type", HEADER_FONT));
        table.addCell(new Phrase("Exp Dt", HEADER_FONT));
        table.addCell(new Phrase("Adult Cap", HEADER_FONT));
        table.addCell(new Phrase("Youth Cap", HEADER_FONT));

        boolean hasInProcess = false;

        for (FacilityCaseloadView fcv : caseload) {
            if (fcv.getStatus() == FacilityStatus.REGULATED || fcv.getStatus() == FacilityStatus.IN_PROCESS) {
                StringBuilder name = new StringBuilder();
                if (fcv.getStatus() == FacilityStatus.IN_PROCESS) {
                    hasInProcess = true;
                    name.append("* ");
                }
                name.append(fcv.getName());

                table.addCell(new Phrase(name.toString(), FONT));
                table.addCell(new Phrase(fcv.getLocationAddress().toString(), FONT));
                table.addCell(new Phrase(fcv.getPrimaryPhone().getFormattedPhoneNumber(), FONT));
                table.addCell(new Phrase(fcv.getDirectorNames(), FONT));

                String typeAbbrev = null;
                /*
                               if (fcv.getLicenseType() != null) {
                                  typeAbbrev = applicationService.getApplicationPropertyValue("facility.license.type." + fcv.getLicenseType().getId()+ ".abbrev");
                               }
                */
                table.addCell(new Phrase(typeAbbrev != null ? typeAbbrev : "", FONT));
                //               table.addCell(new Phrase(fcv.getExpirationDate() != null ? DATE_FORMATTER.format(fcv.getExpirationDate()) : "", FONT));
                table.addCell(new Phrase("", FONT));

                //               if (fcv.getAdultTotalSlots() == null) {
                table.addCell(new Phrase(""));
                //               } else {
                //                  table.addCell(new Phrase(fcv.getAdultTotalSlots().toString(), FONT));
                //               }
                //               if (fcv.getYouthTotalSlots() == null) {
                table.addCell(new Phrase(""));
                //               } else {
                //                  table.addCell(new Phrase(fcv.getYouthTotalSlots().toString(), FONT));
                //               }
            }
        }

        document.add(table);
        if (hasInProcess) {
            document.add(new Paragraph(
                    "* - Facility is in the process of becoming a regulated child care facility.", FONT));
        }

        document.close();
    } catch (DocumentException de) {
        throw new TemplateException(de);
    }
}

From source file:gov.utah.health.uper.reports.Registration.java

/**
 * Set up spacing on page//from  ww  w. ja v a2 s  .  com
 * @param document
 */
private void setUpPage(Document document) {
    document.setPageSize(PageSize.NOTE);
    //left, right, top, bottom
    document.setMargins(100, 100, 100, 100);
    document.open();

}

From source file:gui.TransHistory.java

public void Convertpdf() throws Exception {
    display();/*from www. j  a va2  s .co  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  w ww. ja  va  2s  . 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) {/*w ww.j  a  va  2 s  . c  o m*/
    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();
    Gson gson = new Gson();
    String json = gson.toJson(mentionRepository.findByCampaignId(campaignId));
    document.add(new Paragraph(json));
    document.close();//from   w  w w . ja  v a2 s  .  com

    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 w ww. ja v  a2  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//from  w  ww .ja  v  a  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 {//www.ja  v a 2  s .co 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;
}