Example usage for com.lowagie.text.pdf PdfWriter getDirectContent

List of usage examples for com.lowagie.text.pdf PdfWriter getDirectContent

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter getDirectContent.

Prototype


public PdfContentByte getDirectContent() 

Source Link

Document

Use this method to get the direct content for this document.

Usage

From source file:nl.dykema.jxmlnote.report.pdf.PdfReport.java

License:Open Source License

public void beginReport(File output) throws ReportException {
    try {/*ww w. j  a  va2  s.c om*/
        _canceled = false;
        _doc = new Document();
        _writer = PdfWriter.getInstance(_doc, new FileOutputStream(output));
        setPageSize(PageSize.A4);
        setOrientation(Orientation.PORTRAIT);
        setMargins(new Rectangle(72.0f, 72.0f, 72.0f, 72.0f));

        _writer.setPageEvent(new PdfPageEvent() {

            public void onChapter(PdfWriter arg0, Document arg1, float arg2, com.lowagie.text.Paragraph arg3) {
            }

            public void onChapterEnd(PdfWriter arg0, Document arg1, float arg2) {
            }

            public void onCloseDocument(PdfWriter arg0, Document arg1) {
                PdfReport.super.getReportListeners().informEndReport(PdfReport.this);
            }

            public void onGenericTag(PdfWriter arg0, Document arg1, com.lowagie.text.Rectangle arg2,
                    String arg3) {
            }

            public void onOpenDocument(PdfWriter arg0, Document arg1) {
            }

            public void onParagraph(PdfWriter arg0, Document arg1, float arg2) {
            }

            public void onParagraphEnd(PdfWriter arg0, Document arg1, float arg2) {
            }

            public void onSection(PdfWriter arg0, Document arg1, float arg2, int arg3,
                    com.lowagie.text.Paragraph arg4) {
            }

            public void onSectionEnd(PdfWriter arg0, Document arg1, float arg2) {
            }

            public void onStartPage(PdfWriter wrt, Document doc) {
            }

            public void onEndPage(PdfWriter wrt, Document doc) {
                try {
                    ReportListeners _listeners = PdfReport.super.getReportListeners();
                    _listeners.informNextPage(PdfReport.this);

                    Vector<ReportElement> vhdr = _listeners.getHeader(PdfReport.this);
                    Vector<ReportElement> vftr = _listeners.getFooter(PdfReport.this);

                    PdfContentByte cb = wrt.getDirectContent();

                    // write headers on top of each other
                    if (vhdr != null) {
                        Iterator<ReportElement> it = vhdr.iterator();

                        while (it.hasNext()) {
                            ReportElement hdr = it.next();

                            Rectangle pageSize = PdfReport.this.getPageRect();
                            Rectangle margins = PdfReport.this.getMargins();
                            float ytop = pageSize.top() - margins.top();
                            float hdrHeight = PdfReport.this.getHeight(hdr, null);
                            float rpos = (margins.top() - hdrHeight) / 2;
                            float hytop = ytop + rpos + hdrHeight;

                            if (hdr instanceof PdfTable) {
                                int firstRow = 0, lastRow = -1;
                                PdfTable phdr = (PdfTable) hdr;
                                phdr.writeSelectedRows(firstRow, lastRow, margins.left(), hytop, cb);
                            } else if (hdr instanceof PdfParagraph) {
                                PdfParagraph ppar = (PdfParagraph) hdr;
                                ColumnText ct = new ColumnText(cb);
                                float textWidth = PdfReport.this.getTextWidth();
                                ct.addElement(ppar);
                                ct.setSimpleColumn(margins.left(), ytop + rpos, margins.left() + textWidth,
                                        hytop);
                                ct.go();
                            }
                        }
                    }

                    // write footers on top of each other

                    if (vftr != null) {
                        Iterator<ReportElement> it = vftr.iterator();

                        while (it.hasNext()) {
                            ReportElement ftr = it.next();

                            Rectangle margins = PdfReport.this.getMargins();
                            float ytop = margins.bottom();
                            float hdrHeight = PdfReport.this.getHeight(ftr, null);
                            float rpos = (margins.bottom() - hdrHeight) / 2;
                            float hytop = ytop - rpos;

                            if (ftr instanceof PdfTable) {
                                int firstRow = 0, lastRow = -1;
                                PdfTable pftr = (PdfTable) ftr;
                                pftr.writeSelectedRows(firstRow, lastRow, margins.left(), hytop, cb);
                            } else if (ftr instanceof PdfParagraph) {
                                PdfParagraph ppar = (PdfParagraph) ftr;
                                ColumnText ct = new ColumnText(cb);
                                float textWidth = PdfReport.this.getTextWidth();
                                ct.addElement(ppar);
                                ct.setSimpleColumn(margins.left(), rpos, margins.left() + textWidth, hytop);
                                ct.go();
                            }
                        }
                    }

                } catch (ReportException e) {
                    DefaultXMLNoteErrorHandler.exception(e);
                } catch (DocumentException e) {
                    DefaultXMLNoteErrorHandler.exception(e);
                }

            }

        });

    } catch (Exception e) {
        throw new ReportException(e);
    }
}

