Example usage for com.lowagie.text Document Document

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

Introduction

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

Prototype


public Document(Rectangle pageSize) 

Source Link

Document

Constructs a new Document -object.

Usage

From source file:com.slamd.report.PDFReportGenerator.java

License:Open Source License

/**
 * Generates the report and sends it to the user over the provided servlet
 * response.// w ww  .j av  a  2 s  . co  m
 *
 * @param  requestInfo  State information about the request being processed.
 */
public void generateReport(RequestInfo requestInfo) {
    // Determine exactly what to include in the report.  We will want to strip
    // out any individual jobs that are part of an optimizing job that is also
    // to be included in the report.
    reportOptimizingJobs = new OptimizingJob[optimizingJobList.size()];
    optimizingJobList.toArray(reportOptimizingJobs);

    ArrayList<Job> tmpList = new ArrayList<Job>(jobList.size());
    for (int i = 0; i < jobList.size(); i++) {
        Job job = jobList.get(i);
        String optimizingJobID = job.getOptimizingJobID();
        if ((optimizingJobID != null) && (optimizingJobID.length() > 0)) {
            boolean matchFound = false;

            for (int j = 0; j < reportOptimizingJobs.length; j++) {
                if (optimizingJobID.equalsIgnoreCase(reportOptimizingJobs[j].getOptimizingJobID())) {
                    matchFound = true;
                    break;
                }
            }

            if (matchFound) {
                continue;
            }
        }

        tmpList.add(job);
    }
    reportJobs = new Job[tmpList.size()];
    tmpList.toArray(reportJobs);

    // Prepare to actually generate the report and send it to the user.
    HttpServletResponse response = requestInfo.getResponse();
    if (viewInBrowser) {
        response.setContentType("application/pdf");
    } else {
        response.setContentType("application/x-slamd-report-pdf");
    }
    response.addHeader("Content-Disposition", "filename=\"slamd_data_report.pdf\"");

    try {
        // Create the PDF document and associate it with the response to send to
        // the client.
        Document document = new Document(PageSize.LETTER);
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
        document.addTitle("SLAMD Generated Report");
        document.addCreationDate();
        document.addCreator("SLAMD Distributed Load Generator");
        writer.setPageEvent(this);

        // Open the document and add the table of contents.
        document.open();

        boolean needNewPage = writeContents(document);

        // Write the regular job information.
        for (int i = 0; i < reportJobs.length; i++) {
            if (needNewPage) {
                document.newPage();
            }
            writeJob(document, reportJobs[i]);
            needNewPage = true;
        }

        // Write the optimizing job information.
        for (int i = 0; i < reportOptimizingJobs.length; i++) {
            if (needNewPage) {
                document.newPage();
            }
            writeOptimizingJob(document, reportOptimizingJobs[i]);
            needNewPage = true;
        }

        // Close the document.
        document.close();
    } catch (Exception e) {
        // Not much we can do about this.
        e.printStackTrace();
        return;
    }
}

From source file:com.umlet.control.io.GenPdf.java

License:Open Source License

public void createPdfToStream(OutputStream ostream, DiagramHandler handler) {
    try {/*w  w  w. j av  a  2s .co  m*/
        // We get the Rectangle of our DrawPanel
        java.awt.Rectangle bounds = handler.getDrawPanel().getContentBounds(Constants.PRINTPADDING);
        // and create an iText specific Rectangle from (0,0) to (width,height) in which we draw the diagram
        Rectangle drawSpace = new Rectangle((float) bounds.getWidth(), (float) bounds.getHeight());

        // Create document in which we write the pdf
        Document document = new Document(drawSpace);
        PdfWriter writer = PdfWriter.getInstance(document, ostream);
        document.open();

        PdfContentByte cb = writer.getDirectContent();
        Graphics2D graphics2d = cb.createGraphics(drawSpace.getWidth(), drawSpace.getHeight());

        // We shift the diagram to the upper left corner, so we shift it by (minX,minY) of the contextBounds
        Dimension trans = new Dimension((int) bounds.getMinX(), (int) bounds.getMinY());
        graphics2d.translate(-trans.getWidth(), -trans.getHeight());

        handler.getDrawPanel().paintEntitiesIntoGraphics2D(graphics2d);

        graphics2d.dispose();
        document.close();

    } catch (Exception e) {
        System.out.println("UMLet: Error: Exception in outputPdf: " + e);
    }
}

From source file:com.virtusa.akura.student.controller.MessageBoardController.java

License:Open Source License

/**
 * Merge many pdf files into one file./*from  ww w . j av a 2s . c  o  m*/
 *
 * @param streamOfPDFFiles - a list of inputStreams
 * @param outputStream - an instance of outputStream
 * @param paginate - a boolean
 * @throws AkuraAppException - The exception details that occurred when processing
 */
