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, float marginLeft, float marginRight, float marginTop, float marginBottom) 

Source Link

Document

Constructs a new Document -object.

Usage

From source file:convert.Convertings.java

public void convertTif2PDF(String tifPath, String path) {
    System.out.println("one");
    String arg[] = { tifPath };/*from  w  ww  . ja va 2  s.  c o m*/
    System.out.println("one2");
    if (arg.length < 1) {
        System.out.println("Usage: Tiff2Pdf file1.tif [file2.tif ... fileN.tif]");
        System.exit(1);
    }
    String tiff;
    String pdf;
    System.out.println("two");
    for (int i = 0; i < arg.length; i++) {
        tiff = arg[i];
        pdf = path + ".pdf";
        Document document = new Document(PageSize.LETTER, 0, 0, 0, 0);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf));
            int pages = 0;
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            RandomAccessFileOrArray ra = null;
            int comps = 0;
            try {
                ra = new RandomAccessFileOrArray(tiff);
                comps = TiffImage.getNumberOfPages(ra);
            } catch (Throwable e) {
                System.out.println("Exception in " + tiff + " " + e.getMessage());
                continue;
            }
            System.out.println("Processing: " + tiff);
            for (int c = 0; c < comps; ++c) {
                try {
                    Image img = TiffImage.getTiffImage(ra, c + 1);
                    if (img != null) {
                        System.out.println("page " + (c + 1));
                        System.out.println("img.getDpiX() : " + img.getDpiX());
                        System.out.println("img.getDpiY() : " + img.getDpiY());
                        img.scalePercent(6200f / img.getDpiX(), 6200f / img.getDpiY());
                        //img.scalePercent(img.getDpiX(), img.getDpiY());
                        //document.setPageSize(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
                        img.setAbsolutePosition(0, 0);
                        cb.addImage(img);
                        document.newPage();
                        ++pages;
                    }
                } catch (Throwable e) {
                    System.out.println("Exception " + tiff + " page " + (c + 1) + " " + e.getMessage());
                }
            }
            ra.close();
            document.close();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        System.out.println("done");
    }
}

From source file:de.atomfrede.tools.evalutation.tools.plot.util.PlotUtil.java

License:Open Source License

protected static void writeChartAsPDF(OutputStream out, JFreeChart chart, int width, int height,
        FontMapper mapper) throws IOException {
    Rectangle pagesize = new Rectangle(width, height);
    Document document = new Document(pagesize, 50, 50, 50, 50);
    try {/*w  w  w  .ja v a 2 s  .  c om*/
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2 = tp.createGraphics(width, height, mapper);
        Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2, r2D);
        g2.dispose();
        cb.addTemplate(tp, 0, 0);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    }
    document.close();
}

From source file:de.dhbw.humbuch.util.PDFHandler.java

/**
 * Create a document with the specified sizes and margins. This document is the internal representation 
 * of the PDF./*from w ww  .  j  a v  a  2  s  .c om*/
 */
public PDFHandler() {
    this.document = new Document(new RectangleReadOnly(595, 842), 30f, 30f, 25f, 35f);
}

From source file:de.jdufner.sudoku.generator.pdf.PdfPrinterImpl.java

License:Open Source License

@Override
public void printFrontpage(String name, List<PdfSolution> solutions, String fileName)
        throws DocumentException, FileNotFoundException {
    Document document = new Document(PageSize.A4, 10, 10, 10, 10);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    writeFrontpage(name, document, solutions);
    writer.close();//from   w  w  w  . jav  a 2  s . c  o  m
}

From source file:de.jdufner.sudoku.generator.pdf.PdfPrinterImpl.java

License:Open Source License

@Override
public void printQuests(List<SudokuData> sudokus, String fileName)
        throws DocumentException, FileNotFoundException {
    Document document = new Document(PageSize.A4, 10, 10, 10, 10);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    writeDocument(document, sudokus);// w ww  .  j av a 2 s  .co  m
    writer.close();
}

From source file:de.jdufner.sudoku.generator.pdf.PdfPrinterImpl.java

License:Open Source License

@Override
public void printResults(List<SudokuData> sudokus, String fileName)
        throws DocumentException, FileNotFoundException {
    Document document = new Document(PageSize.A4, 10, 10, 10, 10);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    writeDocument(document, sudokus);/*from   w  w w .  j ava2s . c om*/
    writer.close();
}

From source file:de.maklerpoint.office.Schnittstellen.PDF.ExportListePDF.java

License:Open Source License

