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

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

Introduction

In this page you can find the example usage for com.itextpdf.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:nz.ac.waikato.cms.doc.OverlayFilename.java

License:Open Source License

/**
 * Performs the overlay.//from www.j  a v a  2  s .  com
 *
 * @param input   the input file/dir
 * @param output   the output file/dir
 * @param vpos   the vertical position
 * @param hpos   the horizontal position
 * @param stripPath   whether to strip the path
 * @param stripExt   whether to strip the extension
 * @param pages   the array of pages (1-based) to add the overlay to, null for all
 * @param evenPages   whether to enforce even pages in the document
 * @return      true if successfully overlay
 */
public boolean overlay(File input, File output, int vpos, int hpos, boolean stripPath, boolean stripExt,
        int[] pages, boolean evenPages) {
    PdfReader reader;
    PdfStamper stamper;
    FileOutputStream fos;
    PdfContentByte canvas;
    int i;
    String text;
    int numPages;
    File tmpFile;
    Document document;
    PdfWriter writer;
    PdfImportedPage page;
    PdfContentByte cb;

    reader = null;
    stamper = null;
    fos = null;
    numPages = -1;
    try {
        reader = new PdfReader(input.getAbsolutePath());
        fos = new FileOutputStream(output.getAbsolutePath());
        stamper = new PdfStamper(reader, fos);
        numPages = reader.getNumberOfPages();
        if (pages == null) {
            pages = new int[reader.getNumberOfPages()];
            for (i = 0; i < pages.length; i++)
                pages[i] = i + 1;
        }

        if (stripPath)
            text = input.getName();
        else
            text = input.getAbsolutePath();
        if (stripExt)
            text = text.replaceFirst("\\.[pP][dD][fF]$", "");

        for (i = 0; i < pages.length; i++) {
            canvas = stamper.getOverContent(pages[i]);
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Paragraph(text), hpos, vpos, 0.0f);
        }
    } catch (Exception e) {
        System.err.println("Failed to process " + input + ":");
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (stamper != null)
                stamper.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            if (reader != null)
                reader.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            if (fos != null) {
                fos.flush();
                fos.close();
            }
        } catch (Exception e) {
            // ignored
        }
    }

    // enforce even pages?
    if (evenPages && (numPages > 0) && (numPages % 2 == 1)) {
        reader = null;
        fos = null;
        writer = null;
        tmpFile = new File(output.getAbsolutePath() + "tmp");
        try {
            if (!output.renameTo(tmpFile)) {
                System.err.println("Failed to rename '" + output + "' to '" + tmpFile + "'!");
                return false;
            }
            reader = new PdfReader(tmpFile.getAbsolutePath());
            document = new Document(reader.getPageSize(1));
            fos = new FileOutputStream(output.getAbsoluteFile());
            writer = PdfWriter.getInstance(document, fos);
            document.open();
            document.addCreationDate();
            document.addAuthor(System.getProperty("user.name"));
            cb = writer.getDirectContent();
            for (i = 0; i < reader.getNumberOfPages(); i++) {
                page = writer.getImportedPage(reader, i + 1);
                document.newPage();
                cb.addTemplate(page, 0, 0);
            }
            document.newPage();
            document.add(new Paragraph(" ")); // fake content
            document.close();
        } catch (Exception e) {
            System.err.println("Failed to process " + tmpFile + ":");
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fos != null) {
                    fos.flush();
                    fos.close();
                }
            } catch (Exception e) {
                // ignored
            }
            try {
                if (reader != null)
                    reader.close();
            } catch (Exception e) {
                // ignored
            }
            try {
                if (writer != null)
                    writer.close();
            } catch (Exception e) {
                // ignored
            }
            if (tmpFile.exists()) {
                try {
                    tmpFile.delete();
                } catch (Exception e) {
                    // ignored
                }
            }
        }
    }

    return true;
}

From source file:nz.ac.waikato.cms.supernova.io.PDF.java

License:Open Source License

/**
 * Generates the intermediate data structure.
 *
 * @param test      the test results (measure - [score, percentile])
 * @param angle      the angle to use/*  w  w  w  .  ja  v  a 2s  .  co  m*/
 * @param numFlips      the number of flips
 * @param overallFlipCycles   the overall flip cycles
 * @param errors      for storing error messages
 * @return         null if successfully generated, otherwise error message
 */
