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

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

Introduction

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

Prototype

public PDDocument() 

Source Link

Document

Creates an empty PDF document.

Usage

From source file:javaexample.RadialTextPdf.java

License:Open Source License

public void generateDocument() throws IOException, COSVisitorException {
    PDDocument document = new PDDocument();

    try {//from ww  w . ja v a2 s . com
        // Sets some document metadata.
        PDDocumentInformation information = new PDDocumentInformation();
        information.setTitle("Radial Text PDF example with Apache PDFBox");
        information.setAuthor("Andrea Binello (\"andbin\")");
        document.setDocumentInformation(information);

        // Generates and saves the document.
        generatePage(document);
        document.save(filename);
    } finally {
        try {
            document.close();
        } catch (IOException e) {
        }
    }
}

From source file:javaexample.StandardFontsDemoPdf.java

License:Open Source License

public void generateDocument() throws IOException, COSVisitorException {
    document = new PDDocument();

    try {//from   ww  w .  j a  va2s.com
        // Sets some document metadata.
        PDDocumentInformation information = new PDDocumentInformation();
        information.setTitle("Standard fonts demo PDF example with Apache PDFBox");
        information.setAuthor("Andrea Binello (\"andbin\")");
        document.setDocumentInformation(information);

        // Generates and saves the document.
        generatePages();
        document.save(filename);
    } finally {
        try {
            document.close();
        } catch (IOException e) {
        }
    }
}

From source file:jgnash.PDFBoxTableTest.java

License:Open Source License

@Test
void simpleTest() throws IOException {

    Path tempPath = null;/*  w ww.  java 2 s .c o m*/

    try (PDDocument doc = new PDDocument()) {
        tempPath = Files.createTempFile("test", ".pdf");
        System.out.println(tempPath);

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

        PDFont font = PDType1Font.HELVETICA;

        try (final PDPageContentStream contents = new PDPageContentStream(doc, page)) {
            contents.beginText();
            contents.setFont(font, 11);
            contents.newLineAtOffset(100, 700);
            contents.showText("Hello World!");
            contents.endText();
        }

        doc.save(tempPath.toFile());
    } catch (final IOException e) {
        e.printStackTrace();
    } finally {
        if (tempPath != null) {
            Files.deleteIfExists(tempPath);
        }
    }
}

From source file:jlotoprint.PrintViewUIPanelController.java

public PDDocument generatePDF() throws Exception {

    PDDocument doc = null;//from  w ww .ja  va  2s . c  o  m
    PDPage page = null;
    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();/*w  w w. j  a va  2s . 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:jp.qpg.PDFPrinter.java

License:Apache License

/**
 * @return PDF document/* w ww  .  j av a 2s  .  com*/
 */
protected PDDocument getDocument() {
    return document.orElseGet(() -> {
        PDDocument document = new PDDocument();
        logger.config("add PDDocument: " + document.hashCode());
        this.document = Optional.of(document);
        documentSetup.ifPresent(i -> i.accept(this));
        return document;
    });
}

From source file:merge_split.MergeSplit.java

License:Apache License

private void MergeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MergeButtonActionPerformed
    try {//from w ww .ja  va2  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 w  w .java2s.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;/*  ww w  .  ja va 2  s.  co m*/
    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:merge_split.MergeSplit.java

License:Apache License

private void SplitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SplitButtonActionPerformed
    try {//w w  w . j a  v  a2  s.c  o  m

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

        }
        doc1.setAllSecurityToBeRemoved(true);

        if (MultipleButton.isSelected()) {
            PDDocument pdf1 = new PDDocument();
            PDDocument pdf2 = new PDDocument();
            TreeSet tree = findPages(SplitPagesField.getText());
            for (int j = 0; j < doc1.getNumberOfPages(); j++) {
                PDPage page = doc1.getPage(j);
                if (tree.contains(j + 1)) {
                    pdf1.addPage(page);
                } else {
                    pdf2.addPage(page);

                }
            }
            String destination1 = SplitDestinationField.getText() + "\\" + SplitNameField.getText() + "1.pdf";
            String destination2 = SplitDestinationField.getText() + "\\" + SplitNameField.getText() + "2.pdf";

            PDDocumentInformation info = pdf1.getDocumentInformation();
            info.setAuthor(SplitAuthorField.getText());
            PDDocumentInformation info2 = pdf2.getDocumentInformation();
            info2.setAuthor(SplitAuthorField.getText());
            if (pdf1.getNumberOfPages() > 0) {
                File output1 = new File(destination1);
                pdf1.save(output1);
            }
            if (pdf2.getNumberOfPages() > 0) {
                File output2 = new File(destination2);
                pdf2.save(output2);
            }
            pdf1.close();
            pdf2.close();
        } else if (SingleButton.isSelected()) {

            for (int j = 0; j < doc1.getNumberOfPages(); j++) {
                PDDocument pdf1 = new PDDocument();

                PDPage page = doc1.getPage(j);
                pdf1.addPage(page);
                int pagenumber = j + 1;
                String destination1 = SplitDestinationField.getText() + "\\" + SplitNameField.getText()
                        + pagenumber + ".pdf";

                PDDocumentInformation info = pdf1.getDocumentInformation();
                info.setAuthor(SplitAuthorField.getText());

                if (pdf1.getNumberOfPages() > 0) {
                    File output1 = new File(destination1);
                    pdf1.save(output1);
                }

                pdf1.close();
            }

        }
        doc1.close();

    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Your input is incorrect. Please fill all the fields.",
                "Input warning", JOptionPane.WARNING_MESSAGE);
        java.util.logging.Logger.getLogger(MergeSplit.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);

    }
}