List of usage examples for org.apache.pdfbox.pdmodel PDDocument close
@Override public void close() throws IOException
From source file:com.bgh.myopeninvoice.jsf.jsfbeans.InvoiceBean.java
License:Apache License
public String getImageAttachment(AttachmentEntity attachmentEntity) throws IOException, ImageReadException { if (attachmentEntity != null && attachmentEntity.getContent().length > 0) { if (attachmentEntity.getLoadProxy()) { return "/images/" + attachmentEntity.getFileExtension() + ".png"; } else {/*from w w w.j a v a2 s .co m*/ selectedAttachmentEntity = attachmentEntity; ImageFormat mimeType = Sanselan.guessFormat(attachmentEntity.getContent()); if (mimeType != null && !"UNKNOWN".equalsIgnoreCase(mimeType.name)) { return "data:image/" + mimeType.extension.toLowerCase() + ";base64," + Base64.getEncoder().encodeToString(attachmentEntity.getContent()); } else if (attachmentEntity.getImageData() != null && attachmentEntity.getImageData().length > 0) { return "data:image/png;base64," + Base64.getEncoder().encodeToString(attachmentEntity.getImageData()); } else if ("pdf".equalsIgnoreCase(attachmentEntity.getFileExtension())) { ByteArrayOutputStream baos = null; PDDocument document = null; try { document = PDDocument.load(attachmentEntity.getContent()); final PDPage page = document.getPage(0); PDFRenderer pdfRenderer = new PDFRenderer(document); final BufferedImage bufferedImage = pdfRenderer.renderImage(0); baos = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "png", baos); baos.flush(); attachmentEntity.setImageData(baos.toByteArray()); } finally { if (document != null) { document.close(); } if (baos != null) { baos.close(); } } return "data:image/png;base64," + Base64.getEncoder().encodeToString(attachmentEntity.getImageData()); } else { return null; } } } else if (selectedAttachmentEntity != null && selectedAttachmentEntity.getImageData() != null && selectedAttachmentEntity.getImageData().length > 0) { return "data:image/png;base64," + Base64.getEncoder().encodeToString(selectedAttachmentEntity.getImageData()); } else { return null; } }
From source file:com.bitplan.pdfindex.Pdfindexer.java
License:Apache License
/** * add the given file or URI to the index * //from w ww . j av a 2 s .co m * @param file * @throws Exception */ private void addToIndex(DocumentSource source) throws Exception { PDDocument pddDocument = source.getDocument(); PDFTextStripper textStripper = new PDFTextStripper(); for (int pageNo = 1; pageNo <= pddDocument.getNumberOfPages(); pageNo++) { textStripper.setStartPage(pageNo); textStripper.setEndPage(pageNo); String pageContent = textStripper.getText(pddDocument); // System.out.println(pageContent); Document doc = new Document(); // Add the page number doc.add(new Field("pagenumber", Integer.toString(pageNo), Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field("content", pageContent, Field.Store.NO, Field.Index.ANALYZED)); doc.add(new Field("SOURCE", source.unRooted(this.root), Field.Store.YES, Field.Index.ANALYZED)); documents.add(doc); getIndexWriter().addDocument(doc); } pddDocument.close(); }
From source file:com.cisco.iwe.services.util.EmailMonitor.java
/** * /* w ww. ja v a 2 s .c o m*/ * @param fileDir * @return */ /* This method is used to scan the uploaded expense receipt in .pdf format and extract the text embedded in it. */ public String scanPDF(String fileDir) { PDFParser parser; String parsedText = null; PDFTextStripper pdfStripper = null; PDDocument pdDoc = null; COSDocument cosDoc = null; File file = new File(fileDir); if (!file.isFile()) { System.err.println("File " + fileDir + " does not exist."); return null; } try { parser = new PDFParser(new FileInputStream(file)); } catch (IOException e) { System.err.println("Unable to open PDF Parser. " + e.getMessage()); return null; } try { parser.parse(); cosDoc = parser.getDocument(); pdfStripper = new PDFTextStripper(); pdDoc = new PDDocument(cosDoc); pdfStripper.setStartPage(1); pdfStripper.setEndPage(pdDoc.getNumberOfPages()); parsedText = pdfStripper.getText(pdDoc); } catch (Exception e) { System.err.println("An exception occured in parsing the PDF Document." + e.getMessage()); } finally { try { if (cosDoc != null) cosDoc.close(); if (pdDoc != null) pdDoc.close(); } catch (Exception e) { e.printStackTrace(); } } return parsedText; }
From source file:com.ecmkit.service.convert.impl.PDFToImage.java
License:Apache License
/** * Infamous main method./*from w w w. j a va2 s . c o m*/ * * @param args Command line arguments, should be one and a reference to a file. * * @throws Exception If there is an error parsing the document. */ public static void main(String[] args) throws Exception { boolean useNonSeqParser = false; String password = ""; String pdfFile = null; String outputPrefix = null; String imageFormat = "jpg"; int startPage = 1; int endPage = Integer.MAX_VALUE; String color = "rgb"; int resolution; float cropBoxLowerLeftX = 0; float cropBoxLowerLeftY = 0; float cropBoxUpperRightX = 0; float cropBoxUpperRightY = 0; try { resolution = Toolkit.getDefaultToolkit().getScreenResolution(); } catch (HeadlessException e) { resolution = 96; } for (int i = 0; i < args.length; i++) { if (args[i].equals(PASSWORD)) { i++; if (i >= args.length) { usage(); } password = args[i]; } else if (args[i].equals(START_PAGE)) { i++; if (i >= args.length) { usage(); } startPage = Integer.parseInt(args[i]); } else if (args[i].equals(END_PAGE)) { i++; if (i >= args.length) { usage(); } endPage = Integer.parseInt(args[i]); } else if (args[i].equals(IMAGE_FORMAT)) { i++; imageFormat = args[i]; } else if (args[i].equals(OUTPUT_PREFIX)) { i++; outputPrefix = args[i]; } else if (args[i].equals(COLOR)) { i++; color = args[i]; } else if (args[i].equals(RESOLUTION)) { i++; resolution = Integer.parseInt(args[i]); } else if (args[i].equals(CROPBOX)) { i++; cropBoxLowerLeftX = Float.valueOf(args[i]).floatValue(); i++; cropBoxLowerLeftY = Float.valueOf(args[i]).floatValue(); i++; cropBoxUpperRightX = Float.valueOf(args[i]).floatValue(); i++; cropBoxUpperRightY = Float.valueOf(args[i]).floatValue(); } else if (args[i].equals(NONSEQ)) { useNonSeqParser = true; } else { if (pdfFile == null) { pdfFile = args[i]; } } } if (pdfFile == null) { usage(); } else { if (outputPrefix == null) { outputPrefix = pdfFile.substring(0, pdfFile.lastIndexOf('.')); } PDDocument document = null; try { if (useNonSeqParser) { document = PDDocument.loadNonSeq(new File(pdfFile), null, password); } else { document = PDDocument.load(pdfFile); if (document.isEncrypted()) { try { document.decrypt(password); } catch (InvalidPasswordException e) { if (args.length == 4)//they supplied the wrong password { System.err.println("Error: The supplied password is incorrect."); System.exit(2); } else { //they didn't supply a password and the default of "" was wrong. System.err.println("Error: The document is encrypted."); usage(); } } } } //PDFont font = PDTrueTypeFont.loadTTF(document, new File("/usr/share/fonts/truetype/simsun.ttc")); int imageType = 24; if ("bilevel".equalsIgnoreCase(color)) { imageType = BufferedImage.TYPE_BYTE_BINARY; } else if ("indexed".equalsIgnoreCase(color)) { imageType = BufferedImage.TYPE_BYTE_INDEXED; } else if ("gray".equalsIgnoreCase(color)) { imageType = BufferedImage.TYPE_BYTE_GRAY; } else if ("rgb".equalsIgnoreCase(color)) { imageType = BufferedImage.TYPE_INT_RGB; } else if ("rgba".equalsIgnoreCase(color)) { imageType = BufferedImage.TYPE_INT_ARGB; } else { System.err.println("Error: the number of bits per pixel must be 1, 8 or 24."); System.exit(2); } //if a CropBox has been specified, update the CropBox: //changeCropBoxes(PDDocument document,float a, float b, float c,float d) if (cropBoxLowerLeftX != 0 || cropBoxLowerLeftY != 0 || cropBoxUpperRightX != 0 || cropBoxUpperRightY != 0) { changeCropBoxes(document, cropBoxLowerLeftX, cropBoxLowerLeftY, cropBoxUpperRightX, cropBoxUpperRightY); } //Make the call PDFImageWriter imageWriter = new PDFImageWriter(); boolean success = imageWriter.writeImage(document, imageFormat, password, startPage, endPage, outputPrefix, imageType, resolution); if (!success) { System.err.println("Error: no writer found for image format '" + imageFormat + "'"); System.exit(1); } } catch (Exception e) { System.err.println(e); } finally { if (document != null) { document.close(); } } } }
From source file:com.encodata.PDFSigner.PDFSigner.java
public void createPDFFromImage(String inputFile, String imagePath, String outputFile, String x, String y, String width, String height, CallbackContext callbackContext) throws IOException { if (inputFile == null || imagePath == null || outputFile == null) { callbackContext.error("Expected localFile and remoteFile."); } else {/*from ww w. ja v a2 s . co m*/ // the document PDDocument doc = null; try { doc = PDDocument.load(new File(inputFile)); //we will add the image to the first page. PDPage page = doc.getPage(0); // createFromFile is the easiest way with an image file // if you already have the image in a BufferedImage, // call LosslessFactory.createFromImage() instead PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc); PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true); // contentStream.drawImage(ximage, 20, 20 ); // better method inspired by http://stackoverflow.com/a/22318681/535646 // reduce this value if the image is too large float scale = 1f; contentStream.drawImage(pdImage, Float.parseFloat(x), Float.parseFloat(y), Float.parseFloat(width) * scale, Float.parseFloat(height) * scale); contentStream.close(); doc.save(outputFile); callbackContext.success(outputFile); } catch (Exception e) { callbackContext.error(e.toString()); } finally { if (doc != null) { doc.close(); } } } }
From source file:com.enonic.cms.plugin.extractor.PdfExtractor.java
License:Open Source License
@Override public String extractText(String mimeType, InputStream inputStream, String encoding) throws IOException { if (canHandle(mimeType)) { PDDocument doc = PDDocument.load(inputStream); PDFTextStripper stripper = new PDFTextStripper(); String text = stripper.getText(doc); doc.close(); return text; } else {//from w w w .j av a 2s.c o m return null; } }
From source file:com.evanbelcher.DrillBook.display.DBDesktopPane.java
License:Open Source License
/** * Prints the current page to a pdf file * * @throws IOException if the file cannot be found or the pdf cannot be created */// w w w .j a va2 s . c o m protected void printCurrentPageToPdf() throws IOException { io.clearActivePoints(); ddf.updateAll(io.getActivePoints()); String fileName = DBMenuBar.cleanseFileName( Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6) + ": " + Main.getCurrentPage().toDisplayString().replaceAll("\\|", "-")); File f = new File(Main.getFilePath()); f.mkdirs(); f = new File(Main.getFilePath() + fileName + ".pdf"); BufferedImage bi = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); paintComponent(g); g.dispose(); PDDocument doc = null; try { doc = new PDDocument(); boolean crop = true; State.print(field); for (Point p : Main.getCurrentPage().getDots().keySet()) if (p.getX() < field.getWidth() * 0.1 + field.getX() || p.getX() > field.getWidth() * 0.9 + field.getX()) { crop = false; break; } if (Main.getCurrentPage().getTextPoint().getX() < field.getWidth() * 0.1 + field.getX() || Main.getCurrentPage().getTextPoint().getX() + 100 > field.getWidth() * 0.9 + field.getX()) crop = false; float scale = 1.0f; if (crop) scale = 0.8f; PDPage page = new PDPage(new PDRectangle((float) field.getWidth() * scale, (float) field.getHeight())); doc.addPage(page); PDImageXObject pdImage = LosslessFactory.createFromImage(doc, bi); PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true); contentStream.drawImage(pdImage, -1 * field.x - (float) (((1 - scale) / 2.0f) * field.getWidth()), -1 * field.y, pdImage.getWidth(), pdImage.getHeight()); contentStream.close(); doc.save(f); } finally { if (doc != null) doc.close(); } }
From source file:com.evanbelcher.DrillBook.display.DBDesktopPane.java
License:Open Source License
/** * Prints every page to a pdf file//from w ww . j a v a2 s .c om * * @throws IOException if the file cannot be found or the pdf cannot be created */ protected void printAllPagesToPdf() throws IOException { io.clearActivePoints(); ddf.updateAll(io.getActivePoints()); File f = new File(Main.getFilePath()); f.mkdirs(); String fileName = DBMenuBar.cleanseFileName(Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6)); f = new File(Main.getFilePath() + fileName + " full show" + ".pdf"); boolean crop = true; a: for (int pageNum : Main.getPages().keySet()) { for (Point p : Main.getPages().get(pageNum).getDots().keySet()) { if (p.getX() < field.getWidth() * 0.1 + field.getX() || p.getX() > field.getWidth() * 0.9 + field.getX()) { crop = false; break a; } } if (Main.getPages().get(pageNum).getTextPoint().getX() < field.getWidth() * 0.1 + field.getX() || Main.getPages().get(pageNum).getTextPoint().getX() + 100 > field.getWidth() * 0.9 + field.getX()) { crop = false; break; } } float scale = 1.0f; if (crop) scale = 0.8f; PDDocument doc = null; try { doc = new PDDocument(); for (int i : Main.getPages().keySet()) { Main.setCurrentPage(i); BufferedImage bi = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); paintComponent(g); g.dispose(); PDPage page = new PDPage( new PDRectangle((float) field.getWidth() * scale, (float) field.getHeight())); doc.addPage(page); PDImageXObject pdImage = LosslessFactory.createFromImage(doc, bi); PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true); contentStream.drawImage(pdImage, -1 * field.x - (float) (((1 - scale) / 2.0f) * field.getWidth()), -1 * field.y, pdImage.getWidth(), pdImage.getHeight()); contentStream.close(); } doc.save(f); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (doc != null) doc.close(); pdf.updateAfterPrintAll(); } }
From source file:com.evanbelcher.DrillBook.DotSheetMaker.java
License:Open Source License
/** * Prints all dot sheets to pdf files/*from ww w . jav a 2 s . com*/ */ private void printAllToPdf() throws IOException { printing = true; String folder = DBMenuBar.cleanseFileName(Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6)) + " Dot Sheets/"; File f = new File(Main.getFilePath() + folder); f.mkdirs(); PDDocument doc = null; String[] chars = new String[26]; for (int i = 0; i < 26; i++) chars[i] = String.valueOf((char) (65 + i)); try { for (String letter : chars) { doc = new PDDocument(); String fileName = Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6) + " " + DBMenuBar.cleanseFileName(letter); f = new File(Main.getFilePath() + folder + fileName + " dot sheet.pdf"); ArrayList<String> list = new ArrayList<>(map.keySet()); list.sort(nameComparator); for (String dotName : list) { if (dotName.replaceAll("[0-9]", "").equals(letter)) { int i = 0; PDPage page = new PDPage(); doc.addPage(page); PDFont font = PDType1Font.HELVETICA_BOLD; PDPageContentStream contentStream = new PDPageContentStream(doc, page); contentStream.beginText(); contentStream.setFont(font, 10.0f); contentStream.newLineAtOffset(10, page.getMediaBox().getHeight() - 20); contentStream.showText(Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6)); contentStream.endText(); contentStream.beginText(); contentStream.setFont(font, 12.0f); contentStream.newLineAtOffset(page.getMediaBox().getWidth() * 0.3f, page.getMediaBox().getHeight() - 20); contentStream.showText(dotName); contentStream.endText(); contentStream.beginText(); contentStream.setFont(font, 10.0f); contentStream.newLineAtOffset(page.getMediaBox().getWidth() * 0.6f, page.getMediaBox().getHeight() - 20); contentStream.showText("Name: ______________________________"); contentStream.endText(); contentStream.close(); float margin = 10; float tableWidth = page.getMediaBox().getWidth() - (2 * margin); float yStartNewPage = page.getMediaBox().getHeight() - (3 * margin); //noinspection UnnecessaryLocalVariable float yStart = yStartNewPage; float bottomMargin = 70; BaseTable table = new BaseTable(yStart, yStartNewPage, bottomMargin, tableWidth, margin, doc, page, true, true); //Create Header row Row<PDPage> headerRow = table.createRow(15f); Cell<PDPage> headerCell = headerRow.createCell(100 / 7f, "Set #"); headerCell.setAlign(HorizontalAlignment.CENTER); headerCell.setFillColor(HEADER_COLOR); headerRow.createCell(300 / 7f, "Horizontal").copyCellStyle(headerCell); headerRow.createCell(300 / 7f, "Vertical").copyCellStyle(headerCell); table.addHeaderRow(headerRow); for (int pageNum : new TreeSet<>(map.get(dotName).keySet())) { String text = map.get(dotName).get(pageNum); String[] lines = text.split("\\n"); String line1 = lines[0].replace("Horizontal - ", ""); String line2 = lines[1].replace("Vertical - ", ""); Row<PDPage> row = table.createRow(10f); Cell<PDPage> cell = row.createCell(100 / 7f, pageNum + ""); cell.setAlign(HorizontalAlignment.CENTER); cell.setFillColor(openingSets.contains(pageNum) ? OPENING_SET_COLOR : NORMAL_COLOR); row.createCell(300 / 7f, line1).copyCellStyle(cell); row.createCell(300 / 7f, line2).copyCellStyle(cell); if (++i >= 35) { table.draw(); page = new PDPage(); doc.addPage(page); table = new BaseTable(yStart, yStartNewPage, bottomMargin, tableWidth, margin, doc, page, true, true); //Create Header row headerRow = table.createRow(15f); headerCell = headerRow.createCell(100 / 7f, "Set #"); headerCell.setAlign(HorizontalAlignment.CENTER); headerCell.setFillColor(HEADER_COLOR); headerRow.createCell(300 / 7f, "Horizontal").copyCellStyle(headerCell); headerRow.createCell(300 / 7f, "Vertical").copyCellStyle(headerCell); table.addHeaderRow(headerRow); i -= 35; } } table.draw(); } } if (doc.getNumberOfPages() > 0) doc.save(f); else doc.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (doc != null) doc.close(); } printing = false; }
From source file:com.fangxin365.core.utils.PDFMerger.java
License:Apache License
/** * Merge the list of source documents, saving the result in the destination * file./*w w w . j a v a2s . c o m*/ * * @throws IOException * If there is an error saving the document. * @throws COSVisitorException * If an error occurs while saving the destination file. */ public void mergeDocuments() throws IOException, COSVisitorException { PDDocument destination = null; InputStream sourceFile; PDDocument source; if (sources != null && sources.size() > 0) { java.util.Vector<PDDocument> tobeclosed = new java.util.Vector<PDDocument>(); try { Iterator<InputStream> sit = sources.iterator(); sourceFile = sit.next(); destination = PDDocument.load(sourceFile); while (sit.hasNext()) { sourceFile = sit.next(); source = PDDocument.load(sourceFile); tobeclosed.add(source); appendDocument(destination, source); } if (destinationStream == null) { destination.save(destinationFileName); } else { destination.save(destinationStream); } } finally { if (destination != null) { destination.close(); } for (PDDocument doc : tobeclosed) { doc.close(); } } } }