public void write() throws DocumentException, FileNotFoundException {

    SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm");

    Document doc = null;/*from   w  ww .java 2  s  . c  o m*/

    if (titles.length > 7)
        doc = new Document(PageSize.A4.rotate(), 20, 20, 20, 20);
    else
        doc = new Document(PageSize.A4, 20, 20, 20, 20);

    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(filename));
    doc.addAuthor("MaklerPoint - www.maklerpoint.de");
    doc.addCreator("MaklerPoint - www.maklerpoint.de");
    doc.addCreationDate();
    doc.addTitle(title);

    doc.open();

    doc.add(new Paragraph(title, FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, Color.BLACK)));

    Table t = new Table(titles.length, data.length + 1);
    t.setPadding(3);
    t.setSpacing(0);
    t.setBorderWidth(1);

    for (int i = 0; i < titles.length; i++) {
        Cell c1 = new Cell(titles[i]);
        c1.setHeader(true);
        t.addCell(c1);
    }
    t.endHeaders();

    for (int i = 0; i < data.length; i++) {
        for (int j = 0; j < data[i].length; j++) {
            Cell c1 = null;
            if (data[i][j] != null)
                c1 = new Cell(data[i][j].toString());
            else
                c1 = new Cell("");
            t.addCell(c1);
        }
    }

    doc.add(t);

    if (footer == null) {
        doc.add(new Paragraph(
                ("Export " + title + " - Genereriert am " + df.format(new Date(System.currentTimeMillis())))
                        + " von MaklerPoint",
                FontFactory.getFont(FontFactory.TIMES, 10, Font.NORMAL, Color.black)));
    } else {
        doc.add(new Paragraph(footer, FontFactory.getFont(FontFactory.TIMES, 10, Font.NORMAL, Color.black)));
    }

    doc.close();
}

From source file:de.tr1.cooperator.manager.web.CreateSubscriberListAction.java

License:Open Source License

