Example usage for com.itextpdf.text Image getInstance

List of usage examples for com.itextpdf.text Image getInstance

Introduction

In this page you can find the example usage for com.itextpdf.text Image getInstance.

Prototype

public static Image getInstance(final Image image) 

Source Link

Document

gets an instance of an Image

Usage

From source file:com.vectorprint.report.itext.DefaultElementProducer.java

License:Open Source License

@Override
public void loadPdf(File pdf, PdfWriter writer, byte[] password, ImageProcessor imageProcessor, int... pages)
        throws VectorPrintException {
    RandomAccessFileOrArray ra = null;//from www  .  j  av  a2s .c om
    try {
        RandomAccessSourceFactory rasf = new RandomAccessSourceFactory();
        ra = new RandomAccessFileOrArray(rasf.createBestSource(pdf.getPath()));
        PdfReader reader = new PdfReader(ra, password);
        if (pages == null) {
            for (int i = 0; i < reader.getNumberOfPages();) {
                imageProcessor.processImage(Image.getInstance(writer.getImportedPage(reader, ++i)));
                writer.freeReader(reader);
            }
        } else {
            for (int i : pages) {
                imageProcessor.processImage(Image.getInstance(writer.getImportedPage(reader, i)));
                writer.freeReader(reader);
            }
        }
    } catch (BadElementException | IOException ex) {
        throw new VectorPrintException(String.format("unable to load image %s", pdf.toString()), ex);
    } finally {
        if (ra != null) {
            try {
                ra.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:com.vectorprint.report.itext.DefaultElementProducer.java

License:Open Source License

@Override
public void loadPdf(InputStream pdf, PdfWriter writer, Certificate certificate, Key key,
        String securityProvider, ImageProcessor imageProcessor, int... pages) throws VectorPrintException {
    // first download, then load
    File f = null;/* w w  w.j  av a2 s .  co m*/
    try {
        f = File.createTempFile("pdf.", "pdf");
        f.deleteOnExit();
        IOHelper.load(pdf, new FileOutputStream(f), ReportConstants.DEFAULTBUFFERSIZE, true);
        PdfReader reader = new PdfReader(f.getPath(), certificate, key, securityProvider);
        if (pages == null) {
            for (int i = 0; i < reader.getNumberOfPages();) {
                imageProcessor.processImage(Image.getInstance(writer.getImportedPage(reader, ++i)));
                writer.freeReader(reader);
            }
        } else {
            for (int i : pages) {
                imageProcessor.processImage(Image.getInstance(writer.getImportedPage(reader, i)));
                writer.freeReader(reader);
            }
        }
    } catch (BadElementException | IOException ex) {
        throw new VectorPrintException(String.format("unable to load image %s", pdf.toString()), ex);
    } finally {
        if (f != null) {
            f.delete();
        }
    }
}

From source file:com.vectorprint.report.itext.EventHelper.java

License:Open Source License

/**
 * this image will be used for painting the total number of pages and for a failure header when failures are printed
 * inside the report./*from  w w w  .j av  a  2 s. co m*/
 *
 * @see #printFailureHeader(com.itextpdf.text.pdf.PdfTemplate, float, float)
 * @see #printTotalPages(com.itextpdf.text.pdf.PdfTemplate, float, float)
 * @param template
 * @return
 * @throws BadElementException
 */
protected Image getTemplateImage(PdfTemplate template) throws BadElementException {
    if (templateImage == null) {
        templateImage = Image.getInstance(template);
        templateImage.setAbsolutePosition(0, 0);
    }

    return templateImage;
}

From source file:com.vectorprint.report.itext.TocOutputStream.java

License:Open Source License

@Override
public void secondPass(InputStream firstPass, OutputStream orig) throws IOException {
    PdfReader reader = null;// w w w  .  ja va 2  s .co  m
    VectorPrintDocument vpd = (VectorPrintDocument) outer.getDocument();
    try {
        reader = new PdfReader(firstPass);
        prepareToc();
        // init fresh components for second pass styling
        StylerFactory _stylerFactory = outer.getStylerFactory().getClass().newInstance();
        StylerFactoryHelper.SETTINGS_ANNOTATION_PROCESSOR.initSettings(_stylerFactory, outer.getSettings());
        _stylerFactory.setLayerManager(outer.getElementProducer());
        _stylerFactory.setImageLoader(outer.getElementProducer());
        outer.getStyleHelper().setStylerFactory(_stylerFactory);
        EventHelper event = outer.getEventHelper().getClass().newInstance();
        event.setItextStylerFactory(_stylerFactory);
        event.setElementProvider(outer.getElementProducer());
        ((DefaultElementProducer) outer.getElementProducer()).setPh(event);
        Document d = new VectorPrintDocument(event, _stylerFactory, outer.getStyleHelper());
        PdfWriter w = PdfWriter.getInstance(d, orig);
        w.setPageEvent(event);
        outer.getStyleHelper().setVpd((VectorPrintDocument) d);
        _stylerFactory.setDocument(d, w);
        DocumentStyler ds = _stylerFactory.getDocumentStyler();
        outer.getStyleHelper().style(d, null, StyleHelper.toCollection(ds));
        d.open();
        ds.styleAfterOpen(d, null);
        List outline = SimpleBookmark.getBookmark(reader);
        if (!ds.getValue(DocumentSettings.TOCAPPEND, Boolean.class)) {
            printToc(d, w, vpd);
            if (outline != null) {
                int cur = w.getCurrentPageNumber();
                SimpleBookmark.shiftPageNumbers(outline, cur, null);
            }
            d.newPage();
        }
        outer.getSettings().put(ReportConstants.DEBUG, Boolean.FALSE.toString());
        for (int p = 1; p <= reader.getNumberOfPages(); p++) {
            Image page = Image.getInstance(w.getImportedPage(reader, p));
            page.setAbsolutePosition(0, 0);
            d.setPageSize(page);
            d.newPage();
            Chunk i = new Chunk(" ");
            if (vpd.getToc().containsKey(p)) {
                Section s = null;
                for (Map.Entry<Integer, List<Section>> e : vpd.getToc().entrySet()) {
                    if (e.getKey() == p) {
                        s = e.getValue().get(0);
                        break;
                    }
                }
                i.setLocalDestination(s.getTitle().getContent());
            }
            d.add(i);
            w.getDirectContent().addImage(page);
            w.freeReader(reader);
        }
        if (_stylerFactory.getDocumentStyler().getValue(DocumentSettings.TOCAPPEND, Boolean.class)) {
            printToc(d, w, vpd);
        }
        w.setOutlines(outline);
        if (outer.isWasDebug()) {
            event.setLastPage(outer.getWriter().getCurrentPageNumber());
            d.setPageSize(new Rectangle(ItextHelper.mmToPts(297), ItextHelper.mmToPts(210)));
            d.setMargins(5, 5, 5, 5);
            d.newPage();
            outer.getSettings().put(ReportConstants.DEBUG, Boolean.TRUE.toString());
            event.setDebugHereAfter(true);
            DebugHelper.appendDebugInfo(w, d, outer.getSettings(), _stylerFactory);
        }
        d.close();
    } catch (VectorPrintException | DocumentException | InstantiationException | IllegalAccessException ex) {
        throw new VectorPrintRuntimeException(ex);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:com.vectorprint.report.jfree.ItextChartHelper.java

License:Open Source License

/**
 *
 * @param chart the chart tp plot/*from w w  w .j  a v a  2s.c  o m*/
 * @param contentByte the canvas to plot to
 * @param width the width of the chart will be fit to
 * @param height the height of the chart will be fit to
 * @return
 * @throws BadElementException
 */
public static Image getChartImage(JFreeChart chart, PdfContentByte contentByte, float width, float height,
        float opacity) throws BadElementException {

    // create PdfTemplate from PdfContentByte
    PdfTemplate template = contentByte.createTemplate(width, height);
    template.saveState();
    PdfGState pgs = new PdfGState();
    pgs.setFillOpacity(opacity);
    pgs.setStrokeOpacity(opacity);
    template.setGState(pgs);

    // create Graphics2D from PdfTemplate
    Graphics2D g2 = new PdfGraphics2D(template, width, height);

    // setup the drawing area
    Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);

    // pass the Graphics2D and drawing area to JFreeChart
    chart.draw(g2, r2D);
    g2.dispose(); // always dispose this

    template.restoreState();

    // create Image from PdfTemplate
    return Image.getInstance(template);
}

From source file:com.vectorprint.report.svg.BatikHelper.java

License:Open Source License

/**
 *
 * @param svg the svg document//from   w w w .ja v a2  s  .com
 * @param contentByte the canvas to plot to
 * @param width the width in pt of the svg will be fit to
 * @param height the height in pt of the svg will be fit to
 * @return
 * @throws BadElementException
 */
public static Image getSVGImage(Reader svg, PdfContentByte contentByte, float width, float height,
        float opacity) throws BadElementException, IOException {
    return Image.getInstance(getSVGTemplate(svg, contentByte, width, height, opacity));
}

From source file:com.vimbox.hr.LicensePDFGenerator.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w w .ja v  a 2  s .co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/pdf");
    String fileName = request.getParameter("license_name");
    String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
    String path = System.getProperty("user.dir") + "/documents/licenses/" + fileName;
    path = path.replaceAll("%20", " ");
    if (ext.equalsIgnoreCase("pdf")) {
        FileInputStream baos = new FileInputStream(path);

        OutputStream os = response.getOutputStream();

        byte buffer[] = new byte[8192];
        int bytesRead;

        while ((bytesRead = baos.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }

        os.flush();
        os.close();
    } else {
        try {
            // Document Settings //
            Document document = new Document();
            PdfWriter.getInstance(document, response.getOutputStream());
            document.open();

            // Loading MC //
            PdfPTable table = new PdfPTable(1);
            table.setWidthPercentage(100);
            // the cell object
            PdfPCell cell;

            Image img = Image.getInstance(path);
            int indentation = 0;
            float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin()
                    - indentation) / img.getWidth()) * 100;
            img.scalePercent(scaler);
            //img.scaleAbsolute(80f, 80f);
            cell = new PdfPCell(img);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
            document.add(table);
            //-----------------------------------//
            document.close();
        } catch (DocumentException de) {
            throw new IOException(de.getMessage());
        }
    }

}

From source file:com.wabacusdemo.PdfInterceptor_dataexportpdfpage1_vp6.java

License:Open Source License

/**
 * PDF???/*from  w w  w.j  a  v  a2  s.c om*/
 */
public void displayPerColDataWithoutTemplate(AbsReportType reportTypeObj, Object configbean, int rowidx,
        String value, PdfPCell cell) {
    if (!(configbean instanceof ColBean)) {//??<group/>
        return;
    }
    ReportRequest rrequest = reportTypeObj.getReportRequest();
    ColBean cbean = (ColBean) configbean;
    if ("photo".equals(cbean.getProperty()) && rowidx >= 0) {//????
        if (value != null && !value.trim().equals("")) {
            String serverName = rrequest.getRequest().getServerName();
            String serverPort = String.valueOf(rrequest.getRequest().getServerPort());
            while (value.startsWith("/"))
                value = value.substring(1).trim();
            value = "http://" + serverName + ":" + serverPort + "/" + value;//URL
            try {
                cell.setFixedHeight(50f);
                Image img = Image.getInstance(value);
                cell.setImage(img);//?URL?
                // cell.addElement(new Paragraph(newvalue,font));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.wabacusdemo.PdfInterceptor_dataexportpdfpage1_vp7.java

License:Open Source License

/**
 * ?PDF??PDF?/*  w w w . j  a  v a2 s .  co  m*/
 * ???
 */
public void afterDisplayPdfPageWithoutTemplate(Document document, AbsReportType reportTypeObj) {
    super.afterDisplayPdfPageWithoutTemplate(document, reportTypeObj);
    ReportRequest rrequest = reportTypeObj.getReportRequest();
    String serverName = rrequest.getRequest().getServerName();
    String serverPort = String.valueOf(rrequest.getRequest().getServerPort());
    String imgurl = "http://" + serverName + ":" + serverPort + Config.webroot
            + "wabacusdemo/pdftemplate/logo.gif";//?URL
    try {
        Image img = Image.getInstance(imgurl);
        float width = document.getPageSize().getWidth();
        float height = document.getPageSize().getHeight();
        //width = width - img.getWidth();
        img.setAbsolutePosition(width / 2, height / 2 + 300f);
        img.setAlignment(Image.ALIGN_CENTER);
        document.add(img);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.workhub.utils.PDFUtils.java

private static void addContent(Document document, List<ElementModel> models) throws DocumentException {
    for (int i = 0; i < models.size(); i++) {
        ElementModel elementModel = models.get(i);
        Anchor anchor = new Anchor(elementModel.getTitle(), catFont);
        anchor.setName(elementModel.getTitle());
        // Second parameter is the number of the chapter
        Chapter catPart = new Chapter(new Paragraph(anchor), i + 1);

        Paragraph content = new Paragraph();
        catPart.add(content);//from   w  ww  .  j a  v  a 2  s . co  m
        addEmptyLine(content, 2);

        switch (elementModel.getType()) {
        case Constants.TYPE_ELEMENT_TEXT:
            content.add(new Paragraph(((TextElementModel) elementModel).getContent(), smallBold));

            break;
        case Constants.TYPE_ELEMENT_LINK:
            content.add(new Paragraph(((LinkElementModel) elementModel).getContent(), smallBold));

            break;
        case Constants.TYPE_ELEMENT_PICTURE:
            Image image1;
            try {
                if (((PictureElementModel) elementModel).getContent() != null) {
                    image1 = Image.getInstance(((PictureElementModel) elementModel).getContent());

                    content.add(image1);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        case Constants.TYPE_ELEMENT_FILE:
            content.add(new Paragraph(((FileElementModel) elementModel).getTitle(), smallBold));
            break;

        }

        document.add(catPart);
    }

}