public ByteArrayOutputStream generatePlot(Map<String, List<Double>> test, double angle,
        Map<String, Integer> numFlips, int overallFlipCycles, StringBuilder errors) {
    ByteArrayOutputStream result;
    Document document;
    PdfWriter writer;
    PdfContentByte canvas;
    PdfTemplate template;
    Graphics2D g;

    result = new ByteArrayOutputStream();
    g = null;
    document = null;
    try {
        document = new Document(new Rectangle(m_Width, m_Height));
        writer = PdfWriter.getInstance(document, result);
        document.open();
        canvas = writer.getDirectContent();
        template = canvas.createTemplate(m_Width, m_Height);
        g = new PdfGraphics2D(template, m_Width, m_Height);
        draw(g, test, angle, numFlips, overallFlipCycles, errors);
        canvas.addTemplate(template, 0, 0);
    } catch (Exception e) {
        errors.append(Utils.throwableToString(e));
    } finally {
        try {
            if (g != null)
                g.dispose();
        } catch (Exception e) {
            // ignored
        }
        try {
            if (document != null)
                document.close();
        } catch (Exception e) {
            // ignored
        }
    }

    return result;
}

From source file:omr.score.ui.SheetPdfOutput.java

License:Open Source License

public void write() throws Exception {
    FileOutputStream fos = new FileOutputStream(file);
    Document document = null;//ww w .  j a v a 2 s . com
    PdfWriter writer = null;

    try {
        for (TreeNode pn : score.getPages()) {
            Page page = (Page) pn;
            Dimension dim = page.getDimension();

            if (document == null) {
                document = new Document(new Rectangle(dim.width, dim.height));
                writer = PdfWriter.getInstance(document, fos);
                document.open();
            } else {
                document.setPageSize(new Rectangle(dim.width, dim.height));
                document.newPage();
            }

            PdfContentByte cb = writer.getDirectContent();
            Graphics2D g2 = cb.createGraphics(dim.width, dim.height);
            g2.scale(1, 1);

            // Painting
            PagePhysicalPainter painter = new PagePhysicalPainter(g2, Color.BLACK, // Foreground color
                    false, // No voice painting
                    true, // Paint staff lines
                    false); // No annotations
            page.accept(painter);

            // This is the end...
            g2.dispose();
        }
    } catch (Exception ex) {
        logger.warn("Error printing " + score.getRadix(), ex);
        throw ex;
    } finally {
        if (document != null) {
            document.close();
        }
    }

    fos.close();
}

From source file:org.audiveris.omr.score.ui.BookPdfOutput.java

License:Open Source License

/**
 * Write the PDF output for the provided sheet if any, otherwise for the whole book.
 *
 * @param sheet desired sheet or null/*from   ww w  .  jav  a  2  s .  c om*/
 * @throws Exception if printing goes wrong
 */
