List of usage examples for org.apache.pdfbox.pdmodel PDDocument getDocumentCatalog
public PDDocumentCatalog getDocumentCatalog()
From source file:org.nuxeo.pdf.PDFWatermarking.java
License:Open Source License
/** * Adds the watermark to the Blob passed to the constructor. * <p>/*from w ww .j a v a2 s. c o m*/ * If no setter has been used, the DEFAULT_nnn values apply * <p> * If * <code>text</text> is empty or null, a simple copy of the original Blob is returned * <p> * With thanks to the sample code found at https://issues.apache.org/jira/browse/PDFBOX-1176 * and to Jack (https://jackson-brain.com/a-better-simple-pdf-stamper-in-java/) * * @return a new Blob with the watermark on each page * * @throws ClientException * * @since 6.0 */ public Blob watermark() throws ClientException { Blob result = null; PDDocument pdfDoc = null; PDPageContentStream contentStream = null; if (text == null || text.isEmpty()) { try { File tempFile = File.createTempFile("nuxeo-pdfwatermarking-", ".pdf"); blob.transferTo(tempFile); result = new FileBlob(tempFile); // Just duplicate the info result.setFilename(blob.getFilename()); result.setMimeType(blob.getMimeType()); result.setEncoding(blob.getEncoding()); Framework.trackFile(tempFile, result); return result; } catch (IOException e) { throw new ClientException(e); } } // Set up the graphic state to handle transparency // Define a new extended graphic state PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState(); // Set the transparency/opacity extendedGraphicsState.setNonStrokingAlphaConstant(alphaColor); try { pdfDoc = PDDocument.load(blob.getStream()); PDFont font = PDType1Font.getStandardFont(fontFamily); int[] rgb = PDFUtils.hex255ToRGB(hex255Color); List<?> allPages = pdfDoc.getDocumentCatalog().getAllPages(); int max = allPages.size(); for (int i = 0; i < max; i++) { contentStream = null; PDPage page = (PDPage) allPages.get(i); PDRectangle pageSize = page.findMediaBox(); PDResources resources = page.findResources(); // Get the defined graphic states. HashMap<String, PDExtendedGraphicsState> graphicsStateDictionary = (HashMap<String, PDExtendedGraphicsState>) resources .getGraphicsStates(); if (graphicsStateDictionary != null) { graphicsStateDictionary.put("TransparentState", extendedGraphicsState); resources.setGraphicsStates(graphicsStateDictionary); } else { Map<String, PDExtendedGraphicsState> m = new HashMap<>(); m.put("TransparentState", extendedGraphicsState); resources.setGraphicsStates(m); } if (invertY) { yPosition = pageSize.getHeight() - yPosition; } float stringWidth = font.getStringWidth(text) * fontSize / 1000f; int pageRot = page.findRotation(); boolean pageRotated = pageRot == 90 || pageRot == 270; boolean textRotated = textRotation != 0 && textRotation != 360; int totalRot = pageRot - textRotation; float pageWidth = pageRotated ? pageSize.getHeight() : pageSize.getWidth(); float pageHeight = pageRotated ? pageSize.getWidth() : pageSize.getHeight(); double centeredXPosition = pageRotated ? pageHeight / 2f : (pageWidth - stringWidth) / 2f; double centeredYPosition = pageRotated ? (pageWidth - stringWidth) / 2f : pageHeight / 2f; contentStream = new PDPageContentStream(pdfDoc, page, true, true, true); contentStream.beginText(); contentStream.setFont(font, fontSize); contentStream.appendRawCommands("/TransparentState gs\n"); contentStream.setNonStrokingColor(rgb[0], rgb[1], rgb[2]); if (pageRotated) { contentStream.setTextRotation(Math.toRadians(totalRot), centeredXPosition, centeredYPosition); } else if (textRotated) { contentStream.setTextRotation(Math.toRadians(textRotation), xPosition, yPosition); } else { contentStream.setTextTranslation(xPosition, yPosition); } contentStream.drawString(text); contentStream.endText(); contentStream.close(); contentStream = null; } result = PDFUtils.saveInTempFile(pdfDoc); } catch (IOException | COSVisitorException e) { throw new ClientException(e); } finally { if (contentStream != null) { try { contentStream.close(); } catch (IOException e) { // Ignore } } PDFUtils.closeSilently(pdfDoc); } return result; }
From source file:org.nuxeo.pdf.PDFWatermarking.java
License:Open Source License
public Blob watermarkWithImage(Blob inBlob, int x, int y, float scale) throws ClientException { Blob result = null;//from www. j a v a 2 s.c o m PDDocument pdfDoc = null; PDPageContentStream contentStream = null; scale = (scale <= 0f) ? 1.0f : scale; try { BufferedImage tmp_image = ImageIO.read(inBlob.getStream()); pdfDoc = PDDocument.load(blob.getStream()); PDXObjectImage ximage = new PDPixelMap(pdfDoc, tmp_image); List<?> allPages = pdfDoc.getDocumentCatalog().getAllPages(); int max = allPages.size(); for (int i = 0; i < max; i++) { PDPage page = (PDPage) allPages.get(i); contentStream = new PDPageContentStream(pdfDoc, page, true, true); contentStream.endMarkedContentSequence(); contentStream.drawXObject(ximage, x, y, ximage.getWidth() * scale, ximage.getHeight() * scale); /* * AffineTransform at = new AffineTransform(ximage.getWidth() * * scale, 200, 200, ximage.getHeight() * scale, x, y); * at.rotate(Math.toRadians(90)); * contentStream.drawXObject(ximage, at); */ contentStream.close(); contentStream = null; } result = PDFUtils.saveInTempFile(pdfDoc); } catch (IOException | COSVisitorException e) { throw new ClientException(e); } finally { if (contentStream != null) { try { contentStream.close(); } catch (IOException e) { // Ignore } } PDFUtils.closeSilently(pdfDoc); } return result; }
From source file:org.nuxeo.pdf.test.PDFWatermarkingTest.java
License:Open Source License
protected void checkHasImage(Blob inBlob, int inExpectedWidth, int inExpectedHeight) throws Exception { PDDocument doc = PDDocument.load(inBlob.getStream()); utils.track(doc);/*from ww w. j a va 2 s . c om*/ List<?> allPages = doc.getDocumentCatalog().getAllPages(); int max = allPages.size(); for (int i = 1; i < max; i++) { PDPage page = (PDPage) allPages.get(i); PDResources pdResources = page.getResources(); Map<String, PDXObject> allXObjects = pdResources.getXObjects(); assertNotNull(allXObjects); boolean gotIt = false; for (Map.Entry<String, PDXObject> entry : allXObjects.entrySet()) { PDXObject xobject = entry.getValue(); if (xobject instanceof PDXObjectImage) { PDXObjectImage pdxObjectImage = (PDXObjectImage) xobject; if (inExpectedWidth == pdxObjectImage.getWidth() && inExpectedHeight == pdxObjectImage.getHeight()) { gotIt = true; break; } } } assertTrue("Page " + i + "does not have the image", gotIt); } doc.close(); utils.untrack(doc); }
From source file:org.ochan.control.ThumbnailController.java
License:Open Source License
@SuppressWarnings("unchecked") private BufferedImage takeCaptureOfPDFPage1(byte[] data) { try {//from ww w .j av a 2 s. c om ByteArrayInputStream bais = new ByteArrayInputStream(data); PDDocument document = PDDocument.load(bais); // get the first page. List<PDPage> pages = (List<PDPage>) document.getDocumentCatalog().getAllPages(); PDPage page = pages.get(0); BufferedImage image = page.convertToImage(); document.close(); return image; } catch (Exception e) { LOG.error("Unable to convert pdf page 1 into godlike image", e); } return null; }
From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java
License:Apache License
@Override public Size thumbnailPDF(VFSLeaf pdfFile, VFSLeaf thumbnailFile, int maxWidth, int maxHeight) { InputStream in = null;// www . j a v a 2s.c om PDDocument document = null; try { WorkThreadInformations.setInfoFiles(null, pdfFile); WorkThreadInformations.set("Generate thumbnail VFSLeaf=" + pdfFile); in = pdfFile.getInputStream(); document = PDDocument.load(in); if (document.isEncrypted()) { try { document.decrypt(""); } catch (Exception e) { log.info("PDF document is encrypted: " + pdfFile); throw new CannotGenerateThumbnailException("PDF document is encrypted: " + pdfFile); } } List pages = document.getDocumentCatalog().getAllPages(); PDPage page = (PDPage) pages.get(0); BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_BGR, 72); Size size = scaleImage(image, thumbnailFile, maxWidth, maxHeight); if (size != null) { return size; } return null; } catch (CannotGenerateThumbnailException e) { return null; } catch (Exception e) { log.warn("Unable to create image from pdf file.", e); return null; } finally { WorkThreadInformations.unset(); FileUtils.closeSafely(in); if (document != null) { try { document.close(); } catch (IOException e) { //only a try, fail silently } } } }
From source file:org.olat.core.commons.services.thumbnail.impl.PDFToThumbnail.java
License:Apache License
@Override public FinalSize generateThumbnail(VFSLeaf pdfFile, VFSLeaf thumbnailFile, int maxWidth, int maxHeight) throws CannotGenerateThumbnailException { InputStream in = null;// w w w .j av a 2s. c om PDDocument document = null; try { in = pdfFile.getInputStream(); document = PDDocument.load(in); if (document.isEncrypted()) { try { document.decrypt(""); } catch (Exception e) { log.info("PDF document is encrypted: " + pdfFile); throw new CannotGenerateThumbnailException("PDF document is encrypted: " + pdfFile); } } List pages = document.getDocumentCatalog().getAllPages(); PDPage page = (PDPage) pages.get(0); BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_BGR, 72); Size size = ImageHelper.scaleImage(image, thumbnailFile, maxWidth, maxHeight); return new FinalSize(size.getWidth(), size.getWidth()); } catch (CannotGenerateThumbnailException e) { throw e; } catch (Exception e) { log.warn("Unable to create image from pdf file.", e); throw new CannotGenerateThumbnailException(e); } finally { FileUtils.closeSafely(in); if (document != null) { try { document.close(); } catch (IOException e) { // only a try, fail silently } } } }
From source file:org.olat.course.certificate.manager.CertificatePDFFormWorker.java
License:Apache License
public File fill(CertificateTemplate template, File destinationDir, String certificateFilename) { PDDocument document = null; InputStream templateStream = null; try {//from w ww .j a va2s .c o m File templateFile = null; if (template != null) { templateFile = certificatesManager.getTemplateFile(template); } if (templateFile != null && templateFile.exists()) { templateStream = new FileInputStream(templateFile); } else { templateStream = CertificatesManager.class.getResourceAsStream("template.pdf"); } document = PDDocument.load(templateStream); PDDocumentCatalog docCatalog = document.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); if (acroForm != null) { fillUserProperties(acroForm); fillRepositoryEntry(acroForm); fillCertificationInfos(acroForm); fillAssessmentInfos(acroForm); } if (!destinationDir.exists()) { destinationDir.mkdirs(); } File certificateFile = new File(destinationDir, certificateFilename); OutputStream out = new FileOutputStream(certificateFile); document.save(out); out.flush(); out.close(); return certificateFile; } catch (Exception e) { log.error("", e); return null; } finally { IOUtils.closeQuietly(document); IOUtils.closeQuietly(templateStream); } }
From source file:org.olat.course.certificate.ui.UploadCertificateController.java
License:Apache License
private boolean validatePdf(File template) { boolean allOk = true; PDDocument document = null; try (InputStream in = Files.newInputStream(template.toPath())) { document = PDDocument.load(in);/*from ww w .j av a 2 s.c o m*/ if (document.isEncrypted()) { fileEl.setErrorKey("upload.error.encrypted", null); allOk &= false; } else { //check if we can write the form PDDocumentCatalog docCatalog = document.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); if (acroForm != null) { @SuppressWarnings("unchecked") List<PDField> fields = acroForm.getFields(); for (PDField field : fields) { field.setValue("test"); } } document.save(new DevNullOutputStream()); } } catch (IOException ex) { logError("", ex); if (ex.getMessage() != null && ex.getMessage().contains("Don't know how to calculate the position for non-simple fonts")) { fileEl.setErrorKey("upload.error.simplefonts", null); } else { fileEl.setErrorKey("upload.unkown.error", null); } allOk &= false; } catch (Exception ex) { logError("", ex); fileEl.setErrorKey("upload.unkown.error", null); allOk &= false; } finally { IOUtils.closeQuietly(document); } return allOk; }
From source file:org.opencps.util.ExtractTextLocations.java
License:Open Source License
public ExtractTextLocations(String fullPath) throws IOException { PDDocument document = null; try {//from w ww . j a v a 2s. co m File input = new File(fullPath); document = PDDocument.load(input); if (document.isEncrypted()) { try { document.decrypt(StringPool.BLANK); } catch (Exception e) { _log.error(e); } } // ExtractTextLocations printer = new ExtractTextLocations(); List allPages = document.getDocumentCatalog().getAllPages(); if (allPages != null && allPages.size() > 0) { PDPage page = (PDPage) allPages.get(0); PDStream contents = page.getContents(); if (contents != null) { this.processStream(page, page.findResources(), page.getContents().getStream()); } PDRectangle pageSize = page.findMediaBox(); if (pageSize != null) { setPageWidth(pageSize.getWidth()); setPageHeight(pageSize.getHeight()); setPageLLX(pageSize.getLowerLeftX()); setPageURX(pageSize.getUpperRightX()); setPageLLY(pageSize.getLowerLeftY()); setPageURY(pageSize.getUpperRightY()); } } } catch (Exception e) { _log.error(e); } finally { if (document != null) { document.close(); } } }
From source file:org.oscarehr.document.web.SplitDocumentAction.java
License:Open Source License
public ActionForward split(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String docNum = request.getParameter("document"); String[] commands = request.getParameterValues("page[]"); Document doc = documentDAO.getDocument(docNum); // String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR"); // new File(docdownload); String docdownload = EDocUtil.getDocumentDir(doc.getDocfilename()); String newFilename = doc.getDocfilename(); String dbPrefix = EDocUtil.getDocumentPrefix(doc.getDocfilename()); // FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename()); FileInputStream input = new FileInputStream(EDocUtil.getDocumentPath(newFilename)); PDFParser parser = new PDFParser(input); parser.parse();/* ww w. jav a2s.c o m*/ PDDocument pdf = parser.getPDDocument(); PDDocument newPdf = new PDDocument(); List pages = pdf.getDocumentCatalog().getAllPages(); if (commands != null) { for (String c : commands) { String[] command = c.split(","); int pageNum = Integer.parseInt(command[0]); int rotation = Integer.parseInt(command[1]); PDPage p = (PDPage) pages.get(pageNum - 1); p.setRotation(rotation); newPdf.addPage(p); } } //newPdf.save(docdownload + newFilename); if (newPdf.getNumberOfPages() > 0) { LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get(); // EDoc newDoc = new EDoc("","", newFilename, "", loggedInInfo.loggedInProvider.getProviderNo(), doc.getDoccreator(), "", 'A', oscar.util.UtilDateUtilities.getToday("yyyy-MM-dd"), "", "", "demographic", "-1",0); EDoc newDoc = new EDoc("", "", EDocUtil.getDocumentFileName(newFilename), "", loggedInInfo.loggedInProvider.getProviderNo(), doc.getDoccreator(), "", 'A', oscar.util.UtilDateUtilities.getToday("yyyy-MM-dd"), "", "", "demographic", "-1", 0); newDoc.setFileName(dbPrefix + '.' + newDoc.getFileName()); newDoc.setDocPublic("0"); newDoc.setContentType("application/pdf"); newDoc.setNumberOfPages(newPdf.getNumberOfPages()); String newDocNo = EDocUtil.addDocumentSQL(newDoc); // //newPdf.save(docdownload + newDoc.getFileName()); System.gc(); //avoid Windows lock on channel newPdf.save(docdownload + EDocUtil.getDocumentFileName(newDoc.getFileName())); newPdf.close(); WebApplicationContext ctx = WebApplicationContextUtils .getRequiredWebApplicationContext(request.getSession().getServletContext()); ProviderInboxRoutingDao providerInboxRoutingDao = (ProviderInboxRoutingDao) ctx .getBean("providerInboxRoutingDAO"); providerInboxRoutingDao.addToProviderInbox("0", newDocNo, "DOC"); List<ProviderInboxItem> routeList = providerInboxRoutingDao.getProvidersWithRoutingForDocument("DOC", docNum); for (ProviderInboxItem i : routeList) { providerInboxRoutingDao.addToProviderInbox(i.getProviderNo(), newDocNo, "DOC"); } providerInboxRoutingDao.addToProviderInbox(loggedInInfo.loggedInProvider.getProviderNo(), newDocNo, "DOC"); QueueDocumentLinkDao queueDocumentLinkDAO = (QueueDocumentLinkDao) ctx.getBean("queueDocumentLinkDAO"); Integer qid = 1; Integer did = Integer.parseInt(newDocNo.trim()); queueDocumentLinkDAO.addToQueueDocumentLink(qid, did); ProviderLabRoutingDao providerLabRoutingDao = (ProviderLabRoutingDao) SpringUtils .getBean("providerLabRoutingDao"); List<ProviderLabRoutingModel> result = providerLabRoutingDao.getProviderLabRoutingDocuments(docNum); if (!result.isEmpty()) { new ProviderLabRouting().route(newDocNo, result.get(0).getProviderNo(), "DOC"); } PatientLabRoutingDao patientLabRoutingDao = (PatientLabRoutingDao) SpringUtils .getBean("patientLabRoutingDao"); List<PatientLabRouting> result2 = patientLabRoutingDao.findDocByDemographic(docNum); if (!result2.isEmpty()) { PatientLabRouting newPatientRoute = new PatientLabRouting(); newPatientRoute.setDemographicNo(result2.get(0).getDemographicNo()); newPatientRoute.setLabNo(Integer.parseInt(newDocNo)); newPatientRoute.setLabType("DOC"); patientLabRoutingDao.persist(newPatientRoute); } DocumentDAO documentDao = (DocumentDAO) SpringUtils.getBean("documentDAO"); CtlDocument result3 = documentDao.getCtrlDocument(Integer.parseInt(docNum)); if (result3 != null) { CtlDocumentPK ctlDocumentPK = new CtlDocumentPK(Integer.parseInt(newDocNo), "demographic"); CtlDocument newCtlDocument = new CtlDocument(ctlDocumentPK, result3.getModuleId()); newCtlDocument.setStatus(result3.getStatus()); documentDao.saveCtlDocument(newCtlDocument); } } pdf.close(); input.close(); return mapping.findForward("success"); }