Example usage for org.apache.pdfbox.pdmodel PDDocument addPage

List of usage examples for org.apache.pdfbox.pdmodel PDDocument addPage

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDDocument addPage.

Prototype

public void addPage(PDPage page) 

Source Link

Document

This will add a page to the document.

Usage

From source file:geotheme.pdf.generatePDF.java

License:Open Source License

public ByteArrayOutputStream createPDFFromImage(wmsParamBean wpb, String host)
        throws IOException, COSVisitorException {
    PDDocument doc = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    OutputStreamWriter wr = null;
    OutputStreamWriter wl = null;
    URLConnection geoConn = null;
    URLConnection legConn = null;

    int width = 500;
    int height = 500;

    wpb.setBBOX(retainAspectRatio(wpb.getBBOX()));

    StringBuffer sb = new StringBuffer();
    sb.append(this.pdfURL);
    sb.append("&layers=").append(this.pdfLayers);
    sb.append("&bbox=").append(wpb.getBBOX());
    sb.append("&Format=image/jpeg");
    sb.append("&width=").append(width);
    sb.append("&height=").append(height);

    try {//from  www.  j a v  a  2  s  . co m
        wpb.setREQUEST("GetMap");
        wpb.setWIDTH(Integer.toString(width));
        wpb.setHEIGHT(Integer.toString(height));

        URL url = new URL(host);
        URL urll = new URL(host);
        URL osm = new URL(sb.toString());

        geoConn = url.openConnection();
        geoConn.setDoOutput(true);

        legConn = urll.openConnection();
        legConn.setDoOutput(true);

        wr = new OutputStreamWriter(geoConn.getOutputStream(), "UTF-8");
        wr.write(wpb.getURL_PARAM());

        wr.flush();

        wpb.setREQUEST("GetLegendGraphic");
        wpb.setTRANSPARENT("FALSE");
        wpb.setWIDTH("");
        wpb.setHEIGHT("");

        wl = new OutputStreamWriter(legConn.getOutputStream(), "UTF-8");
        wl.write(wpb.getURL_PARAM() + "&legend_options=fontSize:9;");
        wl.flush();

        doc = new PDDocument();

        PDPage page = new PDPage(/*PDPage.PAGE_SIZE_A4*/);
        doc.addPage(page);

        BufferedImage img = ImageIO.read(geoConn.getInputStream());
        BufferedImage leg = ImageIO.read(legConn.getInputStream());

        PDXObjectImage ximage = new PDPixelMap(doc, img);
        PDXObjectImage xlegend = new PDPixelMap(doc, leg);
        PDXObjectImage xosm = new PDJpeg(doc, osm.openStream());

        PDPageContentStream contentStream = new PDPageContentStream(doc, page);

        PDFont font = PDType1Font.HELVETICA_OBLIQUE;

        contentStream.beginText();
        contentStream.setFont(font, 8);
        contentStream.moveTextPositionByAmount(450, 10);
        Date date = new Date();
        contentStream.drawString(date.toString());
        contentStream.endText();

        contentStream.beginText();
        contentStream.setFont(font, 8);
        contentStream.moveTextPositionByAmount(10, 10);
        contentStream.drawString("GeoFuse Report: mario.basa@gmail.com");
        contentStream.endText();

        contentStream.drawImage(xosm, 20, 160);
        contentStream.drawImage(ximage, 20, 160);
        contentStream.drawImage(xlegend, width - xlegend.getWidth() - 3, 170);

        contentStream.beginText();
        contentStream.setFont(font, 50);
        contentStream.moveTextPositionByAmount(20, 720);
        contentStream.drawString(wpb.getPDF_TITLE());
        contentStream.endText();

        contentStream.beginText();
        contentStream.setFont(font, 18);
        contentStream.moveTextPositionByAmount(20, 695);
        contentStream.drawString(wpb.getPDF_NOTE());
        contentStream.endText();

        contentStream.setStrokingColor(180, 180, 180);

        float bx[] = { 10f, 10f, 30 + width, 30 + width, 10f };
        float by[] = { 150f, 170 + height, 170 + height, 150f, 150f };
        contentStream.drawPolygon(bx, by);

        contentStream.close();

        doc.save(baos);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (doc != null) {
            doc.close();
        }

        if (wr != null) {
            wr.close();
        }

        if (wl != null) {
            wl.close();
        }
    }

    return baos;
}

From source file:GUI.Helper.PDFIOHelper.java

