List of usage examples for org.apache.pdfbox.pdmodel PDDocument getDocumentCatalog
public PDDocumentCatalog getDocumentCatalog()
From source file:org.oscarehr.document.web.SplitDocumentAction.java
License:Open Source License
public ActionForward rotate180(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Document doc = documentDAO.getDocument(request.getParameter("document")); // String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR"); String docdownload = EDocUtil.getDocumentPath(doc.getDocfilename()); if (doc.getContenttype().equals("application/pdf")) { FileInputStream input = null; PDDocument pdf = null; try {//w w w .ja va2s.com // FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename()); input = new FileInputStream(docdownload); PDFParser parser = new PDFParser(input); parser.parse(); pdf = parser.getPDDocument(); int x = 1; for (Object p : pdf.getDocumentCatalog().getAllPages()) { PDPage pg = (PDPage) p; Integer r = (pg.getRotation() != null ? pg.getRotation() : 0); pg.setRotation((r + 180) % 360); ManageDocumentAction.deleteCacheVersion(doc, x); x++; } // pdf.save(docdownload + doc.getDocfilename()); pdf.save(docdownload); } finally { if (pdf != null) pdf.close(); input.close(); } } else if (doc.getContenttype().equals("image/jpg") || doc.getContenttype().equals("image/png") || doc.getContenttype().equals("image/gif")) { String documentDir = EDocUtil.getDocumentDir(doc.getDocfilename()); File file = new File(documentDir + doc.getDocfilename()); BufferedImage image = ImageIO.read(file); if (image == null) return null; BufferedImage rotatedImage = new BufferedImage(image.getHeight(), image.getWidth(), BufferedImage.TYPE_INT_ARGB); String suffix = null; String contentType = doc.getContenttype(); if (contentType.equalsIgnoreCase("image/jpg") || contentType.equalsIgnoreCase("image/jpeg")) { suffix = "jpg"; } else if (contentType.equalsIgnoreCase("image/png")) { suffix = "png"; } else if (contentType.equalsIgnoreCase("image/gif")) { suffix = "gif"; } AffineTransform tx = AffineTransform.getScaleInstance(1, -1); tx = AffineTransform.getScaleInstance(-1, -1); tx.translate(-image.getWidth(null), -image.getHeight(null)); AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); image = op.filter(image, null); ImageIO.write(image, suffix, file); } else { //umknown type - does nothing } return null; }
From source file:org.oscarehr.document.web.SplitDocumentAction.java
License:Open Source License
public ActionForward rotate90(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Document doc = documentDAO.getDocument(request.getParameter("document")); FileInputStream input = new FileInputStream(EDocUtil.getDocumentPath(doc.getDocfilename())); PDFParser parser = new PDFParser(input); parser.parse();/*from ww w . j a va2 s.com*/ PDDocument pdf = parser.getPDDocument(); int x = 1; for (Object p : pdf.getDocumentCatalog().getAllPages()) { PDPage pg = (PDPage) p; Integer r = (pg.getRotation() != null ? pg.getRotation() : 0); pg.setRotation((r + 90) % 360); ManageDocumentAction.deleteCacheVersion(doc, x); x++; } pdf.save(EDocUtil.getDocumentPath(doc.getDocfilename())); pdf.close(); input.close(); return null; }
From source file:org.oscarehr.document.web.SplitDocumentAction.java
License:Open Source License
public ActionForward removeFirstPage(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Document doc = documentDAO.getDocument(request.getParameter("document")); // String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR"); String docdownload = EDocUtil.getDocumentPath(doc.getDocfilename()); // FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename()); FileInputStream input = new FileInputStream(docdownload); PDFParser parser = new PDFParser(input); parser.parse();//from w w w .j a v a2 s . c o m PDDocument pdf = parser.getPDDocument(); // Documents must have at least 2 pages, for the first page to be removed. if (pdf.getNumberOfPages() <= 1) { return null; } int x = 1; for (Object p : pdf.getDocumentCatalog().getAllPages()) { ManageDocumentAction.deleteCacheVersion(doc, x); x++; } pdf.removePage(0); EDocUtil.subtractOnePage(request.getParameter("document")); // pdf.save(docdownload + doc.getDocfilename()); System.gc(); //avoid Win channel lock problem pdf.save(docdownload); pdf.close(); input.close(); return null; }
From source file:org.paxle.parser.pdf.impl.PdfParser.java
License:Open Source License
/** * A function to extract embedded URIs from the PDF-document. * //from w w w . jav a 2 s .c om */ protected void extractURLs(IParserDocument parserDoc, PDDocument pddDoc) throws IOException { final PDDocumentCatalog pddDocCatalog = pddDoc.getDocumentCatalog(); if (pddDocCatalog == null) return; @SuppressWarnings("unchecked") final List<PDPage> allPages = pddDocCatalog.getAllPages(); if (allPages == null || allPages.isEmpty()) return; for (int i = 0; i < allPages.size(); i++) { final PDFTextStripperByArea stripper = new PDFTextStripperByArea(); final PDPage page = (PDPage) allPages.get(i); @SuppressWarnings("unchecked") final List<PDAnnotation> annotations = page.getAnnotations(); if (annotations == null || annotations.isEmpty()) return; //first setup text extraction regions for (int j = 0; j < annotations.size(); j++) { final PDAnnotation annot = (PDAnnotation) annotations.get(j); if (annot instanceof PDAnnotationLink) { final PDAnnotationLink link = (PDAnnotationLink) annot; final PDRectangle rect = link.getRectangle(); //need to reposition link rectangle to match text space float x = rect.getLowerLeftX(); float y = rect.getUpperRightY(); float width = rect.getWidth(); float height = rect.getHeight(); int rotation = page.findRotation(); if (rotation == 0) { PDRectangle pageSize = page.findMediaBox(); y = pageSize.getHeight() - y; } else if (rotation == 90) { //do nothing } Rectangle2D.Float awtRect = new Rectangle2D.Float(x, y, width, height); stripper.addRegion("" + j, awtRect); } } stripper.extractRegions(page); for (int j = 0; j < annotations.size(); j++) { final PDAnnotation annot = (PDAnnotation) annotations.get(j); if (annot instanceof PDAnnotationLink) { final PDAnnotationLink link = (PDAnnotationLink) annot; final PDAction action = link.getAction(); final String urlText = stripper.getTextForRegion("" + j); if (action instanceof PDActionURI) { final PDActionURI embeddedUri = (PDActionURI) action; final URI temp = URI.create(embeddedUri.getURI()); parserDoc.addReference(temp, urlText, Constants.SERVICE_PID + ":" + PID); } } } } }
From source file:org.paxle.parser.pdf.impl.PdfParser.java
License:Open Source License
/** * A function to extract the content of embedded files from a PDF document. *///from w w w . j a v a2 s . c o m protected void extractEmbeddedFiles(URI location, IParserDocument parserDoc, PDDocument pddDoc) throws IOException { final PDDocumentCatalog pddDocCatalog = pddDoc.getDocumentCatalog(); if (pddDocCatalog == null) return; final PDDocumentNameDictionary nameDic = pddDocCatalog.getNames(); if (nameDic == null) return; final PDEmbeddedFilesNameTreeNode embeddedFiles = nameDic.getEmbeddedFiles(); if (embeddedFiles == null) return; @SuppressWarnings("unchecked") final Map<String, Object> names = embeddedFiles.getNames(); if (names == null || names.isEmpty()) return; final IParserContext context = this.contextLocal.getCurrentContext(); for (Entry<String, Object> name : names.entrySet()) { // final String fileDesc = name.getKey(); final Object fileObj = name.getValue(); if (fileObj == null) continue; if (fileObj instanceof PDComplexFileSpecification) { final PDComplexFileSpecification embeddedFileSpec = (PDComplexFileSpecification) fileObj; final PDEmbeddedFile embeddedFile = embeddedFileSpec.getEmbeddedFile(); // getting the embedded file name and mime-type final String fileName = embeddedFileSpec.getFile(); final String fileMimeType = embeddedFile.getSubtype(); if (fileMimeType == null) { this.logger.warn(String.format("No mime-type specified form embedded file '%s#%s'.", location, fileName)); continue; } // getting a parser to parse the content final ISubParser sp = context.getParser(fileMimeType); if (sp == null) { this.logger.warn(String.format("No parser found to parse embedded file '%s#%s' with type '%s'.", location, fileName, fileMimeType)); continue; } // parsing content InputStream embeddedFileStream = null; try { embeddedFileStream = embeddedFile.createInputStream(); final IParserDocument subParserDoc = sp.parse(location, "UTF-8", embeddedFileStream); if (subParserDoc.getMimeType() == null) { subParserDoc.setMimeType(fileMimeType); } parserDoc.addSubDocument(fileName, subParserDoc); } catch (ParserException e) { this.logger.error(String.format( "Unexpected error while parsing parse embedded file '%s#%s' with type '%s': %s", location, fileName, fileMimeType, e.getMessage())); } finally { if (embeddedFileStream != null) try { embeddedFileStream.close(); } catch (Exception e) { this.logger.error(e); } } } } }
From source file:org.pdfgal.pdfgal.pdfgal.impl.PDFGalImpl.java
License:Open Source License
@Override public List<String> split(final String inputUri, final String outputUri, final List<Integer> pages) throws IOException, COSVisitorException { final List<String> result = new ArrayList<String>(); if (StringUtils.isNotBlank(inputUri) && StringUtils.isNotBlank(outputUri) && CollectionUtils.isNotEmpty(pages)) { final PDDocument doc = PDDocument.load(inputUri); final List<PDDocument> splittedDocs = new ArrayList<PDDocument>(); @SuppressWarnings("unchecked") final List<PDPage> pagesList = doc.getDocumentCatalog().getAllPages(); // This section creates a new document for each split // indicated into the list, except the last one. Integer currentPage = 0;// w ww. ja va 2 s. c om for (final Integer page : pages) { final PDDocument document = new PDDocument(); for (Integer i = currentPage; i <= page - 2; i++) { document.addPage(pagesList.get(i)); } splittedDocs.add(document); currentPage = page - 1; document.close(); } // This section splits the last document final PDDocument lastDocument = new PDDocument(); for (Integer i = currentPage; i < pagesList.size(); i++) { lastDocument.addPage(pagesList.get(i)); } splittedDocs.add(lastDocument); lastDocument.close(); Integer subIndex = 1; for (final PDDocument document : splittedDocs) { final String extension = this.converterUtils.addSubIndexBeforeExtension(outputUri, subIndex++); document.save(extension); result.add(extension); } doc.close(); } else { throw new IllegalArgumentException(Constants.ILLEGAL_ARGUMENT_EXCEPTION_MESSAGE); } return result; }
From source file:org.pdfgal.pdfgal.pdfgal.impl.PDFGalImpl.java
License:Open Source License
@Override public void putWatermark(final String inputUri, final String outputUri, final String text, final Color color, final Float alpha, final WatermarkPosition watermarkPosition, final List<Integer> pages) throws IOException, COSVisitorException, WatermarkOutOfLengthException { if (StringUtils.isNotBlank(inputUri) && StringUtils.isNotBlank(outputUri) && StringUtils.isNotBlank(text) && color != null && alpha != null && watermarkPosition != null) { // If watermark position is not centered, then max length is the // same for landscape and portrait, text length is tested here so // there is no need to continue. if (!WatermarkPosition.CENTER.equals(watermarkPosition) && text.length() > watermarkPosition.getMaxLengthPortrait()) { throw new WatermarkOutOfLengthException(Constants.WATERMARK_OUT_OF_LENGTH_EXCEPTION_MESSAGE); }/*from ww w .ja v a 2s . c o m*/ final PDDocument doc = PDDocument.load(inputUri); final List<?> allPages = doc.getDocumentCatalog().getAllPages(); this.converterUtils.deleteNonSelectedPositions(allPages, pages); if (CollectionUtils.isNotEmpty(allPages)) { for (final Object object : allPages) { final PDPage page = (PDPage) object; // The transparency, opacity of graphic objects can be set // directly // on the drawing commands but need to be set to a graphic // state // which will become part of the resources. Graphic state is // set // up. this.watermarkUtils.setUpGraphicState(page, alpha); // Now we will be able to call the state definition before // doing // the // drawing try { this.watermarkUtils.addWatermark(doc, page, color, text, watermarkPosition); } catch (final WatermarkOutOfLengthException e) { doc.close(); throw e; } } } doc.save(outputUri); doc.close(); } else { throw new IllegalArgumentException(Constants.ILLEGAL_ARGUMENT_EXCEPTION_MESSAGE); } }
From source file:org.pdfgal.pdfgal.pdfgal.impl.PDFGalImpl.java
License:Open Source License
@Override public void addBookmarks(final String inputUri, final String outputUri, final String title, final List<PDFGalBookmark> pdfGalBookmarksList) throws IOException, COSVisitorException { if (StringUtils.isNotBlank(inputUri) && StringUtils.isNotBlank(outputUri) && StringUtils.isNotEmpty(title) && CollectionUtils.isNotEmpty(pdfGalBookmarksList)) { final PDDocument doc = PDDocument.load(inputUri); final PDDocumentOutline outline = new PDDocumentOutline(); doc.getDocumentCatalog().setDocumentOutline(outline); final PDOutlineItem pagesOutline = new PDOutlineItem(); pagesOutline.setTitle(title);/*from w w w . j a va 2 s . c o m*/ @SuppressWarnings("unchecked") final List<PDPage> pages = doc.getDocumentCatalog().getAllPages(); outline.appendChild(pagesOutline); for (final PDFGalBookmark pdfGalBookmark : pdfGalBookmarksList) { if (pdfGalBookmark != null && pdfGalBookmark.isInitializated()) { final PDPage page = pages.get(pdfGalBookmark.getPage() - 1); final PDPageFitWidthDestination dest = new PDPageFitWidthDestination(); dest.setPage(page); final PDOutlineItem bookmark = new PDOutlineItem(); bookmark.setDestination(dest); bookmark.setTitle(pdfGalBookmark.getText()); pagesOutline.appendChild(bookmark); } } pagesOutline.openNode(); outline.openNode(); doc.save(outputUri); doc.close(); } else { throw new IllegalArgumentException(Constants.ILLEGAL_ARGUMENT_EXCEPTION_MESSAGE); } }
From source file:org.pdfgal.pdfgal.pdfgal.impl.PDFGalImpl.java
License:Open Source License
@Override public void reIndexPageNumbers(final String inputUri, final String outputUri, final List<PDFGalPageNumbering> pdfGalPageNumberingList) throws IOException, COSVisitorException { if (StringUtils.isNotBlank(inputUri) && StringUtils.isNotBlank(outputUri) && CollectionUtils.isNotEmpty(pdfGalPageNumberingList)) { final PDDocument doc = PDDocument.load(inputUri); final PDPageLabels pdPageLabels = new PDPageLabels(doc); for (final PDFGalPageNumbering pageNumbering : pdfGalPageNumberingList) { if (pageNumbering.isInitializated()) { final PDPageLabelRange pdPageLabelRange = new PDPageLabelRange(); pdPageLabelRange.setStyle(pageNumbering.getNumberingStyle().getValue()); pdPageLabels.setLabelItem(pageNumbering.getPageNumber() - 1, pdPageLabelRange); }//from w w w .j a v a2s .c om } doc.getDocumentCatalog().setPageLabels(pdPageLabels); doc.save(outputUri); doc.close(); } else { throw new IllegalArgumentException(Constants.ILLEGAL_ARGUMENT_EXCEPTION_MESSAGE); } }
From source file:org.pdfgal.pdfgal.validator.impl.PDFGalValidatorImpl.java
License:Open Source License
@Override public boolean allLandscape(final String path) { boolean result = true; PDDocument document; try {/*from ww w. j a va2s . com*/ document = PDDocument.load(path); @SuppressWarnings("unchecked") final List<PDPage> pagesList = document.getDocumentCatalog().getAllPages(); if (CollectionUtils.isNotEmpty(pagesList)) { for (final PDPage page : pagesList) { if ((page != null) && (page.getMediaBox() != null) && (page.getMediaBox().getHeight() > page.getMediaBox().getWidth())) { result = false; break; } } } document.close(); } catch (final IOException e) { result = false; } return result; }