From source file:nl.knaw.dans.common.lang.pdf.PdfPageLayouter.java

License:Apache License

public void onStartPage(final PdfWriter writer, final Document document) {
    if (headerImage == null)
        return;//from  www.  j a  v  a2 s  .  c  o  m

    final float top = document.top();
    final PdfContentByte canvas = writer.getDirectContent();
    float resizeFactor = // TODO make calculation logic clearer
            headerImage.getHeight() / (MARGIN_TOP - HEADER_PADDING);
    final float width = headerImage.getWidth() / resizeFactor;
    final float height = headerImage.getHeight() / resizeFactor;

    try {
        canvas.addImage(headerImage, width, 0, 0, height, MARGIN_LEFT, top - HEADER_POSITION);
    } catch (final Exception cause) {
        logger.error("can't add header image to PDF page " + document.getPageNumber(), cause);
    }

}

From source file:nl.knaw.dans.common.lang.pdf.PdfPageLayouter.java

License:Apache License

public void onEndPage(final PdfWriter writer, final Document document) {
    final float bottom = document.bottom();
    final float centerX = getCenterX(document);
    final PdfContentByte canvas = writer.getDirectContent();
    final int rotation = 0;

    final PdfPTable table = new PdfPTable(5);
    table.setTotalWidth(PAGE_NUMBER_TABLE_WIDTH);
    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
    table.getDefaultCell().setBorder(0);

    table.addCell(TO_FIRST);/*from  w  ww  . ja v a2s  . com*/
    table.addCell(TO_PREV);
    table.addCell(new Phrase(new Chunk("" + document.getPageNumber(), FONT)));
    table.addCell(TO_NEXT);
    table.addCell(TO_LAST);

    table.writeSelectedRows(0, -1, centerX - (table.getTotalWidth() / 2), bottom - FOOTER_POSITION, canvas);
    if (footerPhrase == null)
        return;
    showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase(footerPhrase), centerX, bottom - FOOTER_POSITION,
            rotation);
}

From source file:org.adempiere.pdf.Document.java

License:Open Source License

