List of usage examples for org.apache.pdfbox.pdmodel PDPage getMediaBox
public PDRectangle getMediaBox()
From source file:com.repeatability.pdf.PDFTextStripper.java
License:Apache License
private void fillBeadRectangles(PDPage page) { beadRectangles = new ArrayList<PDRectangle>(); for (PDThreadBead bead : page.getThreadBeads()) { if (bead == null) { // can't skip, because of null entry handling in processTextPosition() beadRectangles.add(null);// w w w.j a v a2 s . c o m continue; } PDRectangle rect = bead.getRectangle(); // bead rectangle is in PDF coordinates (y=0 is bottom), // glyphs are in image coordinates (y=0 is top), // so we must flip PDRectangle mediaBox = page.getMediaBox(); float upperRightY = mediaBox.getUpperRightY() - rect.getLowerLeftY(); float lowerLeftY = mediaBox.getUpperRightY() - rect.getUpperRightY(); rect.setLowerLeftY(lowerLeftY); rect.setUpperRightY(upperRightY); // adjust for cropbox PDRectangle cropBox = page.getCropBox(); if (cropBox.getLowerLeftX() != 0 || cropBox.getLowerLeftY() != 0) { rect.setLowerLeftX(rect.getLowerLeftX() - cropBox.getLowerLeftX()); rect.setLowerLeftY(rect.getLowerLeftY() - cropBox.getLowerLeftY()); rect.setUpperRightX(rect.getUpperRightX() - cropBox.getLowerLeftX()); rect.setUpperRightY(rect.getUpperRightY() - cropBox.getLowerLeftY()); } beadRectangles.add(rect); } }
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 ww . j a v a 2s . co 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.vns.pdf.impl.PdfDocument.java
License:Apache License
private PdfDocument(String pdfFileName) throws IOException { this.pdfFileName = pdfFileName; setWorkingDir();//from w ww. j ava 2s . com 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 w w w . j av a2 s . c o m 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 ww . j a v a 2 s . co m*/ // 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:controldeadministradores.Admin.java
public void crearPDF(String file, String body) throws Exception { String outputFileName = file + ".pdf"; // if (args.length > 0) // outputFileName = args[0]; // Create a document and add a page to it PDDocument document = new PDDocument(); PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4); // PDPage.PAGE_SIZE_LETTER is also possible PDRectangle rect = page1.getMediaBox(); // rect can be used to get the page width and height document.addPage(page1);//from w w w .j a v a 2s . c o m // Create a new font object selecting one of the PDF base fonts PDFont fontPlain = PDType1Font.HELVETICA; PDFont fontBold = PDType1Font.HELVETICA_BOLD; PDFont fontItalic = PDType1Font.HELVETICA_OBLIQUE; PDFont fontMono = PDType1Font.COURIER; // Start a new content stream which will "hold" the to be created content PDPageContentStream cos = new PDPageContentStream(document, page1); int line = 0; // Define a text content stream using the selected font, move the cursor and draw some text cos.beginText(); cos.setFont(fontPlain, 14); cos.moveTextPositionByAmount(100, rect.getHeight() - 50 * (++line)); cos.drawString("Reporte de " + file); cos.endText(); String[] txtLine = body.split("-"); for (int k = 0; k < txtLine.length; k++) { cos.beginText(); cos.setFont(fontPlain, 12); cos.moveTextPositionByAmount(100, rect.getHeight() - 50 * (++line)); cos.drawString(txtLine[k]); cos.endText(); cos.close(); } // Make sure that the content stream is closed: // Save the results and ensure that the document is properly closed: document.save(outputFileName); document.close(); }
From source file:ddf.catalog.transformer.input.pdf.GeoPdfParserImpl.java
License:Open Source License
/** * A PDF Neatline defines the area of a PDF image with relation to the PDF page. If no neatline is given * it is assumed that the image encompasses the entire page. This functiong generates a NeatLine * in this fashion.//from w w w . j av a 2s . c o m * @param pdPage the page to generate the NeatLine * @return an array of points representing the NeatLine */ private COSArray generateNeatLineFromPDFDimensions(PDPage pdPage) { COSArray neatLineArray = new COSArray(); String width = String.valueOf(pdPage.getMediaBox().getWidth()); String height = String.valueOf(pdPage.getMediaBox().getHeight()); neatLineArray.add(new COSString("0")); neatLineArray.add(new COSString("0")); neatLineArray.add(new COSString(width)); neatLineArray.add(new COSString("0")); neatLineArray.add(new COSString(width)); neatLineArray.add(new COSString(height)); neatLineArray.add(new COSString("0")); neatLineArray.add(new COSString(height)); return neatLineArray; }
From source file:de.fau.amos4.util.ZipGenerator.java
License:Open Source License
public void generate(OutputStream out, Locale locale, float height, Employee employee, int fontSize, String zipPassword) throws ZipException, NoSuchMessageException, IOException, COSVisitorException, CloneNotSupportedException { final ZipOutputStream zout = new ZipOutputStream(out); if (zipPassword == null) { // Use default password if none is set. zipPassword = "fragebogen"; }/* w ww . ja v a 2 s .c o m*/ ZipParameters params = new ZipParameters(); params.setFileNameInZip("employee.txt"); params.setCompressionLevel(Zip4jConstants.COMP_DEFLATE); params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA); params.setEncryptFiles(true); params.setReadHiddenFiles(false); params.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES); params.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256); params.setPassword(zipPassword); params.setSourceExternalStream(true); zout.putNextEntry(null, params); zout.write((AppContext.getApplicationContext().getMessage("HEADER", null, locale) + "\n\n").getBytes()); zout.write( (AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale) + "\n\n") .getBytes()); Iterator it = employee.getPersonalDataFields().entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); zout.write((pair.getKey() + ": " + pair.getValue() + '\n').getBytes()); it.remove(); // avoids a ConcurrentModificationException } zout.write(("\n\n" + AppContext.getApplicationContext().getMessage("print.section.taxes", null, locale) + "\n\n").getBytes()); it = employee.getTaxesFields().entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); zout.write((pair.getKey() + ": " + pair.getValue() + '\n').getBytes()); it.remove(); // avoids a ConcurrentModificationException } zout.closeEntry(); // Create a document and add a page to it PDDocument document = new PDDocument(); PDPage page = new PDPage(); document.addPage(page); float y = -1; int margin = 100; // Create a new font object selecting one of the PDF base fonts PDFont font = PDType1Font.TIMES_ROMAN; // Start a new content stream which will "hold" the to be created content PDPageContentStream contentStream = new PDPageContentStream(document, page); // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World" contentStream.beginText(); y = page.getMediaBox().getHeight() - margin + height; contentStream.moveTextPositionByAmount(margin, y); /* List<String> list = StringUtils.splitEqually(fileContent, 90); for (String e : list) { contentStream.moveTextPositionByAmount(0, -15); contentStream.drawString(e); } */ contentStream.setFont(PDType1Font.TIMES_BOLD, 36); contentStream.drawString(AppContext.getApplicationContext().getMessage("HEADER", null, locale)); contentStream.setFont(PDType1Font.TIMES_BOLD, 14); contentStream.moveTextPositionByAmount(0, -4 * height); contentStream.drawString( AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale)); contentStream.moveTextPositionByAmount(0, -2 * height); contentStream.setFont(font, fontSize); it = employee.getPersonalDataFields().entrySet().iterator(); while (it.hasNext()) { StringBuffer nextLineToDraw = new StringBuffer(); Map.Entry pair = (Map.Entry) it.next(); nextLineToDraw.append(pair.getKey()); nextLineToDraw.append(": "); nextLineToDraw.append(pair.getValue()); contentStream.drawString(nextLineToDraw.toString()); contentStream.moveTextPositionByAmount(0, -height); it.remove(); // avoids a ConcurrentModificationException } contentStream.setFont(PDType1Font.TIMES_BOLD, 14); contentStream.moveTextPositionByAmount(0, -2 * height); contentStream .drawString(AppContext.getApplicationContext().getMessage("print.section.taxes", null, locale)); contentStream.moveTextPositionByAmount(0, -2 * height); contentStream.setFont(font, fontSize); it = employee.getTaxesFields().entrySet().iterator(); while (it.hasNext()) { StringBuffer nextLineToDraw = new StringBuffer(); Map.Entry pair = (Map.Entry) it.next(); nextLineToDraw.append(pair.getKey()); nextLineToDraw.append(": "); nextLineToDraw.append(pair.getValue()); contentStream.drawString(nextLineToDraw.toString()); contentStream.moveTextPositionByAmount(0, -height); it.remove(); // avoids a ConcurrentModificationException } contentStream.endText(); // Make sure that the content stream is closed: contentStream.close(); // Save the results and ensure that the document is properly closed: ByteArrayOutputStream pdfout = new ByteArrayOutputStream(); document.save(pdfout); document.close(); ZipParameters params2 = (ZipParameters) params.clone(); params2.setFileNameInZip("employee.pdf"); zout.putNextEntry(null, params2); zout.write(pdfout.toByteArray()); zout.closeEntry(); // Write the zip to client zout.finish(); zout.flush(); zout.close(); }
From source file:de.fau.amos4.web.PrintDataController.java
License:Open Source License
@RequestMapping("/employee/download/zip") public void EmployeeDownloadZip(HttpServletResponse response, @RequestParam(value = "id", required = true) long employeeId) throws IOException { int fontSize = 12; float height = 1; height = height * fontSize * 1.05f;//w ww . j a va 2 s .c om //Prepare textfile contents Employee employee = employeeRepository.findOne(employeeId); Locale locale = LocaleContextHolder.getLocale(); Map<String, String> fields = employee.getFields(); response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment;filename=employee.zip"); final ZipOutputStream zout = new ZipOutputStream(response.getOutputStream()); try { ZipParameters params = new ZipParameters(); params.setFileNameInZip("employee.txt"); params.setCompressionLevel(Zip4jConstants.COMP_DEFLATE); params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA); params.setEncryptFiles(true); params.setReadHiddenFiles(false); params.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES); params.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256); params.setPassword("AMOS"); params.setSourceExternalStream(true); zout.putNextEntry(null, params); zout.write((AppContext.getApplicationContext().getMessage("EmployeeForm.header", null, locale) + "\n\n") .getBytes()); //zout.println(); zout.write((AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale) + "\n\n").getBytes()); //zout.println(); Iterator it = fields.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); zout.write((pair.getKey() + ": " + pair.getValue() + '\n').getBytes()); it.remove(); // avoids a ConcurrentModificationException } zout.closeEntry(); try { // Create a document and add a page to it PDDocument document = new PDDocument(); PDPage page = new PDPage(); document.addPage(page); float y = -1; int margin = 100; float maxStringLength = page.getMediaBox().getWidth() - 2 * margin; // Create a new font object selecting one of the PDF base fonts PDFont font = PDType1Font.TIMES_ROMAN; // Start a new content stream which will "hold" the to be created content PDPageContentStream contentStream = new PDPageContentStream(document, page); // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World" contentStream.beginText(); y = page.getMediaBox().getHeight() - margin + height; contentStream.moveTextPositionByAmount(margin, y); /* List<String> list = StringUtils.splitEqually(fileContent, 90); for (String e : list) { contentStream.moveTextPositionByAmount(0, -15); contentStream.drawString(e); } */ fields = employee.getFields(); contentStream.setFont(PDType1Font.TIMES_BOLD, 36); contentStream.drawString( AppContext.getApplicationContext().getMessage("EmployeeForm.header", null, locale)); contentStream.setFont(PDType1Font.TIMES_BOLD, 14); contentStream.moveTextPositionByAmount(0, -4 * height); contentStream.drawString( AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale)); contentStream.moveTextPositionByAmount(0, -2 * height); contentStream.setFont(font, fontSize); it = fields.entrySet().iterator(); while (it.hasNext()) { StringBuffer nextLineToDraw = new StringBuffer(); Map.Entry pair = (Map.Entry) it.next(); nextLineToDraw.append(pair.getKey()); nextLineToDraw.append(": "); nextLineToDraw.append(pair.getValue()); contentStream.drawString(nextLineToDraw.toString()); contentStream.moveTextPositionByAmount(0, -height); it.remove(); // avoids a ConcurrentModificationException } contentStream.endText(); // Make sure that the content stream is closed: contentStream.close(); // Save the results and ensure that the document is properly closed: ByteArrayOutputStream pdfout = new ByteArrayOutputStream(); document.save(pdfout); document.close(); ZipParameters params2 = (ZipParameters) params.clone(); params2.setFileNameInZip("employee.pdf"); zout.putNextEntry(null, params2); zout.write(pdfout.toByteArray()); zout.closeEntry(); } catch (CloneNotSupportedException | COSVisitorException e) { e.printStackTrace(); } // Write the zip to client zout.finish(); zout.flush(); zout.close(); } catch (ZipException e) { e.printStackTrace(); } }
From source file:de.ifsr.adam.ImageGenerator.java
License:Open Source License
/** * Takes a snapshot of the Pane and prints it to a pdf. * * @return True if no IOException occurred *///from ww w . java2 s.c om private boolean printToPDF(String filePath, Pane pane) { //Scene set up Group root = new Group(); Scene printScene = new Scene(root); printScene.getStylesheets().add(this.stylesheetURI.toString()); //Snapshot generation ArrayList<WritableImage> images = new ArrayList<>(); try { ObservableList<Node> panes = pane.getChildren(); for (int i = 0; i < panes.size(); i++) { GridPane gridPane = (GridPane) panes.get(i); ((Group) printScene.getRoot()).getChildren().clear(); ((Group) printScene.getRoot()).getChildren().addAll(gridPane); images.add(printScene.snapshot(null)); panes.add(i, gridPane); } } catch (Exception e) { log.error(e); return false; } //PDF Setup File outFile = new File(filePath + "." + "pdf"); Iterator<WritableImage> iterImages = images.iterator(); PDDocument doc = new PDDocument(); try { while (iterImages.hasNext()) { //Page setup PDPage page = new PDPage(); doc.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, false); //Image setup BufferedImage bufImage = SwingFXUtils.fromFXImage(iterImages.next(), null); PDPixelMap pixelMap = new PDPixelMap(doc, bufImage); int width = (int) (page.getMediaBox().getWidth()); int height = (int) (page.getMediaBox().getHeight()); Dimension dim = new Dimension(width, height); contentStream.drawXObject(pixelMap, 0, 0, dim.width, dim.height); contentStream.close(); } doc.save(outFile); return true; } catch (IOException | COSVisitorException e) { log.error(e); return false; } }