List of usage examples for org.apache.pdfbox.pdmodel PDDocument getDocumentCatalog
public PDDocumentCatalog getDocumentCatalog()
From source file:org.github.jipsg.pdfbox.PdfToImageConverter.java
License:Apache License
/** * Split a PDF document into images./*from w ww .j ava 2s . c o m*/ * * @param pdDocument the source document * @param imageFormat the requested image format, e.g. "jpeg" * @param startPage the first extracted page * @param endPage the las extracted page * @param resolution the resolution of the extracted images * @param color the color model, e.g. "rgb", "gray" * @return a list of images * @throws Exception the conversion failed */ @SuppressWarnings("unchecked") public List<BufferedImage> toImages(PDDocument pdDocument, String imageFormat, int startPage, int endPage, int resolution, String color) throws Exception { /** Validate.notNull(pdDocument, "pdDocument is null"); Validate.notEmpty(imageFormat, "imageFormat is null"); Validate.isTrue(startPage > 0, "invalid start page : " + startPage); Validate.isTrue(endPage >= startPage, "invalid end page : " + endPage); Validate.isTrue(resolution >= 0, "invalid resolution : " + resolution); */ List<BufferedImage> result = new ArrayList<BufferedImage>(); int imageType = getImageType(color); List<PDPage> pages = pdDocument.getDocumentCatalog().getAllPages(); int pagesSize = pages.size(); for (int i = startPage - 1; i < endPage && i < pagesSize; i++) { PDPage page = pages.get(i); PDRectangle cropBox = page.findCropBox(); int currResolution = calculateResolution(resolution, cropBox.getWidth(), cropBox.getHeight()); BufferedImage image = page.convertToImage(imageType, currResolution); result.add(image); } return result; }
From source file:org.isisaddons.module.pdf.fixture.dom.templates.CustomerConfirmation.java
License:Apache License
/** * Loads the template pdf file and populates it with the order details * * @param order The order with the details for the pdf document * @return The populated PDF document//from w w w . ja v a 2 s.co m * @throws Exception If the loading or the populating of the document fails for some reason */ private PDDocument loadAndPopulateTemplate(Order order) throws Exception { PDDocument pdfDocument = PDDocument.load(new ByteArrayInputStream(pdfAsBytes)); PDAcroForm pdfForm = pdfDocument.getDocumentCatalog().getAcroForm(); List<PDField> fields = pdfForm.getFields(); SortedSet<OrderLine> orderLines = order.getOrderLines(); for (PDField field : fields) { String fullyQualifiedName = field.getFullyQualifiedName(); if ("orderDate".equals(fullyQualifiedName)) { field.setValue(order.getDate().toString()); } else if ("orderNumber".equals(fullyQualifiedName)) { field.setValue(order.getNumber()); } else if ("customerName".equals(fullyQualifiedName)) { field.setValue(order.getCustomerName()); } else if ("message".equals(fullyQualifiedName)) { String message = "You have ordered '" + orderLines.size() + "' products"; field.setValue(message); } else if ("preferences".equals(fullyQualifiedName)) { field.setValue(order.getPreferences()); } } int i = 1; Iterator<OrderLine> orderLineIterator = orderLines.iterator(); while (i < 7 && orderLineIterator.hasNext()) { OrderLine orderLine = orderLineIterator.next(); String descriptionFieldName = "orderLine|" + i + "|desc"; pdfForm.getField(descriptionFieldName).setValue(orderLine.getDescription()); String costFieldName = "orderLine|" + i + "|cost"; pdfForm.getField(costFieldName).setValue(orderLine.getDescription()); String quantityFieldName = "orderLine|" + i + "|quantity"; pdfForm.getField(quantityFieldName).setValue(orderLine.getDescription()); i++; } return pdfDocument; }
From source file:org.jahia.modules.dm.thumbnails.impl.PDFBoxPDF2ImageConverterService.java
License:Open Source License
public BufferedImage getImageOfPage(InputStream pdfInputStream, int pageNumber) throws DocumentOperationException { BufferedImage image = null;// ww w .j a v a 2 s.c o m long timer = System.currentTimeMillis(); PDDocument pdfDoc = null; try { pdfDoc = PDDocument.load(pdfInputStream); PDPage page = (PDPage) pdfDoc.getDocumentCatalog().getAllPages().get(pageNumber); image = page.convertToImage(imageType, resolution); if (image != null && logger.isDebugEnabled()) { logger.debug("Generated an image for the page {} of the supplied input stream in {} ms", pageNumber, (System.currentTimeMillis() - timer)); } } catch (IndexOutOfBoundsException e) { logger.warn("No page with the number {} found in the PDF document", pageNumber); } catch (IOException e) { throw new DocumentOperationException("Error occurred trying to generate an image for the page " + pageNumber + " of the supplied input stream", e); } finally { try { pdfDoc.close(); } catch (Exception e) { // ignore } } return image; }
From source file:org.jahia.modules.docviewer.PDFBoxPDF2ImageConverterService.java
License:Open Source License
public BufferedImage getImageOfPage(InputStream pdfInputStream, int pageNumber) throws Exception { BufferedImage image = null;//from w w w. j a va2s . co m PDDocument pdfDoc = null; try { pdfDoc = PDDocument.load(pdfInputStream); PDPage page = (PDPage) pdfDoc.getDocumentCatalog().getAllPages().get(pageNumber); image = page.convertToImage(imageType, resolution); } catch (IndexOutOfBoundsException e) { logger.warn("No page with the number {} found in the PDF document", pageNumber); } finally { try { pdfDoc.close(); } catch (Exception e) { // ignore } } return image; }
From source file:org.kuali.coeus.common.impl.person.signature.PersonSignatureServiceImpl.java
License:Open Source License
/** * This method is to scan for signature tag in each page and apply the signature * at desired location./* www . ja v a 2s . c o m*/ * @param imageData * @param originalByteArrayOutputStream */ @SuppressWarnings("unchecked") protected ByteArrayOutputStream scanAndApplyAutographInEachPage(byte[] imageData, ByteArrayOutputStream originalByteArrayOutputStream) throws Exception { ByteArrayOutputStream outputStream = originalByteArrayOutputStream; byte[] pdfFileData = originalByteArrayOutputStream.toByteArray(); PDDocument originalDocument = getPdfDocument(pdfFileData); //PDDocument.load(is); PDDocument signatureDocument = new PDDocument(); List<PDPage> originalDocumentPages = originalDocument.getDocumentCatalog().getAllPages(); for (PDPage page : originalDocumentPages) { List<String> signatureTags = new ArrayList<String>(getSignatureTagParameter()); PersonSignatureLocationHelper printer = new PersonSignatureLocationHelper(signatureTags); PDStream contents = page.getContents(); if (contents != null) { printer.processStream(page, page.findResources(), page.getContents().getStream()); } PDPage signaturePage = new PDPage(); if (printer.isSignatureTagExists()) { PDJpeg signatureImage = new PDJpeg(signatureDocument, getBufferedImage(imageData)); PDPageContentStream stream = new PDPageContentStream(signatureDocument, signaturePage, true, true); for (PersonSignaturePrintHelper signatureHelper : printer.getPersonSignatureLocations()) { float coordinateX = signatureHelper.getCoordinateX(); float coordinateY = signatureHelper.getCoordinateY() - signatureImage.getHeight() - ADDITIONAL_SPACE_BETWEEN_TAG_AND_IMAGE; stream.drawImage(signatureImage, coordinateX, coordinateY); stream.close(); } } else { signaturePage = page; } signatureDocument.addPage(signaturePage); } Overlay overlay = new Overlay(); overlay.overlay(signatureDocument, originalDocument); originalDocument.save(outputStream); originalDocument.close(); signatureDocument.close(); return outputStream; }
From source file:org.kuali.kra.printing.service.impl.PersonSignatureServiceImpl.java
License:Educational Community License
/** * This method is to remove interactive fields from the form. * @param pdfBytes/*from w w w . j av a2s. c o m*/ * @return * @throws Exception */ protected ByteArrayOutputStream getFlattenedPdfForm(byte[] pdfBytes) throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); InputStream is = new ByteArrayInputStream(pdfBytes); PDDocument pdDoc = PDDocument.load(is); PDDocumentCatalog pdCatalog = pdDoc.getDocumentCatalog(); PDAcroForm acroForm = pdCatalog.getAcroForm(); COSDictionary acroFormDict = acroForm.getDictionary(); COSArray fields = (COSArray) acroFormDict.getDictionaryObject("Fields"); fields.clear(); pdDoc.save(byteArrayOutputStream); return byteArrayOutputStream; }
From source file:org.mustangproject.ZUGFeRD.ZUGFeRDExporter.java
License:Open Source License
/** * Embeds an external file (generic - any type allowed) in the PDF. * * @param doc PDDocument to attach the file to. * @param filename name of the file that will become attachment name in the PDF * @param relationship how the file relates to the content, e.g. "Alternative" * @param description Human-readable description of the file content * @param subType type of the data e.g. could be "text/xml" - mime like * @param data the binary data of the file/attachment * @throws java.io.IOException/* w w w .j a va 2 s .c o m*/ */ public void PDFAttachGenericFile(PDDocument doc, String filename, String relationship, String description, String subType, byte[] data) throws IOException { fileAttached = true; PDComplexFileSpecification fs = new PDComplexFileSpecification(); fs.setFile(filename); COSDictionary dict = fs.getCOSObject(); dict.setName("AFRelationship", relationship); dict.setString("UF", filename); dict.setString("Desc", description); ByteArrayInputStream fakeFile = new ByteArrayInputStream(data); PDEmbeddedFile ef = new PDEmbeddedFile(doc, fakeFile); ef.setSubtype(subType); ef.setSize(data.length); ef.setCreationDate(new GregorianCalendar()); ef.setModDate(GregorianCalendar.getInstance()); fs.setEmbeddedFile(ef); // In addition make sure the embedded file is set under /UF dict = fs.getCOSObject(); COSDictionary efDict = (COSDictionary) dict.getDictionaryObject(COSName.EF); COSBase lowerLevelFile = efDict.getItem(COSName.F); efDict.setItem(COSName.UF, lowerLevelFile); // now add the entry to the embedded file tree and set in the document. PDDocumentNameDictionary names = new PDDocumentNameDictionary(doc.getDocumentCatalog()); PDEmbeddedFilesNameTreeNode efTree = names.getEmbeddedFiles(); if (efTree == null) { efTree = new PDEmbeddedFilesNameTreeNode(); } Map<String, PDComplexFileSpecification> namesMap = new HashMap<>(); Map<String, PDComplexFileSpecification> oldNamesMap = efTree.getNames(); if (oldNamesMap != null) { for (String key : oldNamesMap.keySet()) { namesMap.put(key, oldNamesMap.get(key)); } } namesMap.put(filename, fs); efTree.setNames(namesMap); names.setEmbeddedFiles(efTree); doc.getDocumentCatalog().setNames(names); // AF entry (Array) in catalog with the FileSpec COSArray cosArray = (COSArray) doc.getDocumentCatalog().getCOSObject().getItem("AF"); if (cosArray == null) { cosArray = new COSArray(); } cosArray.add(fs); COSDictionary dict2 = doc.getDocumentCatalog().getCOSObject(); COSArray array = new COSArray(); array.add(fs.getCOSObject()); // see below dict2.setItem("AF", array); doc.getDocumentCatalog().getCOSObject().setItem("AF", cosArray); }
From source file:org.mycore.media.MCRMediaPDFParser.java
License:Open Source License
/** * Parse file and store metadata in related Object. * // ww w . ja v a 2 s .c om * @return MCRMediaObject * can be held any MCRMediaObject * @see MCRMediaObject#clone() */ @SuppressWarnings("unchecked") public synchronized MCRMediaObject parse(File file) throws Exception { if (!file.exists()) throw new IOException("File \"" + file.getName() + "\" doesn't exists!"); MCRPDFObject media = new MCRPDFObject(); LOGGER.info("parse " + file.getName() + "..."); PDDocument pdf = PDDocument.load(file); try { media.fileName = file.getName(); media.fileSize = file.length(); media.folderName = (file.getAbsolutePath()).replace(file.getName(), ""); PDPageTree pages = pdf.getDocumentCatalog().getPages(); media.numPages = pdf.getNumberOfPages(); PDPage page = (PDPage) pages.get(0); PDRectangle rect = page.getMediaBox(); media.width = Math.round(rect.getWidth()); media.height = Math.round(rect.getHeight()); PDDocumentInformation info = pdf.getDocumentInformation(); if (info != null) { media.tags = new MCRMediaTagObject(); media.tags.author = info.getAuthor(); media.tags.creator = info.getCreator(); media.tags.producer = info.getProducer(); media.tags.title = info.getTitle(); media.tags.subject = info.getSubject(); media.tags.keywords = info.getKeywords(); } } catch (Exception e) { LOGGER.error(e.getMessage()); throw new Exception(e.getMessage()); } finally { pdf.close(); } return media; }
From source file:org.nuxeo.ecm.platform.convert.tests.BaseConverterTest.java
License:Apache License
public static boolean isPDFA(File pdfFile) throws Exception { PDDocument pddoc = PDDocument.load(pdfFile); XMPMetadata xmp = pddoc.getDocumentCatalog().getMetadata().exportXMPMetadata(); Document doc = xmp.getXMPDocument(); // <rdf:Description xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/" // rdf:about=""> // <pdfaid:part>1</pdfaid:part> // <pdfaid:conformance>A</pdfaid:conformance> // </rdf:Description> NodeList list = doc.getElementsByTagName("pdfaid:conformance"); return list != null && "A".equals(list.item(0).getTextContent()); }
From source file:org.nuxeo.pdf.PDFPageNumbering.java
License:Open Source License
/** * Add page numbers and returns a <i>new</i> Blob. Original blob is not * modified. This code assumes:/* ww w.ja v a 2 s .com*/ * <ul> * <li>There is no page numbers already (it always draw the numbers)</li> * <li>The pdf is not rotated</li> * <li>Default values apply: * <ul> * <li><code>inStartAtPage</code> and <code>inStartAtNumber</code> are set * to 1 if they are passed < 1.</li> * <li>If <code>inStartAtPage</code> is > number of pages it also is reset * to 1</li> * <li><code>inFontName</code> is set to "Helvetica" if "" or null</li> * <li><code>inFontSize</code> is <= 0, it is set to 16</li> * <li><code>inHex255Color</code> is set to black if "", null or if its * length < 6. Expected format is 0xrrggbb, #rrggbb or just rrggbb</li> * <li><code>inPosition</code> is set to <code>BOTTOM_RIGHT</code> if null</li> * </ul> * </li> * <li></li> * </ul> * * @param inBlob * @param inStartAtPage * @param inStartAtNumber * @param inFontName * @param inFontSize * @param inHex255Color * @param inPosition * @return Blob * @throws IOException * @throws COSVisitorException * * @since 5.9.5 */ public Blob addPageNumbers(int inStartAtPage, int inStartAtNumber, String inFontName, float inFontSize, String inHex255Color, PAGE_NUMBER_POSITION inPosition) throws IOException, COSVisitorException { Blob result = null; PDDocument doc = null; inStartAtPage = inStartAtPage < 1 ? 1 : inStartAtPage; int pageNumber = inStartAtNumber < 1 ? 1 : inStartAtNumber; inFontSize = inFontSize <= 0 ? DEFAULT_FONT_SIZE : inFontSize; int[] rgb = PDFUtils.hex255ToRGB(inHex255Color); try { doc = PDDocument.load(blob.getStream()); List<?> allPages; PDFont font; int max; if (inFontName == null || inFontName.isEmpty()) { font = PDType1Font.HELVETICA; } else { font = PDType1Font.getStandardFont(inFontName); if (font == null) { font = new PDType1Font(inFontName); } } allPages = doc.getDocumentCatalog().getAllPages(); max = allPages.size(); inStartAtPage = inStartAtPage > max ? 1 : inStartAtPage; for (int i = inStartAtPage; i <= max; i++) { String pageNumAsStr = "" + pageNumber; pageNumber += 1; PDPage page = (PDPage) allPages.get(i - 1); PDPageContentStream footercontentStream = new PDPageContentStream(doc, page, true, true); float stringWidth = font.getStringWidth(pageNumAsStr) * inFontSize / 1000f; float stringHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() * inFontSize / 1000; PDRectangle pageRect = page.findMediaBox(); float xMoveAmount, yMoveAmount; if (inPosition == null) { inPosition = PAGE_NUMBER_POSITION.BOTTOM_RIGHT; } switch (inPosition) { case BOTTOM_LEFT: xMoveAmount = 10; yMoveAmount = pageRect.getLowerLeftY() + 10; break; case BOTTOM_CENTER: xMoveAmount = (pageRect.getUpperRightX() / 2) - (stringWidth / 2); yMoveAmount = pageRect.getLowerLeftY() + 10; break; case TOP_LEFT: xMoveAmount = 10; yMoveAmount = pageRect.getHeight() - stringHeight - 10; break; case TOP_CENTER: xMoveAmount = (pageRect.getUpperRightX() / 2) - (stringWidth / 2); yMoveAmount = pageRect.getHeight() - stringHeight - 10; break; case TOP_RIGHT: xMoveAmount = pageRect.getUpperRightX() - 10 - stringWidth; yMoveAmount = pageRect.getHeight() - stringHeight - 10; break; // Bottom-right is the default default: xMoveAmount = pageRect.getUpperRightX() - 10 - stringWidth; yMoveAmount = pageRect.getLowerLeftY() + 10; break; } footercontentStream.beginText(); footercontentStream.setFont(font, inFontSize); footercontentStream.moveTextPositionByAmount(xMoveAmount, yMoveAmount); footercontentStream.setNonStrokingColor(rgb[0], rgb[1], rgb[2]); footercontentStream.drawString(pageNumAsStr); footercontentStream.endText(); footercontentStream.close(); } File tempFile = File.createTempFile("pdfutils-", ".pdf"); doc.save(tempFile); result = new FileBlob(tempFile); Framework.trackFile(tempFile, result); } finally { if (doc != null) { doc.close(); } } return result; }