Example usage for org.apache.pdfbox.pdmodel.common PDRectangle PDRectangle

List of usage examples for org.apache.pdfbox.pdmodel.common PDRectangle PDRectangle

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel.common PDRectangle PDRectangle.

Prototype

public PDRectangle(float width, float height) 

Source Link

Document

Constructor.

Usage

From source file:merge_split.MergeSplit.java

License:Apache License

private void RotateButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RotateButton1ActionPerformed
    PDDocument document = new PDDocument();
    InputStream in = null;//from   ww w .  j av  a 2  s  .  c  om
    BufferedImage bimg = null;

    try {
        in = new FileInputStream((String) ImageFileField.getText());

        bimg = ImageIO.read(in);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Image could not be read.", "Image could not be read",
                JOptionPane.WARNING_MESSAGE);
    }
    float width = bimg.getWidth();
    float height = bimg.getHeight();
    PDPage page = new PDPage(new PDRectangle(width, height));
    document.addPage(page);
    PDImageXObject imgpdf;
    try {
        imgpdf = PDImageXObject.createFromFile((String) ImageFileField.getText(), document);

        try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
            contentStream.drawImage(imgpdf, 0, 0);
        }

        in.close();
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Image could not be converted.", "Proccess could not be finished",
                JOptionPane.WARNING_MESSAGE);
    }
    String destination = ImageDestinationField.getText() + "\\" + ImageNameField.getText() + ".pdf";
    PDDocumentInformation info = document.getDocumentInformation();
    info.setAuthor(ImageAuthorField.getText());
    File output = new File(destination);

    try {
        document.save(output);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Not all fields were filled.", "Input Problem",
                JOptionPane.WARNING_MESSAGE);
    }
    try {
        document.close();
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Not all fields were filled.", "Input Problem",
                JOptionPane.WARNING_MESSAGE);
    }
}

From source file:model.objects.Project.java

License:Apache License

/**
 * /*from w  w  w.  j a v a2s.c o m*/
 * @param _doc
 * @param _bi
 * @param _pageindex       index of page to which the BufferedImage is 
 *                      inserted.
 *                      If it is equal to -1, new page is created.
 *                   
 */
public void attatchToPDF(final PDDocument _doc, final BufferedImage _bi, final int _pageindex) {
    PDPage page = null;
    try {
        if (_pageindex == -1) {
            page = new PDPage(new PDRectangle(State.getImageSize().width, State.getImageSize().height));

            _doc.addPage(page);
        } else {
            page = _doc.getPage(_pageindex);
            //             page.setCropBox(new PDRectangle(State.getImageSize().width , 
            //                   State.getImageSize().height ));

        }

        int width = (int) page.getCropBox().getWidth();
        int height = (int) page.getCropBox().getHeight();

        PDImageXObject ximage = LosslessFactory.createFromImage(_doc,
                //                 _bi);
                Utils.resizeImage(width, height, _bi));

        PDPageContentStream content = new PDPageContentStream(_doc, page, true, true);

        // contentStream.drawImage(ximage, 20, 20 );
        // better method inspired by http://stackoverflow.com/a/22318681/535646
        // reduce this value if the image is too large
        float scale = 1f;
        content.drawImage(ximage, 20, 20, ximage.getWidth() * scale, ximage.getHeight() * scale);

        content.close();
        //  LosslessFactory.createFromImage(doc, bim)
        //              content.drawImage(ximage, 0, 0);
        //              content.close();
    } catch (IOException ie) {
        //handle exception
    }
}

From source file:org.apache.openmeetings.web.room.wb.WbPanel.java

License:Apache License