public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate)
        throws AkuraAppException {

    final int fontSize = 8, leftRightAlignment = 8;
    final int min = 0;
    final int max = 5;
    final int size = 300;
    final int xAxis = -150;
    final int pageHeight = 550;
    final int pageHieghtfromBottom = 16;
    final int pageRecHeight = 580;
    final int recHeightFromBottom = 14;
    Document document = new Document(PageSize.A4);
    try {
        List<InputStream> pdfs = streamOfPDFFiles;
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }
        // Create a writer for the output stream
        PdfWriter writer = null;
        BaseFont bf = null;
        try {
            writer = PdfWriter.getInstance(document, outputStream);

            document.open();

            bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                if (currentPageNumber != 2) {
                    document.newPage();
                }
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                if (currentPageNumber == 1) {
                    cb.addTemplate(page, 0, xAxis);
                } else if (currentPageNumber != 2) {
                    cb.addTemplate(page, 0, 0);
                }

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, fontSize);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + AkuraWebConstant.REPORT_GPL, size,
                            max, min);
                    cb.newlineText();
                    cb.endText();

                    if (currentPageNumber != 2) {
                        int pageNo = currentPageNumber;
                        if (currentPageNumber != 1) {
                            pageNo = currentPageNumber - 1;
                        }

                        // write the page number inside a rectangle.
                        cb.fillStroke();
                        cb.rectangle(leftRightAlignment, recHeightFromBottom, pageRecHeight,
                                leftRightAlignment);
                        cb.beginText();
                        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, PAGE + pageNo, pageHeight,
                                pageHieghtfromBottom, 0);
                        cb.endText();
                        cb.stroke();
                    }
                }
            }
            pageOfCurrentReaderPDF = 0;
        }

        outputStream.flush();

        document.close();

        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:Controleur.CtrlImprimerOrdonnance.java

public void RemplirOrdonnance() {
    ResultSet res;/*from   ww w .j ava 2  s.  co m*/
    String nomEtablissement = "";
    String adresseEtablissement = "";
    int telEtablissement = 0;
    String nomPatient = "";
    String prenomPatient = "";
    String dateNaissPatient = null;
    String traitement = "";
    Etablissement etab = new Etablissement();
    try {
        res = etab.getEtablissement();
        nomEtablissement = res.getString("nomEtab");
        adresseEtablissement = res.getString("adresseEtab");
        telEtablissement = res.getInt("telEtab");
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, "erreur \n" + e.getMessage());
    }
    Medecin med1 = new Medecin();
    Medecin med2 = med1.getMedecinById(Fen.getIdm());
    String nomMedecin = med2.getNomMedecin();
    String prenomMedecin = med2.getPrenomMedecin();
    String specialiteMedecin = med2.getSpecialite();
    Patient patient = new Patient();
    res = patient.getPatient(Fen.getIdp());
    try {
        res.next();
        nomPatient = res.getString("nomPatient");
        prenomPatient = res.getString("prenomPatient");
        dateNaissPatient = res.getString("dateNaissance");
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, "erreur \n" + e.getMessage());
    }

    traitement = Fen.getTxtTraitement().getText();

    Document document = new Document(PageSize.A4);
    try {
        PdfWriter.getInstance(document, new FileOutputStream("./ordonnance.pdf"));
        document.open();
        Date d = new Date();
        Paragraph paragraph = new Paragraph(d.toLocaleString(),
                FontFactory.getFont(FontFactory.COURIER, 20, Font.BOLD));
        paragraph.setAlignment(Element.ALIGN_RIGHT);
        paragraph.setIndentationRight(50f);
        document.add(paragraph);
        paragraph = new Paragraph("Dr " + nomMedecin + " " + prenomMedecin,
                FontFactory.getFont(FontFactory.COURIER, 20, Font.BOLD));
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("SPECIALISTE EN " + specialiteMedecin);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph(nomEtablissement);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph(adresseEtablissement);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("Tl : " + telEtablissement);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("                      ");
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("nom & prenom :" + nomPatient + " " + prenomPatient,
                FontFactory.getFont(FontFactory.COURIER, 20, Font.BOLD));
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("Ne(e) le :" + dateNaissPatient);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("                       ");
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);

        Chunk chunk = new Chunk("Ordonnance", FontFactory.getFont(FontFactory.COURIER, 30, Font.BOLD));
        chunk.setUnderline(Color.BLACK, 3.0f, 0.0f, 0.0f, -0.2f, PdfContentByte.LINE_CAP_BUTT);
        paragraph = new Paragraph();
        paragraph.setAlignment(Element.ALIGN_CENTER);
        paragraph.add(chunk);
        document.add(paragraph);

        paragraph = new Paragraph("                       ");
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph(traitement);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);

        Runtime r = Runtime.getRuntime();
        r.exec("cmd /C ./ordonnance.pdf");
    } catch (DocumentException de) {
        de.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    document.close();
}