/**
 * This method is called by the struts-framework if the submit-button is pressed.
 * It creates a PDF-File and puts in into the output-stream of the response.
 *///  w  ww .ja  v a  2s.  c  om
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    CreateSubscriberListForm myForm = (CreateSubscriberListForm) form;
    boolean bSortByName;

    if (myForm.getSortBy().equals(myForm.SORTBYPN))
        bSortByName = false;
    else
        bSortByName = true;

    //create Collection for the results...
    Event eEvent = EventManager.getInstance().getEventByID(myForm.getEventID());
    Collection cSubscriberList = UserManager.getInstance().getUsersByCollection(eEvent.getSubscriberList());
    Collection cExamResults = EventResultManager.getInstance().getResults(eEvent.getID());

    Iterator cSubscriberListIT = cSubscriberList.iterator();
    Collection cSubscriberResultList = new ArrayList();

    while (cSubscriberListIT.hasNext()) {
        User CurUser = (User) cSubscriberListIT.next();
        String UserPNR = CurUser.getPersonalNumber();

        Iterator cExamResultsIT = cExamResults.iterator();
        ExamResult curExamResult = null;
        String ResultUserPNR = null;
        while (cExamResultsIT.hasNext()) {
            curExamResult = (ExamResult) cExamResultsIT.next();

            ResultUserPNR = curExamResult.getUserPersonalNumber();
            if (UserPNR.equals(ResultUserPNR))
                break;
        }

        if (UserPNR.equals(ResultUserPNR)) {
            if (bSortByName) {
                UserResultSortByName URS = new UserResultSortByName(CurUser, "" + curExamResult.getResult());
                cSubscriberResultList.add(URS);
            } else {
                UserResultSortByPersonalNumber URS = new UserResultSortByPersonalNumber(CurUser,
                        "" + curExamResult.getResult());
                cSubscriberResultList.add(URS);
            }
        } else {
            if (bSortByName) {
                UserResultSortByName URS = new UserResultSortByName(CurUser, "-");
                cSubscriberResultList.add(URS);
            } else {
                UserResultSortByPersonalNumber URS = new UserResultSortByPersonalNumber(CurUser, "-");
                cSubscriberResultList.add(URS);
            }
        }

    }

    //sort List
    Collections.sort((List) cSubscriberResultList);

    BaseFont bf;
    //36pt = 0.5inch
    Document document = new Document(PageSize.A4, 36, 36, 72, 72);

    try {
        bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    } catch (Exception e) {
        Log.addLog("CreateSubscriberListAction: Error creating BaseFont: " + e);
        //2do: add ErrorMessage and return to inputFormular!
        return mapping.findForward("GeneralFailure");
    }

    //calculate the number of cols and their width
    int cols = 0;
    ArrayList alWidth = new ArrayList();
    float boldItalicFactor = 1.2f;
    if (myForm.getShowNumber())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_NUMBER, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowPersonalNumber())
        alWidth.add(new Float(
                boldItalicFactor * bf.getWidthPoint(TABLEHEADER_PERSONALNUMBER, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowName())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_NAME, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowEmail())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_EMAIL, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowResult())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_RESULT, TABLEHEADER_FONTSIZE)));

    if (myForm.getAddInfoField())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_INFO, TABLEHEADER_FONTSIZE)));

    if (myForm.getAddSignField())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_SIGN, TABLEHEADER_FONTSIZE)));

    cols = alWidth.size();

    float totalWidth = 0;
    //calculate the whole length
    Iterator alIterator = alWidth.iterator();
    for (; alIterator.hasNext(); totalWidth += ((Float) alIterator.next()).floatValue())
        ;

    //calculate relativ width for the table
    float[] width = new float[cols];
    alIterator = alWidth.iterator();
    int i = 0;
    while (alIterator.hasNext()) {
        float pixLength = ((Float) alIterator.next()).floatValue();
        //alWidthRelativ.add( new Float( pixLength/totalWidth ) );
        width[i] = pixLength / totalWidth;
        i++;
    }

    //needed for the shrink (enlarge?)
    float shrinkFactor;

    try {
        //1st: set correct outputstream
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());

        //1.5st: set content-stuff
        response.setContentType("application/pdf");

        //2nd: set EventManager for PageEvents to Helper
        writer.setPageEvent(
                new CreateSubscriberListActionHelper(myForm.getHeaderLeft(), myForm.getHeaderRight()));

        //3rd: open document for editing the content
        document.open();

        //4th: add content
        Phrase pInfoText = new Phrase(myForm.getInfoText(), new Font(bf, 12, Font.BOLD));
        document.add(pInfoText);

        //PdfPTable( cols )
        PdfPTable table = new PdfPTable(width);

        float documentWidth = document.right() - document.left();
        if (documentWidth < totalWidth) {
            table.setTotalWidth(documentWidth);
            shrinkFactor = documentWidth / totalWidth;
        } else {
            table.setTotalWidth(totalWidth);
            shrinkFactor = 1;
        }
        table.setLockedWidth(true);

        Font headerFont = new Font(bf, TABLEHEADER_FONTSIZE * shrinkFactor, Font.BOLDITALIC);
        Font cellFont = new Font(bf, TABLECELL_FONTSIZE * shrinkFactor, Font.NORMAL);

        if (myForm.getShowNumber())
            table.addCell(new Phrase(TABLEHEADER_NUMBER, headerFont));
        if (myForm.getShowPersonalNumber())
            table.addCell(new Phrase(TABLEHEADER_PERSONALNUMBER, headerFont));
        if (myForm.getShowName())
            table.addCell(new Phrase(TABLEHEADER_NAME, headerFont));
        if (myForm.getShowEmail())
            table.addCell(new Phrase(TABLEHEADER_EMAIL, headerFont));
        if (myForm.getShowResult())
            table.addCell(new Phrase(TABLEHEADER_RESULT, headerFont));
        if (myForm.getAddInfoField())
            table.addCell(new Phrase(TABLEHEADER_INFO, headerFont));
        if (myForm.getAddSignField())
            table.addCell(new Phrase(TABLEHEADER_SIGN, headerFont));

        //fill table
        Iterator iSRL = cSubscriberResultList.iterator();
        int counter = 1;
        while (iSRL.hasNext()) {
            UserResult curResult = (UserResult) iSRL.next();

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            if (myForm.getShowNumber())
                table.addCell(new Phrase("" + counter++, cellFont));

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            if (myForm.getShowPersonalNumber())
                table.addCell(new Phrase(curResult.getPersonalNumber(), cellFont));

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            if (myForm.getShowName())
                table.addCell(new Phrase(curResult.getSurname() + ", " + curResult.getFirstName(), cellFont));
            if (myForm.getShowEmail())
                table.addCell(new Phrase(curResult.getEmailAddress(), cellFont));
            if (myForm.getShowResult())
                table.addCell(new Phrase(curResult.getResult(), cellFont));
            if (myForm.getAddInfoField())
                table.addCell(new Phrase("", cellFont));
            if (myForm.getAddSignField())
                table.addCell(new Phrase("", cellFont));
        }

        //set how many rows are header...
        table.setHeaderRows(1);

        document.add(table);

        //5th: close document, write the output to the stream...
        document.close();
    } catch (Exception de) {
        Log.addLog("CreateSubscriberListAction: Error creating PDF: " + de);
    }

    //we dont need to return a forward, because we write directly to the outputstream!
    return null;
}

