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

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

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

This will close the underlying COSDocument object.

Usage

From source file:com.mycompany.textextract.textExtract.java

public static void main(String[] args) throws IOException {
    File folder = new File(args[0]);
    File target = new File(args[1]);
    String[] files = folder.list();
    for (String filename : files) {
        if (new File(filename).isFile() && !Arrays.asList(target.list()).contains(filename + ".txt")) {
            try {
                PDDocument doc = PDDocument.load(folder.getAbsolutePath() + "/" + filename);
                PDFTextStripper strip = new PDFTextStripper();
                PrintWriter writer = new PrintWriter(target.getAbsolutePath() + "/" + filename + ".txt",
                        "UTF-8");
                writer.print(strip.getText(doc));
                doc.close();
                writer.close();/*from   w  w w .  j  a  va2 s.co m*/
            } catch (Exception e) {
                System.out.println("writing failed-" + e.toString());
            }
        }
    }
}

From source file:com.netsteadfast.greenstep.util.PdfConvertUtils.java

License:Apache License

@SuppressWarnings("unchecked")
public static List<File> toImageFiles(File pdfFile, int resolution) throws Exception {
    PDDocument document = PDDocument.loadNonSeq(pdfFile, null);
    List<PDPage> pages = document.getDocumentCatalog().getAllPages();
    File tmpDir = new File(Constants.getWorkTmpDir() + "/" + PdfConvertUtils.class.getSimpleName() + "/"
            + System.currentTimeMillis() + "/");
    FileUtils.forceMkdir(tmpDir);/*from   w  ww  .  j a  v a2s . c  o  m*/
    List<File> files = new LinkedList<File>();
    int len = String.valueOf(pages.size() + 1).length();
    for (int i = 0; i < pages.size(); i++) {
        String name = StringUtils.leftPad(String.valueOf(i + 1), len, "0");
        BufferedImage bufImage = pages.get(i).convertToImage(BufferedImage.TYPE_INT_RGB, resolution);
        File imageFile = new File(tmpDir.getPath() + "/" + name + ".png");
        FileOutputStream fos = new FileOutputStream(imageFile);
        ImageIOUtil.writeImage(bufImage, "png", fos, resolution);
        fos.flush();
        fos.close();
        files.add(imageFile);
    }
    document.close();
    tmpDir = null;
    return files;
}

From source file:com.ning.billing.recurly.TestRecurlyClient.java

License:Apache License

@Test(groups = "integration")
public void testCreateInvoiceAndRetrieveInvoicePdf() throws Exception {
    final Account accountData = TestUtils.createRandomAccount();

    PDDocument pdDocument = null;
    try {//from  ww w  .j a  va2s.c  om

        // Create a user
        final Account account = recurlyClient.createAccount(accountData);

        // Create an Adjustment
        final Adjustment a = new Adjustment();
        a.setUnitAmountInCents(150);
        a.setCurrency(CURRENCY);

        final Adjustment createdA = recurlyClient.createAccountAdjustment(accountData.getAccountCode(), a);

        // Post an invoice/invoice the adjustment
        final Invoice invoiceData = new Invoice();
        invoiceData.setCollectionMethod("manual");
        invoiceData.setLineItems(null);
        final Invoice invoice = recurlyClient.postAccountInvoice(accountData.getAccountCode(), invoiceData)
                .getChargeInvoice();
        Assert.assertNotNull(invoice);

        InputStream pdfInputStream = recurlyClient.getInvoicePdf(invoice.getId());
        Assert.assertNotNull(pdfInputStream);

        pdDocument = PDDocument.load(pdfInputStream);
        String pdfString = new PDFTextStripper().getText(pdDocument);

        Assert.assertNotNull(pdfString);
        Assert.assertTrue(pdfString.contains("Invoice # " + invoice.getId()));
        Assert.assertTrue(pdfString.contains("Subtotal $" + 1.5));
        // Attempt to close the invoice
        final Invoice closedInvoice = recurlyClient.markInvoiceSuccessful(invoice.getId());
        Assert.assertEquals(closedInvoice.getState(), "paid", "Invoice not closed successfully");

    } finally {
        if (pdDocument != null) {
            pdDocument.close();
        }
        // Close the account
        recurlyClient.closeAccount(accountData.getAccountCode());
    }
}