public static void writeSummaryReport(MainController mc) {

    mc.selectStep(6);/*from   w  ww  . ja  va2  s . com*/
    FileChooser fc = new FileChooser();
    fc.setTitle("Save WZITS Tool Project");
    fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File (.pdf)", "*.pdf"));
    if (mc.getProject().getSaveFile() != null) {
        File initDir = mc.getProject().getSaveFile().getParentFile();
        if (initDir.isDirectory()) {
            fc.setInitialDirectory(initDir);
        }
    }
    File saveFile = fc.showSaveDialog(MainController.getWindow()); //mc.getMainWindow()
    if (saveFile != null) {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                boolean exportSuccess = true;
                try {
                    PDDocument doc = new PDDocument();
                    for (int factSheetIdx = 1; factSheetIdx <= 8; factSheetIdx++) {

                        Node n = mc.goToFactSheet(factSheetIdx, true);
                        MainController.getStage().show();
                        BorderPane bp = (BorderPane) ((ScrollPane) n).getContent();

                        PDPage page = new PDPage();
                        doc.addPage(page);

                        PDPageContentStream content = new PDPageContentStream(doc, page);

                        WritableImage wi = bp.snapshot(new SnapshotParameters(), null);

                        double prefHeight = wi.getHeight();
                        double prefWidth = wi.getWidth();
                        BufferedImage bi = SwingFXUtils.fromFXImage(wi, null);

                        PDImageXObject ximage = LosslessFactory.createFromImage(doc, bi);
                        int drawWidth = (int) Math.min(MAX_DRAW_WIDTH, Math.round(WIDTH_FACTOR * prefWidth));
                        int drawHeight = (int) Math.round(HEIGHT_FACTOR * prefHeight);
                        int numPages = (int) Math.ceil(drawHeight / MAX_DRAW_HEIGHT);
                        drawHeight = (int) Math.min(MAX_DRAW_HEIGHT, drawHeight);
                        content.drawImage(ximage, MARGIN_LEFT_X, MARGIN_TOP_Y - drawHeight, drawWidth,
                                drawHeight);
                        content.fillAndStroke();
                        content.close();
                    }
                    drawReportHeaderFooter(doc, mc.getProject(), true);
                    doc.save(saveFile);
                    doc.close();
                } catch (IOException ie) {
                    System.out.println("ERROR");
                    exportSuccess = false;
                }
                if (exportSuccess) {
                    Alert al = new Alert(Alert.AlertType.CONFIRMATION);
                    al.setTitle("WZITS Tool");
                    al.setHeaderText("Fact sheet export successful");
                    al.showAndWait();
                } else {
                    Alert al = new Alert(Alert.AlertType.WARNING);
                    al.setTitle("WZITS Tool");
                    al.setHeaderText("Fact sheet export failed");
                    al.showAndWait();
                }
                mc.selectStep(6);
            }
        });
    }
}

From source file:GUI.Helper.PDFIOHelper.java

public static void writeStepSummary(MainController mc, int factSheetIdx) {
    Node n = mc.goToFactSheet(factSheetIdx, false);
    FileChooser fc = new FileChooser();
    fc.setTitle("Save WZITS Tool Project");
    fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File (.pdf)", "*.pdf"));
    if (mc.getProject().getSaveFile() != null) {
        File initDir = mc.getProject().getSaveFile().getParentFile();
        if (initDir.isDirectory()) {
            fc.setInitialDirectory(initDir);
        }/* w ww  . jav  a  2 s .  c  o  m*/
    }
    File saveFile = fc.showSaveDialog(MainController.getWindow()); //mc.getMainWindow()
    if (saveFile != null) {

        BorderPane bp = (BorderPane) ((ScrollPane) n).getContent();
        //Scene scene = new Scene(bp);
        //n.applyCss();
        //bp.applyCss();
        //WritableImage wi = scene.snapshot(null);

        WritableImage wi = bp.snapshot(new SnapshotParameters(), null);

        double prefHeight = wi.getHeight();
        double prefWidth = wi.getWidth();

        BufferedImage bi = SwingFXUtils.fromFXImage(wi, null);
        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);
        boolean exportSuccess = false;
        try {
            //ImageIO.write(bi, "png", new File("test.png"));
            PDPageContentStream content = new PDPageContentStream(doc, page);
            PDImageXObject ximage = LosslessFactory.createFromImage(doc, bi);
            int drawWidth = (int) Math.min(MAX_DRAW_WIDTH, Math.round(WIDTH_FACTOR * prefWidth));
            int drawHeight = (int) Math.round(HEIGHT_FACTOR * prefHeight);
            int numPages = (int) Math.ceil(drawHeight / MAX_DRAW_HEIGHT);
            drawHeight = (int) Math.min(MAX_DRAW_HEIGHT, drawHeight);
            content.drawImage(ximage, MARGIN_LEFT_X, MARGIN_TOP_Y - drawHeight, drawWidth, drawHeight);
            content.fillAndStroke();
            content.close();
            drawReportHeaderFooter(doc, mc.getProject(), true);
            doc.save(saveFile);
            doc.close();
            exportSuccess = true;
        } catch (IOException ie) {
            System.out.println("ERROR");
        }
        if (exportSuccess) {
            Alert al = new Alert(Alert.AlertType.CONFIRMATION);
            al.setTitle("WZITS Tool");
            al.setHeaderText("Fact sheet export successful");
            al.showAndWait();
        } else {
            Alert al = new Alert(Alert.AlertType.WARNING);
            al.setTitle("WZITS Tool");
            al.setHeaderText("Fact sheet export failed");
            al.showAndWait();
        }
    }
}