From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java

License:Apache License

/**
 * Sets the default size of the page and creates the pdf document (com.lowagie.text.Document) instance.
 * /*from   w  w  w  . j  a  v  a2s  .  c om*/
 * @param pagesizemode the pagesizemode
 * @param pagesize the pagesize
 * 
 * @return the pdf-document instance
 * 
 * @throws ImageInterpreterException the image interpreter exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
private Document setPDFPageSizeForFirstPage(PdfPageSize pagesizemode, Rectangle pagesize)
        throws ImageInterpreterException, IOException {

    Document pdfdoc;
    boolean isTitlePage = false;

    // set page size of the PDF
    if ((pagesizemode == PdfPageSize.ORIGINAL) && (pdftitlepage == null)) {
        LOGGER.debug("Page size of the first page is size of first image");

        // GDZ: Check if this changes the order of the Pages
        // What if 0000002 ist intentionaly before 00000001 ?

        // page size is set to size of first page of the document
        // (first image of imageURLs)
        Map<Integer, UrlImage> sortedMap = new TreeMap<Integer, UrlImage>(imageURLs);
        for (Integer key : sortedMap.keySet()) {

            // do the image exists ?
            while (key < sortedMap.size()
                    && sortedMap.get(key).getURL().openConnection().getContentLength() == 0) {
                key++;
            }

            if ((pdftitlepages != null) && (pdftitlepages.get(key) != null)) {
                // title page for Document Part available; set pagesize to
                // A4
                pagesize = setA4pagesize();
                isTitlePage = true;
                break;
            }

            // no title page, so get the size of the first page
            UrlImage pdfpage = imageURLs.get(key);

            if (pdfpage.getURL() != null) {
                // it's an image file
                URL url = pdfpage.getURL();
                LOGGER.debug("Using image" + pdfpage.getURL().toString());
                ImageInterpreter myInterpreter = ImageFileFormat.getInterpreter(url, httpproxyhost,
                        httpproxyport, httpproxyuser, httpproxypassword);

                float xres = myInterpreter.getXResolution();
                float yres = myInterpreter.getYResolution();

                int height = myInterpreter.getHeight();
                int width = myInterpreter.getWidth();

                int image_w_points = (width * 72) / ((int) xres);
                int image_h_points = (height * 72) / ((int) yres);

                pagesize = new Rectangle(image_w_points, image_h_points); // set
                // a retangle in the size of the image
                break; // get out of loop
            } else if (pdfpage.getClass() == PDFPage.class && ((PDFPage) pdfpage).getPdfreader() != null) {
                // a pdf page, not an image file

                PdfReader pdfreader = ((PDFPage) pdfpage).getPdfreader();
                pagesize = pdfreader.getPageSize(pdfpage.getPageNumber());

            }
        }

    } else if (pdftitlepage != null) {
        isTitlePage = true;
        LOGGER.debug("Page size of the first page is A4, cause it is a title page");
        pagesize = setA4pagesize();
    } else {
        // page size is set to A4, because either the whole
        // PDF is in A4 or we will have a title page which is
        // in A4
        LOGGER.debug("Page size of the first page is A4, page size mode is " + pagesizemode);
        pagesize = setA4pagesize();
    }

    if (pagesize != null) { // pagesize is a rectangle; pagesize sets the
        // page for the first page
        pdfdoc = new Document(pagesize, 2.5f * 72f / 2.54f, 2.5f * 72f / 2.54f, 2.5f * 72f / 2.54f,
                3f * 72f / 2.54f);
        if (isTitlePage) {
            pdfdoc.setMargins(pdftitlepage.getLeftMargin(), pdftitlepage.getRightMargin(),
                    pdftitlepage.getTopMargin(), pdftitlepage.getBottomMargin());
        }
    } else {
        LOGGER.warn("No pagesize available.... strange!");
        pdfdoc = new Document();
    }
    return pdfdoc;
}

From source file:edtscol.client.Imprime.java

License:CeCILL license

private void ouvrirDocument() {
    try {//from w w  w  .  ja  v a2  s .  co  m
        document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
        writer = PdfWriter.getInstance(document, new FileOutputStream(chemin));

        initMetaDocument();
        document.open();
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
}