Example usage for org.apache.pdfbox.rendering PDFRenderer PDFRenderer

List of usage examples for org.apache.pdfbox.rendering PDFRenderer PDFRenderer

Introduction

In this page you can find the example usage for org.apache.pdfbox.rendering PDFRenderer PDFRenderer.

Prototype

public PDFRenderer(PDDocument document) 

Source Link

Document

Creates a new PDFRenderer.

Usage

From source file:org.saiku.web.rest.resources.ExporterResource.java

License:Apache License

/**
 * Export chart to a file./*from  ww w  .  j av  a 2s  .co m*/
 * @summary Export Chart.
 * @param type The export type (png, svg, jpeg)
 * @param svg The SVG
 * @param size The size
 * @param name The name
 * @return A reponse containing the chart export.
 */
@POST
@Produces({ "image/*" })
@Path("/saiku/chart")
public Response exportChart(@FormParam("type") @DefaultValue("png") String type, @FormParam("svg") String svg,
        @FormParam("size") Integer size, @FormParam("name") String name) {
    try {
        final String imageType = type.toUpperCase();
        Converter converter = Converter.byType("PDF");
        if (converter == null) {
            throw new Exception("Image convert is null");
        }

        //             resp.setContentType(converter.getContentType());
        //             resp.setHeader("Content-disposition", "attachment; filename=chart." + converter.getExtension());
        //             final Integer size = req.getParameter("size") != null? Integer.parseInt(req.getParameter("size")) : null;
        //             final String svgDocument = req.getParameter("svg");
        //             if (svgDocument == null)
        //             {
        //                 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'svg' parameter");
        //                 return;
        //             }
        if (StringUtils.isBlank(svg)) {
            throw new Exception("Missing 'svg' parameter");
        }
        final InputStream in = new ByteArrayInputStream(svg.getBytes("UTF-8"));
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        converter.convert(in, out, size);
        out.flush();
        byte[] doc = out.toByteArray();
        byte[] b = null;
        if (getVersion() != null && !getVersion().contains("EE")) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            PdfReader reader = new PdfReader(doc);
            PdfStamper pdfStamper = new PdfStamper(reader, baos);

            URL dir_url = ExporterResource.class.getResource("/org/saiku/web/svg/watermark.png");
            Image image = Image.getInstance(dir_url);

            for (int i = 1; i <= reader.getNumberOfPages(); i++) {

                PdfContentByte content = pdfStamper.getOverContent(i);

                image.setAbsolutePosition(450f, 280f);
                /*image.setAbsolutePosition(reader.getPageSize(1).getWidth() - image.getScaledWidth(), reader.getPageSize
                   (1).getHeight() - image.getScaledHeight());*/
                //image.setAlignment(Image.MIDDLE);
                content.addImage(image);
            }
            pdfStamper.close();
            b = baos.toByteArray();
        } else {
            b = doc;
        }

        if (!type.equals("pdf")) {

            PDDocument document = PDDocument.load(new ByteArrayInputStream(b), null);

            PDPageTree pdPages = document.getDocumentCatalog().getPages();
            PDPage page = pdPages.get(0);
            BufferedImage o = new PDFRenderer(document).renderImage(0);
            ByteArrayOutputStream imgb = new ByteArrayOutputStream();
            String ct = "";
            String ext = "";
            if (type.equals("png")) {
                ct = "image/png";
                ext = "png";
            } else if (type.equals("jpg")) {
                ct = "image/jpg";
                ext = "jpg";
            }
            ImageIO.write(o, type, imgb);
            byte[] outfile = imgb.toByteArray();
            if (name == null || name.equals("")) {
                name = "chart";
            }
            return Response.ok(outfile).type(ct)
                    .header("content-disposition", "attachment; filename = " + name + "." + ext)
                    .header("content-length", outfile.length).build();
        } else {
            if (name == null || name.equals("")) {
                name = "chart";
            }
            return Response.ok(b).type(converter.getContentType())
                    .header("content-disposition",
                            "attachment; filename = " + name + "." + converter.getExtension())
                    .header("content-length", b.length).build();
        }
    } catch (Exception e) {
        log.error("Error exporting Chart to  " + type, e);
        return Response.serverError().entity(e.getMessage()).status(Status.INTERNAL_SERVER_ERROR).build();
    }
}

From source file:org.silverpeas.core.util.PdfUtil.java

License:Open Source License

/**
 * Converts the first page of a PDF file into a JPEG image.
 * @param pdfSource the source pdf file, this content is not modified by this method.
 * @param imageDestination the destination file of the image representing the first page.
 *//*from ww w .j  a v  a  2s  . c  o  m*/
public static void firstPageAsImage(File pdfSource, File imageDestination) {
    if (pdfSource == null || !pdfSource.isFile()) {
        throw new SilverpeasRuntimeException(PDF_FILE_ERROR_MSG);
    } else if (!FileUtil.isPdf(pdfSource.getPath())) {
        throw new SilverpeasRuntimeException(NOT_PDF_FILE_ERROR_MSG);
    }
    try (final PDDocument document = PDDocument.load(pdfSource)) {
        final PDFRenderer pdfRenderer = new PDFRenderer(document);
        final BufferedImage image = pdfRenderer.renderImage(0);
        ImageIO.write(image, "jpg", imageDestination);
    } catch (Exception e) {
        SilverLogger.getLogger(PdfUtil.class).error(e);
        throw new SilverpeasRuntimeException(
                "A problem has occurred during the adding of an image into a pdf file", e);
    }
}

