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:com.beetle.framework.web.controller.DocumentController.java

License:LGPL

private void createPDF(OutputStream out, IDocument doc, WebInput wi) throws IOException, ServletException {
    this.setContentType("application/pdf");
    ByteArrayOutputStream baos = new ByteArrayOutputStream(INITIAL_SIZE);
    Document document = new Document(PageSize.A4);
    DocInfo di;//from  www .ja v  a  2  s .  c o  m
    try {
        PdfWriter.getInstance(document, baos);
        di = new DocInfo(IDocument.TYPE_PDF);
        di.setPdfDocument(document);
        // 
        doc.createAttribute(wi, di);
        document.open();
        // 
        doc.createContent(wi, di);
        document.close();
        this.setContentLength(baos.size());
        baos.writeTo(out);
    } catch (Exception ex1) {
        throw new ServletException(ex1);
    } finally {
        if (out != null) {
            out.flush();
            out.close();
            out = null;
        }
        if (baos != null) {
            baos.close();
            baos = null;
        }
        document = null;
        di = null;
        doc = null;
    }
}

From source file:com.benfante.minimark.blo.AssessmentPdfBuilder.java

License:Apache License

/**
 * Build the contatenated PDF for a list of assessments.
 *
 * @param assessments The assessments//from w  ww .  ja v a 2s  . c o m
 * @param baseUrl The base URL for retrieving images and resource. If null it will not be set.
 * @param locale The locale for producing the document. Id null, the default locale will be used.
 * @return The PDF document.
 */
public byte[] buildPdf(List<AssessmentFilling> assessments, String baseUrl, Locale locale) throws Exception {
    ByteArrayOutputStream pdfos = new ByteArrayOutputStream();
    List master = new ArrayList();
    Document document = null;
    PdfCopy writer = null;
    PdfOutline rootOutline = null;
    try {
        int f = 0;
        int pageOffset = 0;
        for (AssessmentFilling assessment : assessments) {
            // we create a reader for a certain document
            PdfReader reader = new PdfReader(buildPdf(assessment, baseUrl, locale));
            reader.consolidateNamedDestinations();
            // we retrieve the total number of pages
            int n = reader.getNumberOfPages();
            List bookmarks = SimpleBookmark.getBookmark(reader);
            if (bookmarks != null) {
                if (pageOffset != 0) {
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                }
                master.addAll(bookmarks);
            }
            pageOffset += n;
            if (f == 0) {
                // step 1: creation of a document-object
                document = new Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, pdfos);
                writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
                // step 3: we open the document
                document.open();
                // initialize rootOutline for assessment bookmarks creation
                PdfContentByte cb = writer.getDirectContent();
                rootOutline = cb.getRootOutline();
            }
            // step 4: we add content
            new PdfOutline(rootOutline, new PdfDestination(PdfDestination.FIT),
                    assessment.getLastName() + " " + assessment.getFirstName());
            PdfImportedPage page;
            for (int i = 0; i < n;) {
                ++i;
                page = writer.getImportedPage(reader, i);
                writer.addPage(page);
            }
            PRAcroForm form = reader.getAcroForm();
            if (form != null) {
                writer.copyAcroForm(reader);
            }
            f++;
        }
    } finally {
        if (pdfos != null) {
            try {
                pdfos.close();
            } catch (IOException ioe) {
            }
        }
        if (!master.isEmpty()) {
            writer.setOutlines(master);
        }
        // step 5: we close the document
        if (document != null && document.isOpen()) {
            document.close();
        }
    }
    return pdfos.toByteArray();
}

From source file:com.bytecode.customexporter.PDFCustomExporter.java

