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:songscribe.publisher.publisheractions.ExportPDFAction.java

License:Open Source License

public void actionPerformed(ActionEvent e) {
    if (publisher.isBookNull()) {
        return;// w  w  w .j a v a  2 s.  co  m
    }

    if (pfd.showDialog()) {
        File saveFile = pfd.getFile();

        if (!saveFile.getName().toLowerCase().endsWith(".pdf")) {
            saveFile = new File(saveFile.getAbsolutePath() + ".pdf");
        }

        if (saveFile.exists()) {
            int answ = JOptionPane.showConfirmDialog(publisher,
                    "The file " + saveFile.getName() + " already exists. Do you want to overwrite it?",
                    publisher.PROG_NAME, JOptionPane.YES_NO_OPTION);
            if (answ == JOptionPane.NO_OPTION) {
                return;
            }
        }

        float resolution = 72f / MusicSheet.RESOLUTION;
        Book book = publisher.getBook();
        Document document = new Document(new com.lowagie.text.Rectangle(book.getPageSize().x * resolution,
                book.getPageSize().y * resolution, book.getPageSize().width * resolution,
                book.getPageSize().height * resolution), 0, 0, 0, 0);

        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(saveFile));
            document.addCreator(publisher.PROG_NAME);
            document.open();
            PdfContentByte cb = writer.getDirectContent();

            for (ListIterator<Page> it = book.pageIterator(); it.hasNext();) {
                Graphics2D g2 = cb.createGraphicsShapes(book.getPageSize().width * resolution,
                        book.getPageSize().height * resolution);
                g2.scale(resolution, resolution);
                it.next().paint(g2, it.nextIndex() - 1, false, 0, book.getPageSize().height);
                g2.dispose();

                if (it.hasNext()) {
                    document.newPage();
                }
            }

            document.close();
            Utilities.openExportFile(publisher, saveFile);
        } catch (DocumentException e1) {
            publisher.showErrorMessage("An unexprected error occured and could not export into PDF.");
            logger.error("PDF save", e1);
        } catch (FileNotFoundException e1) {
            publisher.showErrorMessage(MainFrame.COULD_NOT_SAVE_MESSAGE);
            logger.error("PDF save", e1);
        }
    }
}

From source file:songscribe.ui.mainframeactions.ExportPDFAction.java

License:Open Source License

public static void createPDF(Data data, File outputFile, Boolean isGUI) {
    float resolution = 72f / MusicSheet.RESOLUTION;
    float paperWidth = data.paperWidth * resolution;
    float paperHeight = data.paperHeight * resolution;
    MainFrame mainFrame = data.mainFrame;
    Document document = new Document(new Rectangle(0, 0, paperWidth, paperHeight), 0, 0, 0, 0);
    document.addCreator(mainFrame.PROG_NAME);
    document.addTitle(mainFrame.getMusicSheet().getComposition().getSongTitle());

    // Scale to fit
    int sheetWidth = mainFrame.getMusicSheet().getSheetWidth();
    int sheetHeight = mainFrame.getMusicSheet().getSheetHeight();
    double horizontalMargin = (data.leftInnerMargin + data.rightOuterMargin) * resolution;
    double horizontalScale = (paperWidth - horizontalMargin) / sheetWidth;
    double verticalMargin = (data.topMargin + data.bottomMargin) * resolution;
    double verticalScale = (paperHeight - verticalMargin) / sheetHeight;
    double scale;
    double leftMargin = data.leftInnerMargin * resolution;

    if (horizontalScale < verticalScale) {
        scale = horizontalScale;//  ww  w  .j a v a  2s. c  om
    } else {
        // If scaling vertically, the horizontal margin will be larger than
        // what is specified in Data. So we calculate the total margin available,
        // then give the left margin the same fraction of the total margin
        // it would have had before scaling.
        scale = verticalScale;
        double scaledMargin = paperWidth - (sheetWidth * scale);
        double leftMarginFactor = (double) data.leftInnerMargin
                / (double) (data.leftInnerMargin + data.rightOuterMargin);
        leftMargin = scaledMargin * leftMarginFactor;
    }

    try {
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g2 = cb.createGraphicsShapes(paperWidth, paperHeight);
        g2.translate(leftMargin, data.topMargin * resolution);
        mainFrame.getMusicSheet().getBestDrawer().drawMusicSheet(g2, false, scale);
        g2.dispose();
        document.close();

        if (isGUI) {
            Utilities.openExportFile(mainFrame, outputFile);
        }
    } catch (DocumentException e1) {
        if (isGUI) {
            mainFrame.showErrorMessage("An unexpected error occurred and could not export as PDF.");
        }

        logger.error("PDF save", e1);
    } catch (FileNotFoundException e1) {
        if (isGUI) {
            mainFrame.showErrorMessage(MainFrame.COULD_NOT_SAVE_MESSAGE);
        }

        logger.error("PDF save", e1);
    }
}