From source file:com.odc.pdfextractor.parser.CleanPdfParser.java

License:Apache License

/**
 * This will print the documents docBuilder.
 *
 * @param args The command line arguments.
 *
 * @throws Exception If there is an error parsing the document.
 *//*from  ww w  .ja  v  a  2  s . c  o  m*/
public DocumentLocation processPdf(String filename) throws Exception {

    PDDocument document = null;
    try {
        document = PDDocument.load(filename);
        if (document.isEncrypted()) {
            try {
                document.decrypt("");
            } catch (InvalidPasswordException e) {
                System.err.println("Error: Document is encrypted with a password.");
                System.exit(1);
            }
        }
        List allPages = document.getDocumentCatalog().getAllPages();
        System.out.print("Extracting text from PDF");
        for (int i = 0; i < allPages.size(); i++) {
            PDPage page = (PDPage) allPages.get(i);
            System.out.print(".");
            PDStream contents = page.getContents();
            if (contents != null) {
                this.processStream(page, page.findResources(), page.getContents().getStream());
            }
            docBuilder.incrementPage();
        }
    } finally {
        System.out.println();
        if (document != null) {
            document.close();
        }
    }
    return docBuilder.getDoc();
}

From source file:com.openkm.extractor.PdfTextExtractor.java

License:Open Source License

/**
 * {@inheritDoc}//  w ww. j av  a2 s  .  c  om
 */
@SuppressWarnings("rawtypes")
public String extractText(InputStream stream, String type, String encoding) throws IOException {
    try {
        PDFParser parser = new PDFParser(new BufferedInputStream(stream));

        try {
            parser.parse();
            PDDocument document = parser.getPDDocument();

            if (document.isEncrypted()) {
                try {
                    document.decrypt("");
                    document.setAllSecurityToBeRemoved(true);
                } catch (Exception e) {
                    throw new IOException("Unable to extract text: document encrypted", e);
                }
            }

            CharArrayWriter writer = new CharArrayWriter();
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setLineSeparator("\n");
            stripper.writeText(document, writer);
            String st = writer.toString().trim();
            log.debug("TextStripped: '{}'", st);

            if (Config.SYSTEM_PDF_FORCE_OCR || st.length() <= 1) {
                log.warn("PDF does not contains text layer");

                // Extract images from PDF
                StringBuilder sb = new StringBuilder();

                if (!Config.SYSTEM_PDFIMAGES.isEmpty()) {
                    File tmpPdf = FileUtils.createTempFile("pdf");
                    File tmpDir = new File(EnvironmentDetector.getTempDir());
                    String baseName = FileUtils.getFileName(tmpPdf.getName());
                    document.save(tmpPdf);
                    int pgNum = 1;

                    try {
                        for (PDPage page : (List<PDPage>) document.getDocumentCatalog().getAllPages()) {
                            HashMap<String, Object> hm = new HashMap<String, Object>();
                            hm.put("fileIn", tmpPdf.getPath());
                            hm.put("firstPage", pgNum);
                            hm.put("lastPage", pgNum++);
                            hm.put("imageRoot", tmpDir + File.separator + baseName);
                            String cmd = TemplateUtils.replace("SYSTEM_PDFIMAGES", Config.SYSTEM_PDFIMAGES, hm);
                            ExecutionUtils.runCmd(cmd);

                            for (File tmp : tmpDir.listFiles()) {
                                if (tmp.getName().startsWith(baseName + "-")) {
                                    if (page.findRotation() > 0) {
                                        ImageUtils.rotate(tmp, tmp, page.findRotation());
                                    }

                                    try {
                                        String txt = doOcr(tmp);
                                        sb.append(txt).append(" ");
                                        log.debug("OCR Extracted: {}", txt);
                                    } finally {
                                        FileUtils.deleteQuietly(tmp);
                                    }
                                }
                            }
                        }
                    } finally {
                        FileUtils.deleteQuietly(tmpPdf);
                    }
                } else {
                    for (PDPage page : (List<PDPage>) document.getDocumentCatalog().getAllPages()) {
                        PDResources resources = page.getResources();
                        Map<String, PDXObject> images = resources.getXObjects();

                        if (images != null) {
                            for (String key : images.keySet()) {
                                PDXObjectImage image = (PDXObjectImage) images.get(key);
                                String prefix = "img-" + key + "-";
                                File pdfImg = null;

                                try {
                                    pdfImg = File.createTempFile(prefix, ".png");
                                    log.debug("Writing image: {}", pdfImg.getPath());

                                    // Won't work until PDFBox 1.8.9
                                    ImageIO.write(image.getRGBImage(), "png", pdfImg);

                                    if (page.findRotation() > 0) {
                                        ImageUtils.rotate(pdfImg, pdfImg, page.findRotation());
                                    }

                                    // Do OCR
                                    String txt = doOcr(pdfImg);
                                    sb.append(txt).append(" ");
                                    log.debug("OCR Extracted: {}", txt);
                                } finally {
                                    FileUtils.deleteQuietly(pdfImg);
                                }
                            }
                        }
                    }
                }

                return sb.toString();
            } else {
                return writer.toString();
            }
        } finally {
            try {
                PDDocument doc = parser.getPDDocument();
                if (doc != null) {
                    doc.close();
                }
            } catch (IOException e) {
                // ignore
            }
        }
    } catch (Exception e) {
        // it may happen that PDFParser throws a runtime
        // exception when parsing certain pdf documents
        log.warn("Failed to extract PDF text content", e);
        throw new IOException(e.getMessage(), e);
    } finally {
        stream.close();
    }
}

