List of usage examples for org.apache.pdfbox.pdmodel.font PDFont getFontDescriptor
@Override
public PDFontDescriptor getFontDescriptor()
From source file:com.fileOperations.StampPDF.java
/** * This stamps docketed files.// www. ja v a 2s . c o m * * @param file String (full file path) * @param docketTime Timestamp * @param dept */ public static void stampDocument(String file, Timestamp docketTime, String dept) { // the document PDDocument doc = null; try { PDFont stampFont = PDType1Font.TIMES_ROMAN; float stampFontSize = 14; String title = PDFBoxTools.HeaderTimeStamp(docketTime) + " " + dept; float titleWidth = stampFont.getStringWidth(title) / 1000 * stampFontSize; float titleHeight = stampFont.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * stampFontSize; int marginTop = 20; doc = PDDocument.load(new File(file)); if (!doc.isEncrypted()) { for (int i = 0; i < doc.getPages().getCount(); i++) { PDPageContentStream contentStream = null; PDPage page = (PDPage) doc.getPages().get(i); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true); page.getResources().getFontNames(); contentStream.beginText(); contentStream.setFont(stampFont, stampFontSize); contentStream.setNonStrokingColor(Color.RED); contentStream.newLineAtOffset((page.getMediaBox().getWidth() - titleWidth) / 2, page.getMediaBox().getHeight() - marginTop - titleHeight); contentStream.showText(title); contentStream.endText(); contentStream.close(); } doc.save(file); } } catch (IOException ex) { ExceptionHandler.Handle(ex); } finally { if (doc != null) { try { doc.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); } } } }
From source file:com.github.gujou.deerbelling.sonarqube.service.PdfApplicationGenerator.java
License:Open Source License
private static void title(String text, PDFont font, int fontSize, PDDocument doc) throws IOException { if (positionHeight + (page.getMediaBox().getHeight() / 6) >= page.getMediaBox().getHeight()) { if (positionTitleWidth > DEFAULT_TITLE_MARGIN_WIDTH) { initNewPage(doc);//from w ww. ja v a2 s. c o m } else { writeToRight(); } } // Jump line if not the first page title. if (positionHeight != DEFAULT_MARGIN_HEIGHT) { positionHeight += (titleSpaceHeight * 2); } PDPageContentStream stream = new PDPageContentStream(doc, page, AppendMode.APPEND, false); stream.setNonStrokingColor(DEFAULT_TEXT_COLOR); float textWidth = font.getStringWidth(text) / 1000 * fontSize; float textHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize; stream.beginText(); stream.setFont(font, fontSize); stream.newLineAtOffset(positionTitleWidth, page.getMediaBox().getHeight() - positionHeight - textHeight); stream.showText(text); stream.endText(); stream.close(); positionHeight += titleSpaceHeight + textHeight; }
From source file:com.github.gujou.deerbelling.sonarqube.service.PdfApplicationGenerator.java
License:Open Source License
private static int centerText(String text, PDFont font, int fontSize, PDPage page, PDDocument doc) throws IOException { PDPageContentStream stream = new PDPageContentStream(doc, page, AppendMode.APPEND, false); stream.setNonStrokingColor(DEFAULT_TEXT_COLOR); float textWidth = font.getStringWidth(text) / 1000 * fontSize; float textHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize; stream.beginText();//from w w w . jav a 2 s. c o m stream.setFont(font, fontSize); stream.newLineAtOffset((page.getMediaBox().getWidth() - textWidth) / 2, page.getMediaBox().getHeight() - positionHeight - textHeight); stream.showText(text); stream.endText(); stream.close(); positionHeight += textHeight; return (int) textHeight; }
From source file:com.github.gujou.deerbelling.sonarqube.service.PdfApplicationGenerator.java
License:Open Source License
private static void rightText(String text, PDFont font, int fontSize, PDPage page, PDDocument doc) throws IOException { PDPageContentStream stream = new PDPageContentStream(doc, page, AppendMode.APPEND, false); stream.setNonStrokingColor(DEFAULT_TEXT_COLOR); float textWidth = font.getStringWidth(text) / 1000 * fontSize; float textHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize; stream.beginText();/*ww w .j a v a2 s .co m*/ stream.setFont(font, fontSize); stream.newLineAtOffset(page.getMediaBox().getWidth() - textWidth - DEFAULT_LOGO_RIGHT_MARGIN_WIDTH, page.getMediaBox().getHeight() - positionHeight - textHeight); stream.showText(text); stream.endText(); stream.close(); positionHeight += textHeight; }
From source file:com.github.gujou.deerbelling.sonarqube.service.PdfApplicationGenerator.java
License:Open Source License
private static void leftText(String text, PDFont font, int fontSize, PDPage page, PDDocument doc) throws IOException { PDPageContentStream stream = new PDPageContentStream(doc, page, AppendMode.APPEND, false); stream.setNonStrokingColor(DEFAULT_TEXT_COLOR); float textWidth = font.getStringWidth(text) / 1000 * fontSize; float textHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize; stream.beginText();/*from w ww . j a v a 2 s . c o m*/ stream.setFont(font, fontSize); stream.newLineAtOffset(DEFAULT_LOGO_LEFT_MARGIN_WIDTH, page.getMediaBox().getHeight() - positionHeight - textHeight); stream.showText(text); stream.endText(); stream.close(); positionHeight += textHeight; }
From source file:com.github.gujou.deerbelling.sonarqube.service.PdfApplicationGenerator.java
License:Open Source License
private static void attribute(PDImageXObject logo, int logoHeight, int logoWidth, String value, String label, PDFont font, int fontSize, PDDocument doc, String index, boolean isPercent, Color color) throws IOException { int dataFontSize = (int) (fontSize * 1.5f); int labelFontSize = fontSize; float logoYCoordinate = page.getMediaBox().getHeight() - positionHeight - logoHeight; float textWidth = (font.getStringWidth(value) / 1000 * dataFontSize) + (font.getStringWidth(label) / 1000 * labelFontSize); float textHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * dataFontSize; float textYCoordinate = page.getMediaBox().getHeight() - positionHeight - (logoHeight / 2) - (textHeight / 2);/*from w w w . j a v a 2s .co m*/ float dataXCoordinate = positionLogoWidth + logoHeight + DEFAULT_SPACE_WIDTH; positionHeight += spaceHeight + ((logoHeight < textHeight) ? textHeight : logoHeight); if (positionHeight >= page.getMediaBox().getHeight()) { if (positionLogoWidth > DEFAULT_ICON_MARGIN_WIDTH) { initNewPage(doc); attribute(logo, logoHeight, logoWidth, value, label, font, labelFontSize, doc, index, isPercent, color); } else { writeToRight(); attribute(logo, logoHeight, logoWidth, value, label, font, labelFontSize, doc, index, isPercent, color); } } else { PDPageContentStream stream = new PDPageContentStream(doc, page, AppendMode.APPEND, false); try { stream.drawImage(logo, positionLogoWidth, logoYCoordinate, logoWidth, logoHeight); stream.beginText(); stream.setFont(font, dataFontSize); stream.setNonStrokingColor(color); stream.newLineAtOffset(dataXCoordinate, textYCoordinate + 6); stream.showText(value); stream.setNonStrokingColor(DEFAULT_TEXT_COLOR); stream.setFont(font, labelFontSize); stream.showText(label); if (index != null) { stream.newLineAtOffset(textWidth, (int) (labelFontSize * 0.3)); stream.setFont(PDType1Font.COURIER_BOLD, (int) (labelFontSize * 0.8)); stream.showText("("); stream.setNonStrokingColor(color); stream.showText(index); if (isPercent) { stream.showText("%"); } stream.setNonStrokingColor(DEFAULT_TEXT_COLOR); stream.showText(")"); } } finally { stream.endText(); stream.close(); } } }
From source file:com.helger.pdflayout.spec.PDFFont.java
License:Apache License
public PDFFont(@Nonnull final PDFont aFont) { m_aFont = ValueEnforcer.notNull(aFont, "Font"); final PDFontDescriptor aFD = aFont.getFontDescriptor(); // 2.0.0 code. Does not work with 1.8.4 // if (aFD == null) // {//from w ww .ja v a2 s . c o m // if (aFont instanceof PDType0Font) // { // final PDFont aDescendantFont = ((PDType0Font) aFont).getDescendantFont // (); // if (aDescendantFont != null) // aFD = aDescendantFont.getFontDescriptor (); // } // } if (aFD == null) throw new IllegalArgumentException("Failed to determined FontDescriptor from specified font " + aFont); m_fBBHeight = aFD.getFontBoundingBox().getHeight(); }
From source file:com.repeatability.pdf.PDFTextStreamEngine.java
License:Apache License
/** * This method was originally written by Ben Litchfield for PDFStreamEngine. *///from w ww. j a v a 2 s. c o m @Override protected void showGlyph(Matrix textRenderingMatrix, PDFont font, int code, String unicode, Vector displacement) throws IOException { // // legacy calculations which were previously in PDFStreamEngine // PDGraphicsState state = getGraphicsState(); Matrix ctm = state.getCurrentTransformationMatrix(); float fontSize = state.getTextState().getFontSize(); float horizontalScaling = state.getTextState().getHorizontalScaling() / 100f; Matrix textMatrix = getTextMatrix(); BoundingBox bbox = font.getBoundingBox(); if (bbox.getLowerLeftY() < Short.MIN_VALUE) { // PDFBOX-2158 and PDFBOX-3130 // files by Salmat eSolutions / ClibPDF Library bbox.setLowerLeftY(-(bbox.getLowerLeftY() + 65536)); } // 1/2 the bbox is used as the height todo: why? float glyphHeight = bbox.getHeight() / 2; // sometimes the bbox has very high values, but CapHeight is OK PDFontDescriptor fontDescriptor = font.getFontDescriptor(); if (fontDescriptor != null) { float capHeight = fontDescriptor.getCapHeight(); if (capHeight != 0 && capHeight < glyphHeight) { glyphHeight = capHeight; } } // transformPoint from glyph space -> text space float height; if (font instanceof PDType3Font) { height = font.getFontMatrix().transformPoint(0, glyphHeight).y; } else { height = glyphHeight / 1000; } float displacementX = displacement.getX(); // the sorting algorithm is based on the width of the character. As the displacement // for vertical characters doesn't provide any suitable value for it, we have to // calculate our own if (font.isVertical()) { displacementX = font.getWidth(code) / 1000; // there may be an additional scaling factor for true type fonts TrueTypeFont ttf = null; if (font instanceof PDTrueTypeFont) { ttf = ((PDTrueTypeFont) font).getTrueTypeFont(); } else if (font instanceof PDType0Font) { PDCIDFont cidFont = ((PDType0Font) font).getDescendantFont(); if (cidFont instanceof PDCIDFontType2) { ttf = ((PDCIDFontType2) cidFont).getTrueTypeFont(); } } if (ttf != null && ttf.getUnitsPerEm() != 1000) { displacementX *= 1000f / ttf.getUnitsPerEm(); } } // (modified) combined displacement, this is calculated *without* taking the character // spacing and word spacing into account, due to legacy code in TextStripper float tx = displacementX * fontSize * horizontalScaling; float ty = displacement.getY() * fontSize; // (modified) combined displacement matrix Matrix td = Matrix.getTranslateInstance(tx, ty); // (modified) text rendering matrix Matrix nextTextRenderingMatrix = td.multiply(textMatrix).multiply(ctm); // text space -> device space float nextX = nextTextRenderingMatrix.getTranslateX(); float nextY = nextTextRenderingMatrix.getTranslateY(); // (modified) width and height calculations float dxDisplay = nextX - textRenderingMatrix.getTranslateX(); float dyDisplay = height * textRenderingMatrix.getScalingFactorY(); // // start of the original method // // Note on variable names. There are three different units being used in this code. // Character sizes are given in glyph units, text locations are initially given in text // units, and we want to save the data in display units. The variable names should end with // Text or Disp to represent if the values are in text or disp units (no glyph units are // saved). float glyphSpaceToTextSpaceFactor = 1 / 1000f; if (font instanceof PDType3Font) { glyphSpaceToTextSpaceFactor = font.getFontMatrix().getScaleX(); } float spaceWidthText = 0; try { // to avoid crash as described in PDFBOX-614, see what the space displacement should be spaceWidthText = font.getSpaceWidth() * glyphSpaceToTextSpaceFactor; } catch (Throwable exception) { LOG.warn(exception, exception); } if (spaceWidthText == 0) { spaceWidthText = font.getAverageFontWidth() * glyphSpaceToTextSpaceFactor; // the average space width appears to be higher than necessary so make it smaller spaceWidthText *= .80f; } if (spaceWidthText == 0) { spaceWidthText = 1.0f; // if could not find font, use a generic value } // the space width has to be transformed into display units float spaceWidthDisplay = spaceWidthText * textRenderingMatrix.getScalingFactorX(); // use our additional glyph list for Unicode mapping unicode = font.toUnicode(code, glyphList); // when there is no Unicode mapping available, Acrobat simply coerces the character code // into Unicode, so we do the same. Subclasses of PDFStreamEngine don't necessarily want // this, which is why we leave it until this point in PDFTextStreamEngine. if (unicode == null) { if (font instanceof PDSimpleFont) { char c = (char) code; unicode = new String(new char[] { c }); } else { // Acrobat doesn't seem to coerce composite font's character codes, instead it // skips them. See the "allah2.pdf" TestTextStripper file. return; } } // adjust for cropbox if needed Matrix translatedTextRenderingMatrix; if (translateMatrix == null) { translatedTextRenderingMatrix = textRenderingMatrix; } else { translatedTextRenderingMatrix = Matrix.concatenate(translateMatrix, textRenderingMatrix); nextX -= pageSize.getLowerLeftX(); nextY -= pageSize.getLowerLeftY(); } processTextPosition(new TextPosition(pageRotation, pageSize.getWidth(), pageSize.getHeight(), translatedTextRenderingMatrix, nextX, nextY, dyDisplay, dxDisplay, spaceWidthDisplay, unicode, new int[] { code }, font, fontSize, (int) (fontSize * textMatrix.getScalingFactorX()))); }
From source file:com.zilbo.flamingSailor.TE.PDFParser.java
License:Apache License
@Override protected void endPage(PDPage page) throws IOException { super.endPage(page); int pieceID = 0; Map<String, Map<Integer, Long>> fontCounts = new HashMap<>(); List<TextPiece> wordsOfThisPage = new ArrayList<>(); for (List<TextPosition> aCharactersByArticle : charactersByArticle) { // int len = aCharactersByArticle.size(); for (TextPosition t : aCharactersByArticle) { // copy information TextPiece w = new TextPiece(pieceID++); PDFont font = t.getFont(); PDFontDescriptor fontDescriptor = font.getFontDescriptor(); // w.setFontDescriptor(fontDescriptor); if (fontDescriptor == null) { w.setFontName("UNKNOWN"); } else { w.setFontName(fontDescriptor.getFontName()); }// ww w . ja v a 2 s .c om /* * 100: a simple step to fix the font size to the normal range, for those documents in unknown codes that PDFBox can not process now */ if (t.getFontSize() < 0.3 && t.getYScale() <= 1.0) { w.setFontSize(t.getFontSize() * 100); w.setHeight(Math.max(t.getYScale(), t.getFontSize()) * 100); w.setXScale(t.getXScale()); w.setYScale(t.getYScale()); } else { if (t.getYScale() < 0.3 && t.getFontSize() <= 1.0) { w.setYScale(t.getYScale() * 100); w.setXScale(t.getXScale() * 100); w.setHeight(Math.max(t.getYScale() * 100, t.getFontSize())); } else { w.setFontSize(t.getFontSize()); w.setHeight(Math.max(t.getYScale(), t.getFontSize())); w.setXScale(t.getXScale()); w.setYScale(t.getYScale()); } } Map<Integer, Long> counts = fontCounts.get(w.getFontName()); if (counts == null) { counts = new HashMap<>(); fontCounts.put(w.getFontName(), counts); } Long count = counts.get((int) Math.round(w.getHeight())); if (count == null) { count = 1L; } else { count += 1L; } counts.put((int) Math.round(w.getHeight()), count); w.setWidth(Math.abs(t.getWidth())); w.setGeom(t.getX(), t.getY(), w.getWidth(), w.getHeight()); w.setText(t.getCharacter()); w.setWidthOfSpace(t.getWidthOfSpace()); wordsOfThisPage.add(w); } } currentPage.processPage(wordsOfThisPage, fontCounts); currentPage.setText(outString.getBuffer().toString()); outString.getBuffer().setLength(0); List<PDAnnotation> annotations = page.getAnnotations(); for (PDAnnotation annotation : annotations) { if (annotation instanceof PDAnnotationLink) { PDAnnotationLink l = (PDAnnotationLink) annotation; PDRectangle rect = l.getRectangle(); PDDestination dest = l.getDestination(); if (dest instanceof PDPageXYZDestination) { PDPageXYZDestination xyzDestination = (PDPageXYZDestination) dest; PDPage pageDest = ((PDPageXYZDestination) dest).getPage(); if (rect != null) { if (xyzDestination.getPageNumber() < 0) { int pageNumber = allpages.indexOf(pageDest) + 1; Rectangle2D hotbox = new Rectangle2D.Double(rect.getLowerLeftX(), rect.getLowerLeftY(), (rect.getUpperRightX() - rect.getLowerLeftX()), (rect.getUpperRightY() - rect.getLowerLeftY())); Point2D toPoint = new Point2D.Double(xyzDestination.getLeft(), xyzDestination.getTop()); currentPage.addLink(new PDLink(hotbox, pageNumber, toPoint)); } } } } } /* The following code is REALLY raw. initial testing seemed to show memory leaks, and was REALLY slow. PDResources r = page.getResources(); Map<String, PDXObjectImage> images = r.getImages(); for (Map.Entry<String, PDXObjectImage> e : images.entrySet()) { BufferedImage bi = null; try { // currentPage.addImage(bi); // (e.getValue()).write2file("/tmp/II" + e.getKey()); if (e.getValue() instanceof PDJpeg) { PDJpeg jpg = (PDJpeg) e.getValue(); bi = jpg.getRGBImage(); ColorSpace cs = bi.getColorModel().getColorSpace(); File jpgFile = new File("/tmp/II" + e.getKey() + ".jpg"); if (cs instanceof ColorSpaceCMYK) { logger.info("Ignoring image with CMYK color space"); } else { // ImageIO.write(bi, "jpg", jpgFile); jpg.write2file("/tmp/II"+ e.getKey()); } } else { (e.getValue()).write2file("/tmp/II" + e.getKey()); } } catch (Exception ee) { logger.info("can't read image ;-(", ee); } } */ textPageList.add(currentPage); currentPage = null; }
From source file:de.hrogge.CompactPDFExport.PDFSeite.java
License:Apache License
public float berechneTextUeberlauf(PDFont font, int x1, int x2, int height, String text) throws IOException { PDFontDescriptor descr = font.getFontDescriptor(); float boxProp, textProp; float boxWidth, boxHeight; float textWidth, textHeight; boxHeight = (pageHeight / 60.0f * height) - 2 * randText; boxWidth = (getX(x2) - getX(x1)) - 2 * randText; boxProp = boxWidth / boxHeight;/*from w w w. ja va2s . c o m*/ textHeight = (descr.getFontBoundingBox().getHeight()) / 1000f; textWidth = font.getStringWidth(text) / 1000f; textProp = textWidth / textHeight; if (textProp > boxProp) { return textProp / boxProp; } return 1.0f; }