List of usage examples for org.apache.pdfbox.pdmodel PDDocument load
public static PDDocument load(byte[] input) 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 {/*w w w .ja va 2 s.c o 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.coast.PDFPrinter.java
License:Apache License
/** * Entry point./*from w w w . j a v a 2s.com*/ */ public static void main(String args[]) throws PrinterException, IOException { if (args.length != 1) { System.err.println("usage: java " + PDFPrinter.class.getName() + " <input>"); System.exit(1); } String filename = args[0]; PDDocument document = PDDocument.load(new File(filename)); // choose your printing method: print(document); //printWithAttributes(document); //printWithDialog(document); //printWithDialogAndAttributes(document); //printWithPaper(document); }
From source file:com.coast.PDFPrinter.java
License:Apache License
@Override public Object onCall(MuleEventContext eventContext) throws Exception { // TODO Auto-generated method stub MuleMessage _message = eventContext.getMessage(); String _fileName = _message.getInvocationProperty("file_name"); String _dirName = _message.getInvocationProperty("dest_directory"); String _path = _dirName + "/" + _fileName; System.out.println("Transformig to PDF file:" + _path); //byte [] _bytePayload = eventContext.getMessage().getPayloadAsBytes(); PDDocument document = PDDocument.load(new File(_path)); // choose your printing method: print(document);/*from w w w.j a va 2 s. c o m*/ return null; }
From source file:com.devnexus.ting.web.controller.PdfUtils.java
License:Apache License
public PdfUtils(float margin, String title) throws IOException { this.margin = margin; doc = new PDDocument(); baseFont = PDType0Font.load(doc, PdfUtils.class.getResourceAsStream("/fonts/Arial.ttf")); headerFont = PDType1Font.HELVETICA_BOLD; subHeaderFont = PDType1Font.HELVETICA_BOLD; devnexusLogo = PDDocument.load(PdfUtils.class.getResourceAsStream("/fonts/devnexus-logo.pdf")); this.currentPage = new PDPage(); this.pages.add(currentPage); this.doc.addPage(currentPage); final PDRectangle mediabox = currentPage.getMediaBox(); this.width = mediabox.getWidth() - 2 * margin; float startX = mediabox.getLowerLeftX() + margin; float startY = mediabox.getUpperRightY() - margin; this.initialHeightCounter = startY; this.heightCounter = startY; LOGGER.info(String.format(/*from w w w . j av a 2 s . co m*/ "Margin: %s, width: %s, startX: %s, " + "startY: %s, heightCounter: %s, baseFontSize: %s, headerFontSize: %s", margin, width, startX, startY, heightCounter, baseFont, headerFont)); contents = new PDPageContentStream(doc, currentPage); // Add Logo final LayerUtility layerUtility = new LayerUtility(doc); final PDFormXObject logo = layerUtility.importPageAsForm(devnexusLogo, 0); final AffineTransform affineTransform = AffineTransform.getTranslateInstance(100, startY - 50); affineTransform.scale(2d, 2d); layerUtility.appendFormAsLayer(currentPage, logo, affineTransform, "devnexus-logo"); this.heightCounter -= 100; this.contents.beginText(); this.contents.setFont(headerFont, headerFontSize); this.currentLeading = this.lineSpacing * baseFontSize; this.contents.setLeading(this.currentLeading); contents.newLineAtOffset(50, heightCounter); println(title); this.contents.setFont(baseFont, baseFontSize); this.currentLeading = this.lineSpacing * baseFontSize; this.contents.setLeading(this.currentLeading); println(); }
From source file:com.ecm.pdfbox.PdfPrinting.java
License:Apache License
/** * Entry point./*from w w w . ja v a 2 s .c o m*/ */ public static void main(String args[]) throws PrinterException, IOException { if (args.length != 1) { System.err.println("usage: java " + PdfPrinting.class.getName() + " <input>"); System.exit(1); } String filename = args[0]; PDDocument document = PDDocument.load(new File(filename)); // choose your printing method: print(document); //printWithAttributes(document); //printWithDialog(document); //printWithDialogAndAttributes(document); //printWithPaper(document); }
From source file:com.ecmkit.service.convert.impl.PDFToImage.java
License:Apache License
/** * Infamous main method./*from ww w . j a v a 2 s.co 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 {/* ww w.j a va 2 s .c o 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.enginkutuk.pdfboxsample.PDFBoxSample.java
public void readPdfFile(String path) { try {//from ww w . jav a2 s. c o m PDDocument document = null; document = PDDocument.load(new File(path)); document.getClass(); if (!document.isEncrypted()) { PDFTextStripperByArea stripper = new PDFTextStripperByArea(); stripper.setSortByPosition(true); PDFTextStripper Tstripper = new PDFTextStripper(); String st = Tstripper.getText(document); System.out.println(st); JOptionPane.showMessageDialog(null, st); } } catch (Exception e) { e.printStackTrace(); } }
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();//from ww w . j a va2s.c o m return text; } else { return null; } }
From source file:com.esri.geoportal.commons.pdf.PdfUtils.java
License:Apache License
/** * Reads metadata values from a PDF file. * //from w w w.ja v a2s .c o m * @param rawBytes the PDF to read * @param defaultTitle title to be used if the PDF metadata doesn't have one * @param geometryServiceUrl url of a <a href="https://developers.arcgis.com/rest/services-reference/geometry-service.htm">geometry service</a> for reprojecting coordinates. * * @return metadata properties or null if the PDF cannot be read. * * @throws IOException on parsing error */ public static Properties readMetadata(byte[] rawBytes, String defaultTitle, String geometryServiceUrl) throws IOException { Properties ret = new Properties(); // Attempt to read in the PDF file try (PDDocument document = PDDocument.load(rawBytes)) { // See if we can read the PDF if (!document.isEncrypted()) { // Get document metadata PDDocumentInformation info = document.getDocumentInformation(); if (info != null) { if (info.getTitle() != null) { ret.put(PROP_TITLE, info.getTitle()); } else { ret.put(PROP_TITLE, defaultTitle); } if (info.getSubject() != null) { ret.put(PROP_SUBJECT, info.getSubject()); } else { StringBuilder psudoSubject = new StringBuilder(""); psudoSubject.append("\nAuthor: " + info.getAuthor()); psudoSubject.append("\nCreator: " + info.getCreator()); psudoSubject.append("\nProducer: " + info.getProducer()); ret.put(PROP_SUBJECT, psudoSubject.toString()); } if (info.getModificationDate() != null) { ret.put(PROP_MODIFICATION_DATE, info.getModificationDate().getTime()); } else { ret.put(PROP_MODIFICATION_DATE, info.getCreationDate().getTime()); } } else { LOG.warn("Got null metadata for PDF file"); return null; } // Attempt to read in geospatial PDF data COSObject measure = document.getDocument().getObjectByType(COSName.getPDFName("Measure")); String bBox = null; if (measure != null) { // This is a Geospatial PDF (i.e. Adobe's standard) COSDictionary dictionary = (COSDictionary) measure.getObject(); float[] coords = ((COSArray) dictionary.getItem("GPTS")).toFloatArray(); bBox = generateBbox(coords); } else { PDPage page = document.getPage(0); if (page.getCOSObject().containsKey(COSName.getPDFName("LGIDict"))) { // This is a GeoPDF (i.e. TerraGo's standard) bBox = extractGeoPDFProps(page, geometryServiceUrl); } } if (bBox != null) { ret.put(PROP_BBOX, bBox); } } else { LOG.warn("Cannot read encrypted PDF file"); return null; } } catch (IOException ex) { LOG.error("Exception reading PDF", ex); throw ex; } return ret; }