@Override
public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle,
        boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor, boolean subTable) throws IOException {
    try {//ww  w.  j  a  v  a  2  s.co  m
        Document document = new Document();
        if (orientation.equalsIgnoreCase("Landscape"))
            document.setPageSize(PageSize.A4.rotate());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        StringTokenizer st = new StringTokenizer(tableId, ",");
        while (st.hasMoreElements()) {
            String tableName = (String) st.nextElement();
            UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(),
                    tableName);
            if (component == null) {
                throw new FacesException("Cannot find component \"" + tableName + "\" in view.");
            }
            if (!(component instanceof DataTable || component instanceof DataList)) {
                throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName()
                        + "\", exporter must target a PrimeFaces DataTable/DataList.");
            }

            if (preProcessor != null) {
                preProcessor.invoke(context.getELContext(), new Object[] { document });
            }

            if (!document.isOpen()) {
                document.open();
            }
            if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) {

                Font tableTitleFont = FontFactory.getFont(FontFactory.TIMES, encodingType, Font.DEFAULTSIZE,
                        Font.BOLD);
                Paragraph title = new Paragraph(tableTitle, tableTitleFont);
                document.add(title);

                Paragraph preface = new Paragraph();
                addEmptyLine(preface, 3);
                document.add(preface);
            }
            PdfPTable pdf;
            DataList list = null;
            DataTable table = null;
            if (component instanceof DataList) {
                list = (DataList) component;
                pdf = exportPDFTable(context, list, pageOnly, encodingType);
            } else {
                table = (DataTable) component;
                pdf = exportPDFTable(context, table, pageOnly, selectionOnly, encodingType, subTable);
            }

            if (pdf != null) {
                document.add(pdf);
            }
            // add a couple of blank lines
            Paragraph preface = new Paragraph();
            addEmptyLine(preface, datasetPadding);
            document.add(preface);

            if (postProcessor != null) {
                postProcessor.invoke(context.getELContext(), new Object[] { document });
            }
        }
        document.close();

        writePDFToResponse(context.getExternalContext(), baos, filename);

    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:com.byterefinery.rmbench.export.diagram.PDFDiagramExporter.java

License:Open Source License

protected void doExport(OutputStream out, IFigure figure) {

    Rectangle bounds = getBounds(figure);
    Document document = new Document(new com.lowagie.text.Rectangle(bounds.width, bounds.height));

    PdfWriter pdf;//  w ww.jav a 2  s.  c om
    try {
        pdf = PdfWriter.getInstance(document, out);
        document.open();
        document.add(new Chunk(" "));
    } catch (DocumentException e) {
        ExportPlugin.logError(e);
        return;
    }
    PdfContentByte contentbytes = pdf.getDirectContent();
    PdfTemplate template = contentbytes.createTemplate(bounds.width, bounds.height);
    Graphics2D graphics2d = template.createGraphics(bounds.width, bounds.height);
    try {
        GraphicsToGraphics2DAdaptor graphics = new GraphicsToGraphics2DAdaptor(graphics2d,
                bounds.getTranslated(bounds.getLocation().negate()));
        graphics.translate(bounds.getLocation().negate());
        figure.paint(graphics);
    } finally {
        graphics2d.dispose();
        contentbytes.addTemplate(template, 0, 0);
        document.close();
    }
}

From source file:com.centurylink.mdw.designer.pages.ExportHelper.java

License:Apache License

/**
 * Export a process//from  w  ww. java2 s. c o m
 * @param filename the file name (including path) where the document will be generated
 * @param format can be docx, pdf, rtf, html and bpmn
 * @param canvas for printing process images
 * @param graph the process to be printed.
 */
public void exportProcess(String filename, String format, Graph process, DesignerCanvas canvas)
        throws Exception {

    initialize(false);

    String oldNodeIdType = process.getNodeIdType();

    try {
        process.setNodeIdType(nodeIdType);
        options.add(SECTION_NUMBER);
        if (format.equals(DOCX)) {
            DocxBuilder builder = printProcessDocx(filename, process, canvas);
            builder.save(new java.io.File(filename));
            return;
        } else if (format.equals(HTML)) {
            StringBuffer sb = printPrologHtml("Process " + process.getName());
            printProcessHtml(sb, canvas, 0, process, filename);
            printEpilogHtml(sb, filename);
            return;
        } else if (format.equals(JPG) || format.equals(PNG)) {
            byte[] imgBytes = printImage(-1f, canvas, process.getGraphSize(),
                    format.equals(JPG) ? "jpeg" : "png");
            OutputStream os = null;
            try {
                os = new FileOutputStream(new File(filename));
                os.write(imgBytes);
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
                throw ex;
            } finally {
                if (os != null)
                    os.close();
            }
        } else if (format.equals(BPMN2)) {
            new BPMNHelper().exportProcess(process.getProcessVO(), filename);
        } else { // itext processor
            Document document = new Document();
            try {
                DocWriter writer = null;
                if (format.equals(RTF)) {
                    writer = RtfWriter2.getInstance(document, new FileOutputStream(filename));
                } else if (format.equals(PDF)) {
                    writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
                }

                document.open();
                document.setPageSize(PageSize.LETTER);
                Rectangle page_size = document.getPageSize();
                Chapter chapter = printOneProcessPdf(writer, canvas, format, 1, process, filename, page_size);
                document.add(chapter);
            } catch (Exception ex) {
                ex.printStackTrace();
                throw ex;
            } finally {
                // step 5: we close the document
                document.close();
            }
        }
    } finally {
        process.setNodeIdType(oldNodeIdType);
    }
}