From source file:info.informationsea.venn.graphics.VennDrawPDF.java

License:Open Source License

public static <T> void draw(VennFigure<T> vennFigure, PDDocument doc) throws IOException {
    // based on https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/CreatePDFA.java?revision=1703059&view=markup
    PDFont font = PDType0Font.load(doc, VennDrawPDF.class.getResourceAsStream("../fx/mplus-1p-regular.ttf"));

    Rectangle2D drawRect = vennFigure.drawRect(str -> stringBoundingBox(font, str, FONT_SIZE));
    PDRectangle pageSize = new PDRectangle((float) drawRect.getWidth() + MARGIN * 2,
            (float) drawRect.getHeight() + MARGIN * 2);
    PDPage page = new PDPage(pageSize);
    doc.addPage(page);

    VennDrawPDF.draw(vennFigure, doc, page, font, pageSize);

    // PDF/A1b support
    /*//from w ww. j a  v  a 2 s . c  o  m
    // add XMP metadata
    XMPMetadata xmp = XMPMetadata.createXMPMetadata();
            
    try
    {
    DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();
    dc.setTitle("Venn Diagram");
    dc.setSource("VennDraw "+ VersionResolver.getVersion());
    dc.setDescription("Venn Diagram");
            
    PDFAIdentificationSchema id = xmp.createAndAddPFAIdentificationSchema();
    id.setPart(1);
    id.setConformance("B");
            
    XmpSerializer serializer = new XmpSerializer();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    serializer.serialize(xmp, baos, true);
            
    PDMetadata metadata = new PDMetadata(doc);
    metadata.importXMPMetadata(baos.toByteArray());
    doc.getDocumentCatalog().setMetadata(metadata);
    } catch(BadFieldValueException|TransformerException  e) {
    throw new RuntimeException(e);
    }
            
    // sRGB output intent
    InputStream colorProfile = VennDrawPDF.class.getResourceAsStream(
        "sRGB Color Space Profile.icm");
    PDOutputIntent intent = new PDOutputIntent(doc, colorProfile);
    intent.setInfo("sRGB IEC61966-2.1");
    intent.setOutputCondition("sRGB IEC61966-2.1");
    intent.setOutputConditionIdentifier("sRGB IEC61966-2.1");
    intent.setRegistryName("http://www.color.org");
    doc.getDocumentCatalog().addOutputIntent(intent);
    */
}

From source file:javaexample.RadialTextPdf.java

License:Open Source License