public void write(Sheet sheet) throws Exception {
    FileOutputStream fos = null;
    Document document = null;
    PdfWriter writer = null;

    try {
        final List<SheetStub> stubs = (sheet != null) ? Arrays.asList(sheet.getStub()) : book.getValidStubs();
        fos = new FileOutputStream(file);

        for (SheetStub stub : stubs) {
            final int width = stub.getSheet().getWidth();
            final int height = stub.getSheet().getHeight();

            if (document == null) {
                document = new Document(new Rectangle(width, height));
                writer = PdfWriter.getInstance(document, fos);
                document.open();
            } else {
                document.setPageSize(new Rectangle(width, height));
                document.newPage();
            }

            PdfContentByte cb = writer.getDirectContent();
            Graphics2D g2 = cb.createGraphics(width, height);

            // Scale: 1
            g2.scale(1, 1);

            // Anti-aliasing ON
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // Painting
            SheetResultPainter painter = new SheetResultPainter(stub.getSheet(), g2, false, // No voice painting
                    true, // Paint staff lines
                    false); // No annotations
            g2.setColor(Color.BLACK);

            painter.process();

            // This is the end...
            g2.dispose();
        }

        logger.info("Book printed to {}", file);
    } finally {
        if (document != null) {
            document.close();
        }

        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:org.cejug.yougi.web.report.EventAttendeeCertificate.java

License:Open Source License

public void setCertificateTemplate(PdfWriter writer, String urlTemplate) throws IOException {
    writer.setPageEvent(this);

    PdfReader reader = new PdfReader(urlTemplate);
    page = writer.getImportedPage(reader, 1);
    canvas = writer.getDirectContent();
}

From source file:org.com.controller.BarcodeController.java

@RequestMapping(value = "/barprocess", method = RequestMethod.POST)
public void barpdfgen(@ModelAttribute(value = "quick") BargenTemp bt, Model m, HttpServletResponse response,
        HttpServletRequest request, OutputStream outputStream) throws Exception {
    System.out.println("on process" + bt.getIsbn());
    if ("".equals(bt.getIsbn())) {
        System.out.println("on process 2");
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename= barcode");
        Document document = new Document(new Rectangle(340, 842));
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        document.open();//  ww  w .j  av  a 2  s  .c  o  m
        PdfContentByte cb = writer.getDirectContent();
        int q = Integer.parseInt(bt.getQuantity());
        System.out.println("QUANTITU" + q);
        document.add(new Paragraph("Cod-39: DATE: " + bt.getDate()));
        document.add(new Paragraph("=========================================="));
        document.add(new Paragraph("                                                                     "));
        PdfPTable table = new PdfPTable(5);
        for (int i = 0; i <= q; i++) {
            Barcode39 code39ext = new Barcode39();
            code39ext.setCode(bt.getBno());
            code39ext.setStartStopText(false);
            code39ext.setExtended(true);
            table.addCell(code39ext.createImageWithBarcode(cb, null, null));

        }
        document.add(table);
        // step 5
        document.close();
        autocomplete(bt);
        //return "null";
    }

}

From source file:org.dspace.disseminate.CitationDocument.java

/**
 * Attempts to add a Logo to the document from the given resource. Returns
 * true on success and false on failure.
 *
 * @param doc The document to add the logo to. (Added to the top right
 * corner of the first page./*from   w ww .j a  v a2 s .c o m*/
 * @param writer The writer associated with the given Document.
 * @param res The resource/path to the logo file. This file can be any of
 * the following formats:
 *  GIF, PNG, JPEG, PDF
 *
 * @return Succesfully added logo to document.
 */
private boolean addLogoToDocument(Document doc, PdfWriter writer, String res) {
    boolean ret = false;
    try {
        //First we try to get the logo as if it is a Java Resource
        URL logoURL = this.getClass().getResource(res);
        log.debug(res + " -> " + logoURL.toString());
        if (logoURL == null) {
            logoURL = new URL(res);
        }

        if (logoURL != null) {
            String mtype = URLConnection.guessContentTypeFromStream(logoURL.openStream());
            if (mtype == null) {
                mtype = URLConnection.guessContentTypeFromName(res);
            }
            log.debug("Determined MIMETYPE of logo: " + mtype);
            if (PDF_MIMES.contains(mtype)) {
                //Handle pdf logos.
                PdfReader reader = new PdfReader(logoURL);
                PdfImportedPage logoPage = writer.getImportedPage(reader, 1);
                Image logo = Image.getInstance(logoPage);
                float x = doc.getPageSize().getWidth() - doc.rightMargin() - logo.getScaledWidth();
                float y = doc.getPageSize().getHeight() - doc.topMargin() - logo.getScaledHeight();
                logo.setAbsolutePosition(x, y);
                doc.add(logo);
                ret = true;
            } else if (RASTER_MIMES.contains(mtype)) {
                //Use iText's Image class
                Image logo = Image.getInstance(logoURL);

                //Determine the position of the logo (upper-right corner) and
                //place it there.
                float x = doc.getPageSize().getWidth() - doc.rightMargin() - logo.getScaledWidth();
                float y = doc.getPageSize().getHeight() - doc.topMargin() - logo.getScaledHeight();
                logo.setAbsolutePosition(x, y);
                writer.getDirectContent().addImage(logo);
                ret = true;
            } else if (SVG_MIMES.contains(mtype)) {
                //Handle SVG Logos
                log.error("SVG Logos are not supported yet.");
            } else {
                //Cannot use other mimetypes
                log.debug("Logo MIMETYPE is not supported.");
            }
        } else {
            log.debug("Could not create URL to Logo resource: " + res);
        }
    } catch (Exception e) {
        log.error("Could not add logo (" + res + ") to cited document: " + e.getMessage());
        ret = false;
    }
    return ret;
}

From source file:org.fhaes.fhsamplesize.view.SSIZCurveChart.java

License:Open Source License

/**
 * Save chart as PDF file. Requires iText library.
 * //from  w w  w. j  a  va 2s.  c  o  m
 * @param chart JFreeChart to save.
 * @param fileName Name of file to save chart in.
 * @param width Width of chart graphic.
 * @param height Height of chart graphic.
 * @throws Exception if failed.
 * @see <a href="http://www.lowagie.com/iText">iText</a>
 */
@SuppressWarnings("deprecation")
public static void writeAsPDF(File fileToSave, int width, int height) throws Exception {

    if (chart != null) {
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(fileToSave.getAbsolutePath()));

            // convert chart to PDF with iText:
            Rectangle pagesize = new Rectangle(width, height);
            Document document = new Document(pagesize, 50, 50, 50, 50);
            try {
                PdfWriter writer = PdfWriter.getInstance(document, out);
                document.addAuthor("JFreeChart");
                document.open();

                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(width, height);
                Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());

                Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
                chart.draw(g2, r2D, null);
                g2.dispose();
                cb.addTemplate(tp, 0, 0);
            } finally {
                document.close();
            }
        } finally {
            if (out != null)
                out.close();
        }
    }
}