@Override
protected void processWbAction(WbAction a, JSONObject obj, AjaxRequestTarget target) throws IOException {
    Client c = rp.getClient();//from  ww  w  .  j  av a  2  s. co m
    if (c == null) {
        return;
    }
    switch (a) {
    case createObj:
    case modifyObj: {
        JSONObject o = obj.optJSONObject("obj");
        if (o != null && "pointer".equals(o.getString(ATTR_TYPE))) {
            sendWbOthers(a, obj);
            return;
        }
    }
        break;
    case downloadPdf: {
        boolean moder = c.hasRight(Room.Right.moderator);
        Room r = rp.getRoom();
        if ((moder && !r.isHidden(RoomElement.ActionMenu)) || (!moder && r.isAllowUserQuestions())) {
            try (PDDocument doc = new PDDocument()) {
                JSONArray arr = obj.getJSONArray("slides");
                for (int i = 0; i < arr.length(); ++i) {
                    String base64Image = arr.getString(i).split(",")[1];
                    byte[] bb = Base64.decodeBase64(base64Image);
                    BufferedImage img = ImageIO.read(new ByteArrayInputStream(bb));
                    float width = img.getWidth();
                    float height = img.getHeight();
                    PDPage page = new PDPage(new PDRectangle(width, height));
                    PDImageXObject pdImageXObject = LosslessFactory.createFromImage(doc, img);
                    try (PDPageContentStream contentStream = new PDPageContentStream(doc, page,
                            AppendMode.APPEND, false)) {
                        contentStream.drawImage(pdImageXObject, 0, 0, width, height);
                    }
                    doc.addPage(page);
                }
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                doc.save(baos);
                rp.startDownload(target, baos.toByteArray());
            }
        }
        return;
    }
    case loadVideos: {
        StringBuilder sb = new StringBuilder("WbArea.initVideos(");
        JSONArray arr = new JSONArray();
        for (Entry<Long, Whiteboard> entry : wbm.list(roomId)) {
            Whiteboard wb = entry.getValue();
            for (JSONObject o : wb.list()) {
                String ft = o.optString(ATTR_FILE_TYPE);
                if (BaseFileItem.Type.Recording.name().equals(ft)
                        || BaseFileItem.Type.Video.name().equals(ft)) {
                    JSONObject _sts = o.optJSONObject(PARAM_STATUS);
                    if (_sts == null) {
                        continue;
                    }
                    JSONObject sts = new JSONObject(_sts.toString()); //copy
                    sts.put("pos", sts.getDouble("pos")
                            + (System.currentTimeMillis() - sts.getLong(PARAM_UPDATED)) * 1. / 1000);
                    arr.put(new JSONObject().put("wbId", wb.getId()).put("uid", o.getString("uid"))
                            .put(ATTR_SLIDE, o.getString(ATTR_SLIDE)).put(PARAM_STATUS, sts));
                }
            }
        }
        sb.append(arr.toString()).append(");");
        target.appendJavaScript(sb);
        return;
    }
    default:
        break;
    }

    //presenter-right
    if (c.hasRight(Right.presenter)) {
        switch (a) {
        case createWb: {
            Whiteboard wb = wbm.add(roomId, c.getUser().getLanguageId());
            sendWbAll(WbAction.createWb, getAddWbJson(wb));
        }
            break;
        case removeWb: {
            long id = obj.optLong("wbId", -1);
            if (id > -1) {
                wbm.remove(roomId, id);
                sendWbAll(WbAction.removeWb, obj);
            }
        }
            break;
        case activateWb: {
            long _id = obj.optLong("wbId", -1);
            if (_id > -1) {
                wbm.activate(roomId, _id);
                sendWbAll(WbAction.activateWb, obj);
            }
        }
            break;
        case renameWb: {
            Whiteboard wb = wbm.get(roomId).get(obj.optLong("wbId", -1));
            if (wb != null) {
                wbm.update(roomId, wb.setName(obj.getString("name")));
                sendWbAll(WbAction.renameWb, obj);
            }
        }
            break;
        case setSlide: {
            Whiteboard wb = wbm.get(roomId).get(obj.optLong("wbId", -1));
            if (wb != null) {
                wb.setSlide(obj.optInt(ATTR_SLIDE, 0));
                wbm.update(roomId, wb);
                sendWbOthers(WbAction.setSlide, obj);
            }
        }
            break;
        case clearAll: {
            clearAll(roomId, obj.getLong("wbId"));
        }
            break;
        case setSize: {
            Whiteboard wb = wbm.get(roomId).get(obj.getLong("wbId"));
            wb.setWidth(obj.getInt(ATTR_WIDTH));
            wb.setHeight(obj.getInt(ATTR_HEIGHT));
            wb.setZoom(obj.getDouble(ATTR_ZOOM));
            wb.setZoomMode(ZoomMode.valueOf(obj.getString("zoomMode")));
            wbm.update(roomId, wb);
            sendWbOthers(WbAction.setSize, getAddWbJson(wb));
        }
            break;
        default:
            break;
        }
    }
    //wb-right
    if (c.hasRight(Right.presenter) || c.hasRight(Right.whiteBoard)) {
        switch (a) {
        case createObj: {
            Whiteboard wb = wbm.get(roomId).get(obj.getLong("wbId"));
            JSONObject o = obj.getJSONObject("obj");
            wb.put(o.getString("uid"), o);
            wbm.update(roomId, wb);
            addUndo(wb.getId(), new UndoObject(UndoObject.Type.add, o));
            sendWbOthers(WbAction.createObj, obj);
        }
            break;
        case modifyObj: {
            Whiteboard wb = wbm.get(roomId).get(obj.getLong("wbId"));
            JSONArray arr = obj.getJSONArray("obj");
            JSONArray undo = new JSONArray();
            for (int i = 0; i < arr.length(); ++i) {
                JSONObject _o = arr.getJSONObject(i);
                String uid = _o.getString("uid");
                JSONObject po = wb.get(uid);
                if (po != null) {
                    undo.put(po);
                    wb.put(uid, _o);
                }
            }
            if (arr.length() != 0) {
                wbm.update(roomId, wb);
                addUndo(wb.getId(), new UndoObject(UndoObject.Type.modify, undo));
            }
            sendWbOthers(WbAction.modifyObj, obj);
        }
            break;
        case deleteObj: {
            Whiteboard wb = wbm.get(roomId).get(obj.getLong("wbId"));
            JSONArray arr = obj.getJSONArray("obj");
            JSONArray undo = new JSONArray();
            for (int i = 0; i < arr.length(); ++i) {
                JSONObject _o = arr.getJSONObject(i);
                JSONObject u = wb.remove(_o.getString("uid"));
                if (u != null) {
                    undo.put(u);
                }
            }
            if (undo.length() != 0) {
                wbm.update(roomId, wb);
                addUndo(wb.getId(), new UndoObject(UndoObject.Type.remove, undo));
            }
            sendWbAll(WbAction.deleteObj, obj);
        }
            break;
        case clearSlide: {
            Whiteboard wb = wbm.get(roomId).get(obj.getLong("wbId"));
            JSONArray arr = wb.clearSlide(obj.getInt(ATTR_SLIDE));
            if (arr.length() != 0) {
                wbm.update(roomId, wb);
                addUndo(wb.getId(), new UndoObject(UndoObject.Type.remove, arr));
            }
            sendWbAll(WbAction.clearSlide, obj);
        }
            break;
        case save:
            wb2save = obj.getLong("wbId");
            fileName.open(target);
            break;
        case undo: {
            Long wbId = obj.getLong("wbId");
            UndoObject uo = getUndo(wbId);
            if (uo != null) {
                Whiteboard wb = wbm.get(roomId).get(wbId);
                switch (uo.getType()) {
                case add: {
                    JSONObject o = new JSONObject(uo.getObject());
                    wb.remove(o.getString("uid"));
                    wbm.update(roomId, wb);
                    sendWbAll(WbAction.deleteObj, obj.put("obj", new JSONArray().put(o)));
                }
                    break;
                case remove: {
                    JSONArray arr = new JSONArray(uo.getObject());
                    for (int i = 0; i < arr.length(); ++i) {
                        JSONObject o = arr.getJSONObject(i);
                        wb.put(o.getString("uid"), o);
                    }
                    wbm.update(roomId, wb);
                    sendWbAll(WbAction.createObj, obj.put("obj", new JSONArray(uo.getObject())));
                }
                    break;
                case modify: {
                    JSONArray arr = new JSONArray(uo.getObject());
                    for (int i = 0; i < arr.length(); ++i) {
                        JSONObject o = arr.getJSONObject(i);
                        wb.put(o.getString("uid"), o);
                    }
                    wbm.update(roomId, wb);
                    sendWbAll(WbAction.modifyObj, obj.put("obj", arr));
                }
                    break;
                }
            }
        }
            break;
        case videoStatus: {
            Whiteboard wb = wbm.get(roomId).get(obj.getLong("wbId"));
            String uid = obj.getString("uid");
            JSONObject po = wb.get(uid);
            if (po != null && "video".equals(po.getString(ATTR_TYPE))) {
                JSONObject ns = obj.getJSONObject(PARAM_STATUS);
                po.put(PARAM_STATUS, ns.put(PARAM_UPDATED, System.currentTimeMillis()));
                wbm.update(roomId, wb.put(uid, po));
                obj.put(ATTR_SLIDE, po.getInt(ATTR_SLIDE));
                sendWbAll(WbAction.videoStatus, obj);
            }
        }
            break;
        default:
            break;
        }
    }
}