private void generatePage(PDDocument document) throws IOException {
    // Creates a new page.
    PDPage page = new PDPage(pageRect);
    document.addPage(page);

    // Gets boundings of the page.
    PDRectangle rect = page.getMediaBox();

    // Calculates the side of the square that fits into the page.
    float squareSide = Math.min(rect.getWidth(), rect.getHeight());

    // Calculates the center point of the page.
    float centerX = (rect.getLowerLeftX() + rect.getUpperRightX()) / 2;
    float centerY = (rect.getLowerLeftY() + rect.getUpperRightY()) / 2;

    PDPageContentStream cos = new PDPageContentStream(document, page);

    // Creates the font for the radial text.
    PDFont font = PDType1Font.HELVETICA_BOLD; // Standard font
    float fontSize = squareSide / 30;
    float fontAscent = font.getFontDescriptor().getAscent() / 1000 * fontSize;

    // Calculates key values for the drawings.
    float textX = squareSide / 3.4F; // x of the text.
    float textY = -fontAscent / 2; // y of the text (for vertical centering of text).
    float lineToX = textX * 0.97F; // x destination for the line.
    float lineWidth = squareSide / 900; // width of lines.

    // Moves the origin (0,0) of the axes to the center of the page.
    cos.concatenate2CTM(AffineTransform.getTranslateInstance(centerX, centerY));

    for (float degrees = 0; degrees < 360; degrees += 7.5) {
        double radians = degrees2Radians(degrees);

        // Creates a pure color with the hue based on the angle.
        Color textColor = Color.getHSBColor(degrees / 360.0F, 1, 1);

        // Saves the graphics state because the angle changes on each iteration.
        cos.saveGraphicsState();//  w w  w  .  j  a  v  a  2s .  c o m

        // Rotates the axes by the angle expressed in radians.
        cos.concatenate2CTM(AffineTransform.getRotateInstance(radians));

        // Draws a line from the center of the page.
        cos.setLineWidth(lineWidth);
        cos.moveTo(0, 0);
        cos.lineTo(lineToX, 0);
        cos.stroke();

        // Draws the radial text.
        cos.beginText();
        cos.setNonStrokingColor(textColor);
        cos.setFont(font, fontSize);
        cos.moveTextPositionByAmount(textX, textY);
        cos.drawString("PDF");
        cos.endText();

        // Restores the graphics state to remove rotation transformation.
        cos.restoreGraphicsState();
    }

    cos.close();
}

From source file:jlotoprint.PrintViewUIPanelController.java