From source file:org.fhaes.neofhchart.PDFExportOptionsDialog.java

License:Open Source License

/**
 * Performs the export operation using the currentChart as the source.
 * /*from w w  w  . j a  v a2  s .  c  o m*/
 * @return true if the operation completed successfully, false otherwise
 */
private boolean doExportToPDF() {

    boolean completedSuccessfully = false;

    if (currentChart != null) {
        log.debug("Exporting to PDF...");
        Document document = null;

        if (cboPaperSize.getSelectedItem() instanceof Rectangle) {
            Rectangle rect = (Rectangle) cboPaperSize.getSelectedItem();

            if (radLandscape.isSelected()) {
                rect = rect.rotate();
            }

            document = new Document(rect, 10, 10, 10, 10);
        } else {
            Rectangle rect = new Rectangle(currentChart.getTotalWidth(), currentChart.getTotalHeight());
            document = new Document(rect, 10, 10, 10, 10);
        }

        try {
            currentChart.setVisibilityOfNoExportElements(false);

            PdfWriter writer = PdfWriter.getInstance(document,
                    new FileOutputStream(outputFile.getAbsolutePath()));
            document.open();

            int width = (int) document.getPageSize().getWidth();
            int height = (int) document.getPageSize().getHeight();

            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate template = cb.createTemplate(width, height);

            @SuppressWarnings("deprecation")
            Graphics2D g2 = template.createGraphics(width, height);

            PrintTranscoder prm = new PrintTranscoder();
            TranscoderInput ti = new TranscoderInput(currentChart.getSVGDocument());
            prm.transcode(ti, null);

            PageFormat pg = new PageFormat();
            Paper pp = new Paper();
            pp.setSize(width, height);
            pp.setImageableArea(0, 0, width, height);
            pg.setPaper(pp);
            prm.print(g2, pg, 0);
            g2.dispose();

            ImgTemplate img = new ImgTemplate(template);
            document.add(img);

            completedSuccessfully = true;
        } catch (DocumentException e) {
            System.err.println(e);
        } catch (IOException e) {
            System.err.println(e);
        } finally {
            currentChart.setVisibilityOfNoExportElements(true);
        }

        document.close();
    }

    return completedSuccessfully;
}

From source file:org.fossa.rolp.util.LebPageHelper.java

License:Open Source License

@Override
public void onOpenDocument(PdfWriter writer, Document document) {
    writer.getDirectContent().createTemplate(60, 16);
}