From source file:org.primaresearch.pdf.PageToPdfConverterUsingPdfBox.java

License:Apache License

private void addPage(PDDocument doc, Page page) {
    try {//from   w w  w  .  jav a  2 s .c o m
        // Create a new blank page and add it to the document

        //TODO Use image DPI and size
        //The measurement unit of the PDF is point (1 Point = 0.0352777778 cm)
        //For now: Set the PDF size to the PAGE size (1px = 1pt)
        //PDPage pdfPage = new PDPage(PDPage.PAGE_SIZE_A4); 
        PDPage pdfPage = new PDPage(new PDRectangle(page.getLayout().getWidth(), page.getLayout().getHeight()));
        doc.addPage(pdfPage);

        if (DEBUG) {
            System.out.println("Mediabox width: " + pdfPage.getMediaBox().getWidth());
            System.out.println("Mediabox height: " + pdfPage.getMediaBox().getHeight());
        }

        // Start a new content stream which will "hold" the to be created content
        PDPageContentStream contentStream = new PDPageContentStream(doc, pdfPage);

        try {
            addText(contentStream, page);
            // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
            //contentStream.beginText();
            //contentStream.setFont( font, 12 );
            //contentStream.moveTextPositionByAmount( 100, 700 );
            //contentStream.drawString( "Hello World" );
            //contentStream.endText();
        } finally {
            // Make sure that the content stream is closed:
            contentStream.close();
        }
    } catch (Exception exc) {
        exc.printStackTrace();
    }

}