private static void writePDF(Pageable pageable, OutputStream output) {
    try {/*from w  w w . j  a  v a 2s  . c o m*/
        final PageFormat pf = pageable.getPageFormat(0);

        final com.lowagie.text.Document document = new com.lowagie.text.Document(
                new Rectangle((int) pf.getWidth(), (int) pf.getHeight()));
        final PdfWriter writer = PdfWriter.getInstance(document, output);
        writer.setPdfVersion(PdfWriter.VERSION_1_2);
        document.open();
        final DefaultFontMapper mapper = new DefaultFontMapper();

        //Elaine 2009/02/17 - load additional font from directory set in PDF_FONT_DIR of System Configurator 
        String pdfFontDir = MSysConfig.getValue(PDF_FONT_DIR, "");
        if (pdfFontDir != null && pdfFontDir.trim().length() > 0) {
            pdfFontDir = pdfFontDir.trim();
            File dir = new File(pdfFontDir);
            if (dir.exists() && dir.isDirectory())
                mapper.insertDirectory(pdfFontDir);
        }
        //

        final float w = (float) pf.getWidth();
        final float h = (float) pf.getHeight();
        final PdfContentByte cb = writer.getDirectContent();
        for (int page = 0; page < pageable.getNumberOfPages(); page++) {
            if (page != 0) {
                document.newPage();
            }

            final PdfTemplate tp = cb.createTemplate(w, h);
            final Graphics2D g2 = tp.createGraphics(w, h, mapper);
            tp.setWidth(w);
            tp.setHeight(h);
            pageable.getPrintable(page).print(g2, pf, page);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
        }
        document.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.adempiere.util.Document.java

private static void writePDF(Pageable pageable, OutputStream output) {
    try {/*  ww  w .  j  a  v  a2s .c om*/
        final PageFormat pf = pageable.getPageFormat(0);

        Rectangle pageSize = new Rectangle((int) pf.getWidth(), (int) pf.getHeight());
        final com.lowagie.text.Document document = new com.lowagie.text.Document(pageSize);
        final PdfWriter writer = PdfWriter.getInstance(document, output);
        writer.setPdfVersion(PdfWriter.VERSION_1_2);
        document.open();
        final DefaultFontMapper mapper = new DefaultFontMapper();

        String pdfFontDir = /* MSysConfig.getValue( */PDF_FONT_DIR/* , "") */;
        if (pdfFontDir != null && pdfFontDir.trim().length() > 0) {
            pdfFontDir = pdfFontDir.trim();
            File dir = new File(pdfFontDir);
            if (dir.exists() && dir.isDirectory())
                mapper.insertDirectory(pdfFontDir);
        }
        final float w = (float) pf.getWidth();
        final float h = (float) pf.getHeight();
        final PdfContentByte cb = writer.getDirectContent();
        for (int page = 0; page < pageable.getNumberOfPages(); page++) {
            if (page != 0) {
                document.newPage();
            }

            final PdfTemplate tp = cb.createTemplate(w, h);
            final Graphics2D g2 = tp.createGraphics(w, h, mapper);
            tp.setWidth(w);
            tp.setHeight(h);
            pageable.getPrintable(page).print(g2, pf, page);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
        }
        document.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.adempiere.webui.apps.AEnv.java

License:Open Source License

/**
 *
 * @param pdfList//w w w . ja va 2 s. c o  m
 * @param outFile
 * @throws IOException
 * @throws DocumentException
 * @throws FileNotFoundException
 */
public static void mergePdf(List<File> pdfList, File outFile)
        throws IOException, DocumentException, FileNotFoundException {
    Document document = null;
    PdfWriter copy = null;
    for (File f : pdfList) {
        PdfReader reader = new PdfReader(f.getAbsolutePath());
        if (document == null) {
            document = new Document(reader.getPageSizeWithRotation(1));
            copy = PdfWriter.getInstance(document, new FileOutputStream(outFile));
            document.open();
        }
        int pages = reader.getNumberOfPages();
        PdfContentByte cb = copy.getDirectContent();
        for (int i = 1; i <= pages; i++) {
            document.newPage();
            PdfImportedPage page = copy.getImportedPage(reader, i);
            cb.addTemplate(page, 0, 0);
        }
    }
    document.close();
}

From source file:org.adempiere.webui.apps.ProcessDialog.java

License:Open Source License

public void onPrintShipments() {
    //   Loop through all items
    List<File> pdfList = new ArrayList<File>();
    for (int i = 0; i < m_ids.length; i++) {
        int M_InOut_ID = m_ids[i];
        ReportEngine re = ReportEngine.get(Env.getCtx(), ReportEngine.SHIPMENT, M_InOut_ID);
        pdfList.add(re.getPDF());/* ww w. j  a  v  a  2 s  .  c  o  m*/
    }

    if (pdfList.size() > 1) {
        try {
            File outFile = File.createTempFile("PrintShipments", ".pdf");
            Document document = null;
            PdfWriter copy = null;
            for (File f : pdfList) {
                String fileName = f.getAbsolutePath();
                PdfReader reader = new PdfReader(fileName);
                reader.consolidateNamedDestinations();
                if (document == null) {
                    document = new Document(reader.getPageSizeWithRotation(1));
                    copy = PdfWriter.getInstance(document, new FileOutputStream(outFile));
                    document.open();
                }
                int pages = reader.getNumberOfPages();
                PdfContentByte cb = copy.getDirectContent();
                for (int i = 1; i <= pages; i++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, i);
                    cb.addTemplate(page, 0, 0);
                }
            }
            document.close();

            hideBusyDialog();
            Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(outFile));
            SessionManager.getAppDesktop().showWindow(win, "center");
        } catch (Exception e) {
            log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    } else if (pdfList.size() > 0) {
        hideBusyDialog();
        try {
            Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(pdfList.get(0)));
            SessionManager.getAppDesktop().showWindow(win, "center");
        } catch (Exception e) {
            log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }
}

From source file:org.adempiere.webui.apps.ProcessDialog.java

License:Open Source License

public void onPrintInvoices() {
    //   Loop through all items
    List<File> pdfList = new ArrayList<File>();
    for (int i = 0; i < m_ids.length; i++) {
        int C_Invoice_ID = m_ids[i];
        ReportEngine re = ReportEngine.get(Env.getCtx(), ReportEngine.INVOICE, C_Invoice_ID);
        pdfList.add(re.getPDF());// w ww .j  av  a  2s  .  c  o m
    }

    if (pdfList.size() > 1) {
        try {
            File outFile = File.createTempFile("PrintInvoices", ".pdf");
            Document document = null;
            PdfWriter copy = null;
            for (File f : pdfList) {
                PdfReader reader = new PdfReader(f.getAbsolutePath());
                if (document == null) {
                    document = new Document(reader.getPageSizeWithRotation(1));
                    copy = PdfWriter.getInstance(document, new FileOutputStream(outFile));
                    document.open();
                }
                PdfContentByte cb = copy.getDirectContent(); // Holds the PDF
                int pages = reader.getNumberOfPages();
                for (int i = 1; i <= pages; i++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, i);
                    cb.addTemplate(page, 0, 0);
                }
            }
            document.close();

            hideBusyDialog();
            Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(outFile));
            SessionManager.getAppDesktop().showWindow(win, "center");
        } catch (Exception e) {
            log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    } else if (pdfList.size() > 0) {
        try {
            Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(pdfList.get(0)));
            SessionManager.getAppDesktop().showWindow(win, "center");
        } catch (Exception e) {
            log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }
}

From source file:org.alchemy.core.AlcSession.java

License:Open Source License

/** Save the canvas to a single paged PDF file
 * //from  w  w w.j  ava 2 s. com
 * @param file  The file object to save the pdf to
 * @return      True if save worked, otherwise false
 */
boolean saveSinglePdf(File file) {
    // Get the current 'real' size of the canvas without margins/borders
    java.awt.Rectangle bounds = Alchemy.canvas.getVisibleRect();
    //int singlePdfWidth = Alchemy.window.getWindowSize().width;
    //int singlePdfHeight = Alchemy.window.getWindowSize().height;
    com.lowagie.text.Document document = new com.lowagie.text.Document(
            new com.lowagie.text.Rectangle(bounds.width, bounds.height), 0, 0, 0, 0);
    System.out.println("Save Single Pdf Called: " + file.toString());
    boolean noError = true;

    try {

        PdfWriter singleWriter = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.addTitle("Alchemy Session");
        document.addAuthor(USER_NAME);
        document.addCreator("Alchemy <http://al.chemy.org>");

        // Add metadata and open the document
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        XmpWriter xmp = new XmpWriter(os);
        PdfSchema pdf = new PdfSchema();
        pdf.setProperty(PdfSchema.KEYWORDS, "Alchemy <http://al.chemy.org>");
        //pdf.setProperty(PdfSchema.VERSION, "1.4");
        xmp.addRdfDescription(pdf);
        xmp.close();
        singleWriter.setXmpMetadata(os.toByteArray());

        // To avoid transparent colurs being converted from RGB>CMYK>RGB
        // We have to add everything to a transparency group
        PdfTransparencyGroup transGroup = new PdfTransparencyGroup();
        transGroup.put(PdfName.CS, PdfName.DEVICERGB);

        document.open();

        PdfContentByte cb = singleWriter.getDirectContent();
        PdfTemplate tp = cb.createTemplate(bounds.width, bounds.height);

        document.newPage();

        cb.getPdfWriter().setGroup(transGroup);
        // Make sure the color space is Device RGB
        cb.setDefaultColorspace(PdfName.CS, PdfName.DEVICERGB);

        // Draw into the template and add it to the PDF 
        Graphics2D g2pdf = tp.createGraphics(bounds.width, bounds.height);
        Alchemy.canvas.setGuide(false);
        Alchemy.canvas.vectorCanvas.paintComponent(g2pdf);
        Alchemy.canvas.setGuide(true);
        g2pdf.dispose();
        cb.addTemplate(tp, 0, 0);

    } catch (DocumentException ex) {
        System.err.println(ex);
        noError = false;
    } catch (IOException ex) {
        System.err.println(ex);
        noError = false;
    }

    document.close();

    return noError;
}

From source file:org.andrill.coretools.graphics.driver.pdf.PDFDriver.java

License:Apache License

public static void main(final String[] args) throws Exception {
    Paper paper = Paper.getDefault();

    // raster graphics
    RasterGraphics raster = new RasterGraphics(paper.getWidth(), paper.getHeight(), true);
    raster.pushTransform(AffineTransform.getTranslateInstance(36, 36));
    drawTest(raster);/*  ww w.ja  va  2 s  .c o  m*/
    raster.write(new File("Test.png"));

    // pdf graphics
    Document document = new Document(new com.lowagie.text.Rectangle(paper.getWidth(), paper.getHeight()));
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Test.pdf"));
    document.open();
    drawTest(new GraphicsContext(new PDFDriver(writer.getDirectContent(), paper)));
    document.close();
    writer.close();
}