From source file:com.centurylink.mdw.designer.pages.ExportHelper.java

License:Apache License

/**
 * Export multiple processes/*from w w w  .j  a  va  2s .  com*/
 * @param filename the file name (including path) where the document will be generated
 * @param type can be pdf, rtf and html
 * @param flowchart the designer page (for using its canvas and report errors)
 * @param graphs the list of processes to be printed.
 * @param options options for printing, from the print dialog.
 */
public void exportProcesses(String filename, String type, FlowchartPage flowchart, List<Graph> graphs)
        throws Exception {
    initialize(false);
    options.add(SECTION_NUMBER);
    // step 1: creation of a document-object
    Document document = new Document();
    try {
        // step 2: create PDF or RTF writer
        DocWriter writer;
        if (type.equals(RTF)) {
            writer = RtfWriter2.getInstance(document, new FileOutputStream(filename));
        } else if (type.equals(PDF)) {
            writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        } else {
            boolean directHtml = true;
            if (directHtml) {
                StringBuffer sb = printPrologHtml("Processes");
                Graph process;
                for (int i = 0; i < graphs.size(); i++) {
                    process = graphs.get(i);
                    flowchart.setProcess(process);
                    this.printProcessHtml(sb, flowchart.canvas, i + 1, process, filename);
                }
                printEpilogHtml(sb, filename);
                return;
            }
            writer = HtmlWriter.getInstance(document, new FileOutputStream(filename));
        }
        // step 3: we open the document
        document.open();
        // step 4: we add contents to the document
        document.setPageSize(PageSize.LETTER);
        Graph process;
        Chapter chapter;
        Rectangle page_size = document.getPageSize();
        for (int i = 0; i < graphs.size(); i++) {
            process = graphs.get(i);
            process.setNodeIdType(nodeIdType);
            flowchart.setProcess(process);
            chapter = printOneProcessPdf(writer, flowchart.canvas, type, i + 1, process, filename, page_size);
            document.add(chapter);
        }
    } finally {
        // step 5: we close the document
        document.close();
    }
}

From source file:com.centurylink.mdw.designer.pages.ExportHelper.java

License:Apache License