From source file:org.qi4j.envisage.print.PDFWriter.java

License:Apache License

private void writeGraphPage(GraphDisplay graphDisplay) throws IOException {
    File tFile = File.createTempFile("envisage", "png");
    graphDisplay.saveImage(new FileOutputStream(tFile), "png", 1d);

    BufferedImage img = ImageIO.read(tFile);

    int w = img.getWidth();
    int h = img.getHeight();

    int inset = 40;
    PDRectangle pdRect = new PDRectangle(w + inset, h + inset);
    PDPage page = new PDPage();
    page.setMediaBox(pdRect);/*from   www  .j  a  v a2s . c  o  m*/
    doc.addPage(page);

    PDJpeg xImage = new PDJpeg(doc, img);

    PDPageContentStream contentStream = new PDPageContentStream(doc, page);
    contentStream.drawImage(xImage, (pdRect.getWidth() - w) / 2, (pdRect.getHeight() - h) / 2);
    contentStream.close();
}

From source file:org.wangwei.pdf.hexpdf.HexPDF2.java

License:Apache License

/**
 * Sole constructor, creates a new instance of HexPDF.
 *//*from www .ja  v  a  2 s  . c  om*/
public HexPDF2() {
    super();
    ignorePagebleed = false;
    numPages = 0;
    rightMargin = 50f;
    leftMargin = 50f;
    bottomMargin = 50f;
    topMargin = 50f;
    fontSize = 8;
    font = PDType1Font.COURIER;
    pageSize = new PDRectangle(288, 288);
    // pageSize = PDPage.PAGE_SIZE_A4;
    normalColor = Color.black;
    titleColor = Color.BLUE;
    // orientation = HexPDF2.PORTRAIT; //
    orientation = HexPDF2.LANDSCAPE; // 
    // firstPage();
}

