List of usage examples for org.apache.pdfbox.pdmodel.common PDRectangle getWidth
public float getWidth()
From source file:org.gfbio.idmg.util.PDFUtil.java
private void setDocumentContent() throws IOException { // Attributes for line breaking method printLines PDRectangle mediabox = page.getMediaBox(); float width = mediabox.getWidth() - 2 * margin; // Setting the font to the Content stream content.setFont(boldFont, 24);/*from w w w. ja va 2 s .co m*/ content.setNonStrokingColor(51, 90, 163); // Start of Page Content - Adding Document title content.showText("Data Management Plan"); content.newLine(); yCoordinate -= docTitleSize; // 1 - General Information printHeading("General Project Information"); String title = "Project Name: "; printTitle(title); printLines(userInput.getProjectName(), title, width); printTitle("Research Field: "); printSingleLineAnswer(userInput.getCategory()); title = "Project Characteristics: "; printTitle(title); String characteristics = createCommaSeperatedString(userInput.getReproducible()) + createCommaSeperatedString(userInput.getProjectTypes()); characteristics = characteristics.replaceAll(", $", ""); printLines(characteristics, title, width); // Additional infos if (!isNullOrEmpty(userInput.getReproducibleText())) { printLines(userInput.getReproducibleText(), "", width); } title = "Project Abstract: "; printTitle(title); printMultiLineAnswer((userInput.getProjectAbstract()), title, width); printTitle("Project Data Contact: "); String contact = userInput.getResponsibleName() .concat(", " + userInput.getPhoneNumber() + ", " + userInput.getEmail()).replaceAll(", ,", ","); printLine(contact); title = "Principal Investigator/s: "; printTitle(title); printMultiLineAnswer(userInput.getInvestigators(), title, width); printTitle("Funding Application: "); printSingleLineAnswer(userInput.getFunding().getName()); printLines(userInput.getFundingLink(), "", width); title = "Coordinated Programme: "; printTitle(title); printMultiLineAnswer(userInput.getCoordinatedProgramme(), title, width); printTitle("Part of a Research Unit? "); printSingleLineAnswer(yesOrNo(new Boolean(userInput.isResearchUnit()))); printTitle("Volume of Research Proposal: "); printSingleLineAnswer(userInput.getResearchProposal()); title = "Relevant Policies and Guidelines: "; printTitle(title); printMultiLineAnswer(userInput.getAllPolicies(), title, width); if (!isNullOrEmpty(userInput.getPolicyLink())) { printLines(userInput.getPolicyLink(), "", width); } // 2 - Data Collection printHeading("Data Collection"); printTitle("Physical Objects: "); printSingleLineAnswer(yesOrNo(userInput.getPhysical())); printTitle("Dead or Alive: "); printSingleLineAnswer(deadOrAlive(userInput.getAlive())); printTitle("Taxon-Based: "); printSingleLineAnswer(yesOrNo(userInput.getTaxon())); printTitle("Mainly Sequence Data: "); printSingleLineAnswer(yesOrNo(userInput.getSequenced())); title = "Type of Data: "; printTitle(title); printMultiLineAnswer(userInput.getDatatypes(), title, width); title = "Data Formats: "; printTitle(title); printMultiLineAnswer(userInput.getCreateFormats(), title, width); printTitle("Estimated Data Volume: "); printSingleLineAnswer(StringEscapeUtils.unescapeHtml3(userInput.getDataVolume())); printTitle("Number of Data Sets: "); printSingleLineAnswer(StringEscapeUtils.unescapeHtml3(userInput.getDataSets())); title = "Standards, Methodologies and Tools: "; printTitle(title); printMultiLineAnswer(userInput.getMethodologies(), title, width); // 3 - Metadata printHeading("Documentation and Metadata"); title = "Supported Metadata Schemas: "; printTitle(title); printMultiLineAnswer(userInput.getAllMetadata(), title, width); // Additional infos if (!isNullOrEmpty(userInput.getMetadataDescription())) { printLines(userInput.getMetadataDescription(), "", width); } // 4 - Ethics printHeading("Ethics and Legal Compliance"); title = "Legal Requirements: "; printTitle(title); printMultiLineAnswer(userInput.getAllRequirements(), title, width); printTitle("License: "); printLines(userInput.getLicense().getName(), "", width); printTitle("Access Restriction: "); printSingleLineAnswer(yesOrNo(userInput.getAccessRestriction())); if (userInput.getAccessRestriction() != null && userInput.getAccessRestriction().booleanValue()) { printLines("How long: " + userInput.getAccessDuration(), "", width); printLines("Reason: " + userInput.getAccessReason(), "", width); } // 5 - Preservation and Sharing printHeading("Preservation and Sharing"); title = "Data Submission to GFBio: "; printTitle(title); printMultiLineAnswer(userInput.getDataSubmissions(), title, width); title = "Data Backup: "; printTitle(title); printMultiLineAnswer(userInput.getBackup(), title, width); title = "Data Archiving: "; printTitle(title); printMultiLineAnswer(userInput.getDataArchives(), title, width); printTitle("Persistent Identifier: "); printSingleLineAnswer(userInput.getPid()); // Recommendation printHeading("GFBio recommends"); String recommends = "GFBio provides individual data management support and recommends contacting us for your personal data management strategy and DMP support. " + "We give advice regarding storage, security, quality assurance and backup and help you optimizing the findability, accessibility, interoperability and re-usability of your research data. " + "We highly recommend using common standards for data and metadata formats. You can find an overview of GFBio services on www.gfbio.org."; printLines(recommends, "", width, 11, Color.GRAY, PDType1Font.HELVETICA); // Ending the content stream content.endText(); content.close(); printFooter(); }
From source file:org.github.jipsg.pdfbox.PdfToImageConverter.java
License:Apache License
/** * Split a PDF document into images.//w w w .j av a2s .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.haplo.component.pdfbox.PDF.java
License:Mozilla Public License
/** * Open a PDF and read it's data. close() must be called to clean up nicely. *///from w w w . java 2 s . c o m public PDF(String filename) throws IOException { if (!Operation.isThreadMarkedAsWorker()) { throw new RuntimeException("PDF manipulation can only be performed in a worker process"); } // Not valid by default isValid = false; // Try to load the page try { // Open the PDF for reading this.pdf = PDDocument.load(new File(filename)); this.numberOfPages = this.pdf.getNumberOfPages(); PDPage page = this.pdf.getPage(0); // Width and height PDRectangle cropBox = page.getCropBox(); width = (int) cropBox.getWidth(); height = (int) cropBox.getHeight(); isValid = true; } catch (Exception e) { // Ignore exception, but do clean up nicely close(); } }
From source file:org.haplo.component.pdfbox.PDF.java
License:Mozilla Public License
/** * Render the PDF as an image//from w ww.j a v a 2 s .co m */ public void render(String outFilename, String outFormat, int page, int outWidth, int outHeight) throws IOException { BufferedImage img = null; try { PDPage pdfPage = this.pdf.getPage(page - 1); PDRectangle cropBox = pdfPage.getCropBox(); int pageWidth = (int) cropBox.getWidth(); int pageHeight = (int) cropBox.getHeight(); if (pageHeight <= 0) { pageHeight = 1; } int resolution = (96 * outHeight) / pageHeight; if (resolution < 4) { resolution = 4; } if (resolution > 1000) { resolution = 1000; } if (outHeight < 100 || outWidth < 100) { resolution *= 2; } PDFRenderer pdfRenderer = new PDFRenderer(this.pdf); img = pdfRenderer.renderImageWithDPI(page - 1, resolution, outFormat.equals("png") ? ImageType.ARGB : ImageType.RGB); } catch (Exception e) { Logger.getLogger("org.haplo.app").error("Error rendering PDF: " + e.toString()); throw new RuntimeException("Couldn't render PDF page", e); } // Did it convert? (most likely cause of null return is requested a page which didn't exist) if (img == null) { throw new RuntimeException("Failed to render PDF - did the requested page exist?"); } // Scale the image to the right size BufferedImage original = null; if (img.getWidth() != outWidth || img.getHeight() != outHeight) { original = img; Image scaled = img.getScaledInstance(outWidth, outHeight, Image.SCALE_SMOOTH); img = new BufferedImage(outWidth, outHeight, original.getType()); Graphics2D graphics = img.createGraphics(); graphics.setBackground(Color.WHITE); graphics.clearRect(0, 0, outWidth, outHeight); graphics.drawImage(scaled, 0, 0, null); graphics.dispose(); scaled.flush(); } // Write the image to a file ImageIO.write(img, outFormat, new File(outFilename)); // Free resources img.flush(); if (original != null) { original.flush(); } }
From source file:org.mycore.media.MCRMediaPDFParser.java
License:Open Source License
/** * Parse file and store metadata in related Object. * /* w ww . ja va2 s . c o m*/ * @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.nmrfx.processor.gui.graphicsio.PDFWriter.java
License:Open Source License
public void create(boolean landScape, double width, double height, String fileName) throws GraphicsIOException { // the document this.landScape = landScape; this.fileName = fileName; doc = new PDDocument(); try {//from ww w . j av a2 s . com PDPage page = new PDPage(PDRectangle.LETTER); doc.addPage(page); PDRectangle pageSize = page.getMediaBox(); pageWidth = pageSize.getWidth(); pageHeight = pageSize.getHeight(); contentStream = new PDPageContentStream(doc, page, false, false); // add the rotation using the current transformation matrix // including a translation of pageWidth to use the lower left corner as 0,0 reference if (landScape) { page.setRotation(90); contentStream.transform(new Matrix(0, 1, -1, 0, pageWidth, 0)); } } catch (IOException ioE) { throw new GraphicsIOException(ioE.getMessage()); } }
From source file:org.nuxeo.pdf.PDFInfo.java
License:Open Source License
/** * After building the object with the correct constructor, and after * possibly having set some parsing property (<code>setParseWithXMP()</code> * for example), this method will extract the information from the PDF. * <p>/*w w w. jav a 2 s .co m*/ * After extraction, caller get the info: Either all of them ( * <code>toHashMap()</code> or <code>toString()</code>) or individual info * (see all getters) * * @throws ClientException * * @since 5.9.5 */ public void run() throws ClientException { // In case the caller calls several time the run() method if (!alreadyParsed) { fileName = pdfBlob.getFilename(); // Getting the file size os ok only if the blob is already backed by // a // File. If it is pure Stream, we give up File pdfFile = BlobHelper.getFileFromBlob(pdfBlob); if (pdfFile == null) { fileSize = -1; } else { fileSize = pdfFile.length(); } try { pdfDoc = PDDocument.load(pdfBlob.getStream()); isEncrypted = pdfDoc.isEncrypted(); if (isEncrypted) { pdfDoc.openProtection(new StandardDecryptionMaterial(password)); } numberOfPages = pdfDoc.getNumberOfPages(); PDDocumentCatalog docCatalog = pdfDoc.getDocumentCatalog(); pageLayout = checkNotNull(docCatalog.getPageLayout()); pdfVersion = "" + pdfDoc.getDocument().getVersion(); PDDocumentInformation docInfo = pdfDoc.getDocumentInformation(); author = checkNotNull(docInfo.getAuthor()); contentCreator = checkNotNull(docInfo.getCreator()); keywords = checkNotNull(docInfo.getKeywords()); creationDate = docInfo.getCreationDate(); modificationDate = docInfo.getModificationDate(); producer = checkNotNull(docInfo.getProducer()); subject = checkNotNull(docInfo.getSubject()); title = checkNotNull(docInfo.getTitle()); // Getting dimension is a bit tricky mediaBoxWidthInPoints = -1; mediaBoxHeightInPoints = -1; cropBoxWidthInPoints = -1; cropBoxHeightInPoints = -1; List<PDPage> allPages = docCatalog.getAllPages(); boolean gotMediaBox = false; boolean gotCropBox = false; for (PDPage page : allPages) { if (page != null) { PDRectangle r = page.findMediaBox(); if (r != null) { mediaBoxWidthInPoints = r.getWidth(); mediaBoxHeightInPoints = r.getHeight(); gotMediaBox = true; } r = page.findCropBox(); if (r != null) { cropBoxWidthInPoints = r.getWidth(); cropBoxHeightInPoints = r.getHeight(); gotCropBox = true; } } if (gotMediaBox && gotCropBox) { break; } } if (doXMP) { xmp = null; PDMetadata metadata = docCatalog.getMetadata(); if (metadata != null) { xmp = ""; InputStream xmlInputStream = metadata.createInputStream(); InputStreamReader isr = new InputStreamReader(xmlInputStream); BufferedReader reader = new BufferedReader(isr); String line; do { line = reader.readLine(); if (line != null) { xmp += line + "\n"; } } while (line != null); reader.close(); } } } catch (IOException | BadSecurityHandlerException | CryptographyException e) { throw new ClientException(/* * "Cannot get PDF info: " + * e.getMessage(), */e); } finally { if (pdfDoc != null) { try { pdfDoc.close(); } catch (IOException e) { // Ignore } pdfDoc = null; } alreadyParsed = true; } } }
From source file:org.nuxeo.pdf.PDFLinks.java
License:Apache License
protected void loadAndPreflightPdf() throws NuxeoException { if (pdfDoc == null) { pdfDoc = PDFUtils.load(pdfBlob, password); @SuppressWarnings("unchecked") List<PDPage> allPages = pdfDoc.getDocumentCatalog().getAllPages(); try {// w w w . j a va 2s . c om stripper = new PDFTextStripperByArea(); for (PDPage page : allPages) { List<PDAnnotation> annotations = page.getAnnotations(); for (int j = 0; j < annotations.size(); j++) { PDAnnotation annot = (PDAnnotation) annotations.get(j); if (annot instanceof PDAnnotationLink) { PDAnnotationLink link = (PDAnnotationLink) annot; 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); } } } } catch (IOException e) { throw new NuxeoException("Cannot prefilght and prepare regions", e); } } }
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 w w . j av 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.service.PDFTransformationServiceImpl.java
License:Apache License
@Override public Blob applyTextWatermark(Blob input, String text, WatermarkProperties properties) { // Set up the graphic state to handle transparency // Define a new extended graphic state PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState(); // Set the transparency/opacity extendedGraphicsState.setNonStrokingAlphaConstant((float) properties.getAlphaColor()); try (PDDocument pdfDoc = PDDocument.load(input.getStream())) { PDFont font = PDType1Font.getStandardFont(properties.getFontFamily()); float watermarkWidth = (float) (font.getStringWidth(text) * properties.getFontSize() / 1000f); int[] rgb = PDFUtils.hex255ToRGB(properties.getHex255Color()); for (Object o : pdfDoc.getDocumentCatalog().getAllPages()) { PDPage page = (PDPage) o;// w ww. j a v a 2 s .co m 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); } try (PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page, true, true, true)) { contentStream.beginText(); contentStream.setFont(font, (float) properties.getFontSize()); contentStream.appendRawCommands("/TransparentState gs\n"); contentStream.setNonStrokingColor(rgb[0], rgb[1], rgb[2]); Point2D position = computeTranslationVector(pageSize.getWidth(), watermarkWidth, pageSize.getHeight(), properties.getFontSize(), properties); contentStream.setTextRotation(Math.toRadians(properties.getTextRotation()), position.getX(), position.getY()); contentStream.drawString(text); contentStream.endText(); } } return saveInTempFile(pdfDoc); } catch (Exception e) { throw new NuxeoException(e); } }