From source file:pdf.DailyReportPDF.java

public void createDailyReportPNG(String path) throws IOException {
    File file = new File(path);
    PDDocument doc = PDDocument.load(file);
    PDFRenderer renderer = new PDFRenderer(doc);
    BufferedImage image = renderer.renderImage(0);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy.");
    ImageIO.write(image, "PNG",
            new File("pdf_docs\\daily_reports_picture\\" + "drpic-" + sdf.format(dateOfDailyReport) + ".png"));
    doc.close();//from  w w  w .java  2  s .  c o  m
}

From source file:pdf.NormativPDF.java

public void createNormativPNG(String path) throws IOException {
    File file = new File(path);
    PDDocument doc = PDDocument.load(file);
    PDFRenderer renderer = new PDFRenderer(doc);
    BufferedImage image = renderer.renderImage(0);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy.");
    ImageIO.write(image, "PNG", new File(
            "pdf_docs\\normativ_picture\\" + product.getName() + "-" + sdf.format(dateNormativ) + ".png"));
    doc.close();//  w  w w.j  av a  2  s .c o m
}

From source file:pdf.PDFWindow.java

private void getImages(PDDocument doc) {
    PDFRenderer pdfRenderer = new PDFRenderer(doc);
    images = new ArrayList();
    int numberOfPages = doc.getNumberOfPages();

    Thread thread = new Thread(new Runnable() {
        public void run() {
            for (int page = 0; page < numberOfPages; ++page) {
                BufferedImage bim;
                i = page;// w  w  w . java2s .  c om
                try {
                    bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
                    images.add(bim);
                } catch (IOException ex) {
                    Logger.getLogger(PDFWindow.class.getName()).log(Level.SEVERE, null, ex);
                }
                displayPage();
                try {
                    java.lang.Thread.sleep(100);
                } catch (Exception e) {
                }
            }
        }
    });
    thread.start();
}

From source file:pdf.StockItemsPDF.java

public void createStockItemsPNG(String path) throws IOException {
    File file = new File(path);
    PDDocument doc = PDDocument.load(file);
    PDFRenderer renderer = new PDFRenderer(doc);
    BufferedImage image = renderer.renderImage(0);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy.");
    ImageIO.write(image, "PNG",
            new File("pdf_docs\\stock_items_picture\\" + "sipic-" + sdf.format(dateOfWriteOff) + ".png"));
    doc.close();/* w  w  w  .ja va 2s . co  m*/
}

From source file:pdf.SuppliesListPDF.java

public void createDailyReportPNG(String path) throws IOException {
    File file = new File(path);
    PDDocument doc = PDDocument.load(file);
    PDFRenderer renderer = new PDFRenderer(doc);
    BufferedImage image = renderer.renderImage(0);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy.");
    ImageIO.write(image, "PNG",
            new File("pdf_docs\\lager_lists_picture\\" + "llpic-" + dateSuppliesList.getTime() + ".png"));
    doc.close();//  ww w  .ja v  a2 s .  c  o m
}

From source file:pdf.WorkOrderPDF.java

public static void main(String[] args) throws IOException {
    //DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    //System.out.println(dtf.format(java.time.LocalDateTime.now()));;

    File file = new File("pdf_docs\\work_orders\\work_order_template.pdf");

    PDDocument doc = PDDocument.load(file);
    PDFRenderer renderer = new PDFRenderer(doc);
    BufferedImage image = renderer.renderImage(0);
    ImageIO.write(image, "PNG", new File("pdf_docs\\work_orders_picture\\" + "wopic.png"));
    doc.close();/*from  w  w  w  .j  a  v  a2  s  .c  o  m*/
}

From source file:pdf.WorkOrderPDF.java

public void createWorkOrderPNG(String path) throws IOException {
    File file = new File(path);
    PDDocument doc = PDDocument.load(file);
    PDFRenderer renderer = new PDFRenderer(doc);
    renderer.renderImageWithDPI(0, 600);
    BufferedImage image = renderer.renderImage(0);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy.");
    ImageIO.write(image, "PNG", new File("pdf_docs\\work_orders_picture\\" + "wopic-"
            + numOfWorkOrder.split("\\/")[0] + "_" + numOfWorkOrder.split("/")[1] + ".pdf"));
    doc.close();//w w  w. j  ava 2 s  .  co m

}

From source file:pdf.WriteOffMaterialsPDF.java

public void createWriteOffMaterialsPNG(String path) throws IOException {
    File file = new File(path);
    PDDocument doc = PDDocument.load(file);
    PDFRenderer renderer = new PDFRenderer(doc);
    BufferedImage image = renderer.renderImage(0);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy.");
    ImageIO.write(image, "PNG", new File(
            "pdf_docs\\write_off_materials_picture\\" + "wompic-" + sdf.format(dateOfWriteOff) + ".png"));
    doc.close();//from  w  w  w  .j  a  va 2s .co  m
}