From source file:pl.vane.pdf.factory.PDFFactory.java

License:Open Source License

public static PDDocument create(PDFDocument pdf) throws IOException {

    log.trace("--- pdf start");
    PDDocument document = new PDDocument();

    log.trace("--- load fonts");

    Map<Integer, PDFont> fonts = loadFonts(pdf.getFont(), document);

    for (PDFPage data : pdf.getPage()) {
        // create page with size
        PDPage page = new PDPage();
        PDFPageSize size = data.getSize();
        PDRectangle mediaBox = new PDRectangle(size.getWidth(), size.getHeight());
        page.setMediaBox(mediaBox);/*from   ww w  . ja  v a  2  s. c  o m*/
        document.addPage(page);
        // create content
        PDPageContentStream stream = new PDPageContentStream(document, page);
        for (PDFContent content : data.getContent()) {
            if (content instanceof PDFTextContent) {
                PDFTextContent txt = (PDFTextContent) content;
                PDFont font = fonts.get(txt.getFontId());
                Point p = txt.getStart();
                PDFWriter.drawString(stream, font, txt.getFontSize(), txt.getLeading(), p.getX(), p.getY(),
                        txt.getText());
            }
        }
        stream.close();
    }

    log.trace("--- pdf end");

    return document;
}

From source file:pptxtopdf.TestPptxToPdf.java

public static void main(String[] args)
        throws FileNotFoundException, IOException, COSVisitorException, OpenXML4JException {
    // TODO code application logic here
    String filepath = "/home/sagar/Desktop/Shareback/test.pptx";
    FileInputStream is = new FileInputStream(filepath);
    XMLSlideShow pptx = new XMLSlideShow(is);
    Dimension pgsize = pptx.getPageSize();

    int idx = 1;//from  w w w  . j  a v a  2 s  .c  om
    for (XSLFSlide slide : pptx.getSlides()) {

        BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = img.createGraphics();
        // clear the drawing area
        graphics.setPaint(Color.white);
        graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));

        // render
        slide.draw(graphics);

        // save the output
        FileOutputStream out = new FileOutputStream("/home/sagar/Desktop/Shareback/img/slide-" + idx + ".jpg");
        javax.imageio.ImageIO.write(img, "jpg", out);
        out.close();

        idx++;
    }

    String someimg = "/home/sagar/Desktop/Shareback/pptx/img/";

    PDDocument document = new PDDocument();
    File file = new File(someimg);
    if (!file.exists())
        file.mkdir();

    if (file.isDirectory()) {
        for (File f : file.listFiles()) {

            InputStream in = new FileInputStream(f);

            BufferedImage bimg = ImageIO.read(in);
            float width = bimg.getWidth();
            float height = bimg.getHeight();
            PDPage page = new PDPage(new PDRectangle(width + 10, height + 10));
            document.addPage(page);
            PDXObjectImage img = new PDJpeg(document, new FileInputStream(f));
            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            contentStream.drawImage(img, 0, 0);
            contentStream.close();
            in.close();
        }

        document.save("/home/sagar/Desktop/Shareback/test-generated-pptx.pdf");
        document.close();
    } else {
        System.out.println(someimg + "is not a Directory");
    }

}