public PDDocument generatePDF() throws Exception {

    PDDocument doc = null;
    PDPage page = null;/*from w w w . ja  v a2s .c o m*/
    PDPageContentStream content = null;

    try {
        doc = new PDDocument();
        List<Group> pageList = importPageList(Template.getSourceFile(), Template.getModel());
        for (Parent node : pageList) {

            page = new PDPage(PDPage.PAGE_SIZE_A4);

            doc.addPage(page);

            PDRectangle mediaBox = page.getMediaBox();
            float pageWidth = mediaBox.getWidth();
            float pageHeight = mediaBox.getHeight();

            node.setTranslateX(0);
            node.setTranslateY(0);
            node.setScaleX(1);
            node.setScaleY(1);
            node.applyCss();
            node.layout();
            HashMap<String, Double> result = resizeProportional(node.getBoundsInParent().getWidth(),
                    node.getBoundsInParent().getHeight(), pageWidth, pageHeight, true);

            //get node image
            WritableImage nodeImage = node.snapshot(null, null);
            BufferedImage bufferedImage = SwingFXUtils.fromFXImage(nodeImage, null);

            //set page content
            content = new PDPageContentStream(doc, page);

            PDJpeg image = new PDJpeg(doc, bufferedImage, 1f);
            content.drawXObject(image, 0, 0, result.get("width").intValue(), result.get("height").intValue());

            content.close();
        }
    } catch (Exception ex) {
        throw ex;
    } finally {
        try {
            if (content != null) {
                content.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    return doc;
}

From source file:johnbrooksupgrade.PDFService.java

private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
    Salesman = txtNewUser.getText().isEmpty() ? cmbSalesPerson.getSelectedItem().toString()
            : txtNewUser.getText();/*from w  w w .ja v a  2  s  .co  m*/
    Date = DateInput.getText();
    String ClientName = ClientnameInput.getText();
    String ProjectName = ProjectNameInput.getText();

    if (Branch == null) {
        JOptionPane.showMessageDialog(null, "Please Select a branch and try again.", "Error",
                JOptionPane.ERROR_MESSAGE);
    } else {
        /*** 
         * This is the logic that prints the information to a PDF 
         ***/

        //We want to save the file to Windows' temporary files folder so it can be loaded from there straight away
        //This temporary file is deleted when the program is exited
        File myfile = new File("C:\\Windows\\Temp\\ConveyorFile.pdf");

        //creates a new pdf
        if ((myfile) != null) {
            try {
                PDDocument doc;
                PDPage page;

                doc = new PDDocument();

                // Create a new blank page and add it to the document
                page = new PDPage();
                doc.addPage(page);
                PDFont font = PDType1Font.COURIER_BOLD;
                PDPageContentStream content = new PDPageContentStream(doc, page);
                content.beginText();
                content.setFont(font, 30);

                // creates a new page and gives it formatting of text
                content.moveTextPositionByAmount(110, 600);
                content.drawString("Technical Specifications ");
                PDFont font2 = PDType1Font.COURIER;
                content.setFont(font, 14);
                content.moveTextPositionByAmount(-50, -65);
                content.drawString("Date:" + Date);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Sales person: " + Salesman);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Client Name: " + ClientName);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Project Name: " + ProjectName);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Branch: " + Branch);
                content.moveTextPositionByAmount(0, -32);

                // Specifications    
                content.setFont(PDType1Font.COURIER_BOLD, 20);
                content.drawString("Specifications");
                content.moveTextPositionByAmount(0, -10);
                content.setFont(font, 14);
                content.moveTextPositionByAmount(10, -14);
                content.drawString("Speed of Belt M/pm: " + mainDataEntry.Speedofbeltanswer29f);
                content.moveTextPositionByAmount(0, -14);
                content.drawString(
                        "Drum/Sprocket  Mtrs: " + String.format("%.2f", mainDataEntry.Drumdiameterinput1));
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Metres per minute: " + mainDataEntry.getMetresperminuteanswer4f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Metres per hour: " + mainDataEntry.getMetresperhouranswer5f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Product per hour: " + mainDataEntry.getLengthperhouranswer7f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Kg's per hour: " + mainDataEntry.getKgsperhouranswer9f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Kg at any given time: " + mainDataEntry.getKgatanygiventimeanswer10f());
                content.moveTextPositionByAmount(-10, -28);

                // Results
                content.setFont(PDType1Font.COURIER_BOLD, 20);
                content.drawString("Results");
                content.moveTextPositionByAmount(0, -10);
                content.setFont(font, 14);
                content.moveTextPositionByAmount(10, -14);
                content.drawString("RPM: " + String.format("%.2f", mainDataEntry.getRpmconveyor34()));
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Application Factor: " + mainDataEntry.getRadiananswer25f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Pull Force Kg/f: " + mainDataEntry.PullForce);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Nm Torque: " + mainDataEntry.getNmanswer15f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Service Factor: " + mainDataEntry.getServicefactor17f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Design Kw: " + mainDataEntry.getDesignkwanswer18f());
                content.moveTextPositionByAmount(-10, -28);

                // Gearbox recommendations 

                // only bother with section if the gearbox details aren't empty
                if (!mainDataEntry.GearboxDetailsForPDF.isEmpty()) {
                    content.setFont(PDType1Font.COURIER_BOLD, 20);
                    content.drawString("Gearbox/Motor Recommendations");
                    content.moveTextPositionByAmount(2, -25);
                    content.setFont(PDType1Font.COURIER_BOLD, 18);
                    content.drawString(mainDataEntry.GearboxType + ":");
                    content.setFont(font, 14);
                    content.moveTextPositionByAmount(10, -25);

                    String[] display;

                    // For the brooks cyclo we need to split the string by these values
                    // then write each index of the resulting array separately so the
                    // result doesn't just run off the page
                    display = mainDataEntry.GearboxDetailsForPDF.get(0).split("Ratio: |Overload ");

                    // Only need to do this when the string has been split out by Ratio or Overload
                    // i.e. this is only the case for brooks cyclo, the other two types fit the page fine
                    if (display.length > 1) {
                        display[1] = "Ratio: " + display[1];
                        content.drawString(display[0]);
                        content.moveTextPositionByAmount(0, -14);
                        content.drawString(display[1]);

                        if (display.length > 2) {
                            display[2] = "Overload " + display[2];
                            content.moveTextPositionByAmount(0, -14);
                            content.drawString(display[2]);
                        }
                    } else {
                        // first option must exist for the program to get this far
                        content.drawString(mainDataEntry.GearboxDetailsForPDF.get(0));
                    }

                    content.moveTextPositionByAmount(0, -14);

                    // only bother with the second option if it exists
                    if (mainDataEntry.GearboxDetailsForPDF.size() > 1) {
                        display = mainDataEntry.GearboxDetailsForPDF.get(1).split("Ratio: |Overload ");

                        if (display.length > 1) {
                            content.moveTextPositionByAmount(0, -15);
                            display[1] = "Ratio: " + display[1];
                            content.drawString(display[0]);
                            content.moveTextPositionByAmount(0, -14);
                            content.drawString(display[1]);

                            if (display.length > 2) {
                                display[2] = "Overload " + display[2];
                                content.moveTextPositionByAmount(0, -14);
                                content.drawString(display[2]);
                            }
                        } else {
                            content.moveTextPositionByAmount(0, -14);
                            content.drawString(mainDataEntry.GearboxDetailsForPDF.get(1));
                        }
                    }
                }

                content.endText();

                image2 = ImageIO.read(new File("logosmall.jpg"));
                BufferedImage logo = image2;
                // writes the image to the file

                PDXObjectImage jblogo = new PDPixelMap(doc, logo);

                content.drawImage(jblogo, 20, 650);
                //postions image
                content.close();
                doc.getDocument();
                doc.save(myfile.getAbsolutePath());

                // open the file 
                Desktop.getDesktop().open(myfile);

                doc.close();
                close();
                //saves pdf and closes it
            } catch (IOException | COSVisitorException ie) {
                JOptionPane.showMessageDialog(null, ie.getMessage(), "Error!", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }
}

From source file:merge_split.MergeSplit.java

License:Apache License

private void MergeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MergeButtonActionPerformed
    try {// w w w  .ja  v a  2  s  .  c  om
        PDDocument samplePdf = new PDDocument();
        ArrayList<PDDocument> list = new ArrayList<>();
        for (int i = 0; i < dtm.getRowCount(); i++) {
            File file = new File((String) dtm.getValueAt(i, 0));
            String code = (String) dtm.getValueAt(i, 3);
            PDDocument doc1;
            if (code.equals("ok")) {
                doc1 = PDDocument.load(file);
            } else {
                doc1 = PDDocument.load(file, code);

            }
            list.add(doc1);
            doc1.setAllSecurityToBeRemoved(true);
            TreeSet tree = findPages((String) dtm.getValueAt(i, 2));
            for (int j = 0; j < doc1.getNumberOfPages(); j++) {
                if (tree.contains(j + 1)) {
                    samplePdf.addPage(doc1.getPage(j));
                }

            }

        }
        System.out.println("Number:" + samplePdf.getNumberOfPages());

        String destination = jTextField1.getText() + "\\" + jTextField2.getText() + ".pdf";
        PDDocumentInformation info = samplePdf.getDocumentInformation();
        info.setAuthor(jTextField3.getText());
        File output = new File(destination);

        samplePdf.save(output);

        samplePdf.close();
        for (int i = 0; i < list.size(); i++) {
            list.get(i).close();
        }
    } catch (IOException ex) {

        JOptionPane.showMessageDialog(null, "Your input is incorrect. Please fill all the fields.",
                "Input warning", JOptionPane.WARNING_MESSAGE);
    }

}

From source file:merge_split.MergeSplit.java

License:Apache License

private void RotateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RotateButtonActionPerformed
    try {/*from w ww.  j  a  va 2 s .  c om*/

        PDDocument samplePdf = new PDDocument();
        File file = new File(RotateFileField.getText());
        PDDocument doc1;
        if (rotatecode.equals("ok")) {
            doc1 = PDDocument.load(file);
        } else {
            doc1 = PDDocument.load(file, rotatecode);

        }
        doc1.setAllSecurityToBeRemoved(true);
        TreeSet tree = findPages(RotatePagesField.getText());
        for (int j = 0; j < doc1.getNumberOfPages(); j++) {
            PDPage page = doc1.getPage(j);

            if (tree.contains(j + 1)) {

                if (Rotate90.isSelected()) {
                    page.setRotation(90);
                    samplePdf.addPage(page);
                } else if (Rotate180.isSelected()) {
                    page.setRotation(180);
                    samplePdf.addPage(page);
                } else if (Rotate270.isSelected()) {
                    page.setRotation(270);
                    samplePdf.addPage(page);
                }
            } else {
                samplePdf.addPage(page);

            }

        }

        System.out.println("Number:" + samplePdf.getNumberOfPages());

        String destination = RotateDestinationField.getText() + "\\" + RotateNameField.getText() + ".pdf";
        PDDocumentInformation info = samplePdf.getDocumentInformation();
        info.setAuthor(RotateAuthorField.getText());
        File output = new File(destination);

        samplePdf.save(output);

        samplePdf.close();
    } catch (IOException ex) {
        Logger.getLogger(MergeSplit.class.getName()).log(Level.SEVERE, null, ex);

        JOptionPane.showMessageDialog(null, "Your input is incorrect. Please fill all the fields.",
                "Input warning", JOptionPane.WARNING_MESSAGE);
    }
}

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   w  ww  .  ja  v  a 2s. 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);
    }
}