From source file:storemanagment.FooterOnly.java

/**
 *
 * @param writer//w w w .  ja v a  2s.com
 * @param document
 */
@Override
public void onEndPage(PdfWriter writer, Document document) {
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
            new Phrase("Officer In Charge : " + officerInCharge), 110, 30, 0);
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
            new Phrase("Sign : _________________       " + document.getPageNumber()), 550, 30, 0);
}

From source file:storemanagment.HeaderFooterPageEvent.java

/**
 *
 * @param writer//from  w  w w .j  av a2  s .  c  o  m
 * @param document
 */
@Override
public void onStartPage(PdfWriter writer, Document document) {
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
            new Phrase("     R.NO :" + receiptNO + "\n\n"), 30, 800, 0);
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("" + date + "\n\n"),
            550, 800, 0);
}

From source file:storemanagment.Printing.java

public PdfPCell createImageCellCrip(String path, PdfWriter writer) throws IOException, DocumentException {
    PdfPCell cell = null;//  ww w. ja v a  2  s .  c  o  m
    try {
        Image img = Image.getInstance(path);
        float w = img.getScaledWidth();
        float h = img.getScaledHeight();

        PdfTemplate t = writer.getDirectContent().createTemplate(w, h);
        t.ellipse(0, 0, w, h);
        t.newPath();
        t.addImage(img, w, 0, 0, h, 0, -600);
        Image clipped = Image.getInstance(t);
        cell = new PdfPCell(clipped, true);
        // cell.setFixedHeight(30);
        // cell.setBorder(Rectangle.NO_BORDER);
        //cell.setBorder(R);
        cell.setPaddingTop(10);

    } catch (BadElementException ex) {
        Logger.getLogger(Printing.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MalformedURLException ex) {
        Logger.getLogger(Printing.class.getName()).log(Level.SEVERE, null, ex);
    }

    return cell;
}

From source file:tracer.application.TracerFrame.java

License:Open Source License

/**
 * export full statistic summary of selected traceList (log) to a tab-delimited txt file
 *///from www . j ava  2  s  . c  om
//    public final void doExportStatisticSummary() {
//        final JFrame frame = this;
//
//        FileDialog dialog = new FileDialog(frame, "Export Statistic Summary...", FileDialog.SAVE);
//
//        dialog.setVisible(true);
//        if (dialog.getFile() != null) {
//            File file = new File(dialog.getDirectory(), dialog.getFile());
//
//            // todo use LongTask
//            final String statSummTxt = TraceAnalysis.getStatisticSummary(currentTraceLists);
//
//            try {
//
//                FileWriter writer = new FileWriter(file);
//                writer.write(statSummTxt);
//                writer.close();
//
//            } catch (IOException ioe) {
//                JOptionPane.showMessageDialog(this, "Unable to write file: " + ioe,
//                        "Unable to write file",
//                        JOptionPane.ERROR_MESSAGE);
//            }
//        }
//    }

public final void doExportPDF() {
    FileDialog dialog = new FileDialog(this, "Export PDF Image...", FileDialog.SAVE);

    dialog.setVisible(true);
    if (dialog.getFile() != null) {
        File file = new File(dialog.getDirectory(), dialog.getFile());

        Rectangle2D bounds = tracePanel.getExportableComponent().getBounds();
        Document document = new Document(
                new com.lowagie.text.Rectangle((float) bounds.getWidth(), (float) bounds.getHeight()));
        try {
            // step 2
            PdfWriter writer;
            writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            // step 3
            document.open();
            // step 4
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate((float) bounds.getWidth(), (float) bounds.getHeight());
            Graphics2D g2d = tp.createGraphics((float) bounds.getWidth(), (float) bounds.getHeight(),
                    new DefaultFontMapper());
            tracePanel.getExportableComponent().print(g2d);
            g2d.dispose();
            cb.addTemplate(tp, 0, 0);
        } catch (DocumentException de) {
            JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de, "Export PDF Error",
                    JOptionPane.ERROR_MESSAGE);
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(this, "Error writing PDF file: " + e, "Export PDF Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        document.close();
    }
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createMapAsPDF(File file, LWMap map) {
    // step 1: creation of a document-object
    Document document = new Document(PageSize.LETTER.rotate());

    try {/*from  www  . j  av  a  2  s .  c o m*/
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setDefaultColorspace(PdfName.DEFAULTRGB, null);
        // writer.setStrictImageSequence(true);
        // step 3: we open the document

        document.open();

        PdfContentByte cb = writer.getDirectContent();
        //  cb.setFontAndSize(arg0, arg1)
        PdfTemplate tp = cb.createTemplate(document.getPageSize().getWidth() - 70,
                document.getPageSize().getHeight() - 70);
        // tp.createGraphicsShapes(arg0, arg1) 

        PdfGraphics2D g2d = (PdfGraphics2D) tp.createGraphics(document.getPageSize().getWidth() - 70,
                document.getPageSize().getHeight() - 70, getFontMapper(), false, 60.0f);

        Dimension page = new Dimension((int) document.getPageSize().getWidth() - 70,
                (int) document.getPageSize().getHeight() - 70);
        // compute zoom & offset for visible map components
        Point2D.Float offset = new Point2D.Float();
        offset.x = 35;
        offset.y = 35;
        // center vertically only if landscape mode
        //if (format.getOrientation() == PageFormat.LANDSCAPE)
        //TODO: allow horizontal centering, but not vertical centering (handle in computeZoomFit)
        Rectangle2D bounds = map.getBounds();
        double scale = ZoomTool.computeZoomFit(page, 5, bounds, offset, true);
        //  System.out.println(scale  + " zoom factor...");
        // set up the DrawContext
        DrawContext dc = new DrawContext(g2d, scale, -offset.x, -offset.y, null, // frame would be the PageFormat offset & size rectangle
                map, false); // todo: absolute links shouldn't be spec'd here

        //    dc.setAntiAlias(true);
        dc.setMapDrawing();
        //   dc.setPDFRender(true);
        //dc.setPrioritizeQuality(false); // why was this low quality?
        dc.setPrintQuality();
        //dc.setAntiAlias(false); // why was this turned off?  was it redundant?

        dc.setClipOptimized(true);
        //   dc.setDraftQuality(true);
        //  dc.setRawDrawing();
        //dc.setClipOptimized(false);

        dc.setInteractive(false);
        dc.setDrawPathways(false);

        // VUE.getActiveMap().draw(dc);
        LWPathway.setShowSlides(false);
        map.drawZero(dc);
        LWPathway.setShowSlides(true);
        g2d.dispose();
        //  document.add(new Paragraph(new Chunk().setAnchor("http://www.cnn.com")));
        cb.addTemplate(tp, 0, 0);
        document.newPage();

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

    // step 5: we close the document
    document.close();
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createPresentationNotes8PerPage(File file) {
    //page size notes:
    //martin-top,left,right,bottom = 36
    //widht :612/* w  ww .j a  v  a 2  s . c  om*/
    //height : 792
    //usable space 540 x 720
    // step 1: creation of a document-object
    Document document = new Document(PageSize.LETTER);

    try {
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        //  writer.setDefaultColorspace(PdfName.DEFAULTRGB, null);
        // writer.setStrictImageSequence(true);

        // step 3: we open the document
        document.open();

        // PdfPTable table;
        // PdfPCell cell;            
        int entryCount = 0;
        int entryOnPage = 0;
        int currentIndex = VUE.getActivePathway().getIndex();

        VUE.getActivePathway().setIndex(-1);

        for (LWPathway.Entry entry : VUE.getActivePathway().getEntries()) {

            final LWSlide slide = entry.produceSlide();
            final LWComponent toDraw = (slide == null ? entry.node : slide);

            entryCount++;
            //String label = entry.getLabel();
            PdfContentByte cb = writer.getDirectContent();
            //cb.cr
            PdfTemplate tp = cb.createTemplate(SlideSizeX, SlideSizeY);
            Point2D.Float offset = new Point2D.Float();

            Rectangle2D bounds = null;

            bounds = slide.getBounds();

            Dimension page = null;

            page = new Dimension(SlideSizeX, 172);

            //PdfTemplate tp = cb.createTemplate(document.getPageSize().width()-80, document.getPageSize().height()-80);
            double scale = ZoomTool.computeZoomFit(page, 5, bounds, offset, true);
            PdfGraphics2D g2d = (PdfGraphics2D) tp.createGraphics(SlideSizeX, SlideSizeY, getFontMapper(),
                    false, 60.0f);
            DrawContext dc = new DrawContext(g2d, scale, -offset.x, -offset.y, null, // frame would be the PageFormat offset & size rectangle
                    entry.isMapView() ? entry.getFocal() : slide, false); // todo: absolute links shouldn't be spec'd here

            dc.setClipOptimized(false);
            dc.setPrintQuality();
            //slide.drawZero(dc);
            toDraw.drawFit(dc, 0);

            g2d.dispose();
            //document.add(Image.getInstance(tp));

            if (entryOnPage == 0) {
                drawSequenceNumber(writer, 36, 739, entryCount);
                cb.addTemplate(tp, 56, 583);
            }
            if (entryOnPage == 1) {
                drawSequenceNumber(writer, 296, 739, entryCount);
                cb.addTemplate(tp, 306, 583);
            }
            if (entryOnPage == 2) {
                drawSequenceNumber(writer, 36, 559, entryCount);
                cb.addTemplate(tp, 56, 403);
            }
            if (entryOnPage == 3) {
                drawSequenceNumber(writer, 296, 559, entryCount);
                cb.addTemplate(tp, 306, 403);
            }
            if (entryOnPage == 4) {
                drawSequenceNumber(writer, 36, 375, entryCount);
                cb.addTemplate(tp, 56, 219);
            }
            if (entryOnPage == 5) {
                drawSequenceNumber(writer, 296, 375, entryCount);
                cb.addTemplate(tp, 306, 219);
            }
            if (entryOnPage == 6) {
                drawSequenceNumber(writer, 36, 192, entryCount);
                cb.addTemplate(tp, 56, 36);
                //cb.addTemplate(drawLines(writer),296,18);
            }
            if (entryOnPage == 7) {
                drawSequenceNumber(writer, 296, 192, entryCount);
                cb.addTemplate(tp, 306, 36);
            }

            entryOnPage++;
            if (entryCount % 8 == 0) {
                document.newPage();
                entryOnPage = 0;
            }
        }
        VUE.getActivePathway().setIndex(currentIndex);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

    // step 5: we close the document
    document.close();
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

private static PdfTemplate drawLines(PdfWriter writer) {
    PdfContentByte cb2 = writer.getDirectContent();
    //cb.cr/*from w ww. j a  v  a2 s.c  o  m*/
    PdfTemplate tp2 = cb2.createTemplate(SlideSizeX + 40, SlideSizeY);
    tp2.setColorStroke(Color.gray);
    //tp2.setColorFill(Color.gray);
    int x = 30;
    for (int i = 1; i < 9; i++) {
        tp2.moveTo(0, x);
        tp2.lineTo(SlideSizeX + 40, x);
        tp2.stroke();
        x += 20;
    }

    return tp2;
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

private static void drawSequenceNumber(PdfWriter writer, float x, float y, int seq) {
    PdfContentByte cb = writer.getDirectContent();
    try {/*from   w  w  w. j  a  va2 s. c  o m*/
        cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false), 16);
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    cb.beginText();
    cb.showTextAligned(Element.ALIGN_CENTER, new Integer(seq).toString() + ".", x, y, 0f);
    cb.endText();
    cb.stroke();

    //return tp2;
}