From source file:testppttopdf.TestPptToPdf.java

/**
 * @param args the command line arguments
 *///from  w  w  w .  j  a  va 2s.c o m
public static void main(String[] args) throws FileNotFoundException, IOException, COSVisitorException {
    // TODO code application logic here
    FileInputStream is = new FileInputStream("/home/sagar/Desktop/Shareback/test.ppt");
    HSLFSlideShow ppt = new HSLFSlideShow(is);
    is.close();

    Dimension pgsize = ppt.getPageSize();

    int idx = 1;
    for (HSLFSlide slide : ppt.getSlides()) {

        BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = img.createGraphics();
        // clear the drawing area
        graphics.setPaint(Color.white);
        graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));

        // render
        slide.draw(graphics);

        // save the output
        FileOutputStream out = new FileOutputStream("/home/sagar/Desktop/Shareback/img/slide-" + idx + ".jpg");
        javax.imageio.ImageIO.write(img, "jpg", out);
        out.close();

        idx++;
    }

    String someimg = "/home/sagar/Desktop/Shareback/img/";

    PDDocument document = new PDDocument();
    File file = new File(someimg);
    if (file.isDirectory()) {
        for (File f : file.listFiles()) {

            InputStream in = new FileInputStream(f);

            BufferedImage bimg = ImageIO.read(in);
            float width = bimg.getWidth();
            float height = bimg.getHeight();
            PDPage page = new PDPage(new PDRectangle(width + 10, height + 10));
            document.addPage(page);
            PDXObjectImage img = new PDJpeg(document, new FileInputStream(f));
            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            contentStream.drawImage(img, 0, 0);
            contentStream.close();
            in.close();
        }

        document.save("/home/sagar/Desktop/Shareback/test-generated.pdf");
        document.close();
    } else {
        System.out.println(someimg + "is not a Directory");
    }

}

From source file:testppttopdf.TestPptToPdf.java

static void testPptxToPdf() {
    String filepath = "/home/sagar/Desktop/Shareback/test.pptx";
    FileInputStream is;/*from   w  w  w.  j  a  v  a2  s  .co  m*/
    try {
        is = new FileInputStream(filepath);

        XMLSlideShow pptx = new XMLSlideShow(is);
        Dimension pgsize = pptx.getPageSize();

        int idx = 1;
        for (XSLFSlide slide : pptx.getSlides()) {

            BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = img.createGraphics();
            // clear the drawing area
            graphics.setPaint(Color.white);
            graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));

            // render
            slide.draw(graphics);

            // save the output
            FileOutputStream out = new FileOutputStream(
                    "/home/sagar/Desktop/Shareback/img/slide-" + idx + ".jpg");
            javax.imageio.ImageIO.write(img, "jpg", out);
            out.close();

            idx++;
        }

        String someimg = "/home/sagar/Desktop/Shareback/pptx/img/";

        PDDocument document = new PDDocument();
        File file = new File(someimg);
        if (!file.exists())
            file.mkdir();

        if (file.isDirectory()) {
            for (File f : file.listFiles()) {

                InputStream in = new FileInputStream(f);

                BufferedImage bimg = ImageIO.read(in);
                float width = bimg.getWidth();
                float height = bimg.getHeight();
                PDPage page = new PDPage(new PDRectangle(width + 10, height + 10));
                document.addPage(page);
                PDXObjectImage img = new PDJpeg(document, new FileInputStream(f));
                PDPageContentStream contentStream = new PDPageContentStream(document, page);
                contentStream.drawImage(img, 0, 0);
                contentStream.close();
                in.close();
            }

            document.save("/home/sagar/Desktop/Shareback/test-generated-pptx.pdf");
            document.close();
        } else {
            System.out.println(someimg + "is not a Directory");
        }

    } catch (Exception ex) {
        Logger.getLogger(TestPptToPdf.class.getName()).log(Level.SEVERE, null, ex);
    }
}