From source file:com.opensearchserver.extractor.parser.PdfBox.java

License:Apache License

/**
 * Extract text content using PDFBox/*from  w w  w .  j av a 2s .  co m*/
 * 
 * @param pdf
 * @throws Exception
 */
private void parseContent(PDDocument pdf) throws Exception {
    try {
        if (pdf.isEncrypted())
            pdf.openProtection(new StandardDecryptionMaterial(""));
        extractMetaData(pdf);
        Stripper stripper = new Stripper();
        stripper.getText(pdf);
    } finally {
        if (pdf != null)
            pdf.close();
    }
}

From source file:com.PDF.Resume.java

public ByteArrayOutputStream createResume() throws ParseException, IOException, COSVisitorException {
    System.out.println(imagePath);

    // Create a document and add a page to it
    PDDocument document = new PDDocument();
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
    // PDPage.PAGE_SIZE_LETTER is also possible
    PDRectangle rect = page1.getMediaBox();
    // rect can be used to get the page width and height
    document.addPage(page1);/*from   w w  w  .  ja  v  a2s .c  om*/

    // Create a new font object selecting one of the PDF base fonts
    PDFont fontPlain = PDType1Font.HELVETICA;

    // Start a new content stream which will "hold" the to be created content
    PDPageContentStream cos = new PDPageContentStream(document, page1);

    int line = 0;

    // Define a text content stream using the selected font, move the cursor and draw some text
    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(475, rect.getHeight() - 800 * (++line));
    cos.drawString("Pagina " + ++pagenumber);
    cos.endText();
    line--;

    cos.beginText();
    cos.setFont(fontPlain, 24);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 90 * (++line));
    cos.drawString("Curriculum Vitae");
    cos.endText();

    if (user != null) {
        cos.beginText();
        cos.setFont(fontPlain, 24);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(75, rect.getHeight() - 90 * (++line));
        cos.drawString(user.getSurname() + "");
        cos.endText();
    }

    // add an image
    try {
        BufferedImage awtImage = ImageIO.read(new File(
                "C:\\ICT\\HBO\\Jaar 2\\Project Enterprise Web Apps\\Images\\Info-Support-klein-formaat-JPG.png"));
        PDXObjectImage ximage = new PDPixelMap(document, awtImage);
        float scale = 1f; // alter this value to set the image size
        cos.drawXObject(ximage, 350, 750, ximage.getWidth() * scale, ximage.getHeight() * scale);
    } catch (FileNotFoundException fnfex) {
        System.out.println("No image for you");
    }
    // Make sure that the content stream is closed:
    cos.close();

    //second page
    line = 0;
    PDPage page2 = new PDPage(PDPage.PAGE_SIZE_A4);
    document.addPage(page2);
    cos = new PDPageContentStream(document, page2);

    try {
        BufferedImage awtImage = ImageIO.read(new File(
                "C:\\ICT\\HBO\\Jaar 2\\Project Enterprise Web Apps\\Images\\Info-Support-klein-formaat-JPG.png"));
        PDXObjectImage ximage = new PDPixelMap(document, awtImage);
        float scale = 1f; // alter this value to set the image size
        cos.drawXObject(ximage, 350, 750, ximage.getWidth() * scale, ximage.getHeight() * scale);
    } catch (FileNotFoundException fnfex) {
        System.out.println("No image for you");
    }

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(475, rect.getHeight() - 800 * (++line));
    cos.drawString("Pagina " + ++pagenumber);
    cos.endText();

    line--;

    cos.beginText();
    cos.setFont(fontPlain, 18);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 90 * (++line));
    cos.drawString("Personalia");
    cos.endText();
    line += 4;

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Naam:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getSurname() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Geslacht:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getGender() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Telefoonnummer:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getPersonalPhone() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Emailadres:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getPersonalEmail() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Adres:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getAddress() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Postcode:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getZipCode() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Stad:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getCity() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Provincie:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getRegion() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Functie:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getFunction() + "");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
    cos.drawString("Business Unit:");
    cos.endText();

    cos.beginText();
    cos.setFont(fontPlain, 12);
    cos.setNonStrokingColor(0, 120, 201);
    cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
    cos.drawString(user.getBusinessUnitAsString() + "");
    cos.endText();

    if (!educationList.isEmpty()) {
        line++;
        cos.beginText();
        cos.setFont(fontPlain, 18);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
        cos.drawString("Opleidingen");
        cos.endText();
        for (EmployeeHasEducation e : educationList) {
            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("School:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(e.getEducation().getSchool() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Richting:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(e.getEducation().getDegree() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Niveau:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(e.getEducation().getGrade() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Begindatum:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(e.getStartDate().substring(0, 10) + "");

            cos.endText();
            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Einddatum:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(e.getEndDate().substring(0, 10) + "");
            cos.endText();

        }
    }
    if (!certificateList.isEmpty()) {
        line++;
        cos.beginText();
        cos.setFont(fontPlain, 18);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
        cos.drawString("Certificaten");
        cos.endText();
        for (Certificate c : certificateList) {
            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Certificaat naam:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(c.getName() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Certificaat plaats:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(c.getCertificationAuthority() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Licentienummer:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(c.getLicenseNumber() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Startdatum:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(c.getStartDate().substring(0, 10) + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Einddatum:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(c.getExpirationDate().substring(0, 10) + "");
            cos.endText();
            line++;
        }
        line++;
    }

    cos.close();
    if (!preceedings.isEmpty()) {
        line = 0;
        PDPage page3 = new PDPage(PDPage.PAGE_SIZE_A4);
        document.addPage(page3);
        cos = new PDPageContentStream(document, page3);

        try {
            BufferedImage awtImage = ImageIO.read(new File(
                    "C:\\ICT\\HBO\\Jaar 2\\Project Enterprise Web Apps\\Images\\Info-Support-klein-formaat-JPG.png"));
            PDXObjectImage ximage = new PDPixelMap(document, awtImage);
            float scale = 1f; // alter this value to set the image size
            cos.drawXObject(ximage, 350, 750, ximage.getWidth() * scale, ximage.getHeight() * scale);
        } catch (FileNotFoundException fnfex) {
            System.out.println("No image for you");
        }

        cos.beginText();
        cos.setFont(fontPlain, 12);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(475, rect.getHeight() - 800 * (++line));
        cos.drawString("Pagina " + ++pagenumber);
        cos.endText();

        line--;

        cos.beginText();
        cos.setFont(fontPlain, 18);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(75, rect.getHeight() - 100 * (++line));
        cos.drawString("Projecten");
        line += 4;
        cos.endText();

        for (Preceeding p : preceedings) {
            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Projectnaam:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(p.getProject().getName() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Bedrijfsnaam:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(p.getProject().getCompany().getName() + " ");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Project rol:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(p.getDescription() + "");
            cos.endText();
            //    }

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Startdatum:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(p.getProject().getStartDate() + "");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
            cos.drawString("Einddatum:");
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (line));
            cos.drawString(p.getProject().getEndDate() + "");
            cos.endText();

            line++;
        }
    }
    cos.close();
    //Skills of the user
    if (!skillList.isEmpty()) {

        line = 0;
        PDPage page3 = new PDPage(PDPage.PAGE_SIZE_A4);
        document.addPage(page3);
        cos = new PDPageContentStream(document, page3);

        try {
            BufferedImage awtImage = ImageIO.read(new File(
                    "C:\\ICT\\HBO\\Jaar 2\\Project Enterprise Web Apps\\Images\\Info-Support-klein-formaat-JPG.png"));
            PDXObjectImage ximage = new PDPixelMap(document, awtImage);
            float scale = 1f; // alter this value to set the image size
            cos.drawXObject(ximage, 350, 750, ximage.getWidth() * scale, ximage.getHeight() * scale);
        } catch (FileNotFoundException fnfex) {
            System.out.println("No image for you");
        }

        cos.beginText();
        cos.setFont(fontPlain, 12);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(475, rect.getHeight() - 800 * (++line));
        cos.drawString("Pagina " + ++pagenumber);
        cos.endText();

        line--;

        cos.beginText();
        cos.setFont(fontPlain, 18);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(75, rect.getHeight() - 100 * (++line));
        cos.drawString("Skills");
        cos.endText();
        line += 4;

        cos.beginText();
        cos.setFont(fontPlain, 12);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
        cos.drawString("Skill & Rating:");
        cos.endText();
        cos.beginText();
        cos.setFont(fontPlain, 12);
        cos.setNonStrokingColor(0, 120, 201);
        cos.moveTextPositionByAmount(75, rect.getHeight() - 20 * (++line));
        cos.drawString("Jaren ervaring:");
        cos.endText();
        line -= 2;
        for (SkillRating s : skillList) {

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (++line));
            cos.drawString(s.getSkill().getName() + " niveau " + s.getRating());
            cos.endText();

            cos.beginText();
            cos.setFont(fontPlain, 12);
            cos.setNonStrokingColor(0, 120, 201);
            cos.moveTextPositionByAmount(350, rect.getHeight() - 20 * (++line));
            cos.drawString("" + s.getExpYears());
            cos.endText();
            line++;
        }
    }

    cos.close();
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    document.save(output);

    document.close();

    return output;
}

From source file:com.poscoict.license.service.CertificateService.java

public boolean extractPagesAsImage(String sourceFile, String fileName, int resolution, String password) {

    boolean result = false;
    //? ?//from   ww w  .j a va2  s .  c  o  m
    String imageFormat = Consts.IMG_FORMAT;
    int pdfPageCn = 0;
    PDDocument pdfDoc = null;

    try {
        //PDF?  ?
        pdfDoc = PDDocument.load(sourceFile);

        //PDF? ??  ?
        pdfPageCn = pdfDoc.getNumberOfPages();
    } catch (IOException ioe) {
        logger.error("PDF ?  : ", ioe);
    }

    PDFImageWriter imageWriter = new PDFImageWriter();
    try {
        result = imageWriter.writeImage(pdfDoc, imageFormat, password, 1, //?  ?
                pdfPageCn, //?  ?
                //? ? ?  ?+? "?1.gif" ?
                Consts.IMG_PATH + fileName, BufferedImage.TYPE_INT_RGB, resolution //?   300 
        );
        pdfDoc.close();
    } catch (IOException ioe) {
        logger.error("PDF ?  : ", ioe);
    }
    return result;
}

From source file:com.projectlaver.util.VoucherService.java

License:Open Source License

File generateVoucherPdf(String pdfFilename, File barcodeImageFile, VoucherDTO dto) {

    // the result 
    File pdfFile = null;/*from w  ww  .j ava  2s . com*/

    // the document
    PDDocument doc = null;
    try {
        // Create a new document and add a page to it
        doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);

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

        // For some reason this may need to happen after reading the image
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);

        /**
         * Read & draw the client logo
         */
        this.drawImageWithMaxEdge(contentStream, 15f, 629, 150,
                this.readImage(new URL(dto.getClientLogoUrl()), doc));

        /**
         *  Read & draw the barcode image
         */

        BufferedImage bim = ImageIO.read(barcodeImageFile);
        PDXObjectImage barcodeImage = new PDPixelMap(doc, bim);

        // inspired by http://stackoverflow.com/a/22318681/535646
        float barcodeScale = 1f; // reduce this value if the image is too large

        this.drawImage(contentStream, 206f, 315f, barcodeImage, barcodeScale);

        /** 
         * Read & draw the social eq logo image
         */

        float logoScale = 0.15f; // reduce this value if the image is too large
        this.drawImage(contentStream, 246f, 265f, this.readImage(new URL(this.socialEqLogoUrl), doc),
                logoScale);

        /**
         * Read & draw the client image
         */
        this.drawImageWithMaxEdge(contentStream, 0f, 145, 612,
                this.readImage(new URL(dto.getClientCampaignImageUrl()), doc));

        /**
         * Add some rectangles to the page to set off the sections
         */

        contentStream.setNonStrokingColor(new Color(0.82f, 0.82f, 0.82f, 0.6f)); // light grey

        /**
         *  around the merchant logo / title
         */

        contentStream.fillRect(0, pageHeight - 10, pageWidth, 10); // top edge
        contentStream.fillRect(0, pageHeight - 175, pageWidth, 10); // bottom edge
        contentStream.fillRect(0, pageHeight - 175, 10, 175); // left edge
        contentStream.fillRect(170, pageHeight - 175, 10, 175); // right of the logo
        contentStream.fillRect(pageWidth - 10, pageHeight - 175, 10, 175); // right edge

        // behind the terms and conditions
        contentStream.fillRect(0f, 0f, pageWidth, 145f);

        /**
         *  Handle the text
         */

        // text color is black
        contentStream.setNonStrokingColor(Color.BLACK);

        // merchant name
        this.printNoWrap(page, contentStream, 195, 712, dto.getMerchantName(), 48);

        // listing title
        this.printNoWrap(page, contentStream, 195, 662, dto.getVoucherTitle(), 24);

        // Long description
        this.printNoWrap(page, contentStream, 30, 582, "Details:", 14);

        PdfParagraph ld = new PdfParagraph(30, 562, dto.getVoucherDetails(), 14);
        this.printLeftAlignedWithWrap(contentStream, ld);

        // Terms and conditions
        this.printNoWrap(page, contentStream, 30, 115, "Terms & Conditions:", 12);

        PdfParagraph toc = new PdfParagraph(30, 100, dto.getVoucherTerms(), 10);
        this.printLeftAlignedWithWrap(contentStream, toc);

        // Make sure that the content stream is closed:
        contentStream.close();

        String pdfPath = System.getProperty("java.io.tmpdir") + pdfFilename;
        doc.save(pdfPath);

        pdfFile = new File(pdfPath);

    } catch (Exception e) {

        throw new RuntimeException("Could not create the PDF File.", e);

    } finally {
        if (doc != null) {

            try {
                doc.close();
            } catch (IOException e) {
                throw new RuntimeException("Could not close the PDF Document.", e);
            }
        }
    }

    return pdfFile;
}

From source file:com.proquest.demo.allinone.PDFLBase.java

/**
 * Extract Text using PDF BOX, instead APDFL
 *
 * @param fileNamePath/*  w  w w.  j  a v a2 s  . c  o m*/
 * @return
 * @throws Exception
 */
public byte[] extractTextPDFBox(final String fileNamePath) throws Exception {
    final String BLANK_SPACE = " ";
    final String UTF_8 = "UTF-8";
    final PropertyReaderLib libPropertyReaderLib = new PropertyReaderLib(PropertyFileNames.PDFLIBRARY);
    final String regex = libPropertyReaderLib
            .getPropertyValue(PdfLibraryKeys.REGEX_TO_REMOVE_FROM_EXTRACTEDTEXT.toString());

    byte[] bytesToReturn = null;
    try {
        final File file = new File(fileNamePath);
        final PDDocument pdfDoc = PDDocument.load(file);
        final PDFTextStripper pdfStripper = new PDFTextStripper();
        final String textFromPDF = pdfStripper.getText(pdfDoc);
        pdfDoc.close();

        bytesToReturn = textFromPDF.getBytes(UTF_8);
        final String textStr = new String(bytesToReturn).replaceAll(regex, BLANK_SPACE);
        bytesToReturn = textStr.getBytes();
    } catch (IOException e) {
        throw new Exception(e.getMessage());
    }
    return bytesToReturn;
}