List of usage examples for org.apache.pdfbox.pdmodel.common PDRectangle getWidth
public float getWidth()
From source file:com.trollworks.gcs.pdfview.PdfPanel.java
License:Open Source License
private void markPageForLoading() { int numberOfPages = mPdf.getNumberOfPages(); if (mPageIndex >= 0 && mPageIndex == numberOfPages) { mPageIndex = numberOfPages - 1;/*from ww w.j av a2s .c o m*/ } if (mPageIndex >= 0 && mPageIndex < numberOfPages) { PDPage page = mPdf.getPage(mPageIndex); PDRectangle cropBox = page.getCropBox(); float scale = SCALES[mScaleIndex] * Toolkit.getDefaultToolkit().getScreenResolution(); mWidth = (int) Math.ceil(cropBox.getWidth() / 72 * scale); mHeight = (int) Math.ceil(cropBox.getHeight() / 72 * scale); mImg = null; mNeedLoad = true; Dimension size = new Dimension(mWidth, mHeight); UIUtilities.setOnlySize(this, size); setSize(size); repaint(); mIgnorePageChange = true; mOwner.updateStatus(mPageIndex, numberOfPages, SCALES[mScaleIndex]); mIgnorePageChange = false; } }
From source file:com.trollworks.gcs.pdfview.PdfRenderer.java
License:Open Source License
@Override protected void writeString(String text, List<TextPosition> textPositions) throws IOException { text = text.toLowerCase();// w w w. j a v a2s. c o m int index = text.indexOf(mTextToHighlight); if (index != -1) { PDPage currentPage = getCurrentPage(); PDRectangle pageBoundingBox = currentPage.getBBox(); AffineTransform flip = new AffineTransform(); flip.translate(0, pageBoundingBox.getHeight()); flip.scale(1, -1); PDRectangle mediaBox = currentPage.getMediaBox(); float mediaHeight = mediaBox.getHeight(); float mediaWidth = mediaBox.getWidth(); int size = textPositions.size(); while (index != -1) { int last = index + mTextToHighlight.length() - 1; for (int i = index; i <= last; i++) { TextPosition pos = textPositions.get(i); PDFont font = pos.getFont(); BoundingBox bbox = font.getBoundingBox(); Rectangle2D.Float rect = new Rectangle2D.Float(0, bbox.getLowerLeftY(), font.getWidth(pos.getCharacterCodes()[0]), bbox.getHeight()); AffineTransform at = pos.getTextMatrix().createAffineTransform(); if (font instanceof PDType3Font) { at.concatenate(font.getFontMatrix().createAffineTransform()); } else { at.scale(1 / 1000f, 1 / 1000f); } Shape shape = flip.createTransformedShape(at.createTransformedShape(rect)); AffineTransform transform = mGC.getTransform(); int rotation = currentPage.getRotation(); if (rotation != 0) { switch (rotation) { case 90: mGC.translate(mediaHeight, 0); break; case 270: mGC.translate(0, mediaWidth); break; case 180: mGC.translate(mediaWidth, mediaHeight); break; default: break; } mGC.rotate(Math.toRadians(rotation)); } mGC.fill(shape); if (rotation != 0) { mGC.setTransform(transform); } } index = last < size - 1 ? text.indexOf(mTextToHighlight, last + 1) : -1; } } }
From source file:com.vigglet.pdf.PdfPage.java
public void addTextBox(PDRectangle rect, int line, String header, List<String> values) throws IOException { float xStart = margin; float xEnd = rect.getWidth() - margin; float height = (float) (values.size() * 10.2); float y = getNextHeaderLine(); //Add the header contents.beginText();//from w ww . j a v a 2s. com contents.setFont(font, 8); contents.moveTextPositionByAmount(margin + 10, y); contents.drawString(header); contents.endText(); y = getNextLine(5); contents.drawLine(xStart, y, xEnd, y);//Top line contents.drawLine(xStart, y, xStart, y - height);//Left line contents.drawLine(xEnd, y, xEnd, y - height);//Right line contents.drawLine(xStart, y - height, xEnd, y - height);//Bottom line //Fill the box float contentBoxTextX = margin + 2; for (String str : values) { contents.beginText(); contents.moveTextPositionByAmount(contentBoxTextX, getNextTextLine()); contents.drawString(str.trim() + "."); contents.endText(); } }
From source file:com.vns.pdf.impl.PdfDocument.java
License:Apache License
private PdfDocument(String pdfFileName) throws IOException { this.pdfFileName = pdfFileName; setWorkingDir();/*from w w w . j a v a2 s. c o m*/ Path filePath = Paths.get(pdfFileName); PosixFileAttributes attrs = Files.getFileAttributeView(filePath, PosixFileAttributeView.class) .readAttributes(); String textAreaFileName = filePath.getFileName().toString() + "_" + filePath.toAbsolutePath().hashCode() + "_" + attrs.size() + "_" + attrs.lastModifiedTime().toString().replace(":", "_") + ".xml"; textAreaFilePath = Paths.get(workingDir.toAbsolutePath().toString(), textAreaFileName); pdfTextStripper = new CustomPDFTextStripper(); document = PDDocument.load(new File(pdfFileName)); pdfRenderer = new PDFRenderer(document); if (Files.notExists(textAreaFilePath, LinkOption.NOFOLLOW_LINKS)) { pdfTextStripper.setSortByPosition(false); pdfTextStripper.setStartPage(0); pdfTextStripper.setEndPage(document.getNumberOfPages()); this.doc = new Doc(new ArrayList<>(), new ArrayList<>()); for (int i = 0; i < document.getNumberOfPages(); i++) { PDPage pdPage = document.getPage(i); PDRectangle box = pdPage.getMediaBox(); this.doc.getPages().add(new Page(new ArrayList<>(), new ArrayList<>(), (int) box.getWidth(), (int) box.getHeight())); } Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream()); try { pdfTextStripper.writeText(document, dummy); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } parseBookmarksAnnotation(); createTextAreaFile(); //document.save(pdfFileName + ".pdf"); } else { loadTextAreaFile(); } }
From source file:com.vns.pdf.impl.PdfDocument.java
License:Apache License
private List<Annotation> parseAnnotation(PDPage pdPage) throws IOException { List<Annotation> annotations = new ArrayList<>(); for (PDAnnotation annt : pdPage.getAnnotations()) { if (annt instanceof PDAnnotationLink) { PDAnnotationLink link = (PDAnnotationLink) annt; PDRectangle rect = link.getRectangle(); float x = rect.getLowerLeftX(); float y = rect.getUpperRightY(); float width = rect.getWidth(); float height = rect.getHeight(); int rotation = pdPage.getRotation(); if (rotation == 0) { PDRectangle pageSize = pdPage.getMediaBox(); y = pageSize.getHeight() - y; } else if (rotation == 90) { //do nothing }/*from www. j a v a2 s .com*/ ActionData actionData = parsePDAction(link.getAction()); if (actionData == null) { actionData = parsePDDestination(link.getDestination()); } if (actionData != null) { Annotation a = new Annotation(x, y, width, height, actionData.destX, actionData.destY, actionData.destPage, actionData.destZoom); annotations.add(a); } } } return annotations; }
From source file:com.yiyihealth.tools.test.DrawPrintTextLocations.java
License:Apache License
private void stripPage(int page) throws IOException { PDFRenderer pdfRenderer = new PDFRenderer(document); image = pdfRenderer.renderImage(page, SCALE); PDPage pdPage = document.getPage(page); PDRectangle cropBox = pdPage.getCropBox(); // flip y-axis flipAT = new AffineTransform(); flipAT.translate(0, pdPage.getBBox().getHeight()); flipAT.scale(1, -1);/*from w w w . j a v a2s .c om*/ // page may be rotated rotateAT = new AffineTransform(); int rotation = pdPage.getRotation(); if (rotation != 0) { PDRectangle mediaBox = pdPage.getMediaBox(); switch (rotation) { case 90: rotateAT.translate(mediaBox.getHeight(), 0); break; case 270: rotateAT.translate(0, mediaBox.getWidth()); break; case 180: rotateAT.translate(mediaBox.getWidth(), mediaBox.getHeight()); break; default: break; } rotateAT.rotate(Math.toRadians(rotation)); } g2d = image.createGraphics(); g2d.setStroke(new BasicStroke(0.1f)); g2d.scale(SCALE, SCALE); setStartPage(page + 1); setEndPage(page + 1); Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream()); writeText(document, dummy); // beads in green g2d.setStroke(new BasicStroke(0.4f)); List<PDThreadBead> pageArticles = pdPage.getThreadBeads(); for (PDThreadBead bead : pageArticles) { PDRectangle r = bead.getRectangle(); GeneralPath p = r .transform(Matrix.getTranslateInstance(-cropBox.getLowerLeftX(), cropBox.getLowerLeftY())); Shape s = flipAT.createTransformedShape(p); s = rotateAT.createTransformedShape(s); g2d.setColor(Color.green); g2d.draw(s); } g2d.dispose(); String imageFilename = filename; int pt = imageFilename.lastIndexOf('.'); imageFilename = imageFilename.substring(0, pt) + "-marked-" + (page + 1) + ".png"; ImageIO.write(image, "png", new File(imageFilename)); }
From source file:de.katho.kBorrow.controller.NewLendingController.java
License:Open Source License
/** * Erzeugt ein PDF-File mit allen relevanten Daten zur als Parameter bergebenen Lending-ID. * /*w ww.ja v a2 s . c om*/ * @param pLendingId ID der Ausleihe, fr die ein PDF erzeugt werden soll. * @throws Exception Wenn Probleme beim Erstellen der Datei auftreten. */ private void createPdfFile(int pLendingId) throws Exception { KLending lending = kLendingModel.getElement(pLendingId); KArticle article = kArticleModel.getElement(lending.getArticleId()); KUser user = kUserModel.getElement(lending.getUserId()); KLender lender = kLenderModel.getElement(lending.getLenderId()); PDDocument doc = new PDDocument(); PDPage page = new PDPage(PDPage.PAGE_SIZE_A4); PDRectangle rect = page.getMediaBox(); doc.addPage(page); PDFont fontNormal = PDType1Font.HELVETICA; PDFont fontBold = PDType1Font.HELVETICA_BOLD; String[] text = { "Artikel: ", "Verliehen von: ", "Ausgeliehen an: ", "Start der Ausleihe: ", "Voraussichtliche Rckgabe: " }; String[] vars = { article.getName(), user.getName() + " " + user.getSurname(), lender.getName() + " " + lender.getSurname() + " (" + lender.getStudentnumber() + ")", lending.getStartDate(), lending.getExpectedEndDate() }; try { File file = createRandomPdf(); PDPageContentStream cos = new PDPageContentStream(doc, page); cos.beginText(); cos.moveTextPositionByAmount(100, rect.getHeight() - 100); cos.setFont(fontBold, 16); cos.drawString("Ausleihe #" + lending.getId()); cos.endText(); int i = 0; while (i < text.length) { cos.beginText(); cos.moveTextPositionByAmount(100, rect.getHeight() - 25 * (i + 2) - 100); cos.setFont(fontBold, 12); cos.drawString(text[i]); cos.moveTextPositionByAmount(rect.getWidth() / 2 - 100, 0); cos.setFont(fontNormal, 12); cos.drawString(vars[i]); cos.endText(); i++; } i = i + 2; cos.setLineWidth(1); cos.addLine(100, rect.getHeight() - 25 * (i + 2) - 100, 300, rect.getHeight() - 25 * (i + 2) - 100); cos.closeAndStroke(); i++; cos.beginText(); cos.moveTextPositionByAmount(100, rect.getHeight() - 25 * (i + 2) - 100); cos.setFont(fontNormal, 12); cos.drawString("Unterschrift " + lender.getName() + " " + lender.getSurname()); cos.endText(); cos.close(); doc.save(file); doc.close(); if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Desktop.Action.OPEN)) { desktop.open(file); } } } catch (IOException | COSVisitorException e) { throw new Exception("Problem bei der Erstellung der PDF-Datei.", e); } }
From source file:de.mirkosertic.desktopsearch.pdfpreview.PDFPreviewGenerator.java
License:Open Source License
@Override public synchronized Preview createPreviewFor(File aFile) { PDDocument theDocument = null;//from w ww.j ava 2 s .c om try { theDocument = PDDocument.load(aFile); List<?> thePages = theDocument.getDocumentCatalog().getAllPages(); if (thePages.isEmpty()) { return null; } PDPage theFirstPage = (PDPage) thePages.get(0); PDRectangle mBox = theFirstPage.findMediaBox(); float theWidthPt = mBox.getWidth(); float theHeightPt = mBox.getHeight(); int theWidthPx = THUMB_WIDTH; // Math.round(widthPt * scaling); int theHeightPx = THUMB_HEIGHT; // Math.round(heightPt * scaling); float theScaling = THUMB_WIDTH / theWidthPt; // resolution / 72.0F; Dimension thePageDimension = new Dimension((int) theWidthPt, (int) theHeightPt); BufferedImage theImage = new BufferedImage(theWidthPx, theHeightPx, BufferedImage.TYPE_INT_RGB); Graphics2D theGraphics = (Graphics2D) theImage.getGraphics(); theGraphics.setBackground(new Color(255, 255, 255, 0)); theGraphics.clearRect(0, 0, theImage.getWidth(), theImage.getHeight()); theGraphics.scale(theScaling, theScaling); PageDrawer theDrawer = new PageDrawer(); theDrawer.drawPage(theGraphics, theFirstPage, thePageDimension); int rotation = theFirstPage.findRotation(); if ((rotation == 90) || (rotation == 270)) { int w = theImage.getWidth(); int h = theImage.getHeight(); BufferedImage rotatedImg = new BufferedImage(w, h, theImage.getType()); Graphics2D g = rotatedImg.createGraphics(); g.rotate(Math.toRadians(rotation), w / 2, h / 2); g.drawImage(theImage, null, 0, 0); } theGraphics.dispose(); return new Preview(ImageUtils.rescale(theImage, THUMB_WIDTH, THUMB_HEIGHT, ImageUtils.RescaleMethod.RESIZE_FIT_ONE_DIMENSION)); } catch (Exception e) { LOGGER.error("Error creating preview for " + aFile, e); return null; } finally { try { // Always close the document theDocument.close(); } catch (Exception e) { } } }
From source file:de.redsix.pdfcompare.PdfComparator.java
License:Apache License
public static ImageWithDimension renderPageAsImage(final PDDocument document, final PDFRenderer expectedPdfRenderer, final int pageIndex) throws IOException { final BufferedImage bufferedImage = expectedPdfRenderer.renderImageWithDPI(pageIndex, DPI); final PDRectangle mediaBox = document.getPage(pageIndex).getMediaBox(); return new ImageWithDimension(bufferedImage, mediaBox.getWidth(), mediaBox.getHeight()); }
From source file:de.rototor.pdfbox.graphics2d.PdfBoxGraphics2D.java
License:Apache License
private void applyShadingAsColor(PDShading shading) throws IOException { /*/*from w w w . j a v a2s.com*/ * If the paint has a shading we must create a tiling pattern and set that as * stroke color... */ PDTilingPattern pattern = new PDTilingPattern(); pattern.setPaintType(PDTilingPattern.PAINT_COLORED); pattern.setTilingType(PDTilingPattern.TILING_CONSTANT_SPACING_FASTER_TILING); PDRectangle anchorRect = bbox; pattern.setBBox(anchorRect); pattern.setXStep(anchorRect.getWidth()); pattern.setYStep(anchorRect.getHeight()); PDAppearanceStream appearance = new PDAppearanceStream(this.document); appearance.setResources(pattern.getResources()); appearance.setBBox(pattern.getBBox()); PDPageContentStream imageContentStream = new PDPageContentStream(document, appearance, ((COSStream) pattern.getCOSObject()).createOutputStream()); imageContentStream.addRect(0, 0, anchorRect.getWidth(), anchorRect.getHeight()); imageContentStream.clip(); imageContentStream.shadingFill(shading); imageContentStream.close(); PDColorSpace patternCS1 = new PDPattern(null); COSName tilingPatternName = xFormObject.getResources().add(pattern); PDColor patternColor = new PDColor(tilingPatternName, patternCS1); contentStream.setNonStrokingColor(patternColor); contentStream.setStrokingColor(patternColor); }