From source file:cz.incad.kramerius.pdf.utils.pdf.DocumentUtils.java

License:Open Source License

public static Document createDocument(Rectangle rect) {
    Document doc = new Document(rect);
    return doc;
}

From source file:cz.incad.kramerius.pdf.utils.pdf.DocumentUtils.java

License:Open Source License

public static Document createDocument(PreparedDocument document) {
    int width = document.getWidth();
    int height = document.getHeight();
    Document doc = new Document(new Rectangle(width, height));
    return doc;/*from   ww w . jav  a2 s  . co  m*/
}

From source file:cz.incad.kramerius.rest.api.k5.client.pdf.PDFResource.java

License:Open Source License

private static StreamingOutput streamingOutput(final File file, final String format) {
    return new StreamingOutput() {
        public void write(OutputStream output) throws IOException, WebApplicationException {
            try {
                Rectangle formatRect = formatRect(format);
                Document document = new Document(formatRect);
                PdfWriter.getInstance(document, output);
                document.open();//from w  w  w. jav  a 2  s.  c  om

                Image image = Image.getInstance(file.toURI().toURL());

                image.scaleToFit(
                        document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin(),
                        document.getPageSize().getHeight() - document.topMargin() - document.bottomMargin());
                document.add(image);

                document.close();

            } catch (Exception e) {
                throw new WebApplicationException(e);
            } finally {
                if (file != null)
                    file.delete();
            }
        }
    };
}

From source file:de.dfki.owlsmx.gui.util.Converter.java

License:Open Source License

public static void convertToPdf(JFreeChart chart, int width, int height, String filename) {
    // step 1       
    Document document = new Document(new Rectangle(width, height));
    try {/* w  w  w  .java  2  s .c  o m*/
        // step 2
        PdfWriter writer;
        writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2d, r2d);
        g2d.dispose();
        cb.addTemplate(tp, 0, 0);
    } catch (DocumentException de) {

    } catch (FileNotFoundException e) {

    }
    // step 5
    document.close();
}

From source file:de.xirp.chart.ChartUtil.java

License:Open Source License

/**
 * Exports the given chart as PDF in the specified size. The
 * export is written to the given path.//from  ww w . j a va2s. c om
 * 
 * @param chart
 *            The chart to export.
 * @param width
 *            The desired width of the PDF.
 * @param height
 *            The desired height of the PDF.
 * @param path
 *            The path to write the PDF to.
 * @see org.jfree.chart.JFreeChart
 */
private static void exportPDF(JFreeChart chart, int width, int height, String path) {
    Document document = new Document(new Rectangle(width, height));
    try {
        PdfWriter writer;
        writer = PdfWriter.getInstance(document, new FileOutputStream(path));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2d, r2d);
        g2d.dispose();
        cb.addTemplate(tp, 0, 0);
    } catch (Exception e) {
        logClass.error("Error: " + e.getMessage() //$NON-NLS-1$
                + Constants.LINE_SEPARATOR, e);
    }
    document.close();
}

From source file:de.xirp.report.ReportGenerator.java

License:Open Source License

/**
 * Generates the PDF from the//  w  w  w .  j a  v a  2 s . com
 * {@link de.xirp.report.Report} and writes the PDF
 * to a file. <br>
 * <br>
 * At first the title and header pages are created. After that the
 * content pages are created.
 * 
 * @return The file name of the PDF.
 * @throws IOException
 *             if something went wrong saving the PDF.
 * @throws DocumentException
 *             if something went wrong generating the PDF.
 * @throws MalformedURLException
 *             if something went wrong saving the PDF.
 * @see de.xirp.report.Report
 */
private static String generatePDF() throws DocumentException, MalformedURLException, IOException {
    String filename = report.getName().replaceAll(" ", "-") + "_report_" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            + report.getHeader().getRobot().getName() + "_" //$NON-NLS-1$
            + Util.getTimeAsString(report.getHeader().getDate()) + ".pdf"; //$NON-NLS-1$

    reportFile = new File(Constants.REPORT_DIR + File.separator + filename);

    // creation of a document-object
    document = new Document(PageSize.A4);

    // we create a writer that listens to the document
    // and directs a PDF-stream to a file
    writer = PdfWriter.getInstance(document, new FileOutputStream(reportFile.getPath()));
    writer.setPdfVersion(PdfWriter.VERSION_1_7);
    writer.setStrictImageSequence(true);

    // open the document
    document.open();

    // add the title page
    addReportTitle();
    addReportContent();
    // close the document
    document.close();

    return filename;
}