public void printImagePdf(String filename, DesignerCanvas canvas, Dimension graphsize) {
    try {//from ww  w .j  a  v  a 2s  .c  o m
        DefaultFontMapper mapper = new DefaultFontMapper();
        FontFactory.registerDirectories();
        mapper.insertDirectory("c:\\winnt\\fonts");
        // mapper.insertDirectory("c:\\windows\\fonts");
        // we create a template and a Graphics2D object that corresponds
        // with it
        int margin = 72; // 1 inch
        float scale = 0.5f;
        boolean multiple_page = true;
        Rectangle page_size;
        if (multiple_page) {
            page_size = PageSize.LETTER.rotate();
        } else {
            page_size = new Rectangle((int) (graphsize.getWidth() * scale) + margin,
                    (int) (graphsize.getHeight() * scale) + margin);
        }
        Document document = new Document(page_size);
        DocWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();
        document.setPageSize(page_size);
        int image_w = (int) page_size.getWidth() - margin;
        int image_h = (int) page_size.getHeight() - margin;
        boolean edsave = canvas.editable;
        canvas.editable = false;
        Color bgsave = canvas.getBackground();
        canvas.setBackground(Color.white);
        if (multiple_page) {
            int horizontal_pages = (int) (graphsize.width * scale) / image_w + 1;
            int vertical_pages = (int) (graphsize.height * scale) / image_h + 1;
            for (int i = 0; i < horizontal_pages; i++) {
                for (int j = 0; j < vertical_pages; j++) {
                    Image img;
                    PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
                    PdfTemplate tp = cb.createTemplate(image_w, image_h);
                    Graphics2D g2 = tp.createGraphics(image_w, image_h, mapper);
                    tp.setWidth(image_w);
                    tp.setHeight(image_h);
                    g2.scale(scale, scale);
                    g2.translate(-i * image_w / scale, -j * image_h / scale);
                    canvas.paintComponent(g2);
                    g2.dispose();
                    img = new ImgTemplate(tp);
                    document.add(img);
                }
            }
        } else {
            Image img;
            PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
            PdfTemplate tp = cb.createTemplate(image_w, image_h);
            Graphics2D g2 = tp.createGraphics(image_w, image_h, mapper);
            tp.setWidth(image_w);
            tp.setHeight(image_h);
            g2.scale(scale, scale);
            canvas.paintComponent(g2);
            g2.dispose();
            img = new ImgTemplate(tp);
            document.add(img);
        }
        canvas.setBackground(bgsave);
        canvas.editable = edsave;
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.compomics.mascotdatfile.research.tool.spectrumviewer.spectrumviewer_gui.Spectrumviewer_gui.java

License:Apache License

/**
 * This method is called whenever the user clicked the button to export the spectrum to pdf.
 *//*from   w ww . java2  s . c o m*/
private void pdfOutputTriggered() {
    if (dtp != null) {

        // Looping boolean.
        boolean lbContinue = true;
        // Previous selected path.
        String previousPath = "/";
        // The file filter to use.
        FileFilter filter = new FileFilter() {
            public boolean accept(File f) {
                boolean result = false;
                if (f.isDirectory() || f.getName().endsWith(".pdf")) {
                    result = true;
                }
                return result;
            }

            public String getDescription() {
                return "PDF file";
            }
        };
        while (lbContinue) {
            JFileChooser jfc = new JFileChooser(previousPath);
            jfc.setDialogTitle("Save spectrum panel as PDF file");
            jfc.setDialogType(JFileChooser.SAVE_DIALOG);
            jfc.setFileFilter(filter);
            int returnVal = jfc.showSaveDialog(this.getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = jfc.getSelectedFile();
                // Append the file extension if it is not already there.
                if (jfc.getFileFilter() == filter && !file.getName().toLowerCase().endsWith(".pdf")) {
                    file = new File(file.getAbsolutePath() + ".pdf");
                }
                // Check for existing file.
                if (file.exists()) {
                    int reply = JOptionPane.showConfirmDialog(this.getParent(),
                            new String[] { "File '" + file.getAbsolutePath() + "' exists.",
                                    "Do you wish to overwrite?" },
                            "File exists!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                    if (reply != JOptionPane.YES_OPTION) {
                        previousPath = file.getParent();
                        continue;
                    }
                }

                // Output to PDF.
                JPanel jpanSpectrum = dtp.getSpectrumPanel();
                float lWidthFloat = (new Double(jpanSpectrum.getSize().getWidth())).floatValue() + 20;
                float lHeightFloat = (new Double(jpanSpectrum.getSize().getHeight())).floatValue();
                int lWidthInt = (new Double(jpanSpectrum.getSize().getWidth())).intValue();
                int lHeightInt = (new Double(jpanSpectrum.getSize().getHeight())).intValue();

                Document document = new Document(new Rectangle(lWidthInt, lHeightInt));

                try {
                    PdfWriter writer;
                    writer = PdfWriter.getInstance(document, new FileOutputStream(file));
                    document.open();
                    PdfContentByte cb = writer.getDirectContent();
                    PdfTemplate tp = cb.createTemplate(lWidthFloat, lHeightFloat);
                    Graphics2D g2;
                    g2 = tp.createGraphicsShapes(lWidthFloat, lHeightFloat);
                    jpanSpectrum.print(g2);
                    g2.dispose();
                    cb.addTemplate(tp, 0, 0);
                    writer.flush();
                    JOptionPane.showMessageDialog(this, "Data successfully written to '" + file + "'!",
                            "Output completed!", JOptionPane.INFORMATION_MESSAGE);
                    document.close();
                } catch (DocumentException e) {
                    JOptionPane.showMessageDialog(this,
                            new String[] { "Unable to create PDF file!", e.getMessage() },
                            "Unable to create PDF file!", JOptionPane.WARNING_MESSAGE);
                } catch (FileNotFoundException e) {
                    // Should never occur.
                    JOptionPane.showMessageDialog(this,
                            new String[] { "Unable to write file!", e.getMessage() }, "Unable to write file!",
                            JOptionPane.WARNING_MESSAGE);
                }

                lbContinue = false;
            } else {
                lbContinue = false;
            }
        }
    } else {
        JOptionPane.showMessageDialog(this, "You need to load a datfile and SpectrumPanel first!",
                "No datfile loaded yet!", JOptionPane.ERROR_MESSAGE);
    }

}

From source file:com.compomics.pepshell.controllers.dataexport.PDFExport.java

License:Apache License

@Override
public void exportImage(BufferedImage imageToExport, String filename) {
    File exportFile = new File(ProgramVariables.EXPORTFOLDER, filename + ".pdf");
    if (append && exportFile.exists()) {

    } else {/* w w  w .  j a  v  a2 s  .  c o  m*/
        File exportImageFile = new File(System.getProperty("file.temp"), filename);
        try {
            ImageIO.write(imageToExport, "png", new FileOutputStream(exportImageFile));
            Image pdfImage = Image.getInstance(exportImageFile.getAbsolutePath());
            Document document = new Document(new Rectangle(pdfImage.absoluteX(), pdfImage.absoluteY()));
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(exportFile));
            document.open();
            document.newPage();
            document.add(pdfImage);
            document.close();
        } catch (DocumentException | IOException ex) {
            FaultBarrier.getInstance().handleException(ex);
        }
    }
}

From source file:com.concursive.connect.web.modules.wiki.utils.WikiPDFUtils.java

License:Open Source License

public static boolean exportToFile(WikiPDFContext context, Connection db) throws Exception {

    LOG.debug("exportToFile-> begin");

    // Context Objects
    Wiki wiki = context.getWiki();//from   ww w. java2  s  . c  om
    Project project = context.getProject();
    File file = context.getFile();
    WikiExportBean exportBean = context.getExportBean();

    // Determine the content to parse
    String content = wiki.getContent();
    if (content == null) {
        return false;
    }

    // Create a pdf
    Document document = new Document(PageSize.LETTER);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));

    // Meta data
    document.addTitle(project.getTitle());
    document.addSubject(wiki.getSubject());
    document.addCreator("Concursive ConcourseConnect");
    document.addAuthor("Wiki Contributor");
    //writer.setPageEvent(new PageNumbersWatermark());

    if (!exportBean.getIncludeTitle()) {
        boolean hasTitle = StringUtils.hasText(wiki.getSubject());
        HeaderFooter pageFooter = new HeaderFooter(
                new Phrase(project.getTitle() + (hasTitle ? ": " + wiki.getSubject() : "") + " - page "),
                new Phrase(""));
        pageFooter.setAlignment(Element.ALIGN_CENTER);
        document.setFooter(pageFooter);
    }

    document.open();

    if (exportBean.getIncludeTitle()) {
        //HeaderFooter pageHeader = new HeaderFooter(new Phrase(project.getTitle()), false);
        //document.setHeader(pageHeader);
        boolean hasTitle = (StringUtils.hasText(wiki.getSubject()));
        HeaderFooter pageFooter = new HeaderFooter(
                new Phrase(project.getTitle() + (hasTitle ? ": " + wiki.getSubject() : "") + " - page "),
                new Phrase(""));
        pageFooter.setAlignment(Element.ALIGN_CENTER);
        document.setFooter(pageFooter);

        // Draw a title page
        Rectangle rectangle = new Rectangle(600, 30);
        rectangle.setBackgroundColor(new Color(100, 100, 100));
        LOG.debug("document.add(rectangle)");
        document.add(rectangle);

        document.add(new Paragraph(project.getTitle(), titleFont));
        if (!"".equals(wiki.getSubject())) {
            document.add(new Paragraph(wiki.getSubject(), titleFont));
        }
        document.add(Chunk.NEWLINE);
        document.add(new Paragraph("Last Modified: " + wiki.getModified(), titleSmallFont));
        document.newPage();
    }

    ArrayList<Integer> wikiListDone = new ArrayList<Integer>();

    appendWiki(context, context.getWiki(), document, db, wikiListDone);
    // Close everything
    document.close();
    writer.close();
    LOG.debug("exportToFile-> finished");
    return true;
}